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 |
|---|---|---|---|---|---|
2f8f2933d018fb2141d9b61747036bb374a51e56 | 7,337 | package fr.n7.stl.tam.ast.impl;
import java.util.List;
import java.util.Optional;
import fr.n7.stl.tam.ast.Fragment;
import fr.n7.stl.tam.ast.Register;
import fr.n7.stl.tam.ast.TAMFactory;
import fr.n7.stl.tam.ast.TAMInstruction;
/**
* Implementation of the factory to build a TAM program AST.
* It relies on a single implementation class TAMInstructionImpl.
* @author Marc Pantel
*
*/
public class TAMFactoryImpl implements TAMFactory {
private static int labelNumber = 0;
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createFragment()
*/
@Override
public Fragment createFragment() {
return new FragmentImpl();
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createLoadL(int)
*/
@Override
public TAMInstruction createLoadL(int _value) {
return new TAMInstructionImpl(
TAMInstructionKind.LOADL,
Optional.empty(),
Optional.empty(),
Optional.of(_value),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createPush(int)
*/
@Override
public TAMInstruction createPush(int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.PUSH,
Optional.empty(),
Optional.empty(),
Optional.of(_size),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createPop(int, int)
*/
@Override
public TAMInstruction createPop(int _keep, int _remove) {
return new TAMInstructionImpl(
TAMInstructionKind.POP,
Optional.empty(),
Optional.empty(),
Optional.of(_remove),
Optional.empty(),
Optional.of(_keep));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createLoad(fr.n7.stl.tam.ast.Register, int, int)
*/
@Override
public TAMInstruction createLoad(Register _register, int _offset, int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.LOAD,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createLoadA(fr.n7.stl.tam.ast.Register, int)
*/
@Override
public TAMInstruction createLoadA(Register _register, int _offset) {
return new TAMInstructionImpl(
TAMInstructionKind.LOADA,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createLoadA(java.lang.String)
*/
@Override
public TAMInstruction createLoadA(String _label) {
return new TAMInstructionImpl(
TAMInstructionKind.LOADA,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_label),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createLoadI(int)
*/
@Override
public TAMInstruction createLoadI(int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.LOADI,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createStore(fr.n7.stl.tam.ast.Register, int, int)
*/
@Override
public TAMInstruction createStore(Register _register, int _offset, int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.STORE,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createStoreI(int)
*/
@Override
public TAMInstruction createStoreI(int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.STOREI,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createJump(fr.n7.stl.tam.ast.Register, int)
*/
@Override
public TAMInstruction createJump(Register _register, int _offset) {
return new TAMInstructionImpl(
TAMInstructionKind.JUMP,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createJump(java.lang.String)
*/
@Override
public TAMInstruction createJump(String _label) {
return new TAMInstructionImpl(
TAMInstructionKind.JUMP,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_label),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createJumpIf(fr.n7.stl.tam.ast.Register, int, int)
*/
@Override
public TAMInstruction createJumpIf(Register _register, int _offset, int _value) {
return new TAMInstructionImpl(
TAMInstructionKind.JUMPIF,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createJumpIf(java.lang.String, int)
*/
@Override
public TAMInstruction createJumpIf(String _label, int _value) {
return new TAMInstructionImpl(
TAMInstructionKind.JUMPIF,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_label),
Optional.of(_value));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createHalt()
*/
@Override
public TAMInstruction createHalt() {
return new TAMInstructionImpl(
TAMInstructionKind.HALT,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty());
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createCall(fr.n7.stl.tam.ast.Register, int, int)
*/
@Override
public TAMInstruction createCall(Register _register, int _offset, int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.CALL,
Optional.empty(),
Optional.of(_register),
Optional.of(_offset),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createCall(java.lang.String, int)
*/
@Override
public TAMInstruction createCall(String _label, int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.CALL,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_label),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createCallI(int)
*/
@Override
public TAMInstruction createCallI(int _size) {
return new TAMInstructionImpl(
TAMInstructionKind.CALLI,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(_size));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createReturn(int, int)
*/
@Override
public TAMInstruction createReturn(int _keep, int _remove) {
return new TAMInstructionImpl(
TAMInstructionKind.RETURN,
Optional.empty(),
Optional.empty(),
Optional.of(_remove),
Optional.empty(),
Optional.of(_keep));
}
/* (non-Javadoc)
* @see fr.n7.stl.tam.ast.TAMFactory#createFragment(java.util.List)
*/
@Override
public Fragment createFragment(List<TAMInstruction> _instructions) {
Fragment _local = new FragmentImpl();
for (TAMInstruction _instruction : _instructions) {
_local.add(_instruction);
}
return _local;
}
@Override
public int createLabelNumber() {
labelNumber++;
return labelNumber;
}
}
| 24.456667 | 88 | 0.690064 |
ec105568d913abf1195182738f72f847b7b5dde4 | 930 | package com.madisp.stupid.expr;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
/**
* The classic ternary expression, e.g. expr ? trueValue : falseValue.
* I know everybody hates it but it has been proven useful from time to time.
*
* In stupid: {@code expr ? trueValue : falseValue}
*/
public class TernaryExpression implements Expression {
private final Expression expression, trueValue, falseValue;
public TernaryExpression(Expression expression, Expression trueValue, Expression falseValue) {
this.expression = expression;
this.trueValue = trueValue;
this.falseValue = falseValue;
}
@Override
public Object value(ExecContext ctx) {
return ctx.getConverter().toBool(ctx.dereference(expression))
? ctx.dereference(trueValue) : ctx.dereference(falseValue);
}
@Override
public Expression[] children() {
return new Expression[] { expression, trueValue, falseValue };
}
}
| 29.0625 | 95 | 0.755914 |
a8a95199bd6ea9972cb92845542e6639cace185f | 3,268 | package vv.spoon.processor;
import spoon.processing.AbstractProcessor;
import spoon.reflect.cu.CompilationUnit;
import spoon.reflect.cu.SourceCodeFragment;
import spoon.reflect.cu.SourcePosition;
import spoon.reflect.reference.CtExecutableReference;
import spoon.reflect.code.CtReturn;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtExecutable;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtParameter;
import spoon.support.reflect.code.CtReturnImpl;
public class LogProcessortree extends AbstractProcessor<CtExecutable<?>> {
@Override
public boolean isToBeProcessed(CtExecutable<?> candidate) {
/*
try {
Class type = candidate.getTarget().getType().getActualClass();
CtExecutableReference executable = candidate.getExecutable();
if(type.equals(java.io.PrintStream.class)
&& isPrint(executable)) {
return true;
}
return false;
} catch (Exception e) {
return false;
}*/
try {
if((candidate instanceof CtMethod) || (candidate instanceof CtConstructor)) {
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
@Override
public void process(CtExecutable<?> element) {
String snippet_enter = "vv.spoon.logger.LogWriter.enter(\"" + this.getElement(element)+ "\")";
CtStatement state_begin = getFactory().Code().createCodeSnippetStatement(snippet_enter);
element.getBody().insertBegin(state_begin);
String snippet_sortie = "vv.spoon.logger.LogWriter.leave(\"" + this.getElement(element)+ "\")";
CtStatement state_end = getFactory().Code().createCodeSnippetStatement(snippet_sortie);
if(element.getBody().getLastStatement().getClass().getSimpleName().equals(CtReturnImpl.class.getSimpleName())){
element.getBody().getLastStatement().insertBefore(state_end);
}else{
element.getBody().insertEnd(state_end);
}
}
public String getElement(CtExecutable<?> element) {
String result = "";
result += element.getParent(CtClass.class).getSimpleName();
result += ".";
if(element instanceof CtConstructor) {
result += element.getParent(CtClass.class).getSimpleName();
} else {
result += element.getSimpleName();
}
result += "(";
for (CtParameter<?> parameter : element.getParameters()) {
result += parameter.toString();
result += ", ";
}
if (result.charAt(result.length() - 1) != '(') {
result = result.substring(0,result.length() - 2);//on retire le dernier set de ", " si au moins un param a été ajouté
}
result += ")";
return result;
}
public String getElement2(CtExecutable<?> element) {
String result = "";
result += element.getParent(CtClass.class).getSimpleName()+".";
result += element.getSimpleName()+"("+element.getParameters()+")";
return result;
}
} | 34.4 | 129 | 0.633109 |
c95ee02ab882bfaab595f89586ae9f02f8bcaeda | 1,880 | /******************************************************************************
* ~ Copyright (c) 2018 [jasonandy@hotmail.com | https://github.com/Jasonandy] *
* ~ *
* ~ 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 cn.ucaner.leecode.cspiration;
public class _213_HouseRobberII {
/**
* 213. House Robber II
* time : O(n)
* space : O(1)
* @param nums
* @return
*/
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
}
public int rob(int[] nums, int lo, int hi) {
int prevNo = 0;
int prevYes = 0;
for (int i = lo; i <= hi; i++) {
int temp = prevNo;
prevNo = Math.max(prevNo, prevYes);
prevYes = nums[i] + temp;
}
return Math.max(prevNo, prevYes);
}
}
| 44.761905 | 86 | 0.433511 |
71565d47b9e7e19645c917e96d117d9d515983f7 | 4,542 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.sdo.model.changesummary;
import commonj.sdo.DataObject;
import commonj.sdo.helper.XMLDocument;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import junit.textui.TestRunner;
import org.eclipse.persistence.testing.sdo.SDOTestCase;
public class ChangeSummaryBug6599313TestCases extends SDOTestCase {
protected DataObject rootObject;
public ChangeSummaryBug6599313TestCases(String name) {
super(name);
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.sdo.model.changesummary.ChangeSummaryBug6599313TestCases" };
TestRunner.main(arguments);
}
public String getSchemaName() {
return ("./org/eclipse/persistence/testing/sdo/helper/xmlhelper/PurchaseOrderDeepWithCS.xsd");
}
protected String getModelFileName() {
return ("./org/eclipse/persistence/testing/sdo/helper/xmlhelper/PurchaseOrderDeepWithCS.xml");
}
public void setUp() {
super.setUp();
try {
InputStream is = new FileInputStream(getSchemaName());
List types = xsdHelper.define(is, null);
XMLDocument document = xmlHelper.load(new FileInputStream(getModelFileName()));
rootObject = document.getRootObject();
} catch (Exception e) {
e.printStackTrace();
fail("An error occurred loading the xsd");
}
}
public void testIsDeletedSingleCase() throws Exception {
DataObject lineItem1 = (DataObject)rootObject.getDataObject("items").getList("item").get(0);
assertNotNull(lineItem1);
lineItem1.unset("product");
rootObject.getChangeSummary().endLogging();
rootObject.getChangeSummary().beginLogging();
//create new object
DataObject newProduct = dataFactory.create("http://www.example.org", "ProductType");
newProduct.set("productName", "testProduct");
lineItem1.set("product", newProduct);
assertCreated(newProduct, rootObject.getChangeSummary());
assertTrue(rootObject.getChangeSummary().isCreated(newProduct));
//delete object
newProduct.delete();
assertFalse(rootObject.getChangeSummary().isDeleted(newProduct));
assertUnchanged(newProduct, rootObject.getChangeSummary());
rootObject.getChangeSummary().endLogging();
assertFalse(rootObject.getChangeSummary().isDeleted(newProduct));
assertUnchanged(newProduct, rootObject.getChangeSummary());
}
public void testIsDeletedManyCase() throws Exception {
rootObject.getChangeSummary().endLogging();
rootObject.getChangeSummary().beginLogging();
List lineItems = rootObject.getDataObject("items").getList("item");
assertNotNull(lineItems);
assertEquals(2, lineItems.size());
//create new object
DataObject newLineItem = dataFactory.create("http://www.example.org", "LineItemType");
newLineItem.set("partNum", "testPartNum");
lineItems.add(newLineItem);
assertEquals(3, lineItems.size());
assertCreated(newLineItem, rootObject.getChangeSummary());
assertTrue(rootObject.getChangeSummary().isCreated(newLineItem));
//delete object
newLineItem.delete();
assertFalse(rootObject.getChangeSummary().isDeleted(newLineItem));
assertUnchanged(newLineItem, rootObject.getChangeSummary());
rootObject.getChangeSummary().endLogging();
assertFalse(rootObject.getChangeSummary().isDeleted(newLineItem));
assertUnchanged(newLineItem, rootObject.getChangeSummary());
}
}
| 42.448598 | 131 | 0.659401 |
9c6245f712d4a7250402143db231fcde049c5179 | 3,812 | package org.semanticweb.more.visitors;
import java.util.Iterator;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLClassExpressionVisitor;
import org.semanticweb.owlapi.model.OWLDataAllValuesFrom;
import org.semanticweb.owlapi.model.OWLDataExactCardinality;
import org.semanticweb.owlapi.model.OWLDataHasValue;
import org.semanticweb.owlapi.model.OWLDataIntersectionOf;
import org.semanticweb.owlapi.model.OWLDataMaxCardinality;
import org.semanticweb.owlapi.model.OWLDataMinCardinality;
import org.semanticweb.owlapi.model.OWLDataOneOf;
import org.semanticweb.owlapi.model.OWLDataSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLObjectAllValuesFrom;
import org.semanticweb.owlapi.model.OWLObjectComplementOf;
import org.semanticweb.owlapi.model.OWLObjectExactCardinality;
import org.semanticweb.owlapi.model.OWLObjectHasSelf;
import org.semanticweb.owlapi.model.OWLObjectHasValue;
import org.semanticweb.owlapi.model.OWLObjectIntersectionOf;
import org.semanticweb.owlapi.model.OWLObjectMaxCardinality;
import org.semanticweb.owlapi.model.OWLObjectMinCardinality;
import org.semanticweb.owlapi.model.OWLObjectOneOf;
import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLObjectUnionOf;
public class SHIFClassExpressionVisitor implements OWLClassExpressionVisitor {
private boolean isSHIF;
public boolean isSHIF(OWLClassExpression exp){
exp.accept(this);
return isSHIF;
}
@Override
public void visit(OWLClass exp){
isSHIF = true;
}
@Override
public void visit(OWLObjectSomeValuesFrom exp){
isSHIF = isSHIF(exp.getFiller());
}
@Override
public void visit(OWLDataSomeValuesFrom exp) {
isSHIF = true;//????????
}
@Override
public void visit(OWLDataHasValue exp) {
isSHIF = false;//???
}
@Override
public void visit(OWLObjectHasValue exp) {
isSHIF = false;//????
}
@Override
public void visit(OWLObjectHasSelf exp) {
isSHIF = false;//?????
}
@Override
public void visit(OWLObjectOneOf exp) {
isSHIF = false;
}
public void visit(OWLDataOneOf exp) {
isSHIF = false;
}
@Override
public void visit(OWLObjectIntersectionOf exp){
isSHIF = true;
Set<OWLClassExpression> conjuncts = exp.asConjunctSet();
Iterator<OWLClassExpression> iterator = conjuncts.iterator();
while (iterator.hasNext() && isSHIF)
isSHIF = isSHIF(iterator.next());
}
public void visit(OWLDataIntersectionOf exp) {
isSHIF = true;//?????
}
/*
* not supported
*/
@Override
public void visit(OWLObjectUnionOf exp) {
isSHIF = true;
Set<OWLClassExpression> exps = exp.getOperands();
Iterator<OWLClassExpression> iterator = exps.iterator();
while (isSHIF && iterator.hasNext())
isSHIF = isSHIF(iterator.next());
}
@Override
public void visit(OWLObjectComplementOf exp) {
isSHIF = isSHIF(exp.getOperand());
}
@Override
public void visit(OWLObjectAllValuesFrom exp) {
isSHIF = isSHIF(exp.getFiller());
}
@Override
public void visit(OWLObjectMinCardinality exp) {
isSHIF = exp.getCardinality() == 1;
}
@Override
public void visit(OWLObjectExactCardinality exp) {
isSHIF = false;
}
@Override
public void visit(OWLObjectMaxCardinality exp) {
isSHIF = false;//could accept this as a negation, but then id have to take it into account when deciding if sth contains negations
}
@Override
public void visit(OWLDataAllValuesFrom exp) {
isSHIF = true;//????
}
@Override
public void visit(OWLDataMinCardinality exp) {
isSHIF = exp.getCardinality() == 1;//???
}
@Override
public void visit(OWLDataExactCardinality exp) {
isSHIF = false;
}
@Override
public void visit(OWLDataMaxCardinality exp) {
isSHIF = false;///idem as for Object
}
} | 25.583893 | 132 | 0.763116 |
93b34d898294082fb02580fe2d2dbfdddc2ab8e3 | 687 | package team23.smartHomeSimulator.model;
import java.util.ArrayList;
import java.util.List;
import team23.smartHomeSimulator.model.request_body.LogItem;
/** POJO for Logs */
public class Logs {
private List<LogItem> logs;
/** Default constructor */
public Logs() {
this.logs = new ArrayList<>();
}
/**
* Getter for logs
*
* @return logs List
*/
public List<LogItem> getLogs() {
return logs;
}
/**
* Setter for logs
*
* @param logs list of LogItem
*/
public void setLogs(List<LogItem> logs) {
this.logs = logs;
}
/** Append to the list of logs @param log LogItem */
public void add(LogItem log) {
logs.add(log);
}
}
| 17.615385 | 60 | 0.634643 |
bebcb1d1ce87105cf2d9451f24e4c3e0833739da | 770 | package io.cem.modules.cem.service;
import io.cem.modules.cem.entity.DicTypeEntity;
import java.util.List;
import java.util.Map;
/**
*/
public interface DicTypeService {
/**
* 根据id获取某条信息
* @param id
* @return DicTypeEntity
*/
DicTypeEntity queryObject(Integer id);
/**
* 获取列表
* @param map
* @return List<DicTypeEntity>
*/
List<DicTypeEntity> queryList(Map<String, Object> map);
/**
* 总数
* @param map
* @return int
*/
int queryTotal(Map<String, Object> map);
/**
* 保存
* @param dicType
*/
void save(DicTypeEntity dicType);
/**
* 更新
* @param dicType
*/
void update(DicTypeEntity dicType);
/**
* 删除
* @param id
*/
void delete(Integer id);
/**
* 批量删除
* @param ids
*/
void deleteBatch(Integer[] ids);
}
| 13.508772 | 56 | 0.625974 |
6c448304f8ca0981564e007a92288c89acd3a87d | 1,521 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.river.twitter.test;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
/**
* To run this test you have to provide your twitter login and twitter password.
* You can also define test duration in seconds (default to 10)
*/
public class TwitterSampleRiverTest extends TwitterRiverAbstractTest {
public static void main(String[] args) throws InterruptedException, IOException {
TwitterSampleRiverTest instance = new TwitterSampleRiverTest();
instance.launcher(args);
}
@Override
protected XContentBuilder addSpecificRiverSettings(XContentBuilder xb) throws IOException {
xb.field("type", "sample");
return xb;
}
}
| 35.372093 | 95 | 0.750822 |
2bc6b75911f67a681f281e12ee88f35ffa885b22 | 1,786 | package com.lxj.xpopupdemo.custom;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import com.lxj.easyadapter.EasyAdapter;
import com.lxj.easyadapter.ViewHolder;
import com.lxj.xpopup.core.DrawerPopupView;
import com.lxj.xpopupdemo.R;
import java.util.ArrayList;
/**
* Description: 自定义带列表的Drawer弹窗
* Create by dance, at 2019/1/9
*/
public class ListDrawerPopupView extends DrawerPopupView {
RecyclerView recyclerView;
public ListDrawerPopupView(@NonNull Context context) {
super(context);
}
@Override
protected int getImplLayoutId() {
return R.layout.custom_list_drawer;
}
final ArrayList<String> data = new ArrayList<>();
@Override
protected void onCreate() {
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
for (int i = 0; i < 50; i++) {
data.add(""+i);
}
final EasyAdapter<String> commonAdapter = new EasyAdapter<String>(data, android.R.layout.simple_list_item_1) {
@Override
protected void bind(@NonNull ViewHolder holder, @NonNull String s, int position) {
holder.setText(android.R.id.text1, s);
}
};
recyclerView.setAdapter(commonAdapter);
findViewById(R.id.btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// if(data.size()==0)return;
// data.remove(0);
// commonAdapter.notifyDataSetChanged();
dismiss();
}
});
}
}
| 29.766667 | 118 | 0.651736 |
ceb2af7e223bcbf52f3cd2d835c57acd8d186af1 | 6,703 | /*
* 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.river.collection;
import java.io.PrintStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
/**
* This class is designed to allow weakly held keys to weakly held
* objects. For example, it can be used for smart proxy objects that
* maintain equality for references to the same remote server. If a
* single VM twice invokes a remote method that returns a proxy for the
* same JavaSpaces server, the references returned by that method
* should be the same. This allows <code>==</code> tests to work for
* proxies to remote servers the same as they would for direct references
* to remote servers, which also maintain this property.
* <p>
* Here is an example that uses this class to ensure that exactly one
* copy of a <code>java.io.Resolvable</code> object exists in each
* VM:
* <pre>
* private WeakTable knownProxies;
*
* public Object readResolve() {
* // deferred creation means this table is not allocated on the server
* if (knownProxies == null)
* knownProxies = new WeakTable();
* return knownProxies.getOrAdd(remoteServer, this);
* }
* </pre>
*
* @author Sun Microsystems, Inc.
*
*/
public class WeakTable {
/** The map of known objects. */
private final HashMap table;
/** The queue of cleared SpaceProxy objects. */
private final ReferenceQueue refQueue;
/** Print debug messages to this stream if not <code>null</code>. */
private static PrintStream DEBUG = null;
/** Object to call back when keys are collected */
private final KeyGCHandler handler;
/**
* Create a new WeakTable object to maintain the maps.
*/
public WeakTable() {
if (DEBUG != null)
DEBUG.println("Creating WeakTable");
table = new HashMap();
refQueue = new ReferenceQueue();
handler = null;
}
/**
* Create a new WeakTable object to maintain the maps that calls
* back the designated object when keys are collected.
*/
public WeakTable(KeyGCHandler handler) {
if (DEBUG != null)
DEBUG.println("Creating WeakTable");
table = new HashMap();
refQueue = new ReferenceQueue();
this.handler = handler;
}
/**
* Return the object that this key maps to. If it currently maps to
* no object, set it to map to the given object. Return either the
* existing entry or the new one, whichever is used.
*/
public synchronized Object getOrAdd(Object key, Object proxy) {
Object existing = get(key);
if (existing != null) {
if (DEBUG != null)
DEBUG.println("WeakTable.getOrAdd: found " + existing);
return existing;
} else {
if (DEBUG != null)
DEBUG.println("WeakTable.getOrAdd: adding " + proxy);
table.put(new WeakKeyReference(key, refQueue),
new WeakReference(proxy, refQueue));
return proxy;
}
}
/**
* Return the value associated with given key, or <code>null</code>
* if no value can be found.
*/
public synchronized Object get(Object key) {
removeBlanks();
WeakKeyReference keyRef = new WeakKeyReference(key);
WeakReference ref = (WeakReference) table.get(keyRef);
Object existing = (ref == null ? null : ref.get());
if (DEBUG != null) {
DEBUG.println("WeakTable.get:ref = " + ref
+ ", existing = " + existing);
}
return existing;
}
/**
* Remove the object that the given key maps to. If found return
* the object, otherwise return null.
*/
public synchronized Object remove(Object key) {
removeBlanks();
WeakKeyReference keyRef = new WeakKeyReference(key);
WeakReference ref = (WeakReference) table.remove(keyRef);
if (ref == null) return null;
return ref.get();
}
/**
* Remove any blank entries from the table. This can be invoked
* by a reaping thread if you like.
*/
/*
* We only clear table entries when the key shows up in the queue,
* since that is much more efficient. Since the key is usually the
* remote reference, and since the remote reference is usually
* referenced only from the proxy, the key reference should be
* cleared around the same time as the proxy reference. If not,
* then all the hangs around unnecessarily is this table entry,
* which is small. This tradeoff seems worth the significant
* efficiency of using the HashMap in the intended way -- efficient
* key access.
*/
public synchronized void removeBlanks() {
if (DEBUG != null)
DEBUG.println("WeakTable.removeBlanks: starting");
Reference ref;
while ((ref = refQueue.poll()) != null) {
if (ref instanceof WeakKeyReference) {
final WeakReference valref = (WeakReference)table.remove(ref);
if (valref != null && handler != null && valref.get() != null)
handler.keyGC(valref.get());
if (DEBUG != null) {
boolean removed = (valref != null);
DEBUG.print("WeakTable.removeBlanks: key=" + ref);
DEBUG.println(", " + (removed ? "" : "!") + "removed, "
+ table.size() + " remain");
}
} else {
if (DEBUG != null)
DEBUG.println("WeakTable.removeBlanks: value=" + ref);
}
}
if (DEBUG != null)
DEBUG.println("WeakTable.removeBlanks: finished");
}
/**
* Handler for clients that need to know when a key is removed
* from the table because it has been collected.
*/
public static interface KeyGCHandler {
/** Called by WeakTable when it notices that a key has been
* collected and the value still exists.
* @param value The value associated with the collected key
*/
public void keyGC(Object value);
}
}
| 34.73057 | 77 | 0.652544 |
076dd9a5202ea97cf356221d3e0b3733fe56822c | 2,311 | /**
* vertigo - simple java starter
*
* Copyright (C) 2013-2018, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com)
* KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vertigo.quarto.services.publisher.odt;
import io.vertigo.app.config.AppConfig;
import io.vertigo.app.config.DefinitionProviderConfig;
import io.vertigo.app.config.ModuleConfig;
import io.vertigo.commons.impl.CommonsFeatures;
import io.vertigo.core.plugins.resource.classpath.ClassPathResourceResolverPlugin;
import io.vertigo.dynamo.impl.DynamoFeatures;
import io.vertigo.dynamo.plugins.environment.DynamoDefinitionProvider;
import io.vertigo.quarto.impl.services.publisher.PublisherManagerImpl;
import io.vertigo.quarto.plugins.publisher.odt.OpenOfficeMergerPlugin;
import io.vertigo.quarto.services.publisher.PublisherManager;
import io.vertigo.quarto.services.publisher.TestPublisherDefinitionProvider;
class MyAppConfig {
public static AppConfig config() {
return AppConfig.builder().beginBoot()
.withLocales("fr_FR")
.addPlugin(ClassPathResourceResolverPlugin.class)
.endBoot()
.addModule(new CommonsFeatures()
.withScript()
.build())
.addModule(new DynamoFeatures()
.build())
.addModule(ModuleConfig.builder("myApp")
.addComponent(PublisherManager.class, PublisherManagerImpl.class)
.addPlugin(OpenOfficeMergerPlugin.class)
.addDefinitionProvider(DefinitionProviderConfig.builder(DynamoDefinitionProvider.class)
.addDefinitionResource("kpr", "io/vertigo/quarto/services/publisher/data/execution.kpr")
.build())
.addDefinitionProvider(TestPublisherDefinitionProvider.class)
.build())
.build();
}
}
| 39.844828 | 99 | 0.770229 |
35653b2dea96e0feceff902acfaf8adeb0068a64 | 2,099 | /*
* 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 javax.enterprise.inject.spi;
import javax.enterprise.inject.Instance;
import java.util.ServiceLoader;
/**
* <p>Static helper class to access the {@link BeanManager}</p>
*
* TODO not yet implemented!
*
* <p>Usage:
* <pre>
* BeanManager bm = CDI.current().getBeanManager();
* </pre>
* </p>
*
*
* @since 1.1
*/
public abstract class CDI<T> implements Instance<T>
{
private static volatile CDI INSTANCE; // temporary implementation
public static CDI<Object> current()
{
if (INSTANCE == null)
{
INSTANCE = ServiceLoader.load(CDIProvider.class).iterator().next().getCDI();
}
return INSTANCE; //X TODO implement!
}
/**
* <p>A container or an application can set this manually. If not
* we will use the {@link java.util.ServiceLoader} and use the
* first service we find.</p>
*
* TODO: clarify if this is per 'application' or general?
*
* @param provider to use
*/
public static void setCDIProvider(CDIProvider provider)
{
//X TODO implement!
if (provider == null)
{
INSTANCE = null;
}
else
{
INSTANCE = provider.getCDI();
}
}
public abstract BeanManager getBeanManager();
}
| 27.986667 | 88 | 0.656027 |
654452e6171f4fd345c9a06f9e8747de71f177c4 | 370 | package io.github.ztkmkoo.dss.core.exception.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExceptionHandler {
Class<? extends Exception>[] exception();
}
| 26.428571 | 56 | 0.810811 |
8ee5762882a3fde7bbbbca539866c0cc9353d22d | 4,301 | /**
* Copyright 2013 Jim Hurne and Joseph Kramer
*
* 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.kanbansalad.scanner.client;
import static org.kanbansalad.scanner.client.CommonConstants.NONE;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.kanbansalad.scanner.client.program.ProgramModel;
import org.kanbansalad.scanner.client.scan.ScanModel;
import org.kanbansalad.scanner.client.tag.CellTag;
import org.kanbansalad.scanner.client.tag.ScanableTag;
public class ListModel implements ScanModel, ProgramModel {
private final String filenameTemplate;
private final List<ScanableTag> scannedTags;
private int selectedTagIndex = NONE;
public ListModel(String filenameTemplate) {
scannedTags = new ArrayList<ScanableTag>();
this.filenameTemplate = filenameTemplate;
}
/*
* (non-Javadoc)
*
* @see org.kdt.ScanModel#add(org.kdt.model.Scanable)
*/
@Override
public void add(ScanableTag scannedTag) {
scannedTags.add(scannedTag);
}
/*
* (non-Javadoc)
*
* @see org.kdt.ScanModel#remove(org.kdt.model.Scanable)
*/
@Override
public void remove(int index) {
scannedTags.remove(index);
}
/*
* (non-Javadoc)
*
* @see org.kdt.program.ProgramModel#replace(int, org.kdt.tag.Scanable)
*/
@Override
public void replace(int position, ScanableTag tag) {
scannedTags.set(position, tag);
}
/*
* (non-Javadoc)
*
* @see org.kdt.ScanModel#clearScannedTags()
*/
@Override
public void clear() {
scannedTags.clear();
selectedTagIndex = CommonConstants.NONE;
}
/*
* (non-Javadoc)
*
* @see org.kdt.ScanModel#getNumScannedTags()
*/
@Override
public int getCount() {
return scannedTags.size();
}
@Override
public ScanableTag get(int position) {
return scannedTags.get(position);
}
public List<ScanableTag> getScannedTags() {
return scannedTags;
}
@Override
public void setSelectedTag(int index) {
this.selectedTagIndex = index;
}
@Override
public int getSelectedTagIndex() {
return selectedTagIndex;
}
@Override
public File dumpToCsv() throws IOException {
return dumpToCsv(new Date());
}
public File dumpToCsv(Date snapshotDate) throws IOException {
File csvFile = generateFileFrom(snapshotDate);
PrintWriter writer = new PrintWriter(csvFile);
try {
writeHeader(writer);
writeBody(snapshotDate, writer);
} finally {
writer.close();
}
return csvFile;
}
private File generateFileFrom(Date snapshotDate) {
File csvFile = new File(String.format(filenameTemplate, snapshotDate));
return csvFile;
}
private void writeHeader(PrintWriter writer) {
writer.println("Date\tTime\tSwimlane\tQueue\tID\tName\tSize");
}
private void writeBody(Date snapshotDate, PrintWriter writer) {
ScanableTag cell = null;
for (ScanableTag tag : scannedTags) {
if (tag instanceof CellTag) {
cell = tag;
} else if (tag.isValid()) {
writeRecord(snapshotDate, cell, tag, writer);
}
}
}
private void writeRecord(Date snapshotDate, ScanableTag cell,
ScanableTag task,
PrintWriter writer) {
writer.printf("%tF\t%<tR\t%s\t%s%n",
snapshotDate,
cell.toDataString(Integer.MAX_VALUE),
task.toDataString(Integer.MAX_VALUE));
}
}
| 26.88125 | 79 | 0.643339 |
f14f8332472849db11ce20c9e4ce6a4807d1c7b8 | 1,149 | package com.xresch.cfw.validation;
/**************************************************************************************************************
* The LogLevelArgumentValidator will validate if the value of the ArgumentDefinition
* is a valid log4j2 log level.
*
* @author Reto Scheiwiller, (c) Copyright 2019
* @license MIT-License
**************************************************************************************************************/
public class LogLevelValidator extends AbstractValidator {
public LogLevelValidator(IValidatable<?> validatable) {
super(validatable);
// TODO Auto-generated constructor stub
}
@Override
public boolean validate(Object value) {
if( !(value instanceof String) ) {
this.setInvalidMessage("The type '"+value.getClass().getName()+"' is not supported for this validator.");
return false;
}else if( ((String)value).toUpperCase().matches("ALL|TRACE|DEBUG|INFO|WARN|ERROR|SEVERE|OFF") ) {
return true;
}else {
this.setInvalidMessage("The value of the argument "+validateable.getLabel()+" is not a valid log4j2 log level.(value='"+value+"')");
return false;
}
}
}
| 35.90625 | 135 | 0.579634 |
a3064f89acc8b18ca4539b7d3414551f96b8c555 | 210 | package coin;
import java.math.BigDecimal;
/*
Concrete flyweight class that extends the Coin class
*/
public class Dime extends Coin {
public Dime() {
super(new BigDecimal(".10"));
}
}
| 14 | 56 | 0.647619 |
6c0afb827a777a7e3ffeb99b83ea8838b70a0d77 | 2,658 | /**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.config;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
/**
* The default predicate (used by {@link DynamicContextualProperty}) which takes a Function to get the value of
* key included in the JSON blob as the input string value of {@link DynamicContextualProperty}.
*
* @author awang
*
*/
public class DefaultContextualPredicate implements Predicate<Map<String, Collection<String>>> {
private final Function<String, String> getValueFromKeyFunction;
public static final DefaultContextualPredicate PROPERTY_BASED = new DefaultContextualPredicate(new Function<String, String>() {
@Override
public String apply(@Nullable String input) {
return DynamicProperty.getInstance(input).getString();
}
});
public DefaultContextualPredicate(Function<String, String> getValueFromKeyFunction) {
this.getValueFromKeyFunction = getValueFromKeyFunction;
}
/**
* For each key in the passed in map, this function returns true if
*
* <li> the value derived from the key using the function (passed in from the constructor) matches <b>any</b> of the value included for the same key in the map
* <li> the above holds true for <b>all</b> keys in the map
*
*/
@Override
public boolean apply(@Nullable Map<String, Collection<String>> input) {
if (null == input) {
throw new NullPointerException();
}
for (Map.Entry<String, Collection<String>> entry: input.entrySet()) {
String key = entry.getKey();
Collection<String> value = entry.getValue();
if (!value.contains(getValueFromKeyFunction.apply(key))) {
return false;
}
}
return true;
}
@Override
public boolean test(@Nullable Map<String, Collection<String>> input) {
return apply(input);
}
}
| 34.519481 | 163 | 0.676448 |
8a40d17df35d4e721585238829270a107e2d2b67 | 2,316 | /*
* Copyright (c) 2017-2018. 放牛极客<l_iupeiyu@qq.com>
* <p>
* 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.
* </p>
*
*/
package com.geekcattle.core.j2cache.autoconfigure;
import com.geekcattle.core.j2cache.cache.support.J2CacheCacheManger;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* 开启对spring cache支持的配置入口
* @author zhangsaizz
*/
@Configuration
@ConditionalOnClass(J2Cache.class)
@EnableConfigurationProperties({ J2CacheExtendConfig.class, CacheProperties.class })
@ConditionalOnProperty(name = "j2cache.open-spring-cache", havingValue = "true")
@EnableCaching
public class J2CacheSpringCacheAutoConfiguration {
private final CacheProperties cacheProperties;
J2CacheSpringCacheAutoConfiguration(CacheProperties cacheProperties) {
this.cacheProperties = cacheProperties;
}
@Bean
@ConditionalOnBean(CacheChannel.class)
public J2CacheCacheManger cacheManager(CacheChannel cacheChannel) {
List<String> cacheNames = cacheProperties.getCacheNames();
J2CacheCacheManger cacheCacheManger = new J2CacheCacheManger(cacheChannel);
cacheCacheManger.setCacheNames(cacheNames);
return cacheCacheManger;
}
}
| 38.6 | 84 | 0.786701 |
b2349fc4079f799d58c68102a9b285eb76bfef7f | 341 | package net.impactdev.logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class Markers {
public static final Marker BOOT = MarkerFactory.getMarker("Boot");
public static final Marker JOIN = MarkerFactory.getMarker("Join");
public static final Marker TRANSLATOR = MarkerFactory.getMarker("Translator");
}
| 26.230769 | 82 | 0.765396 |
290d1187026e0c2a6b22a671accf61f95a82879d | 3,372 | /**
* Copyright 2009-2018 PrimeTek.
*
* 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.primefaces.component.ajaxstatus;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.renderkit.CoreRenderer;
import org.primefaces.util.WidgetBuilder;
public class AjaxStatusRenderer extends CoreRenderer {
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
AjaxStatus status = (AjaxStatus) component;
encodeMarkup(context, status);
encodeScript(context, status);
}
protected void encodeScript(FacesContext context, AjaxStatus status) throws IOException {
String clientId = status.getClientId(context);
WidgetBuilder wb = getWidgetBuilder(context);
wb.init("AjaxStatus", status.resolveWidgetVar(), clientId);
wb.callback(AjaxStatus.START, AjaxStatus.CALLBACK_SIGNATURE, status.getOnstart())
.callback(AjaxStatus.ERROR, AjaxStatus.CALLBACK_SIGNATURE, status.getOnerror())
.callback(AjaxStatus.SUCCESS, AjaxStatus.CALLBACK_SIGNATURE, status.getOnsuccess())
.callback(AjaxStatus.COMPLETE, AjaxStatus.CALLBACK_SIGNATURE, status.getOncomplete());
wb.finish();
}
protected void encodeMarkup(FacesContext context, AjaxStatus status) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = status.getClientId(context);
writer.startElement("div", null);
writer.writeAttribute("id", clientId, null);
if (status.getStyle() != null) writer.writeAttribute("style", status.getStyle(), "style");
if (status.getStyleClass() != null) writer.writeAttribute("class", status.getStyleClass(), "styleClass");
for (String event : AjaxStatus.EVENTS) {
UIComponent facet = status.getFacet(event);
if (facet != null) {
encodeFacet(context, clientId, facet, event, true);
}
}
UIComponent defaultFacet = status.getFacet(AjaxStatus.DEFAULT);
if (defaultFacet != null) {
encodeFacet(context, clientId, defaultFacet, AjaxStatus.DEFAULT, false);
}
writer.endElement("div");
}
protected void encodeFacet(FacesContext context, String clientId, UIComponent facet, String facetName, boolean hidden) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.startElement("div", null);
writer.writeAttribute("id", clientId + "_" + facetName, null);
if (hidden) {
writer.writeAttribute("style", "display:none", null);
}
renderChild(context, facet);
writer.endElement("div");
}
}
| 37.466667 | 143 | 0.693654 |
5460e12456f54fb61153eb34d8414cbbc812d4a0 | 6,289 | /*
* NiFi Rest Api
* The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, definitions of the expected input and output, potential response codes, and the authorizations required to invoke each service.
*
* OpenAPI spec version: 1.5.0
* Contact: dev@nifi.apache.org
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.github.hermannpencole.nifi.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.github.hermannpencole.nifi.swagger.client.model.UriBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Link
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-03-03T16:29:45.931+01:00")
public class Link {
@SerializedName("type")
private String type = null;
@SerializedName("uri")
private String uri = null;
@SerializedName("params")
private Map<String, String> params = null;
@SerializedName("rel")
private String rel = null;
@SerializedName("rels")
private List<String> rels = null;
@SerializedName("uriBuilder")
private UriBuilder uriBuilder = null;
@SerializedName("title")
private String title = null;
public Link type(String type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
**/
@ApiModelProperty(value = "")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Link uri(String uri) {
this.uri = uri;
return this;
}
/**
* Get uri
* @return uri
**/
@ApiModelProperty(value = "")
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Link params(Map<String, String> params) {
this.params = params;
return this;
}
public Link putParamsItem(String key, String paramsItem) {
if (this.params == null) {
this.params = new HashMap<String, String>();
}
this.params.put(key, paramsItem);
return this;
}
/**
* Get params
* @return params
**/
@ApiModelProperty(value = "")
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
public Link rel(String rel) {
this.rel = rel;
return this;
}
/**
* Get rel
* @return rel
**/
@ApiModelProperty(value = "")
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public Link rels(List<String> rels) {
this.rels = rels;
return this;
}
public Link addRelsItem(String relsItem) {
if (this.rels == null) {
this.rels = new ArrayList<String>();
}
this.rels.add(relsItem);
return this;
}
/**
* Get rels
* @return rels
**/
@ApiModelProperty(value = "")
public List<String> getRels() {
return rels;
}
public void setRels(List<String> rels) {
this.rels = rels;
}
public Link uriBuilder(UriBuilder uriBuilder) {
this.uriBuilder = uriBuilder;
return this;
}
/**
* Get uriBuilder
* @return uriBuilder
**/
@ApiModelProperty(value = "")
public UriBuilder getUriBuilder() {
return uriBuilder;
}
public void setUriBuilder(UriBuilder uriBuilder) {
this.uriBuilder = uriBuilder;
}
public Link title(String title) {
this.title = title;
return this;
}
/**
* Get title
* @return title
**/
@ApiModelProperty(value = "")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Link link = (Link) o;
return Objects.equals(this.type, link.type) &&
Objects.equals(this.uri, link.uri) &&
Objects.equals(this.params, link.params) &&
Objects.equals(this.rel, link.rel) &&
Objects.equals(this.rels, link.rels) &&
Objects.equals(this.uriBuilder, link.uriBuilder) &&
Objects.equals(this.title, link.title);
}
@Override
public int hashCode() {
return Objects.hash(type, uri, params, rel, rels, uriBuilder, title);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Link {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" uri: ").append(toIndentedString(uri)).append("\n");
sb.append(" params: ").append(toIndentedString(params)).append("\n");
sb.append(" rel: ").append(toIndentedString(rel)).append("\n");
sb.append(" rels: ").append(toIndentedString(rels)).append("\n");
sb.append(" uriBuilder: ").append(toIndentedString(uriBuilder)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 24.759843 | 479 | 0.609636 |
93c07cb62deace8249fa8d5445ac1bea666fb8eb | 333 | package java8professional.chapter05.i18n_l10n.resourcebundle.javaclass;
import java.util.ListResourceBundle;
public class Tax_en_US extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{"taxCode", new UsTaxCode()}
};
}
}
class UsTaxCode {} | 23.785714 | 71 | 0.672673 |
03713bfa693ff34ec0f0ccd1ce701720550130b7 | 751 | package com.github.yingzhuo.playground.api.v2;
import com.github.yingzhuo.playground.service.TagService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Indexed;
import org.springframework.validation.annotation.Validated;
import java.util.List;
@Slf4j
@Indexed
@Controller
@AllArgsConstructor
@Validated
@PreAuthorize("hasRole('ROLE_USER')")
class TagAction {
private final TagService tagService;
@QueryMapping
List<String> findAllTag() {
return tagService.findAllTags();
}
}
| 25.033333 | 71 | 0.805593 |
555dadf084bd653b8da741cd06205645635b8a81 | 5,200 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.gateway;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.index.CloseableIndexComponent;
import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit;
import org.elasticsearch.index.shard.IndexShardComponent;
import org.elasticsearch.index.translog.Translog;
/**
*
*/
public interface IndexShardGateway extends IndexShardComponent, CloseableIndexComponent {
String type();
/**
* The last / on going recovery status.
*/
RecoveryStatus recoveryStatus();
/**
* The last snapshot status performed. Can be <tt>null</tt>.
*/
SnapshotStatus lastSnapshotStatus();
/**
* The current snapshot status being performed. Can be <tt>null</tt> indicating that no snapshot
* is being executed currently.
*/
SnapshotStatus currentSnapshotStatus();
/**
* Recovers the state of the shard from the gateway.
*/
void recover(boolean indexShouldExists, RecoveryStatus recoveryStatus) throws IndexShardGatewayRecoveryException;
/**
* Snapshots the given shard into the gateway.
*/
SnapshotStatus snapshot(Snapshot snapshot) throws IndexShardGatewaySnapshotFailedException;
/**
* Returns <tt>true</tt> if snapshot is even required on this gateway (i.e. mainly handles recovery).
*/
boolean requiresSnapshot();
/**
* Returns <tt>true</tt> if this gateway requires scheduling management for snapshot
* operations.
*/
boolean requiresSnapshotScheduling();
SnapshotLock obtainSnapshotLock() throws Exception;
public static interface SnapshotLock {
void release();
}
public static final SnapshotLock NO_SNAPSHOT_LOCK = new SnapshotLock() {
@Override
public void release() {
}
};
public static class Snapshot {
private final SnapshotIndexCommit indexCommit;
private final Translog.Snapshot translogSnapshot;
private final long lastIndexVersion;
private final long lastTranslogId;
private final long lastTranslogLength;
private final int lastTotalTranslogOperations;
public Snapshot(SnapshotIndexCommit indexCommit, Translog.Snapshot translogSnapshot, long lastIndexVersion, long lastTranslogId, long lastTranslogLength, int lastTotalTranslogOperations) {
this.indexCommit = indexCommit;
this.translogSnapshot = translogSnapshot;
this.lastIndexVersion = lastIndexVersion;
this.lastTranslogId = lastTranslogId;
this.lastTranslogLength = lastTranslogLength;
this.lastTotalTranslogOperations = lastTotalTranslogOperations;
}
/**
* Indicates that the index has changed from the latest snapshot.
*/
public boolean indexChanged() {
return lastIndexVersion != indexCommit.getGeneration();
}
/**
* Indicates that a new transaction log has been created. Note check this <b>before</b> you
* check {@link #sameTranslogNewOperations()}.
*/
public boolean newTranslogCreated() {
return translogSnapshot.translogId() != lastTranslogId;
}
/**
* Indicates that the same translog exists, but new operations have been appended to it. Throws
* {@link org.elasticsearch.ElasticsearchIllegalStateException} if {@link #newTranslogCreated()} is <tt>true</tt>, so
* always check that first.
*/
public boolean sameTranslogNewOperations() {
if (newTranslogCreated()) {
throw new ElasticsearchIllegalStateException("Should not be called when there is a new translog");
}
return translogSnapshot.length() > lastTranslogLength;
}
public SnapshotIndexCommit indexCommit() {
return indexCommit;
}
public Translog.Snapshot translogSnapshot() {
return translogSnapshot;
}
public long lastIndexVersion() {
return lastIndexVersion;
}
public long lastTranslogId() {
return lastTranslogId;
}
public long lastTranslogLength() {
return lastTranslogLength;
}
public int lastTotalTranslogOperations() {
return this.lastTotalTranslogOperations;
}
}
}
| 33.766234 | 196 | 0.680962 |
f9a643a431a42e8ea28b7da21a2a39e9f497fcb9 | 637 | package com.yantra.core.managers;
import java.sql.Timestamp;
import java.util.Date;
import org.openqa.selenium.WebElement;
import org.testng.Reporter;
public class CmnMethods {
public static void WriteLog(String logType, String msg) {
String callerMethodName = Thread.currentThread().getStackTrace()[2].getMethodName();
Date date= new Date();
long time = date.getTime();
Timestamp ts = new Timestamp(time);
msg = "--" + ts + " " + logType+ " " + callerMethodName + " " + msg + "<br>" + "<br>";
Reporter.log(msg,true);
//Taking Screen shot and attaching it to the Test NG report
}
}
| 24.5 | 89 | 0.659341 |
2d114a3eea22db982975f0cddf7ec145ce1eaaac | 16,180 |
package com.prowidesoftware.swift.model.mx.dic;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Information related to multimodal transportation of goods.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MultimodalTransport2", propOrder = {
"dprtureAirprt",
"dstnAirprt",
"airCrrierNm",
"portOfLoadng",
"portOfDschrge",
"vsslNm",
"plcOfRct",
"plcOfDlvry",
"takngInChrg",
"plcOfFnlDstn",
"trnstLctn",
"roadCrrierNm",
"railCrrierNm"
})
public class MultimodalTransport2 {
@XmlElement(name = "DprtureAirprt")
protected List<AirportName1Choice> dprtureAirprt;
@XmlElement(name = "DstnAirprt")
protected List<AirportName1Choice> dstnAirprt;
@XmlElement(name = "AirCrrierNm")
protected List<String> airCrrierNm;
@XmlElement(name = "PortOfLoadng")
protected List<String> portOfLoadng;
@XmlElement(name = "PortOfDschrge")
protected List<String> portOfDschrge;
@XmlElement(name = "VsslNm")
protected List<String> vsslNm;
@XmlElement(name = "PlcOfRct")
protected List<String> plcOfRct;
@XmlElement(name = "PlcOfDlvry")
protected List<String> plcOfDlvry;
@XmlElement(name = "TakngInChrg")
protected List<String> takngInChrg;
@XmlElement(name = "PlcOfFnlDstn")
protected List<String> plcOfFnlDstn;
@XmlElement(name = "TrnstLctn")
protected List<String> trnstLctn;
@XmlElement(name = "RoadCrrierNm")
protected List<String> roadCrrierNm;
@XmlElement(name = "RailCrrierNm")
protected List<String> railCrrierNm;
/**
* Gets the value of the dprtureAirprt property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dprtureAirprt property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDprtureAirprt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AirportName1Choice }
*
*
*/
public List<AirportName1Choice> getDprtureAirprt() {
if (dprtureAirprt == null) {
dprtureAirprt = new ArrayList<AirportName1Choice>();
}
return this.dprtureAirprt;
}
/**
* Gets the value of the dstnAirprt property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dstnAirprt property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDstnAirprt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AirportName1Choice }
*
*
*/
public List<AirportName1Choice> getDstnAirprt() {
if (dstnAirprt == null) {
dstnAirprt = new ArrayList<AirportName1Choice>();
}
return this.dstnAirprt;
}
/**
* Gets the value of the airCrrierNm property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the airCrrierNm property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAirCrrierNm().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAirCrrierNm() {
if (airCrrierNm == null) {
airCrrierNm = new ArrayList<String>();
}
return this.airCrrierNm;
}
/**
* Gets the value of the portOfLoadng property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the portOfLoadng property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPortOfLoadng().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPortOfLoadng() {
if (portOfLoadng == null) {
portOfLoadng = new ArrayList<String>();
}
return this.portOfLoadng;
}
/**
* Gets the value of the portOfDschrge property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the portOfDschrge property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPortOfDschrge().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPortOfDschrge() {
if (portOfDschrge == null) {
portOfDschrge = new ArrayList<String>();
}
return this.portOfDschrge;
}
/**
* Gets the value of the vsslNm property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the vsslNm property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getVsslNm().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getVsslNm() {
if (vsslNm == null) {
vsslNm = new ArrayList<String>();
}
return this.vsslNm;
}
/**
* Gets the value of the plcOfRct property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the plcOfRct property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlcOfRct().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPlcOfRct() {
if (plcOfRct == null) {
plcOfRct = new ArrayList<String>();
}
return this.plcOfRct;
}
/**
* Gets the value of the plcOfDlvry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the plcOfDlvry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlcOfDlvry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPlcOfDlvry() {
if (plcOfDlvry == null) {
plcOfDlvry = new ArrayList<String>();
}
return this.plcOfDlvry;
}
/**
* Gets the value of the takngInChrg property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the takngInChrg property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTakngInChrg().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getTakngInChrg() {
if (takngInChrg == null) {
takngInChrg = new ArrayList<String>();
}
return this.takngInChrg;
}
/**
* Gets the value of the plcOfFnlDstn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the plcOfFnlDstn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlcOfFnlDstn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPlcOfFnlDstn() {
if (plcOfFnlDstn == null) {
plcOfFnlDstn = new ArrayList<String>();
}
return this.plcOfFnlDstn;
}
/**
* Gets the value of the trnstLctn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the trnstLctn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTrnstLctn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getTrnstLctn() {
if (trnstLctn == null) {
trnstLctn = new ArrayList<String>();
}
return this.trnstLctn;
}
/**
* Gets the value of the roadCrrierNm property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the roadCrrierNm property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRoadCrrierNm().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRoadCrrierNm() {
if (roadCrrierNm == null) {
roadCrrierNm = new ArrayList<String>();
}
return this.roadCrrierNm;
}
/**
* Gets the value of the railCrrierNm property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the railCrrierNm property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRailCrrierNm().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRailCrrierNm() {
if (railCrrierNm == null) {
railCrrierNm = new ArrayList<String>();
}
return this.railCrrierNm;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Adds a new item to the dprtureAirprt list.
* @see #getDprtureAirprt()
*
*/
public MultimodalTransport2 addDprtureAirprt(AirportName1Choice dprtureAirprt) {
getDprtureAirprt().add(dprtureAirprt);
return this;
}
/**
* Adds a new item to the dstnAirprt list.
* @see #getDstnAirprt()
*
*/
public MultimodalTransport2 addDstnAirprt(AirportName1Choice dstnAirprt) {
getDstnAirprt().add(dstnAirprt);
return this;
}
/**
* Adds a new item to the airCrrierNm list.
* @see #getAirCrrierNm()
*
*/
public MultimodalTransport2 addAirCrrierNm(String airCrrierNm) {
getAirCrrierNm().add(airCrrierNm);
return this;
}
/**
* Adds a new item to the portOfLoadng list.
* @see #getPortOfLoadng()
*
*/
public MultimodalTransport2 addPortOfLoadng(String portOfLoadng) {
getPortOfLoadng().add(portOfLoadng);
return this;
}
/**
* Adds a new item to the portOfDschrge list.
* @see #getPortOfDschrge()
*
*/
public MultimodalTransport2 addPortOfDschrge(String portOfDschrge) {
getPortOfDschrge().add(portOfDschrge);
return this;
}
/**
* Adds a new item to the vsslNm list.
* @see #getVsslNm()
*
*/
public MultimodalTransport2 addVsslNm(String vsslNm) {
getVsslNm().add(vsslNm);
return this;
}
/**
* Adds a new item to the plcOfRct list.
* @see #getPlcOfRct()
*
*/
public MultimodalTransport2 addPlcOfRct(String plcOfRct) {
getPlcOfRct().add(plcOfRct);
return this;
}
/**
* Adds a new item to the plcOfDlvry list.
* @see #getPlcOfDlvry()
*
*/
public MultimodalTransport2 addPlcOfDlvry(String plcOfDlvry) {
getPlcOfDlvry().add(plcOfDlvry);
return this;
}
/**
* Adds a new item to the takngInChrg list.
* @see #getTakngInChrg()
*
*/
public MultimodalTransport2 addTakngInChrg(String takngInChrg) {
getTakngInChrg().add(takngInChrg);
return this;
}
/**
* Adds a new item to the plcOfFnlDstn list.
* @see #getPlcOfFnlDstn()
*
*/
public MultimodalTransport2 addPlcOfFnlDstn(String plcOfFnlDstn) {
getPlcOfFnlDstn().add(plcOfFnlDstn);
return this;
}
/**
* Adds a new item to the trnstLctn list.
* @see #getTrnstLctn()
*
*/
public MultimodalTransport2 addTrnstLctn(String trnstLctn) {
getTrnstLctn().add(trnstLctn);
return this;
}
/**
* Adds a new item to the roadCrrierNm list.
* @see #getRoadCrrierNm()
*
*/
public MultimodalTransport2 addRoadCrrierNm(String roadCrrierNm) {
getRoadCrrierNm().add(roadCrrierNm);
return this;
}
/**
* Adds a new item to the railCrrierNm list.
* @see #getRailCrrierNm()
*
*/
public MultimodalTransport2 addRailCrrierNm(String railCrrierNm) {
getRailCrrierNm().add(railCrrierNm);
return this;
}
}
| 27.423729 | 89 | 0.590853 |
c68f448414e7b241b1663bfeebe35fbcfcd07aec | 1,149 | package com.liangxiaoqiao.leetcode.day.hard;
/*
* English
* id: 224
* title: Basic Calculator
* href: https://leetcode.com/problems/basic-calculator
* desc: Implement a basic calculator to evaluate a simple expression string.
* The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
* Example 1:
* Input: "1 + 1"
* Output: 2
* Example 2:
* Input: " 2-1 + 2 "
* Output: 3
* Example 3:
* Input: "(1+(4+5+2)-3)+(6+8)"
* Output: 23
* Note:
* You may assume that the given expression is always valid.
* Do not use the eval built-in library function.
* <p>
* 中文
* 序号: 224
* 标题: 基本计算器
* 链接: https://leetcode-cn.com/problems/basic-calculator
* 描述: 实现一个基本的计算器来计算一个简单的字符串表达式的值。\n字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。\n示例 1:\n输入: \"1 + 1\"\n输出: 2\n示例 2:\n输入: \" 2-1 + 2 \"\n输出: 3\n示例 3:\n输入: \"(1+(4+5+2)-3)+(6+8)\"\n输出: 23\n说明:\n你可以假设所给定的表达式都是有效的。\n请不要使用内置的库函数 eval。
* <p>
* acceptance: 35.0%
* difficulty: Hard
* private: False
*/
//TODO init
public class BasicCalculator {
public int calculate(String s) {
return 0;
}
} | 28.02439 | 230 | 0.64752 |
d67dda3ee501bd5171c5e85bd48346b1b6009a98 | 2,907 | package aop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class TestSpring {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("aop/spring.xml");
EmpService p = context.getBean("/empService", EmpService.class);
EmpService p1 = context.getBean("empService", EmpService.class);
System.out.println("p1 = " + p1);
System.out.println("p = " + p);
String[] Names = context.getBeanDefinitionNames();
for (String name : Names) {
System.out.println("name = " + name);
}
System.out.println("=================");
//根据类型获得id值
String[] beanNamesForType = context.getBeanNamesForType(EmpService.class);
for (String s : beanNamesForType) {
System.out.println("s = " + s);
}
System.out.println("=================");
boolean beanDefinition = context.containsBeanDefinition("2p");
System.out.println("beanDefinition 是否存在 " + beanDefinition);
System.out.println("=================");
boolean b = context.containsBean("2p");
System.out.println("b = " + b);
// empService.find("Spring");
}
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("aop/spring.xml");
Emp emp = (Emp) context.getBean("emp1");
System.out.println("emp = " + emp);
String[] email = emp.getEmail();
for (String s : email) {
System.out.println("s = " + s);
}
System.out.println("=============");
Set<String> tels = emp.getTels();
for (String tel : tels) {
System.out.println("tel = " + tel);
}
System.out.println("=============");
List<String> addr = emp.getAddr();
for (String ad : addr) {
System.out.println("addr = " + ad);
}
System.out.println("=============");
Map<String, String> qqs = emp.getQqs();
Set<String> keys = qqs.keySet();
for (String key : keys) {
System.out.println("key = " + key + " value = " + qqs.get(key));
}
System.out.println("=============");
Properties prop = emp.getProp();
for (String key : prop.stringPropertyNames()) {
System.out.println(key + "=" + prop.getProperty(key));
}
}
// 测试构造方法
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("aop/spring.xml");
Customer customer = (Customer) context.getBean("customer");
System.out.println("customer = " + customer);
}
}
| 33.802326 | 102 | 0.568971 |
0c9253c5a93efa824aac1112ec5d812e23a75bf5 | 791 | package org.hongxi.whatsmars.boot.sample.test;
import org.hongxi.whatsmars.boot.sample.test.Application;
import org.hongxi.whatsmars.boot.sample.test.DemoService;
import org.junit.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.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by shenhongxi on 2020/8/29.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles("dev")
public class ApplicationTest {
@Autowired
private DemoService demoService;
@Test
public void demoService() {
assert "a".equals(demoService.getName());
}
}
| 28.25 | 62 | 0.78129 |
baa8ba5086caf4f3aa1f40f6cfb1949ff1e285bb | 1,987 | package csulb.cecs343.lair;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.RawRes;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtils {
@NonNull
public static final void copyFileFromRawToOthers(@NonNull final Context context, @RawRes int id, @NonNull final String targetPath) {
InputStream in = context.getResources().openRawResource(id);
FileOutputStream out = null;
try {
out = new FileOutputStream(targetPath);
byte[] buff = new byte[1024];
int read = 0;
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyFile(String srcPath, String targetPath) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(srcPath);
out = new FileOutputStream(targetPath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 28.797101 | 136 | 0.490689 |
5e9195145a6ca4ae63824f6acd903bcd4803254c | 103 | package com.adyen.v13.model.payout;
public class ConfirmThirdPartyResponse extends ModifyResponse {
}
| 20.6 | 63 | 0.834951 |
db483f717293cc91722b4e959cfed1eedc977d0a | 2,080 | package zigma;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Parent;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.ButtonType;
import java.io.StringWriter;
import java.io.PrintWriter;
import lib.dir.ValidateConsole;
/**
* Main class of Console program
*/
public class Console extends Application {
@Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("console_fx_sketch.fxml"));
loader.setController(new ConsoleController());
Parent root = loader.load();
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Console[Z I G M A]");
primaryStage.show();
} catch(Exception ex) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Start up error");
alert.setHeaderText("Something went wrong with content loading");
alert.setContentText(ex.getMessage());
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
Label lbl = new Label("The exception stack trace was:");
TextArea txtArea = new TextArea(sw.toString());
txtArea.setEditable(false);
txtArea.setWrapText(true);
txtArea.setMaxWidth(Double.MAX_VALUE);
txtArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(txtArea, Priority.ALWAYS);
GridPane.setHgrow(txtArea, Priority.ALWAYS);
GridPane pane = new GridPane();
pane.setMaxWidth(Double.MAX_VALUE);
pane.add(lbl, 0, 0);
pane.add(txtArea, 0, 1);
alert.getDialogPane().setExpandableContent(pane);
alert.showAndWait();
}
}
public static void main(String[] args) {
ValidateConsole vc = new ValidateConsole();
if(vc.validate()) {
launch(args);
} else {
System.err.println("Invalid software!");
}
}
} | 28.493151 | 73 | 0.710096 |
c966ce1f02eeed63d8b28833860d87943b80c66c | 5,354 | import com.walmartlabs.x12.exceptions.X12ParserException;
import com.walmartlabs.x12.standard.StandardX12Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class BatchFileParser {
private static final Logger LOGGER = LoggerFactory.getLogger(BatchFileParser.class);
private static final StandardX12Parser x12Parser = new StandardX12Parser();
private static final Charset UTF8_CHARSET = StandardCharsets.UTF_8;
private static final Charset LATIN_ONE_CHARSET = StandardCharsets.ISO_8859_1;
private static final Charset MAC_CHARSET = Charset.forName("x-MacRoman");
public static void main(String[] args) throws IOException {
if (args != null && args.length > 0) {
// get list of files in input folder
String inputDirectory = args[0];
Path inputFolder = Paths.get(inputDirectory);
if (Files.exists(inputFolder)) {
Path okFolder = Paths.get(inputDirectory + "/success");
createFolderIfNotExists(okFolder);
Path rejectFolder = Paths.get(inputDirectory + "/failed");
createFolderIfNotExists(rejectFolder);
processDirectory(inputFolder, okFolder, rejectFolder);
} else {
LOGGER.warn("the input folder does not exist");
}
} else {
LOGGER.warn("please provide an input folder as an argument");
}
}
private static void processDirectory(Path inputFolder, Path okFolder, Path rejectFolder) throws IOException {
AtomicInteger successCount = new AtomicInteger(0);
AtomicInteger failedCount = new AtomicInteger(0);
try (Stream<Path> files = Files.list(inputFolder)) {
files.filter(Files::isRegularFile)
.forEach(sourceFile -> {
boolean isSuccess = parseFile(sourceFile, okFolder, rejectFolder);
if (isSuccess) {
successCount.incrementAndGet();
} else {
failedCount.incrementAndGet();
}
});
}
LOGGER.info("Parsed files - successful {}, failed {}", successCount, failedCount);
}
private static boolean parseFile(Path sourceFile, Path okFolder, Path rejectFolder) {
boolean isSuccess = false;
try {
// read the file
String sourceData = readFile(sourceFile);
// parse the file
x12Parser.parse(sourceData);
// copy the file to OK folder
copyFile(sourceFile, okFolder);
isSuccess = true;
} catch (X12ParserException e) {
// copy the file to failed folder
copyFile(sourceFile, rejectFolder);
// write file w/ parsing fail reason
writeReasonFile(sourceFile, rejectFolder, e.getMessage());
} catch (UncheckedIOException | IOException e) {
writeReasonFile(sourceFile, rejectFolder, e.getMessage());
}
return isSuccess;
}
private static String readFile(Path sourceFile) throws IOException {
String fileContents = null;
try {
fileContents = readFile(sourceFile, UTF8_CHARSET);
} catch (UncheckedIOException e) {
Throwable t = e.getCause();
if (t != null && t instanceof MalformedInputException) {
LOGGER.warn("switching encoding to Latin-1");
fileContents = readFile(sourceFile, LATIN_ONE_CHARSET);
} else {
throw e;
}
}
return fileContents;
}
private static String readFile(Path sourceFile, Charset charSet) throws IOException {
// read the file
String content = null;
try (Stream<String> lines = Files.lines(sourceFile, charSet)) {
content = lines.collect(Collectors.joining(System.lineSeparator()));
}
return content;
}
private static void writeReasonFile(Path sourceFile, Path rejectFolder, String errReason) {
try {
Path errFile = rejectFolder.resolve(sourceFile.getFileName() + ".reason.txt");
Files.write(errFile, errReason.getBytes());
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
private static void copyFile(Path fileToCopy, Path folder) {
try {
Path targetFile = folder.resolve(fileToCopy.getFileName());
Files.copy(fileToCopy, targetFile, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
private static void createFolderIfNotExists(Path folder) throws IOException {
if (!Files.exists(folder)) {
Files.createDirectories(folder);
}
}
} | 37.971631 | 113 | 0.620097 |
72659bd126bf46140f5a76ec4cd11f1771560eb2 | 2,697 | package seedu.track2gather.logic.commands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import seedu.track2gather.commons.core.Messages;
import seedu.track2gather.commons.core.index.Index;
import seedu.track2gather.logic.commands.exceptions.CommandException;
import seedu.track2gather.model.Model;
import seedu.track2gather.model.person.Person;
/**
* Updates that a failed call was made to a person in the current SHN enforcement session.
*/
public class FCallCommand extends Command {
public static final String COMMAND_WORD = "fcall";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Updates that a failed call was made to a person in the current SHN enforcement session.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_INCREMENT_PERSON_SUCCESS =
"Failed to call Person: %s (Case No. %s) with %d past failed call attempt(s)";
public static final String MESSAGE_INVALID_MULTIPLE_CALLS =
"Person has already been called in the current session.";
private final Index targetIndex;
/**
* Default constructor to create a new {@code FCallCommand}
*
* @param targetIndex index of target person.
*/
public FCallCommand(Index targetIndex) {
requireNonNull(targetIndex);
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
List<Person> lastShownList = model.getFilteredPersonList();
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
}
Person personToIncrement = lastShownList.get(targetIndex.getZeroBased());
if (personToIncrement.getCallStatus().isCalledInCurrentSession()) {
throw new CommandException(MESSAGE_INVALID_MULTIPLE_CALLS);
}
Person newPerson = new Person(personToIncrement, personToIncrement.getCallStatus().incrementNumFailedCalls());
model.setPerson(personToIncrement, newPerson);
return new CommandResult(String.format(MESSAGE_INCREMENT_PERSON_SUCCESS, newPerson.getName(),
newPerson.getCaseNumber(), newPerson.getCallStatus().getNumFailedCalls()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof FCallCommand // instanceof handles nulls
&& targetIndex.equals(((FCallCommand) other).targetIndex)); // state check
}
}
| 38.528571 | 118 | 0.711531 |
9fdfb057bc694d8fa040d9ab9cc5ab5f77b21820 | 5,618 | package com.cgutman.adblib;
import java.io.Closeable;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class abstracts the underlying ADB streams
* @author Cameron Gutman
*/
public class AdbStream implements Closeable {
/** The AdbConnection object that the stream communicates over */
private AdbConnection adbConn;
/** The local ID of the stream */
private int localId;
/** The remote ID of the stream */
private int remoteId;
/** Indicates whether a write is currently allowed */
private AtomicBoolean writeReady;
/** A queue of data from the target's write packets */
private Queue<byte[]> readQueue;
/** Indicates whether the connection is closed already */
private boolean isClosed;
/**
* Creates a new AdbStream object on the specified AdbConnection
* with the given local ID.
* @param adbConn AdbConnection that this stream is running on
* @param localId Local ID of the stream
*/
public AdbStream(AdbConnection adbConn, int localId)
{
this.adbConn = adbConn;
this.localId = localId;
this.readQueue = new ConcurrentLinkedQueue<byte[]>();
this.writeReady = new AtomicBoolean(false);
this.isClosed = false;
}
/**
* Called by the connection thread to indicate newly received data.
* @param payload Data inside the write message
*/
void addPayload(byte[] payload)
{
synchronized (readQueue) {
readQueue.add(payload);
readQueue.notifyAll();
}
}
/**
* Called by the connection thread to send an OKAY packet, allowing the
* other side to continue transmission.
* @throws IOException If the connection fails while sending the packet
*/
void sendReady() throws IOException
{
/* Generate and send a READY packet */
byte[] packet = AdbProtocol.generateReady(localId, remoteId);
adbConn.outputStream.write(packet);
adbConn.outputStream.flush();
}
/**
* Called by the connection thread to update the remote ID for this stream
* @param remoteId New remote ID
*/
void updateRemoteId(int remoteId)
{
this.remoteId = remoteId;
}
/**
* Called by the connection thread to indicate the stream is okay to send data.
*/
void readyForWrite()
{
writeReady.set(true);
}
/**
* Called by the connection thread to notify that the stream was closed by the peer.
*/
void notifyClose()
{
/* We don't call close() because it sends another CLOSE */
isClosed = true;
/* Unwait readers and writers */
synchronized (this) {
notifyAll();
}
synchronized (readQueue) {
readQueue.notifyAll();
}
}
/**
* Reads a pending write payload from the other side.
* @return Byte array containing the payload of the write
* @throws InterruptedException If we are unable to wait for data
* @throws IOException If the stream fails while waiting
*/
public byte[] read() throws InterruptedException, IOException
{
byte[] data = null;
synchronized (readQueue) {
/* Wait for the connection to close or data to be received */
while (!isClosed && (data = readQueue.poll()) == null) {
readQueue.wait();
}
if (isClosed) {
throw new IOException("Stream closed");
}
}
return data;
}
/**
* Sends a write packet with a given String payload.
* @param payload Payload in the form of a String
* @throws IOException If the stream fails while sending data
* @throws InterruptedException If we are unable to wait to send data
*/
public void write(String payload) throws IOException, InterruptedException
{
/* ADB needs null-terminated strings */
write(payload.getBytes("UTF-8"), false);
write(new byte[]{0}, true);
}
/**
* Sends a write packet with a given byte array payload.
* @param payload Payload in the form of a byte array
* @throws IOException If the stream fails while sending data
* @throws InterruptedException If we are unable to wait to send data
*/
public void write(byte[] payload) throws IOException, InterruptedException
{
write(payload, true);
}
/**
* Queues a write packet and optionally sends it immediately.
* @param payload Payload in the form of a byte array
* @param flush Specifies whether to send the packet immediately
* @throws IOException If the stream fails while sending data
* @throws InterruptedException If we are unable to wait to send data
*/
public void write(byte[] payload, boolean flush) throws IOException, InterruptedException
{
synchronized (this) {
/* Make sure we're ready for a write */
while (!isClosed && !writeReady.compareAndSet(true, false))
wait();
if (isClosed) {
throw new IOException("Stream closed");
}
}
/* Generate a WRITE packet and send it */
byte[] packet = AdbProtocol.generateWrite(localId, remoteId, payload);
adbConn.outputStream.write(packet);
if (flush)
adbConn.outputStream.flush();
}
/**
* Closes the stream. This sends a close message to the peer.
* @throws IOException If the stream fails while sending the close message.
*/
@Override
public void close() throws IOException {
synchronized (this) {
/* This may already be closed by the remote host */
if (isClosed)
return;
/* Notify readers/writers that we've closed */
notifyClose();
}
byte[] packet = AdbProtocol.generateClose(localId, remoteId);
adbConn.outputStream.write(packet);
adbConn.outputStream.flush();
}
/**
* Retreives whether the stream is closed or not
* @return True if the stream is close, false if not
*/
public boolean isClosed() {
return isClosed;
}
} | 26.880383 | 90 | 0.703275 |
dcde92b5fd2935a365b7306e4338683dbe3d8bd3 | 270 | package uk.co.chrisjenx.paralloid.transform;
/**
* Created by chris on 23/10/2013
* Project: Paralloid
*/
public interface Transformer {
/**
* @return can not be null, otherwise scroll will fail
*/
int[] scroll(float x, float y, float factor);
}
| 18 | 58 | 0.655556 |
25ad002c1155421f45342f86fad784125c9c8059 | 497 | package com.github.sputnik906.example.classic.spring.app.dto.common;
import com.github.sputnik906.example.classic.spring.app.domain.common.IdentifiableLong;
import javax.persistence.EntityManager;
import org.mapstruct.Context;
import org.mapstruct.TargetType;
public interface EntityManagerContext {
default <T extends IdentifiableLong> T from(
Long id, @Context EntityManager entityManager, @TargetType Class<T> targetType) {
return entityManager.getReference(targetType, id);
}
}
| 33.133333 | 87 | 0.806841 |
3d65bb20cc10393c1276228ddd5a3bd3ef9016ab | 1,601 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package brain.models;
import brain.controller.ClsUpdateModel;
import brain.controller.IAction;
import java.sql.Date;
/**
*
* @author Brain
*/
public class ClsProvision implements IAction{
private int id;
private ClsFournisseur _fournisseur;
private ClsProduit _Produit;
private Date _dateProvision;
private float _qty;
public ClsProvision() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ClsFournisseur getFournisseur() {
return _fournisseur;
}
public void setFournisseur(ClsFournisseur _fournisseur) {
this._fournisseur = _fournisseur;
}
public ClsProduit getProduit() {
return _Produit;
}
public void setProduit(ClsProduit _Produit) {
this._Produit = _Produit;
}
public Date getDateProvision() {
return _dateProvision;
}
public void setDateProvision(Date _dateProvision) {
this._dateProvision = _dateProvision;
}
public float getQty() {
return _qty;
}
public void setQty(float _qty) {
this._qty = _qty;
}
@Override
public boolean saveData() throws Exception {
return ClsUpdateModel.updateData(this);
}
@Override
public boolean deleteData() throws Exception {
return ClsUpdateModel.deleteData("", getId());
}
}
| 20.792208 | 79 | 0.648345 |
ec0ac04ce16b2c767129d9fa826737e21be007ff | 5,888 | /**
* Imports
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
/**
* The stop and wait sender. It sends of size of 126 bytes.
* The first byte is the sequence number, the second byte is the number of bytes being sent
* the remaining 124 bytes are the data being sent
* The sender will wait a reasonable amount of time before re-sending the packet
* It follows the standard Reliable Data Transfer 3.0 from Computer Networking: A Top-Down Approach.
* All files are sent as bytes.
* @author Dallas Fraser - 110242560
* @author George Lifchits - 100691350
* @version 1.0
* @see Class#UnreliableDatagramSocket
*/
public class StopAndWaitSender {
/**
* {@link socket}: the UDP socket
* @see Class#UnreliableDatagramSocket
* {@link logger}: the logger for the class
* @see Class#Logger
* {@link fp}: the file input stream for reading files
* {@link out_packet}: the datagram packet for responding
* {@link in_packet}: the datagram packet for receiving
* {@link ia}: the internet address of the sender
* {@link sequence}: the sequence number of package (0 or 1)
*/
private UnreliableDatagramSocket socket;
private Logger logger;
private DatagramPacket out_packet;
private DatagramPacket in_packet;
private FileInputStream fp;
private InetAddress ia;
private int sequence;
private int totalBytesRead;
private int DATA_BUF = 124;
private int END_BYTES = DATA_BUF + 1; // 1 + maximum data buf size
private int PACKET_SIZE = DATA_BUF + 2; // 1 byte for seq# and 1 for packet size
private int SO_TIMEOUT = 10000;
private float NS_TO_MS = 1000*1000;
private float NS_TO_S = 1000*1000*1000;
/**
* the public constructor
* @param hostAddress: a String of the host address
* @param senderPort: the port number of the sender
* @param receiverPort: the port number of this receiver
* @param fileName: the name of the file to output
* @param logger: the logger of the class
*
* @throws FileNotFoundException if unable to find file
* @throws UnknownHostException if unable to find address for host
* @throws SocketException if unable to create UDP socket
*/
public StopAndWaitSender(String hostAddress,
int senderPort,
int receiverPort,
String fileName,
Logger logger) throws UnknownHostException,
SocketException,
FileNotFoundException {
this.socket = new UnreliableDatagramSocket(senderPort, logger);
this.logger = logger;
this.ia = InetAddress.getByName(hostAddress);
byte[] data = new byte[PACKET_SIZE];
byte[] in_data = new byte[1];
this.out_packet = new DatagramPacket(data, data.length, this.ia, receiverPort);
this.in_packet = new DatagramPacket(in_data, in_data.length, this.ia, receiverPort);
this.socket.setSoTimeout(SO_TIMEOUT);
this.fp = new FileInputStream(new File(fileName));
this.logger.debug("Created sender");
this.sequence = 0;
}
/**
* Sends the outgoing packet
*/
public void sendPacket() throws IOException {
try {
this.logger.debug("Sending packet");
this.socket.send(this.out_packet);
this.socket.receive(this.in_packet);
this.logger.debug("Got an incoming packet");
if (!this.in_packet.getAddress().equals(this.ia)) {
this.logger.debug("... not from the receiver address, resending packet");
this.sendPacket();
} else {
if (this.in_packet.getData()[0] == this.sequence) {
this.logger.debug("Packet was ACKed");
this.sequence = (this.sequence + 1) % 2; // update the sequence number
} else {
this.logger.debug("ACK received for wrong packet, resending packet");
this.sendPacket();
}
}
} catch(SocketTimeoutException e) {
this.logger.debug("Timeout occurred, resending packet");
this.sendPacket();
}
}
public void sendFile() throws IOException {
this.logger.info("Sender: sending file");
long senderStartTime = System.nanoTime();
byte[] data = new byte[PACKET_SIZE];
int bytesRead;
while ((bytesRead = this.fp.read(data, 2, DATA_BUF)) > 0) {
data[0] = (byte) this.sequence; // set the sequence number
data[1] = (byte) bytesRead; // send number of bytes read
this.out_packet.setData(data); // set data of the packet
this.sendPacket();
this.totalBytesRead += bytesRead;
}
// signal the file is done
data[0] = (byte) this.sequence; // set the sequence number
data[1] = (byte) END_BYTES; // send number of bytes read
this.out_packet.setData(data);
this.sendPacket();
long senderEndTime = System.nanoTime();
double seconds = (senderEndTime - senderStartTime) / NS_TO_S;
this.logger.info("Sender: file sending complete");
this.logger.info(String.format("Total time to send file: %.3f seconds", seconds));
this.logger.info("Total file size: "+ this.totalBytesRead +" bytes");
}
public static void main(String[] args) {
try {
if (args.length < 4) {
throw new Exception("Missing an argument: hostAddress receiverPort senderPort fileName");
}
String hostAddress = args[0];
int receiverPort = new Integer(args[1]).intValue();
int senderPort = new Integer(args[2]).intValue();
String fileName = args[3];
Logger log;
if (args.length > 4) {
int level = new Integer(args[4]).intValue();
log = new Logger(level);
} else {
log = new Logger(2);
}
log.debug(fileName);
StopAndWaitSender sw = new StopAndWaitSender(hostAddress,
senderPort,
receiverPort,
fileName,
log);
sw.sendFile();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
| 34.232558 | 100 | 0.705673 |
97731596f4666921bcbce6f59b0e49ceac4c5971 | 246 | package jdo.humanresoures.model.position.type;
import javax.persistence.Entity;
import jdo.model.BaseType;
@Entity
public class PositionClassificationType extends BaseType {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 15.375 | 58 | 0.764228 |
76699b795d945bb8b1e8ad1fc1ce9427b2b23783 | 702 | package pt.kiko.krip.variables.functions;
import org.bukkit.Bukkit;
import pt.kiko.krip.Krip;
import pt.kiko.krip.lang.Context;
import pt.kiko.krip.lang.results.RuntimeResult;
import pt.kiko.krip.lang.values.KripJavaFunction;
import pt.kiko.krip.lang.values.KripNull;
import java.util.Collections;
public class PrintFunc extends KripJavaFunction {
static {
Krip.registerValue("print", new PrintFunc());
}
public PrintFunc() {
super("print", Collections.singletonList("value"), Krip.context);
}
@Override
public RuntimeResult run(Context context) {
Bukkit.getLogger().info(context.symbolTable.get("value").toString());
return new RuntimeResult().success(new KripNull(context));
}
}
| 25.071429 | 71 | 0.763533 |
f1b9a95450656143020786512aed1ca0579617d3 | 509 | package com.demo.spring.utils;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author Shaowei Zhang on 2021/6/20 13:33
*/
public class ResourceUtils {
@SneakyThrows
public static String getContext(Resource resource) {
return IOUtils.toString(new EncodedResource(resource, UTF_8).getReader());
}
}
| 24.238095 | 82 | 0.764244 |
b9b4b7b301946f0e3aec190ab597d10d95a2d6da | 637 | package com.codetaylor.mc.dropt.modules.dropt.rule.data;
import com.codetaylor.mc.dropt.api.reference.EnumDropStrategy;
import com.codetaylor.mc.dropt.api.reference.EnumReplaceStrategy;
import com.codetaylor.mc.dropt.api.api.RandomFortuneInt;
public class Rule {
public boolean debug = false;
public RuleMatch match = new RuleMatch();
public EnumReplaceStrategy replaceStrategy = EnumReplaceStrategy.REPLACE_ALL;
public EnumDropStrategy dropStrategy = EnumDropStrategy.REPEAT;
public RandomFortuneInt dropCount = new RandomFortuneInt(1);
public RuleDrop[] drops = new RuleDrop[0];
public boolean fallthrough = false;
}
| 35.388889 | 79 | 0.805338 |
89c053a2419db173e6892d788dc6ed1da9c66650 | 1,132 | package com.github.zhuobinchan.distributed.lock.spring.boot.demo.service.impl;
import com.github.zhuobinchan.distributed.lock.spring.annotation.DistributedLock;
import com.github.zhuobinchan.distributed.lock.spring.boot.demo.service.DistributedLockService;
import com.github.zhuobinchan.distributed.lock.spring.boot.demo.service.TestLockView;
import org.springframework.stereotype.Service;
/**
* @author zhuobin chan on 2020-12-23 11:21
*/
@Service
public class DistributedLockServiceImpl implements DistributedLockService {
@Override
@DistributedLock(key = "testKey1")
public String testLockByAnnotation() {
return "testKey1";
}
@Override
@DistributedLock(key = "lockKey1")
public String testLockByAnnotationWithArg(String lockKey1) {
return "testKey1";
}
@Override
@DistributedLock(key = "#lockKey1")
public String testLockByAnnotation(String lockKey1) {
return "lockKey1";
}
@Override
@DistributedLock(key = "#testLockView.lockKey2")
public String testLockByAnnotation(TestLockView testLockView) {
return "testLockView";
}
}
| 29.789474 | 95 | 0.742049 |
ee5e0d11e7d3f4e1a04faf4d11ebc10d3c89df13 | 10,974 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.components.impl;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.BaseComponent;
import com.intellij.openapi.components.ComponentManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceDescriptor;
import com.intellij.openapi.components.ex.ComponentManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.*;
import com.intellij.openapi.extensions.impl.ExtensionComponentAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.PlatformUtils;
import com.intellij.util.io.storage.HeavyProcessLatch;
import com.intellij.util.pico.AssignableToComponentAdapter;
import com.intellij.util.pico.CachingConstructorInjectionComponentAdapter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.*;
import org.picocontainer.defaults.InstanceComponentAdapter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ServiceManagerImpl implements BaseComponent {
private static final Logger LOG = Logger.getInstance(ServiceManagerImpl.class);
private static final ExtensionPointName<ServiceDescriptor> APP_SERVICES = new ExtensionPointName<>("com.intellij.applicationService");
private static final ExtensionPointName<ServiceDescriptor> PROJECT_SERVICES = new ExtensionPointName<>("com.intellij.projectService");
private ExtensionPointName<ServiceDescriptor> myExtensionPointName;
private ExtensionPointListener<ServiceDescriptor> myExtensionPointListener;
public ServiceManagerImpl() {
installEP(APP_SERVICES, ApplicationManager.getApplication());
}
public ServiceManagerImpl(Project project) {
installEP(PROJECT_SERVICES, project);
}
protected ServiceManagerImpl(boolean ignoreInit) {
}
protected void installEP(@NotNull ExtensionPointName<ServiceDescriptor> pointName, @NotNull final ComponentManager componentManager) {
LOG.assertTrue(myExtensionPointName == null, "Already called installEP with " + myExtensionPointName);
myExtensionPointName = pointName;
final ExtensionPoint<ServiceDescriptor> extensionPoint = Extensions.getArea(null).getExtensionPoint(pointName);
final MutablePicoContainer picoContainer = (MutablePicoContainer)componentManager.getPicoContainer();
myExtensionPointListener = new ExtensionPointListener<ServiceDescriptor>() {
@Override
public void extensionAdded(@NotNull final ServiceDescriptor descriptor, final PluginDescriptor pluginDescriptor) {
if (descriptor.overrides) {
// Allow to re-define service implementations in plugins.
ComponentAdapter oldAdapter = picoContainer.unregisterComponent(descriptor.getInterface());
if (oldAdapter == null) {
throw new RuntimeException("Service: " + descriptor.getInterface() + " doesn't override anything");
}
}
if (!Extensions.isComponentSuitableForOs(descriptor.os)) {
return;
}
// empty serviceImplementation means we want to unregister service
if (!StringUtil.isEmpty(descriptor.getImplementation())) {
picoContainer.registerComponent(new MyComponentAdapter(descriptor, pluginDescriptor, (ComponentManagerEx)componentManager));
}
}
@Override
public void extensionRemoved(@NotNull final ServiceDescriptor extension, final PluginDescriptor pluginDescriptor) {
picoContainer.unregisterComponent(extension.getInterface());
}
};
extensionPoint.addExtensionPointListener(myExtensionPointListener);
}
public List<ServiceDescriptor> getAllDescriptors() {
ServiceDescriptor[] extensions = Extensions.getExtensions(myExtensionPointName);
return Arrays.asList(extensions);
}
public static void processAllImplementationClasses(@NotNull ComponentManagerImpl componentManager, @NotNull PairProcessor<Class<?>, PluginDescriptor> processor) {
Collection adapters = componentManager.getPicoContainer().getComponentAdapters();
if (adapters.isEmpty()) {
return;
}
for (Object o : adapters) {
Class aClass;
if (o instanceof MyComponentAdapter) {
MyComponentAdapter adapter = (MyComponentAdapter)o;
PluginDescriptor pluginDescriptor = adapter.myPluginDescriptor;
try {
ComponentAdapter delegate = adapter.myDelegate;
// avoid delegation creation & class initialization
if (delegate == null) {
ClassLoader classLoader = pluginDescriptor == null ? ServiceManagerImpl.class.getClassLoader() : pluginDescriptor.getPluginClassLoader();
aClass = Class.forName(adapter.myDescriptor.getImplementation(), false, classLoader);
}
else {
aClass = delegate.getComponentImplementation();
}
}
catch (Throwable e) {
if (PlatformUtils.isIdeaUltimate()) {
LOG.error(e);
}
else {
// well, component registered, but required jar is not added to classpath (community edition or junior IDE)
LOG.warn(e);
}
continue;
}
if (!processor.process(aClass, pluginDescriptor)) {
break;
}
}
else if (o instanceof ComponentAdapter && !(o instanceof ExtensionComponentAdapter)) {
PluginId pluginId = componentManager.getConfig((ComponentAdapter)o);
// allow InstanceComponentAdapter without pluginId to test
if (pluginId != null || o instanceof InstanceComponentAdapter) {
try {
aClass = ((ComponentAdapter)o).getComponentImplementation();
}
catch (Throwable e) {
LOG.error(e);
continue;
}
processor.process(aClass, pluginId == null ? null : PluginManager.getPlugin(pluginId));
}
}
}
}
@Override
@NonNls
@NotNull
public String getComponentName() {
return getClass().getName();
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
final ExtensionPoint<ServiceDescriptor> extensionPoint = Extensions.getArea(null).getExtensionPoint(myExtensionPointName);
extensionPoint.removeExtensionPointListener(myExtensionPointListener);
}
private static class MyComponentAdapter implements AssignableToComponentAdapter {
private ComponentAdapter myDelegate;
private final ServiceDescriptor myDescriptor;
private final PluginDescriptor myPluginDescriptor;
private final ComponentManagerEx myComponentManager;
private volatile Object myInitializedComponentInstance;
public MyComponentAdapter(final ServiceDescriptor descriptor, final PluginDescriptor pluginDescriptor, ComponentManagerEx componentManager) {
myDescriptor = descriptor;
myPluginDescriptor = pluginDescriptor;
myComponentManager = componentManager;
myDelegate = null;
}
@Override
public String getComponentKey() {
return myDescriptor.getInterface();
}
@Override
public Class getComponentImplementation() {
return getDelegate().getComponentImplementation();
}
@Override
public Object getComponentInstance(@NotNull PicoContainer container) throws PicoInitializationException, PicoIntrospectionException {
Object instance = myInitializedComponentInstance;
if (instance != null) {
return instance;
}
synchronized (this) {
instance = myInitializedComponentInstance;
if (instance != null) {
// DCL is fine, field is volatile
return instance;
}
ComponentAdapter delegate = getDelegate();
if (LOG.isDebugEnabled() &&
ApplicationManager.getApplication().isWriteAccessAllowed() &&
!ApplicationManager.getApplication().isUnitTestMode() &&
PersistentStateComponent.class.isAssignableFrom(delegate.getComponentImplementation())) {
LOG.warn(new Throwable("Getting service from write-action leads to possible deadlock. Service implementation " + myDescriptor.getImplementation()));
}
// prevent storages from flushing and blocking FS
AccessToken token = HeavyProcessLatch.INSTANCE.processStarted("Creating component '" + myDescriptor.getImplementation() + "'");
try {
instance = delegate.getComponentInstance(container);
if (instance instanceof Disposable) {
Disposer.register(myComponentManager, (Disposable)instance);
}
myComponentManager.initializeComponent(instance, true);
myInitializedComponentInstance = instance;
return instance;
}
finally {
token.finish();
}
}
}
@NotNull
private synchronized ComponentAdapter getDelegate() {
if (myDelegate == null) {
Class<?> implClass;
try {
ClassLoader classLoader = myPluginDescriptor != null ? myPluginDescriptor.getPluginClassLoader() : getClass().getClassLoader();
implClass = Class.forName(myDescriptor.getImplementation(), true, classLoader);
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
myDelegate = new CachingConstructorInjectionComponentAdapter(getComponentKey(), implClass, null, true);
}
return myDelegate;
}
@Override
public void verify(final PicoContainer container) throws PicoIntrospectionException {
getDelegate().verify(container);
}
@Override
public void accept(final PicoVisitor visitor) {
visitor.visitComponentAdapter(this);
}
@Override
public String getAssignableToClassName() {
return myDescriptor.getInterface();
}
@Override
public String toString() {
return "ServiceComponentAdapter[" + myDescriptor.getInterface() + "]: implementation=" + myDescriptor.getImplementation() + ", plugin=" + myPluginDescriptor;
}
}
}
| 38.914894 | 164 | 0.720703 |
b9c9a3609e619bbe161605085696d1b7bfbcfc88 | 564 | package bootcamp.proposta.propostas;
import bootcamp.proposta.propostas.cartao.CartaoResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PropostaResponse {
@JsonProperty
private final String nome;
@JsonProperty
private final EstadoProposta estado;
@JsonProperty
private final CartaoResponse cartao;
public PropostaResponse(Proposta proposta) {
this.nome = proposta.getNome();
this.estado = proposta.getEstadoProposta();
this.cartao = new CartaoResponse(proposta.getCartao());
}
}
| 28.2 | 63 | 0.742908 |
6f8d57eddd812187e5527c0f88e7363004fc1760 | 1,046 | package jo.vecmath.ext;
import jo.vecmath.Point3f;
import jo.vecmath.logic.Point3fLogic;
public class Line3f {
private Point3f mP;
private Point3f mN;
public Line3f() {
mP = new Point3f();
mN = new Point3f(0, 0, 1);
}
public Line3f(Point3f p, Point3f n) {
this();
mP.set(p);
mN.set(n);
Point3fLogic.normalize(mN);
}
public Line3f(Line3f l) {
this(l.getP(), l.getN());
}
public String toString() {
return mP.toString() + "--" + mN.toString();
}
public double dist(Point3f m) {
Point3f direct = Point3fLogic.sub(m, mP);
Point3f projected = Point3fLogic.scale(mN, Point3fLogic.dot(direct, mN));
double d = Point3fLogic.mag(Point3fLogic.sub(direct, projected));
return d;
}
public Point3f getP() {
return mP;
}
public void setP(Point3f p) {
mP = p;
}
public Point3f getN() {
return mN;
}
public void setN(Point3f n) {
mN = n;
}
}
| 19.37037 | 81 | 0.553537 |
63cf48631aa61d8d643f41697bd18bc7fb4ba314 | 320 | package io.sdb.service.impl;
import io.sdb.dao.OrderDetailDao;;
import io.sdb.model.OrderDetail;
import io.sdb.service.OrderDetailService;
import org.springframework.stereotype.Service;
@Service
public class OrderDetailServiceImpl extends BaseServiceImpl<OrderDetailDao, OrderDetail> implements OrderDetailService {
}
| 29.090909 | 120 | 0.84375 |
964b47e7a8fc192e01015bd89635f5c1b1230297 | 647 | package cn.navclub.xt.server.service;
import cn.navclub.xt.server.api.CommonResult;
import cn.navclub.xt.server.service.impl.UserServiceProxyImpl;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import java.util.Map;
@ProxyGen
public interface UserService {
static UserService create(Vertx vertx) {
return new UserServiceProxyImpl(vertx);
}
static UserService createProxy(Vertx vertx) {
return new UserServiceVertxEBProxy(vertx, UserService.class.getName());
}
Future<CommonResult<Map<String,String>>> login();
}
| 26.958333 | 79 | 0.760433 |
17d43bbcf797799c77714ef40b58a70e89a1a9bf | 2,712 | package nl.pvanassen.artifactory.cleaner.api;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class FolderInfo {
public static final class Children {
private String uri;
private String folder;
public String getUri() {
return uri;
}
void setUri( String uri ) {
this.uri = uri;
}
public String getFolder() {
return folder;
}
void setFolder( String folder ) {
this.folder = folder;
}
@Override
public String toString() {
return "Children [uri=" + uri + ", folder=" + folder + "]";
}
}
private String uri;
private String repo;
private String path;
private String created;
private String createdBy;
private String lastModified;
private String modifiedBy;
private String lastUpdated;
private Children[] children;
public String getUri() {
return uri;
}
void setUri( String uri ) {
this.uri = uri;
}
public String getRepo() {
return repo;
}
void setRepo( String repo ) {
this.repo = repo;
}
public String getCreated() {
return created;
}
void setCreated( String created ) {
this.created = created;
}
public String getCreatedBy() {
return createdBy;
}
void setCreatedBy( String createdBy ) {
this.createdBy = createdBy;
}
public String getLastModified() {
return lastModified;
}
void setLastModified( String lastModified ) {
this.lastModified = lastModified;
}
public String getModifiedBy() {
return modifiedBy;
}
void setModifiedBy( String modifiedBy ) {
this.modifiedBy = modifiedBy;
}
public String getLastUpdated() {
return lastUpdated;
}
void setLastUpdated( String lastUpdated ) {
this.lastUpdated = lastUpdated;
}
public Children[] getChildren() {
return children;
}
void setChildren( Children[] children ) {
this.children = children;
}
public String getPath() {
return path;
}
void setPath( String path ) {
this.path = path;
}
@Override
public String toString() {
return "FolderInfo [uri=" + uri + ", repo=" + repo + ", path=" + path + ", created=" + created + ", createdBy=" + createdBy + ", lastModified=" + lastModified + ", modifiedBy=" + modifiedBy + ", lastUpdated=" + lastUpdated + ", children=" + Arrays.toString( children ) + "]";
}
}
| 21.696 | 283 | 0.575959 |
ac96d3a68717d68e30da61d4780251b1d317905b | 3,760 | package bwyap.familyfeud.render.state.play;
import java.awt.Graphics;
import bwyap.familyfeud.game.FamilyFeudGame;
import bwyap.familyfeud.game.play.state.StateFaceOff;
import bwyap.familyfeud.game.play.state.StrikeInterface;
import bwyap.familyfeud.game.state.StatePlay;
import bwyap.familyfeud.gui.window.GameWindow;
import bwyap.familyfeud.render.RenderableInterface;
import bwyap.familyfeud.render.RenderingPanel;
import bwyap.familyfeud.render.component.Fader;
import bwyap.familyfeud.render.component.RenderableImage;
import bwyap.gridgame.res.ResourceLoader;
/**
* A RenderStrikes object renders the appropriate strikes
* to the screen when it detects a change in the number of strikes in the
* current game state.
* @author bwyap
*
*/
public class RenderStrikes implements RenderableInterface {
public static final int STRIKE_SIZE = 200;
public static final int STRIKE_TIME = 1500;
private FamilyFeudGame game;
private int strikes;
private RenderableImage img1;
private RenderableImage img2;
private RenderableImage img3;
private Fader strike1;
private Fader strike2;
private Fader strike3;
/**
* Create a new RenderStrikes object
* @param game
*/
public RenderStrikes(FamilyFeudGame game) {
this.game = game;
this.strikes = 0;
this.img1 = new RenderableImage(ResourceLoader.getImage("strike"), STRIKE_SIZE, STRIKE_SIZE);
this.img2 = new RenderableImage(ResourceLoader.getImage("strike"), STRIKE_SIZE, STRIKE_SIZE);
this.img3 = new RenderableImage(ResourceLoader.getImage("strike"), STRIKE_SIZE, STRIKE_SIZE);
this.strike1 = new Fader(STRIKE_TIME, null, img1);
this.strike2 = new Fader(STRIKE_TIME, null, img2);
this.strike3 = new Fader(STRIKE_TIME, null, img3);
// Strikes should initially be disabled
this.strike1.forceFinish();
this.strike2.forceFinish();
this.strike3.forceFinish();
}
/**
* Reset the number of strikes
*/
@Override
public void reset() {
if (game.getState() instanceof StatePlay) {
StatePlay play = (StatePlay) game.getState();
if (play.getPlayState() instanceof StrikeInterface) {
strikes = ((StrikeInterface) play.getPlayState()).getStrikes();
}
}
}
@Override
public void update(float timeElapsed) {
if (game.getState() instanceof StatePlay) {
StatePlay play = (StatePlay) game.getState();
if (play.getPlayState() instanceof StrikeInterface) {
StrikeInterface state = (StrikeInterface) play.getPlayState();
// Detect if number of strikes has changed
if (strikes != state.getStrikes()) {
strikes = state.getStrikes();
// Check if there are strikes to be rendered
if (strikes > 0) {
strike1.reset();
img1.setPosition((GameWindow.WIDTH - STRIKE_SIZE) / 2, 300);
}
if (!(state instanceof StateFaceOff)) {
if (strikes > 1 && strikes < 3) {
strike2.reset();
img1.setPosition((GameWindow.WIDTH - STRIKE_SIZE) / 3, 300);
img2.setPosition((GameWindow.WIDTH - STRIKE_SIZE) / 3 * 2, 300);
}
else if (strikes > 2) {
strike2.reset();
strike3.reset();
img2.setPosition((GameWindow.WIDTH - STRIKE_SIZE)/ 4, 300);
img3.setPosition((GameWindow.WIDTH - STRIKE_SIZE) / 4 * 3, 300);
}
}
}
}
}
if (strikes > 0 && !strike1.finished()) strike1.update(timeElapsed);
if (strikes > 1 && !strike2.finished()) strike2.update(timeElapsed);
if (strikes > 2 && !strike3.finished()) strike3.update(timeElapsed);
}
@Override
public void render(RenderingPanel panel, Graphics g) {
if (strikes > 0 && !strike1.finished()) strike1.render(panel, g);
if (strikes > 1 && !strike2.finished()) strike2.render(panel, g);
if (strikes > 2 && !strike3.finished()) strike3.render(panel, g);
}
}
| 31.333333 | 95 | 0.704787 |
21283a2c740f831813e9e194b804063a38758a6f | 546 | package net.nanofix.field;
/**
* User: Mark
* Date: 31/03/12
* Time: 20:44
*/
public class IntegerField implements Field {
private final int tag;
private final int value;
public IntegerField(int tag, int value) {
this.tag = tag;
this.value = value;
}
@Override
public int getTag() {
return tag;
}
@Override
public byte[] getBytes() {
return new byte[0];
}
@Override
public Integer getValue() {
return value;
}
}
| 16.545455 | 46 | 0.534799 |
d144af4acd5ccec641f5e6d3860d17ccba96f4c8 | 79 | package org.particl.ui.desktop;
public interface IDesktopViewListener {
}
| 11.285714 | 39 | 0.772152 |
c6cf33c5720cfbdce5fd8469e373d669a2c2eb0d | 3,603 | package com.chipsea.ui.activity;
import android.app.Activity;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import com.chipsea.code.util.FileUtil;
import com.chipsea.code.util.ImagePresser;
import com.chipsea.code.util.JLog;
import com.chipsea.code.util.ScreenUtils;
import com.chipsea.ui.R;
import com.chipsea.view.CropImageView;
import com.chipsea.view.text.CustomTextView;
import java.io.File;
public class CropImageActivity extends Activity implements OnClickListener {
private static final String TAG = "CropImageActivity" ;
private ViewHolders mViewHolders;
private String mHeadPicName;
private Uri imageUri; // 图片URI
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop_image);
init();
}
private void init() {
mViewHolders = new ViewHolders();
mViewHolders.cropImageView = (CropImageView) findViewById(R.id.cropimage);
mViewHolders.sure = (CustomTextView) findViewById(R.id.sure);
mViewHolders.cancle = (CustomTextView) findViewById(R.id.cancle);
mViewHolders.sure.setOnClickListener(this);
mViewHolders.cancle.setOnClickListener(this);
String flag = getIntent().getStringExtra(PhotographActivity.FLAG_PICTURE_INTENT);
mHeadPicName=getIntent().getStringExtra(PhotographActivity.FLAG_HEADPIC_NAME);
imageUri = Uri.fromFile(new File(FileUtil.PATH_PICTURE, mHeadPicName));
Bitmap scaleBitmap = null;
if (flag != null) {
if (flag.equals(PhotographActivity.FLAG_PHOTO_NAME)) {
Bitmap bitmap = getBitmapFromUri(imageUri,
getContentResolver());
int degree = ImagePresser
.readPictureDegree(imageUri.getPath());
JLog.e(TAG,"degree = " + degree);
if (degree == 90 || degree == 270) {
scaleBitmap = ImagePresser.zoomBitmap(bitmap,
ScreenUtils.getScreenHeight(this),
ScreenUtils.getScreenWidth(this));
scaleBitmap = ImagePresser.rotaingImageView(degree,
scaleBitmap);
} else {
scaleBitmap = ImagePresser.zoomBitmap(bitmap,
ScreenUtils.getScreenWidth(this),
ScreenUtils.getScreenHeight(this));
}
bitmap.recycle();
} else if (flag.equals(PhotographActivity.FLAG_ABLUM_NAME)) {
scaleBitmap = BitmapFactory
.decodeFile(imageUri.getPath());
}
}
Drawable drawable = new BitmapDrawable(getResources(), scaleBitmap);
mViewHolders.cropImageView.setDrawable(drawable, 100, 100);
}
/**
* 通过uri获取图片
*
* @param uri
* @param contentResolver
* @return
*/
public static Bitmap getBitmapFromUri(Uri uri,
ContentResolver contentResolver) {
try {
// 读取uri所在的图片
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver,
uri);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 控件控制变量
* */
private class ViewHolders {
CropImageView cropImageView;
CustomTextView cancle;
CustomTextView sure;
}
@Override
public void onClick(View v) {
if (v == mViewHolders.sure) {
Bitmap bitmap = mViewHolders.cropImageView.getCropImage();
if (bitmap != null) {
Bitmap comBitmap = ImagePresser.comp(bitmap);
ImagePresser.savePhotoToSDCard(comBitmap, FileUtil.PATH_PICTURE,mHeadPicName);
bitmap.recycle();
setResult(RESULT_OK);
}
}
finish();
}
}
| 29.056452 | 83 | 0.741604 |
12fd02605f8757d5d10a5d6bb2efa785a860ce95 | 3,567 | package commandGenerator.arguments.tags.specific;
import java.util.ArrayList;
import java.util.List;
import commandGenerator.Generator;
import commandGenerator.arguments.objects.Attribute;
import commandGenerator.arguments.objects.AttributeType;
import commandGenerator.arguments.objects.ObjectBase;
import commandGenerator.arguments.tags.Tag;
import commandGenerator.arguments.tags.TagCompound;
import commandGenerator.arguments.tags.TagDouble;
import commandGenerator.arguments.tags.TagInt;
import commandGenerator.arguments.tags.TagList;
import commandGenerator.arguments.tags.TagString;
import commandGenerator.gui.helper.argumentSelection.dataTag.ListSelectionPanel;
public class TagAttributes extends TagList
{
private boolean forMob;
public TagAttributes(String id, boolean forMob, String... applicable)
{
super(id, applicable);
this.forMob = forMob;
if (forMob)
{
TagList list = new TagList("Modifiers") {
@Override
public void askValue()
{}
}.setValue(new ArrayList<Tag>());
List<Tag> tag = new ArrayList<Tag>();
tag.add(list);
tag.add(new TagString("Name").setValue("Name"));
tag.add(new TagDouble("Base").setValue(1.0d));
setValue(tag);
}
}
@Override
public void askValue()
{
panel = new ListSelectionPanel("TAGS:" + getId(), ObjectBase.ATTRIBUTE);
if (!forMob) ((ListSelectionPanel) panel).setList(getValue());
else ((ListSelectionPanel) panel).setList(getAttributes(getValue()));
if (showPanel()) return;
if (!forMob)
{
setValue(((ListSelectionPanel) panel).getList());
return;
}
TagList list = new TagList("Modifiers") {
@Override
public void askValue()
{}
};
list.setValue(((ListSelectionPanel) panel).getList());
List<Tag> tag = new ArrayList<Tag>();
tag.add(list);
tag.add(new TagString("Name").setValue("Name"));
tag.add(new TagDouble("Base").setValue(1.0d));
setValue(tag);
}
@Override
public String commandStructure()
{
String command = super.commandStructure();
if (!forMob) return command;
String newCommand = command.substring(0, command.indexOf('['));
newCommand += "{";
newCommand += command.substring(command.indexOf('[') + 1, command.length() - 1);
newCommand += "}";
return newCommand;
}
@Override
public String display(int details, int lvls)
{
String text = getName();
if (text != "") text += " : ";
List<Tag> value;
if (!forMob) value = getValue();
else
{
value = ((TagList) getValue().get(0)).getValue();
}
if (value.size() == 0) return text + Generator.translate("GENERAL:empty");
for (int i = 0; i < value.size(); i++)
{
text += "<br />";
for (int j = 0; j < lvls; j++)
text += "|";
text += "- ";
TagCompound attribute = (TagCompound) value.get(i);
String id = "generic.maxHealth";
double amount = 1.0D;
int operation = 0;
for (int j = 0; j < attribute.size(); j++)
{
if (attribute.get(j).getId().equals("AttributeName")) id = ((TagString) attribute.get(j)).getValue();
if (attribute.get(j).getId().equals("Amount")) amount = ((TagDouble) attribute.get(j)).getValue();
if (attribute.get(j).getId().equals("Operation")) operation = ((TagInt) attribute.get(j)).getValue();
}
text += new Attribute((AttributeType) Generator.registry.getObjectFromId(id), amount, operation).display();
}
return text;
}
private List<Tag> getAttributes(List<Tag> value)
{
for (int i = 0; i < value.size(); i++) if (value.get(i).getId().equals("Modifiers")) return ((TagList) value.get(i)).getValue();
return new ArrayList<Tag>();
}
}
| 27.229008 | 130 | 0.680123 |
28e5157fa5b69917d55094f41ca35f2c506e2d92 | 296 | package com.tle.web.api.interfaces.beans;
import java.util.List;
public class FileListBean extends AbstractExtendableBean {
private List<BlobBean> files;
public List<BlobBean> getFiles() {
return files;
}
public void setFiles(List<BlobBean> files) {
this.files = files;
}
}
| 18.5 | 58 | 0.722973 |
fd1355f246379150a4c17801c0493be155116a63 | 187 | package com.sonicbase.common;
public class UniqueConstraintViolationException extends RuntimeException {
public UniqueConstraintViolationException(String msg) {
super(msg);
}
}
| 20.777778 | 74 | 0.802139 |
b92fa2b953bab25adedb8f17b0cd44aca242d04b | 3,426 | package car.ccut.com.vehicle.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import car.ccut.com.vehicle.R;
import car.ccut.com.vehicle.interf.ConstantValue;
import car.ccut.com.vehicle.service.MyService;
import car.ccut.com.vehicle.ui.OrderManageActivity;
import car.ccut.com.vehicle.ui.UserCenterActivity;
/**
* *
* へ /|
* /\7 ∠_/
* / │ / /
* │ Z _,< / /`ヽ
* │ ヽ / 〉
* Y ` / /
* イ● 、 ● ⊂⊃〈 /
* () へ | \〈
* >ー 、_ ィ │ // 去吧!
* / へ / ノ<| \\ 比卡丘~
* ヽ_ノ (_/ │// 消灭代码BUG
* 7 |/
* >―r ̄ ̄`ー―_
* Created by WangXin on 2016/5/11 0011.
*/
public class HomeFragment2 extends Fragment implements View.OnClickListener {
@Bind(R.id.tv_title)
TextView title;
@Bind(R.id.iv_title_back)
ImageView back;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment2, container, false);
ButterKnife.bind(this,view);
return view;
}
@Override
@OnClick({R.id.user_center,R.id.order_manage,R.id.drink})
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.user_center:
Intent i=new Intent(getActivity(), UserCenterActivity.class);
startActivity(i);
break;
case R.id.drink:
new AlertDialog.Builder(getActivity())
.setTitle("酒驾检测")
.setMessage("是否向代驾人员发送自身状态信息?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {//添加确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
// TODO Auto-generated method stub
Intent startIntent = new Intent(getActivity(), MyService.class);
getContext().startService(startIntent);
Toast.makeText(getContext(), "已发送",
Toast.LENGTH_SHORT).show();
getContext().stopService(startIntent);
}
})
.setNegativeButton("否", null)
.show();
break;
case R.id.order_manage:
Intent intent = new Intent(getActivity(), OrderManageActivity.class);
intent.putExtra("orderType", ConstantValue.ORDER_FINISH);
startActivity(intent);
break;
}
}
@Override
public void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
}
public void initView(){
title.setText("信息管理");
back.setVisibility(View.GONE);
}
}
| 32.320755 | 103 | 0.563047 |
ba2d144311e19c2b3a4184d9574f5be217c72484 | 8,691 | package cn.katoumegumi.java.http.server.handle;
import cn.katoumegumi.java.common.WsDateUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
public class WebSocketInHandler extends SimpleChannelInboundHandler {
private static final Logger log = LoggerFactory.getLogger(WebSocketInHandler.class);
public static Map<String, Channel> map = new ConcurrentHashMap<>();
private static volatile WebSocketServerHandshaker webSocketServerHandshaker;
private static volatile ExecutorService executorService = Executors.newCachedThreadPool();
static {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
log.info("键值对大小为:{}", map.size());
long startTime = System.currentTimeMillis();
Set<Map.Entry<String, Channel>> set = map.entrySet();
Iterator<Map.Entry<String, Channel>> iterator = set.iterator();
Flux.<Map.Entry<String, Channel>>create(entryFluxSink -> {
while (iterator.hasNext()) {
entryFluxSink.next(iterator.next());
}
entryFluxSink.complete();
}).subscribe(stringChannelEntry -> {
Channel channel = stringChannelEntry.getValue();
//ByteBuf byteBuf = Unpooled.copyInt(9);
channel.writeAndFlush(new PingWebSocketFrame());
});
long endTime = System.currentTimeMillis();
log.info("执行完成,共耗时{}毫秒", (endTime - startTime));
}, 10, 10, TimeUnit.SECONDS);
/* Flux.<Date>generate(fluxSink -> {
fluxSink.next(new Date());
}).timeout(Duration.ofSeconds(1)).subscribe(date -> {
Set<Map.Entry<String,Channel>> set = map.entrySet();
Iterator<Map.Entry<String,Channel>> iterator = set.iterator();
Flux.<Map.Entry<String,Channel>>create(entryFluxSink -> {
while (iterator.hasNext()){
entryFluxSink.next(iterator.next());
}
entryFluxSink.complete();
}).subscribe(stringChannelEntry -> {
Channel channel = stringChannelEntry.getValue();
channel.writeAndFlush(new TextWebSocketFrame(WsDateUtils.dateToString(date,WsDateUtils.CNLONGTIMESTRING)));
});
});*/
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object textWebSocketFrame) throws Exception {
/*ByteBuf byteBuf = textWebSocketFrame.content();
int start = byteBuf.readerIndex();
int end = byteBuf.readableBytes();
byte bytes[] = new byte[end - start];
byteBuf.readBytes(byteBuf,start,end);
String str = new String(bytes);*/
/* String str = textWebSocketFrame.text();
log.info("客户端的消息为{}",str);
Channel channel = channelHandlerContext.channel();
channel.writeAndFlush(new TextWebSocketFrame(str));
channelHandlerContext.flush();*/
//channelHandlerContext.flush();
try {
if (textWebSocketFrame instanceof FullHttpRequest) {
handleRequest(channelHandlerContext, (FullHttpRequest) textWebSocketFrame);
}
if (textWebSocketFrame instanceof WebSocketFrame) {
handleWebSocket(channelHandlerContext, (WebSocketFrame) textWebSocketFrame);
}
} finally {
//ReferenceCountUtil.retain(textWebSocketFrame);
//7ReferenceCountUtil.release(textWebSocketFrame);
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
log.info("用户{}上线", ctx.channel().id());
map.put(ctx.channel().id().asLongText(), ctx.channel());
log.info("通道数量为:{}", map.size());
super.handlerAdded(ctx);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
log.info("用户{}下线", ctx.channel().id());
map.remove(ctx.channel().id().asLongText());
log.info("通道数量为:{}", map.size());
super.handlerRemoved(ctx);
}
private void handleRequest(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
if (!fullHttpRequest.decoderResult().isSuccess() || (!"websocket".equals(fullHttpRequest.headers().get("Upgrade")))) {
handleHttp(channelHandlerContext, fullHttpRequest);
return;
}
WebSocketServerHandshakerFactory webSocketServerHandshakerFactory = new WebSocketServerHandshakerFactory("ws/localhost:1234/ws", null, false);
webSocketServerHandshaker = webSocketServerHandshakerFactory.newHandshaker(fullHttpRequest);
if (webSocketServerHandshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channelHandlerContext.channel());
} else {
webSocketServerHandshaker.handshake(channelHandlerContext.channel(), fullHttpRequest);
}
}
public void handleHttp(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) {
ByteBuf byteBuf = fullHttpRequest.content();
int start = byteBuf.readerIndex();
int end = byteBuf.readableBytes();
byte bytes[] = new byte[end - start];
byteBuf.readBytes(bytes, start, end);
log.info("HTTP传输的数据为:{}", new String(bytes));
String str = "<html><head><title>Netty响应</title></head><body><div style=\"text-align:centre;\">当前时间为" + WsDateUtils.dateToString(new Date(), WsDateUtils.CNLONGTIMESTRING) + "</div></body></html>";
try {
byteBuf = Unpooled.copiedBuffer(str.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
byteBuf = Unpooled.copiedBuffer(str.getBytes());
}
FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
channelHandlerContext.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
//byteBuf.release();
}
private void handleWebSocket(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) {
if (webSocketFrame instanceof CloseWebSocketFrame) {
webSocketServerHandshaker.close(channelHandlerContext.channel(), ((CloseWebSocketFrame) webSocketFrame).retain());
return;
}
if (webSocketFrame instanceof PingWebSocketFrame) {
channelHandlerContext.writeAndFlush(new PongWebSocketFrame(webSocketFrame.content().retain()));
//channelHandlerContext.writeAndFlush(new PongWebSocketFrame());
return;
}
if (webSocketFrame instanceof PongWebSocketFrame) {
//channelHandlerContext.writeAndFlush(new PingWebSocketFrame(webSocketFrame.content().retain()));
return;
}
String str = ((TextWebSocketFrame) webSocketFrame).text();
//channelHandlerContext.writeAndFlush(new TextWebSocketFrame(str));
channelHandlerContext.flush();
executorService.submit(() -> {
sendMsg(channelHandlerContext.channel().id().asLongText(), str);
});
}
public void sendMsg(String channelId, String value) {
Set<Map.Entry<String, Channel>> set = map.entrySet();
Iterator<Map.Entry<String, Channel>> iterator = set.iterator();
Flux.<Map.Entry<String, Channel>>create(channelFluxSink -> {
while (iterator.hasNext()) {
channelFluxSink.next(iterator.next());
}
channelFluxSink.complete();
}).filter(entity -> {
String id = entity.getKey();
if (id.equals(channelId)) {
return false;
} else {
return true;
}
}).subscribe(entity -> {
String id = entity.getKey();
Channel channel = entity.getValue();
TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(id + ":" + value);
channel.writeAndFlush(textWebSocketFrame);
});
}
}
| 42.18932 | 204 | 0.651939 |
09a3de09b7a9ab30ccee84328a3e3e67935681a0 | 22,441 | /*
* Copyright (c) 2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the license.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package gov.llnl.gnem.apps.coda.calibration.model.domain;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import org.springframework.format.annotation.NumberFormat;
import gov.llnl.gnem.apps.coda.common.model.util.Durable;
@Durable
@Entity
@Table(name = "Shape_Fit_Constraints")
public class ShapeFitterConstraints implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Version
private Integer version = 0;
@NumberFormat
private double maxVP1;
@NumberFormat
private double minVP1;
@NumberFormat
private double v0reg;
@NumberFormat
private double maxVP2;
@NumberFormat
private double minVP2;
@NumberFormat
private double maxVP3;
@NumberFormat
private double minVP3;
@NumberFormat
private double maxBP1;
@NumberFormat
private double minBP1;
@NumberFormat
private double b0reg;
@NumberFormat
private double maxBP2;
@NumberFormat
private double minBP2;
@NumberFormat
private double maxBP3;
@NumberFormat
private double minBP3;
@NumberFormat
private double maxGP1;
@NumberFormat
private double minGP1;
@NumberFormat
private double g0reg;
@NumberFormat
private double maxGP2;
@NumberFormat
private double minGP2;
@NumberFormat
private double g1reg;
@NumberFormat
private double maxGP3;
@NumberFormat
private double minGP3;
@NumberFormat
private double yvvMin;
@NumberFormat
private double yvvMax;
@NumberFormat
private double vDistMax;
@NumberFormat
private double vDistMin;
@NumberFormat
private double ybbMin;
@NumberFormat
private double ybbMax;
@NumberFormat
private double bDistMax;
@NumberFormat
private double bDistMin;
@NumberFormat
private double yggMin;
@NumberFormat
private double yggMax;
@NumberFormat
private double gDistMin;
@NumberFormat
private double gDistMax;
@NumberFormat
private double minIntercept;
@NumberFormat
private double maxIntercept;
@NumberFormat
private double minBeta;
@NumberFormat
private double maxBeta;
@NumberFormat
private double minGamma;
@NumberFormat
private double maxGamma;
@NumberFormat
private int iterations;
@NumberFormat
private int fittingPointCount;
@NumberFormat
private double lengthWeight;
public Long getId() {
return id;
}
public ShapeFitterConstraints setId(Long id) {
this.id = id;
return this;
}
public Integer getVersion() {
return version;
}
public ShapeFitterConstraints setVersion(Integer version) {
this.version = version;
return this;
}
public double getMaxVP1() {
return maxVP1;
}
public ShapeFitterConstraints setMaxVP1(double maxVP1) {
this.maxVP1 = maxVP1;
return this;
}
public double getMinVP1() {
return minVP1;
}
public ShapeFitterConstraints setMinVP1(double minVP1) {
this.minVP1 = minVP1;
return this;
}
public double getV0reg() {
return v0reg;
}
public ShapeFitterConstraints setV0reg(double v0reg) {
this.v0reg = v0reg;
return this;
}
public double getMaxVP2() {
return maxVP2;
}
public ShapeFitterConstraints setMaxVP2(double maxVP2) {
this.maxVP2 = maxVP2;
return this;
}
public double getMinVP2() {
return minVP2;
}
public ShapeFitterConstraints setMinVP2(double minVP2) {
this.minVP2 = minVP2;
return this;
}
public double getMaxVP3() {
return maxVP3;
}
public ShapeFitterConstraints setMaxVP3(double maxVP3) {
this.maxVP3 = maxVP3;
return this;
}
public double getMinVP3() {
return minVP3;
}
public ShapeFitterConstraints setMinVP3(double minVP3) {
this.minVP3 = minVP3;
return this;
}
public double getMaxBP1() {
return maxBP1;
}
public ShapeFitterConstraints setMaxBP1(double maxBP1) {
this.maxBP1 = maxBP1;
return this;
}
public double getMinBP1() {
return minBP1;
}
public ShapeFitterConstraints setMinBP1(double minBP1) {
this.minBP1 = minBP1;
return this;
}
public double getB0reg() {
return b0reg;
}
public ShapeFitterConstraints setB0reg(double b0reg) {
this.b0reg = b0reg;
return this;
}
public double getMaxBP2() {
return maxBP2;
}
public ShapeFitterConstraints setMaxBP2(double maxBP2) {
this.maxBP2 = maxBP2;
return this;
}
public double getMinBP2() {
return minBP2;
}
public ShapeFitterConstraints setMinBP2(double minBP2) {
this.minBP2 = minBP2;
return this;
}
public double getMaxBP3() {
return maxBP3;
}
public ShapeFitterConstraints setMaxBP3(double maxBP3) {
this.maxBP3 = maxBP3;
return this;
}
public double getMinBP3() {
return minBP3;
}
public ShapeFitterConstraints setMinBP3(double minBP3) {
this.minBP3 = minBP3;
return this;
}
public double getMaxGP1() {
return maxGP1;
}
public ShapeFitterConstraints setMaxGP1(double maxGP1) {
this.maxGP1 = maxGP1;
return this;
}
public double getMinGP1() {
return minGP1;
}
public ShapeFitterConstraints setMinGP1(double minGP1) {
this.minGP1 = minGP1;
return this;
}
public double getG0reg() {
return g0reg;
}
public ShapeFitterConstraints setG0reg(double g0reg) {
this.g0reg = g0reg;
return this;
}
public double getMaxGP2() {
return maxGP2;
}
public ShapeFitterConstraints setMaxGP2(double maxGP2) {
this.maxGP2 = maxGP2;
return this;
}
public double getMinGP2() {
return minGP2;
}
public ShapeFitterConstraints setMinGP2(double minGP2) {
this.minGP2 = minGP2;
return this;
}
public double getG1reg() {
return g1reg;
}
public ShapeFitterConstraints setG1reg(double g1reg) {
this.g1reg = g1reg;
return this;
}
public double getMaxGP3() {
return maxGP3;
}
public ShapeFitterConstraints setMaxGP3(double maxGP3) {
this.maxGP3 = maxGP3;
return this;
}
public double getMinGP3() {
return minGP3;
}
public ShapeFitterConstraints setMinGP3(double minGP3) {
this.minGP3 = minGP3;
return this;
}
public double getYvvMin() {
return yvvMin;
}
public ShapeFitterConstraints setYvvMin(double yvvMin) {
this.yvvMin = yvvMin;
return this;
}
public double getYvvMax() {
return yvvMax;
}
public ShapeFitterConstraints setYvvMax(double yvvMax) {
this.yvvMax = yvvMax;
return this;
}
public double getvDistMax() {
return vDistMax;
}
public ShapeFitterConstraints setvDistMax(double vDistMax) {
this.vDistMax = vDistMax;
return this;
}
public double getvDistMin() {
return vDistMin;
}
public ShapeFitterConstraints setvDistMin(double vDistMin) {
this.vDistMin = vDistMin;
return this;
}
public double getYbbMin() {
return ybbMin;
}
public ShapeFitterConstraints setYbbMin(double ybbMin) {
this.ybbMin = ybbMin;
return this;
}
public double getYbbMax() {
return ybbMax;
}
public ShapeFitterConstraints setYbbMax(double ybbMax) {
this.ybbMax = ybbMax;
return this;
}
public double getbDistMax() {
return bDistMax;
}
public ShapeFitterConstraints setbDistMax(double bDistMax) {
this.bDistMax = bDistMax;
return this;
}
public double getbDistMin() {
return bDistMin;
}
public ShapeFitterConstraints setbDistMin(double bDistMin) {
this.bDistMin = bDistMin;
return this;
}
public double getYggMin() {
return yggMin;
}
public ShapeFitterConstraints setYggMin(double yggMin) {
this.yggMin = yggMin;
return this;
}
public double getYggMax() {
return yggMax;
}
public ShapeFitterConstraints setYggMax(double yggMax) {
this.yggMax = yggMax;
return this;
}
public double getgDistMin() {
return gDistMin;
}
public ShapeFitterConstraints setgDistMin(double gDistMin) {
this.gDistMin = gDistMin;
return this;
}
public double getgDistMax() {
return gDistMax;
}
public ShapeFitterConstraints setgDistMax(double gDistMax) {
this.gDistMax = gDistMax;
return this;
}
public double getMinIntercept() {
return minIntercept;
}
public ShapeFitterConstraints setMinIntercept(double minIntercept) {
this.minIntercept = minIntercept;
return this;
}
public double getMaxIntercept() {
return maxIntercept;
}
public ShapeFitterConstraints setMaxIntercept(double maxIntercept) {
this.maxIntercept = maxIntercept;
return this;
}
public double getMinBeta() {
return minBeta;
}
public ShapeFitterConstraints setMinBeta(double minBeta) {
this.minBeta = minBeta;
return this;
}
public double getMaxBeta() {
return maxBeta;
}
public ShapeFitterConstraints setMaxBeta(double maxBeta) {
this.maxBeta = maxBeta;
return this;
}
public double getMinGamma() {
return minGamma;
}
public ShapeFitterConstraints setMinGamma(double minGamma) {
this.minGamma = minGamma;
return this;
}
public double getMaxGamma() {
return maxGamma;
}
public ShapeFitterConstraints setMaxGamma(double maxGamma) {
this.maxGamma = maxGamma;
return this;
}
public int getIterations() {
return iterations;
}
public ShapeFitterConstraints setIterations(int iterations) {
this.iterations = iterations;
return this;
}
public int getFittingPointCount() {
return fittingPointCount;
}
public ShapeFitterConstraints setFittingPointCount(int fittingPointCount) {
this.fittingPointCount = fittingPointCount;
return this;
}
public double getLengthWeight() {
return lengthWeight;
}
public ShapeFitterConstraints setLengthWeight(double lengthWeight) {
this.lengthWeight = lengthWeight;
return this;
}
public ShapeFitterConstraints merge(ShapeFitterConstraints other) {
if (other.getId() != null) {
id = other.getId();
}
maxVP1 = other.getMaxVP1();
minVP1 = other.getMinVP1();
v0reg = other.getV0reg();
maxVP2 = other.getMaxVP2();
minVP2 = other.getMinVP2();
maxVP3 = other.getMaxVP3();
minVP3 = other.getMinVP3();
maxBP1 = other.getMaxBP1();
minBP1 = other.getMinBP1();
b0reg = other.getB0reg();
maxBP2 = other.getMaxBP2();
minBP2 = other.getMinBP2();
maxBP3 = other.getMaxBP3();
minBP3 = other.getMinBP3();
maxGP1 = other.getMaxGP1();
minGP1 = other.getMinGP1();
g0reg = other.getG0reg();
maxGP2 = other.getMaxGP2();
minGP2 = other.getMinGP2();
g1reg = other.getG1reg();
maxGP3 = other.getMaxGP3();
minGP3 = other.getMinGP3();
yvvMin = other.getYvvMin();
yvvMax = other.getYvvMax();
ybbMin = other.getYbbMin();
ybbMax = other.getYbbMax();
yggMin = other.getYggMin();
yggMax = other.getYggMax();
minIntercept = other.getMinIntercept();
maxIntercept = other.getMaxIntercept();
minBeta = other.getMinBeta();
maxBeta = other.getMaxBeta();
minGamma = other.getMinGamma();
maxGamma = other.getMaxGamma();
vDistMax = other.getvDistMax();
vDistMin = other.getvDistMin();
bDistMax = other.getbDistMax();
bDistMin = other.getbDistMin();
iterations = other.getIterations();
gDistMin = other.getgDistMin();
gDistMax = other.getgDistMax();
if (other.getFittingPointCount() != 0.0) {
fittingPointCount = other.getFittingPointCount();
}
if (other.getLengthWeight() != 0.0) {
lengthWeight = other.getLengthWeight();
}
return this;
}
@Override
public int hashCode() {
return Objects.hash(
b0reg,
bDistMax,
bDistMin,
fittingPointCount,
g0reg,
g1reg,
gDistMax,
gDistMin,
id,
iterations,
maxBP1,
maxBP2,
maxBP3,
maxBeta,
maxGP1,
maxGP2,
maxGP3,
maxGamma,
maxIntercept,
maxVP1,
maxVP2,
maxVP3,
minBP1,
minBP2,
minBP3,
minBeta,
minGP1,
minGP2,
minGP3,
minGamma,
minIntercept,
minVP1,
minVP2,
minVP3,
v0reg,
vDistMax,
vDistMin,
version,
ybbMax,
ybbMin,
yggMax,
yggMin,
yvvMax,
yvvMin,
lengthWeight);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ShapeFitterConstraints)) {
return false;
}
ShapeFitterConstraints other = (ShapeFitterConstraints) obj;
return Double.doubleToLongBits(b0reg) == Double.doubleToLongBits(other.b0reg)
&& Double.doubleToLongBits(bDistMax) == Double.doubleToLongBits(other.bDistMax)
&& Double.doubleToLongBits(bDistMin) == Double.doubleToLongBits(other.bDistMin)
&& fittingPointCount == other.fittingPointCount
&& Double.doubleToLongBits(g0reg) == Double.doubleToLongBits(other.g0reg)
&& Double.doubleToLongBits(g1reg) == Double.doubleToLongBits(other.g1reg)
&& Double.doubleToLongBits(gDistMax) == Double.doubleToLongBits(other.gDistMax)
&& Double.doubleToLongBits(gDistMin) == Double.doubleToLongBits(other.gDistMin)
&& Objects.equals(id, other.id)
&& iterations == other.iterations
&& Double.doubleToLongBits(maxBP1) == Double.doubleToLongBits(other.maxBP1)
&& Double.doubleToLongBits(maxBP2) == Double.doubleToLongBits(other.maxBP2)
&& Double.doubleToLongBits(maxBP3) == Double.doubleToLongBits(other.maxBP3)
&& Double.doubleToLongBits(maxBeta) == Double.doubleToLongBits(other.maxBeta)
&& Double.doubleToLongBits(maxGP1) == Double.doubleToLongBits(other.maxGP1)
&& Double.doubleToLongBits(maxGP2) == Double.doubleToLongBits(other.maxGP2)
&& Double.doubleToLongBits(maxGP3) == Double.doubleToLongBits(other.maxGP3)
&& Double.doubleToLongBits(maxGamma) == Double.doubleToLongBits(other.maxGamma)
&& Double.doubleToLongBits(maxIntercept) == Double.doubleToLongBits(other.maxIntercept)
&& Double.doubleToLongBits(maxVP1) == Double.doubleToLongBits(other.maxVP1)
&& Double.doubleToLongBits(maxVP2) == Double.doubleToLongBits(other.maxVP2)
&& Double.doubleToLongBits(maxVP3) == Double.doubleToLongBits(other.maxVP3)
&& Double.doubleToLongBits(minBP1) == Double.doubleToLongBits(other.minBP1)
&& Double.doubleToLongBits(minBP2) == Double.doubleToLongBits(other.minBP2)
&& Double.doubleToLongBits(minBP3) == Double.doubleToLongBits(other.minBP3)
&& Double.doubleToLongBits(minBeta) == Double.doubleToLongBits(other.minBeta)
&& Double.doubleToLongBits(minGP1) == Double.doubleToLongBits(other.minGP1)
&& Double.doubleToLongBits(minGP2) == Double.doubleToLongBits(other.minGP2)
&& Double.doubleToLongBits(minGP3) == Double.doubleToLongBits(other.minGP3)
&& Double.doubleToLongBits(minGamma) == Double.doubleToLongBits(other.minGamma)
&& Double.doubleToLongBits(minIntercept) == Double.doubleToLongBits(other.minIntercept)
&& Double.doubleToLongBits(minVP1) == Double.doubleToLongBits(other.minVP1)
&& Double.doubleToLongBits(minVP2) == Double.doubleToLongBits(other.minVP2)
&& Double.doubleToLongBits(minVP3) == Double.doubleToLongBits(other.minVP3)
&& Double.doubleToLongBits(v0reg) == Double.doubleToLongBits(other.v0reg)
&& Double.doubleToLongBits(vDistMax) == Double.doubleToLongBits(other.vDistMax)
&& Double.doubleToLongBits(vDistMin) == Double.doubleToLongBits(other.vDistMin)
&& Objects.equals(version, other.version)
&& Double.doubleToLongBits(ybbMax) == Double.doubleToLongBits(other.ybbMax)
&& Double.doubleToLongBits(ybbMin) == Double.doubleToLongBits(other.ybbMin)
&& Double.doubleToLongBits(yggMax) == Double.doubleToLongBits(other.yggMax)
&& Double.doubleToLongBits(yggMin) == Double.doubleToLongBits(other.yggMin)
&& Double.doubleToLongBits(yvvMax) == Double.doubleToLongBits(other.yvvMax)
&& Double.doubleToLongBits(yvvMin) == Double.doubleToLongBits(other.yvvMin)
&& Double.doubleToLongBits(lengthWeight) == Double.doubleToLongBits(other.lengthWeight);
}
@Override
public String toString() {
return "ShapeFitterConstraints [id="
+ id
+ ", version="
+ version
+ ", maxVP1="
+ maxVP1
+ ", minVP1="
+ minVP1
+ ", v0reg="
+ v0reg
+ ", maxVP2="
+ maxVP2
+ ", minVP2="
+ minVP2
+ ", maxVP3="
+ maxVP3
+ ", minVP3="
+ minVP3
+ ", maxBP1="
+ maxBP1
+ ", minBP1="
+ minBP1
+ ", b0reg="
+ b0reg
+ ", maxBP2="
+ maxBP2
+ ", minBP2="
+ minBP2
+ ", maxBP3="
+ maxBP3
+ ", minBP3="
+ minBP3
+ ", maxGP1="
+ maxGP1
+ ", minGP1="
+ minGP1
+ ", g0reg="
+ g0reg
+ ", maxGP2="
+ maxGP2
+ ", minGP2="
+ minGP2
+ ", g1reg="
+ g1reg
+ ", maxGP3="
+ maxGP3
+ ", minGP3="
+ minGP3
+ ", yvvMin="
+ yvvMin
+ ", yvvMax="
+ yvvMax
+ ", vDistMax="
+ vDistMax
+ ", vDistMin="
+ vDistMin
+ ", ybbMin="
+ ybbMin
+ ", ybbMax="
+ ybbMax
+ ", bDistMax="
+ bDistMax
+ ", bDistMin="
+ bDistMin
+ ", yggMin="
+ yggMin
+ ", yggMax="
+ yggMax
+ ", gDistMin="
+ gDistMin
+ ", gDistMax="
+ gDistMax
+ ", minIntercept="
+ minIntercept
+ ", maxIntercept="
+ maxIntercept
+ ", minBeta="
+ minBeta
+ ", maxBeta="
+ maxBeta
+ ", minGamma="
+ minGamma
+ ", maxGamma="
+ maxGamma
+ ", iterations="
+ iterations
+ ", fittingPointCount="
+ fittingPointCount
+ ", lengthWeight="
+ lengthWeight
+ "]";
}
} | 28.298865 | 208 | 0.572345 |
bed4dfbcf016537667d8f318478db51cb47d1c96 | 2,140 | package dinchi.org.petshots.utils;
/*
* Doctor
* "c_firstname","c_lastname","c_email","c_phoneprimary","c_phonesecondary","c_address"
* */
public class DoctorDetails {
String m_title;
String m_firstname;
String m_lastname;
String m_email;
String m_phonePrimary;
String m_phoneSecondary;
String m_address;
long m_id;
public String getM_title() {
return m_title;
}
public void setM_title(String m_title) {
this.m_title = m_title;
}
public String getM_firstname() {
return m_firstname;
}
public void setM_firstname(String m_firstname) {
this.m_firstname = m_firstname;
}
public String getM_lastname() {
return m_lastname;
}
public void setM_lastname(String m_lastname) {
this.m_lastname = m_lastname;
}
public String getM_email() {
return m_email;
}
public void setM_email(String m_email) {
this.m_email = m_email;
}
public String getM_phonePrimary() {
return m_phonePrimary;
}
public void setM_phonePrimary(String m_phonePrimary) {
this.m_phonePrimary = m_phonePrimary;
}
public String getM_phoneSecondary() {
return m_phoneSecondary;
}
public void setM_phoneSecondary(String m_phoneSecondary) {
this.m_phoneSecondary = m_phoneSecondary;
}
public String getM_address() {
return m_address;
}
public void setM_address(String m_address) {
this.m_address = m_address;
}
public long getM_id() {
return m_id;
}
public void setM_id(long m_id) {
this.m_id = m_id;
}
/*
* Constructor
* */
public DoctorDetails(long id,String title, String firstname,String lastname,
String email,String phonePrimary,String phoneSecondary,String address){
this.m_title = title;
this.m_firstname = firstname;
this.m_lastname = lastname;
this.m_email = email;
this.m_phonePrimary = phonePrimary;
this.m_phoneSecondary = phoneSecondary;
this.m_address = address;
this.m_id = id;
}
/*
* default constructor
* */
public DoctorDetails(){
}
/*
* returns
* for ex : Dr. Srivatsa Haridas or
* Mr. Srivatsa Haridas
* */
@Override
public String toString(){
return m_title + ". " + m_firstname + " " + m_lastname;
}
}
| 18.448276 | 87 | 0.711682 |
a449daa14d6f5547277a823f3063b3d315aabc69 | 7,874 | /**
* Copyright 2016 Symantec Corporation.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.srotya.tau.nucleus.api;
import static org.joda.time.format.ISODateTimeFormat.basicDate;
import static org.joda.time.format.ISODateTimeFormat.basicDateTime;
import static org.joda.time.format.ISODateTimeFormat.basicDateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.basicOrdinalDate;
import static org.joda.time.format.ISODateTimeFormat.basicOrdinalDateTime;
import static org.joda.time.format.ISODateTimeFormat.basicOrdinalDateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.basicTTime;
import static org.joda.time.format.ISODateTimeFormat.basicTTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.basicTime;
import static org.joda.time.format.ISODateTimeFormat.basicTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.basicWeekDate;
import static org.joda.time.format.ISODateTimeFormat.basicWeekDateTime;
import static org.joda.time.format.ISODateTimeFormat.basicWeekDateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.date;
import static org.joda.time.format.ISODateTimeFormat.dateElementParser;
import static org.joda.time.format.ISODateTimeFormat.dateHour;
import static org.joda.time.format.ISODateTimeFormat.dateHourMinute;
import static org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecond;
import static org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction;
import static org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondMillis;
import static org.joda.time.format.ISODateTimeFormat.dateOptionalTimeParser;
import static org.joda.time.format.ISODateTimeFormat.dateParser;
import static org.joda.time.format.ISODateTimeFormat.dateTime;
import static org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.dateTimeParser;
import static org.joda.time.format.ISODateTimeFormat.hour;
import static org.joda.time.format.ISODateTimeFormat.hourMinute;
import static org.joda.time.format.ISODateTimeFormat.hourMinuteSecond;
import static org.joda.time.format.ISODateTimeFormat.hourMinuteSecondFraction;
import static org.joda.time.format.ISODateTimeFormat.hourMinuteSecondMillis;
import static org.joda.time.format.ISODateTimeFormat.localDateOptionalTimeParser;
import static org.joda.time.format.ISODateTimeFormat.localDateParser;
import static org.joda.time.format.ISODateTimeFormat.localTimeParser;
import static org.joda.time.format.ISODateTimeFormat.ordinalDate;
import static org.joda.time.format.ISODateTimeFormat.ordinalDateTime;
import static org.joda.time.format.ISODateTimeFormat.ordinalDateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.tTime;
import static org.joda.time.format.ISODateTimeFormat.tTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.time;
import static org.joda.time.format.ISODateTimeFormat.timeElementParser;
import static org.joda.time.format.ISODateTimeFormat.timeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.timeParser;
import static org.joda.time.format.ISODateTimeFormat.weekDate;
import static org.joda.time.format.ISODateTimeFormat.weekDateTime;
import static org.joda.time.format.ISODateTimeFormat.weekDateTimeNoMillis;
import static org.joda.time.format.ISODateTimeFormat.weekyear;
import static org.joda.time.format.ISODateTimeFormat.weekyearWeek;
import static org.joda.time.format.ISODateTimeFormat.weekyearWeekDay;
import static org.joda.time.format.ISODateTimeFormat.year;
import static org.joda.time.format.ISODateTimeFormat.yearMonth;
import static org.joda.time.format.ISODateTimeFormat.yearMonthDay;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import com.google.gson.JsonObject;
import com.srotya.tau.interceptors.ValidationException;
import com.srotya.tau.interceptors.ValidationInterceptor;
import com.srotya.tau.wraith.Constants;
/**
* @author ambud_sharma
*/
public class DateInterceptor extends ValidationInterceptor {
public static final String TIMESTAMP = "@timestamp";
public static final String DATEFIELD = "dateinterceptor.datefield";
private final DateTimeParser[] formats = { basicDate().getParser(), // yyyyMMdd
basicDateTime().getParser(), // yyyyMMdd'T'HHmmss.SSSZ
basicDateTimeNoMillis().getParser(),
// yyyyMMdd'T'HHmmssZ
basicOrdinalDate().getParser(), // yyyyDDD
basicOrdinalDateTime().getParser(),
// yyyyDDD'T'HHmmss.SSSZ
basicOrdinalDateTimeNoMillis().getParser(), basicTime().getParser(), basicTimeNoMillis().getParser(),
basicTTime().getParser(), basicTTimeNoMillis().getParser(), basicWeekDate().getParser(),
basicWeekDateTime().getParser(), basicWeekDateTimeNoMillis().getParser(), date().getParser(),
dateElementParser().getParser(), dateHour().getParser(), dateHourMinute().getParser(),
dateHourMinuteSecond().getParser(), dateHourMinuteSecondFraction().getParser(),
dateHourMinuteSecondMillis().getParser(), dateOptionalTimeParser().getParser(), dateParser().getParser(),
dateTime().getParser(), dateTimeNoMillis().getParser(), dateTimeParser().getParser(), hour().getParser(),
hourMinute().getParser(), hourMinuteSecond().getParser(), hourMinuteSecondFraction().getParser(),
hourMinuteSecondMillis().getParser(), localDateOptionalTimeParser().getParser(),
localDateParser().getParser(), localTimeParser().getParser(), ordinalDate().getParser(),
ordinalDateTime().getParser(), ordinalDateTimeNoMillis().getParser(), time().getParser(),
timeElementParser().getParser(), timeNoMillis().getParser(), timeParser().getParser(), tTime().getParser(),
tTimeNoMillis().getParser(), weekDate().getParser(), weekDateTime().getParser(),
weekDateTimeNoMillis().getParser(), weekyear().getParser(), weekyearWeek().getParser(),
weekyearWeekDay().getParser(), year().getParser(), yearMonth().getParser(), yearMonthDay().getParser(),
DateTimeFormat.forPattern("yyyy.MM.dd").getParser() };
private DateTimeFormatter formatter;
private String dateField;
public DateInterceptor() {
formatter = new DateTimeFormatterBuilder().append(null, formats).toFormatter();
}
@Override
public void configure(Map<String, String> config) {
if (config.containsKey(DATEFIELD)) {
dateField = config.get(DATEFIELD);
} else {
dateField = TIMESTAMP;
}
}
@Override
public void validate(JsonObject event) throws ValidationException {
try {
DateTime ts = formatter.parseDateTime(event.get(dateField).getAsString());
event.remove(dateField);
event.addProperty(dateField, ts.getMillis());
if (next != null) {
next.validate(event);
}
} catch (Exception e) {
throw new ValidationException(e.getMessage());
}
}
@Override
public void validate(Map<String, Object> eventHeaders) throws ValidationException {
try {
DateTime ts = formatter.parseDateTime(eventHeaders.get(dateField).toString());
eventHeaders.remove(dateField);
eventHeaders.put(Constants.FIELD_TIMESTAMP, ts.getMillis());
if (next != null) {
next.validate(eventHeaders);
}
} catch (Exception e) {
e.printStackTrace();
throw new ValidationException(e.getMessage());
}
}
}
| 49.522013 | 110 | 0.800737 |
f9d932311d2ad65b41106e5d666ba5c49aed5dfe | 626 | package steps.marketData.expirations;
import cucumber.api.java.en.Then;
import entities.marketDataEntities.expirations.Date;
import helpers.ExpirationsHelper;
import utils.Share;
import static org.hamcrest.MatcherAssert.assertThat;
public class ExpirationsAssertionsSteps {
@Then("^I get the expiration dates related to the symbol$")
public void iGetTheExpirationDatesRelatedToTheSymbol(){
assertThat("The dates does not match",
ExpirationsHelper.validateDates(Share.getShare("expirations"),
((Date)Share.getShare("expirationsResponse")).getExpirations()));
}
}
| 32.947368 | 89 | 0.741214 |
086f9e98e5be42df440eca1f15d85676568fa06c | 11,482 | /*
* 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.nifi.lookup;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.controller.ControllerServiceInitializationContext;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.serialization.SimpleRecordSchema;
import org.apache.nifi.serialization.record.MapRecord;
import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.serialization.record.RecordField;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.util.file.monitor.LastModifiedMonitor;
import org.apache.nifi.util.file.monitor.SynchronousFileWatcher;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Tags({"lookup", "cache", "enrich", "join", "csv", "reloadable", "key", "value", "record"})
@CapabilityDescription(
"A reloadable CSV file-based lookup service. When the lookup key is found in the CSV file, " +
"the columns are returned as a Record. All returned fields will be strings."
)
public class CSVRecordLookupService extends AbstractControllerService implements RecordLookupService {
private static final String KEY = "key";
private static final Set<String> REQUIRED_KEYS = Collections.unmodifiableSet(Stream.of(KEY).collect(Collectors.toSet()));
public static final PropertyDescriptor CSV_FILE =
new PropertyDescriptor.Builder()
.name("csv-file")
.displayName("CSV File")
.description("A CSV file that will serve as the data source.")
.required(true)
.addValidator(StandardValidators.FILE_EXISTS_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
static final PropertyDescriptor CSV_FORMAT = new PropertyDescriptor.Builder()
.name("csv-format")
.displayName("CSV Format")
.description("Specifies which \"format\" the CSV data is in.")
.expressionLanguageSupported(ExpressionLanguageScope.NONE)
.allowableValues(Arrays.asList(CSVFormat.Predefined.values()).stream().map(e -> e.toString()).collect(Collectors.toSet()))
.defaultValue(CSVFormat.Predefined.Default.toString())
.required(true)
.build();
public static final PropertyDescriptor CHARSET =
new PropertyDescriptor.Builder()
.name("Character Set")
.description("The Character Encoding that is used to decode the CSV file.")
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
.defaultValue("UTF-8")
.required(true)
.build();
public static final PropertyDescriptor LOOKUP_KEY_COLUMN =
new PropertyDescriptor.Builder()
.name("lookup-key-column")
.displayName("Lookup Key Column")
.description("The field in the CSV file that will serve as the lookup key. " +
"This is the field that will be matched against the property specified in the lookup processor.")
.required(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor IGNORE_DUPLICATES =
new PropertyDescriptor.Builder()
.name("ignore-duplicates")
.displayName("Ignore Duplicates")
.description("Ignore duplicate keys for records in the CSV file.")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.allowableValues("true", "false")
.defaultValue("true")
.required(true)
.build();
private List<PropertyDescriptor> properties;
private volatile ConcurrentMap<String, Record> cache;
private volatile String csvFile;
private volatile CSVFormat csvFormat;
private volatile String charset;
private volatile String lookupKeyColumn;
private volatile boolean ignoreDuplicates;
private volatile SynchronousFileWatcher watcher;
private final ReentrantLock lock = new ReentrantLock();
private void loadCache() throws IllegalStateException, IOException {
if (lock.tryLock()) {
try {
final ComponentLog logger = getLogger();
if (logger.isDebugEnabled()) {
logger.debug("Loading lookup table from file: " + csvFile);
}
ConcurrentHashMap<String, Record> cache = new ConcurrentHashMap<>();
try (final InputStream is = new FileInputStream(csvFile)) {
try (final InputStreamReader reader = new InputStreamReader(is, charset)) {
final CSVParser records = csvFormat.withFirstRecordAsHeader().parse(reader);
RecordSchema lookupRecordSchema = null;
for (final CSVRecord record : records) {
final String key = record.get(lookupKeyColumn);
if (StringUtils.isBlank(key)) {
throw new IllegalStateException("Empty lookup key encountered in: " + csvFile);
} else if (!ignoreDuplicates && cache.containsKey(key)) {
throw new IllegalStateException("Duplicate lookup key encountered: " + key + " in " + csvFile);
} else if (ignoreDuplicates && cache.containsKey(key)) {
logger.warn("Duplicate lookup key encountered: {} in {}", new Object[]{key, csvFile});
}
// Put each key/value pair (except the lookup) into the properties
final Map<String, Object> properties = new HashMap<>();
record.toMap().forEach((k, v) -> {
if (!lookupKeyColumn.equals(k)) {
properties.put(k, v);
}
});
if (lookupRecordSchema == null) {
List<RecordField> recordFields = new ArrayList<>(properties.size());
properties.forEach((k, v) -> recordFields.add(new RecordField(k, RecordFieldType.STRING.getDataType())));
lookupRecordSchema = new SimpleRecordSchema(recordFields);
}
cache.put(key, new MapRecord(lookupRecordSchema, properties));
}
}
}
this.cache = cache;
if (cache.isEmpty()) {
logger.warn("Lookup table is empty after reading file: " + csvFile);
}
} finally {
lock.unlock();
}
}
}
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return properties;
}
@Override
protected void init(final ControllerServiceInitializationContext context) throws InitializationException {
final List<PropertyDescriptor> properties = new ArrayList<>();
properties.add(CSV_FILE);
properties.add(CSV_FORMAT);
properties.add(CHARSET);
properties.add(LOOKUP_KEY_COLUMN);
properties.add(IGNORE_DUPLICATES);
this.properties = Collections.unmodifiableList(properties);
}
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException, IOException {
this.csvFile = context.getProperty(CSV_FILE).evaluateAttributeExpressions().getValue();
this.csvFormat = CSVFormat.Predefined.valueOf(context.getProperty(CSV_FORMAT).getValue()).getFormat();
this.charset = context.getProperty(CHARSET).evaluateAttributeExpressions().getValue();
this.lookupKeyColumn = context.getProperty(LOOKUP_KEY_COLUMN).evaluateAttributeExpressions().getValue();
this.ignoreDuplicates = context.getProperty(IGNORE_DUPLICATES).asBoolean();
this.watcher = new SynchronousFileWatcher(Paths.get(csvFile), new LastModifiedMonitor(), 30000L);
try {
loadCache();
} catch (final IllegalStateException e) {
throw new InitializationException(e.getMessage(), e);
}
}
@Override
public Optional<Record> lookup(final Map<String, Object> coordinates) throws LookupFailureException {
if (coordinates == null) {
return Optional.empty();
}
final String key = (String)coordinates.get(KEY);
if (StringUtils.isBlank(key)) {
return Optional.empty();
}
try {
if (watcher.checkAndReset()) {
loadCache();
}
} catch (final IllegalStateException | IOException e) {
throw new LookupFailureException(e.getMessage(), e);
}
return Optional.ofNullable(cache.get(key));
}
@Override
public Set<String> getRequiredKeys() {
return REQUIRED_KEYS;
}
}
| 44.851563 | 137 | 0.64109 |
14b00d586da32d85cca492ddf28039d0dacc216c | 1,772 |
package net.runelite.client.plugins.zulrah.overlays;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Prayer;
import net.runelite.client.plugins.zulrah.ZulrahInstance;
import net.runelite.client.plugins.zulrah.ZulrahPlugin;
import net.runelite.client.plugins.zulrah.phase.ZulrahPhase;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.plugins.zulrah.ImagePanelComponent;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
@Slf4j
public class ZulrahPrayerOverlay extends Overlay
{
private final Client client;
private final ZulrahPlugin plugin;
@Inject
ZulrahPrayerOverlay(@Nullable Client client, ZulrahPlugin plugin)
{
setPosition(OverlayPosition.BOTTOM_RIGHT);
setPriority(OverlayPriority.MED);
this.client = client;
this.plugin = plugin;
}
@Override
public Dimension render(Graphics2D graphics)
{
ZulrahInstance instance = plugin.getInstance();
if (instance == null)
{
return null;
}
ZulrahPhase currentPhase = instance.getPhase();
if (currentPhase == null)
{
return null;
}
Prayer prayer = currentPhase.isJad() ? null : currentPhase.getPrayer();
if (prayer == null)
{
return null;
}
BufferedImage prayerImage = ZulrahImageManager.getProtectionPrayerBufferedImage(prayer);
ImagePanelComponent imagePanelComponent = new ImagePanelComponent();
imagePanelComponent.setTitle((!client.isPrayerActive(prayer)) ? "Switch!" : "Prayer");
imagePanelComponent.setImage(prayerImage);
return imagePanelComponent.render(graphics);
}
}
| 27.6875 | 90 | 0.784989 |
2ef0371017f91dd135bd48fdb56b6eaee69da263 | 2,530 | /*
* Copyright 2011 Chad Retz
*
* 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.gwtnode.dev.debug.message;
import org.gwtnode.core.node.buffer.Buffer;
import org.gwtnode.dev.debug.BufferBuilder;
import org.gwtnode.dev.debug.BufferStream;
/**
* @author Chad Retz
*/
public class InvokeFromClientMessage extends InvokeMessage {
private final int methodDispatchId;
public InvokeFromClientMessage(int methodDispatchId, Value<?> thisValue,
Value<?>... argValues) {
super(thisValue, argValues);
this.methodDispatchId = methodDispatchId;
length += 4;
}
public InvokeFromClientMessage(BufferStream stream) {
super();
methodDispatchId = stream.readInt();
length += 4;
initThisAndArgs(stream);
}
public int getMethodDispatchId() {
return methodDispatchId;
}
@Override
public String toString() {
return toString(new StringBuilder()).
append(", methodDispatchId: ").
append(methodDispatchId).toString();
}
@Override
public Buffer toBuffer() {
return super.toBuffer(new BufferBuilder().
append(type).
append(methodDispatchId)).toBuffer();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + methodDispatchId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
InvokeFromClientMessage other = (InvokeFromClientMessage) obj;
if (methodDispatchId != other.methodDispatchId) {
return false;
}
return true;
}
}
| 29.08046 | 81 | 0.603162 |
0ca7a59a38a92c4bdcd1ae62fa110fd7f40a8087 | 604 | package net.shmin.auth.permission.model;
import java.util.Set;
/**
* Created by benjamin on 2017/1/4.
* 用户组
*/
public class Group<T, R> {
private T id;
private Set<R> roles;
private T parentId;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
public Set<R> getRoles() {
return roles;
}
public void setRoles(Set<R> roles) {
this.roles = roles;
}
public T getParentId() {
return parentId;
}
public void setParentId(T parentId) {
this.parentId = parentId;
}
}
| 14.731707 | 41 | 0.557947 |
0d13d54d15bbb42b1d43965d407c0afba6665ecb | 8,172 | package core.component;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.internal.WrapsElement;
import core.driver.WebDriverManager;
import core.pageobject.IgnoreInit;
import core.util.StringUtils;
/**
* This is base element extended from WebElement. This is wrapper around
* WebElement. All user defined components would extend this class. This class
* would contain all common methods applicable to all elements
*
* @author prat3ik
*
*/
public class BaseElement implements WebElement, WrapsElement {
@IgnoreInit
protected WebElement el = null;
protected String fieldName = "";
protected Integer explicitWait;
public BaseElement(final String css) {
this.el = this.getDriver().findElement(By.cssSelector(css));
}
public BaseElement(final WebElement el) {
this.el = el;
}
protected WebDriver getDriver() {
return WebDriverManager.getThreadLocalDriver();
}
protected Actions getActionsDriver() {
return new Actions(this.getDriver());
}
public void changeStyleToDisplayHidden() {
final JavascriptExecutor js = (JavascriptExecutor) this.getDriver();
js.executeScript("arguments[0].style.display='none';", this.el);
}
public void changeStyleToDisplay() {
final JavascriptExecutor js = (JavascriptExecutor) this.getDriver();
js.executeScript("arguments[0].style.display='block';", this.el);
}
@Override
public void clear() {
this.el.clear();
}
@Override
public void click() {
this.scrollIntoView();
this.el.click();
}
/**
* This method implements double click functionality on element
*
*/
public void doubleClick() {
this.getActionsDriver().doubleClick(this.el).build().perform();
}
/**
* This method would drag element to target element
*
* @param target
* : target element for drop
*/
public void dragAndDrop(final BaseElement target) {
this.getActionsDriver().clickAndHold(this.el).moveToElement(target.el).release(target.el).build().perform();
}
@Override
public WebElement findElement(final By arg0) {
return this.el.findElement(arg0);
}
@Override
public List<WebElement> findElements(final By arg0) {
return this.el.findElements(arg0);
}
@Override
public String getAttribute(final String arg0) {
return this.el.getAttribute(arg0);
}
@Override
public String getCssValue(final String arg0) {
return this.el.getCssValue(arg0);
}
/**
* This will return font family for an element
*
* @return Font Family used in element
*/
public String getFontFamily() {
String font = this.getCssValue("font-family");
if (font.startsWith("'")) {
font = font.substring(1, font.length() - 1);
}
return font;
}
/**
* This will return font size for element
*
* @return font size of element in px unit
*/
public String getFontSize() {
return this.getCssValue("font-size");
}
@Override
public Point getLocation() {
return this.el.getLocation();
}
/**
* Returns next sibling relative to this element having specified tag name
*
* @param tag
* - Tag name of element
* @return Next sibling having specified tag name
*/
public BaseElement getNextSibling(final String tagXpath) {
return new BaseElement(this.findElement(By.xpath("./following-sibling::" + tagXpath)));
}
@Override
public Dimension getSize() {
return this.el.getSize();
}
@Override
public String getTagName() {
return this.el.getTagName();
}
@Override
public String getText() {
return this.el.getText();
}
@Override
public WebElement getWrappedElement() {
return this.el;
}
@Override
public boolean isDisplayed() {
return this.isElementPresent() && this.el.isDisplayed();
}
/**
* This method checks if element is active or not
*
* @return true if element has active class, false otherwise
*/
public boolean isElementActive() {
return this.el.getAttribute("class").contains("active");
}
/**
* This method checks if element is disabled or not
*
* @return true if element has disabled class, false otherwise
*/
public boolean isElementDisabled() {
return this.el.getAttribute("class").contains("disabled") || "true".equals(this.el.getAttribute("disabled"));
}
/**
* This method checks if element is present or not
*
* @return true if element is present, false otherwise
*/
public boolean isElementPresent() {
boolean isPresent = false;
try {
this.el.isDisplayed();
isPresent = true;
} catch (final Exception e) {
isPresent = false;
}
return isPresent;
}
/**
* This method checks if element is selected or not
*
* @return true if element has selected class, false otherwise
*/
public boolean isElementSelected() {
return this.el.getAttribute("class").contains("selected");
}
@Override
public boolean isEnabled() {
return this.el.isEnabled();
}
@Override
public boolean isSelected() {
return this.el.isSelected();
}
public BaseElement getParentElement() {
return new BaseElement(this.el.findElement(By.xpath("..")));
}
/**
* This method moves mouse to element
*
*/
public void moveTo() {
this.getActionsDriver().moveToElement(this.el).build().perform();
}
/**
* Sometimes element is not visible to user as page is too long. In such
* case, it is required to scroll up/down to element so it become visible in
* page. This method implements this functionality to scroll to make element
* visible in view
*
*/
public void scrollIntoView() {
((JavascriptExecutor) this.getDriver()).executeScript("arguments[0].scrollIntoView(false);", this.el);
}
@Override
public void sendKeys(final CharSequence... arg0) {
this.el.clear();
this.el.sendKeys(arg0);
}
// This method was needed since we encountered a few webelements which don't
// allow clear operation and it results in exception.
public void sendKeysWithoutClear(final CharSequence... arg0) {
this.el.sendKeys(arg0);
}
@Override
public void submit() {
this.el.submit();
}
public String getValue() {
return this.el.getAttribute("value");
}
@Override
public <X> X getScreenshotAs(OutputType<X> arg0) throws WebDriverException {
return this.el.getScreenshotAs(arg0);
}
@Override
public Rectangle getRect() {
return this.el.getRect();
}
public void removeEventHandler(String event) {
final JavascriptExecutor js = (JavascriptExecutor) this.getDriver();
js.executeScript("angular.element(arguments[0]).unbind('" + event + "');", this.el);
}
public void clickUsingJavaScript() {
final JavascriptExecutor js = (JavascriptExecutor) this.getDriver();
js.executeScript("angular.element(arguments[0]).click();", this.el);
}
public void setExplicitWait(Integer explicitWait) {
this.explicitWait = explicitWait;
}
public void setElementName(String elementName) {
this.fieldName = elementName;
}
public void moveToElementAndClick() {
this.getActionsDriver().moveToElement(el).click().build().perform();
}
public boolean isAttributePresent(String attribute) {
boolean result = false;
try {
String value = this.getAttribute(attribute);
if (!value.isEmpty()) {
result = true;
}
} catch (Exception e) {
// this.logger.error(e);
}
return result;
}
public void hover() {
scrollIntoView();
getActionsDriver().moveToElement(el).build().perform();
}
public void hover(int offsetX, int offsetY) {
scrollIntoView();
getActionsDriver().moveToElement(el, offsetX, offsetY).build().perform();
}
private final static String PREVENT_DEFAULT = "function(e) { e.preventDefault() }";
public void preventDefault(String event) {
final JavascriptExecutor js = (JavascriptExecutor) getDriver();
// using jQuery#one so that it only works for one time
js.executeScript("angular.element(arguments[0]).one('" + event + "'," + PREVENT_DEFAULT + ");", el);
}
}
| 24.177515 | 111 | 0.712433 |
7628170645273cfa70c7ecb4026ab8d3e257ef4f | 1,882 | package com.tterrag.k9.util;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import reactor.core.publisher.Flux;
import reactor.core.publisher.GroupedFlux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
public class Monos {
public static <A, B, C> Function<Mono<A>, Mono<C>> flatZipWith(Mono<? extends B> b, BiFunction<A, B, Mono<C>> combinator) {
return in -> in.zipWith(b, combinator).flatMap(Function.identity());
}
public static <A, B, C> Function<Mono<A>, Mono<C>> flatZipWhen(Function<A, Mono<? extends B>> rightGenerator, BiFunction<A, B, Mono<C>> combinator) {
return in -> in.zipWhen(rightGenerator, combinator).flatMap(Function.identity());
}
public static <T> Function<Mono<T>, Mono<Optional<T>>> asOptional() {
return in -> in.map(Optional::of).defaultIfEmpty(Optional.empty());
}
public static <T, R> Function<Mono<T>, Mono<R>> mapOptional(Function<T, Optional<R>> conv) {
return in -> in.flatMap(t -> Mono.justOrEmpty(conv.apply(t)));
}
public static <A, B, C> Function<Mono<A>, Mono<C>> zipOptional(Optional<? extends B> b, BiFunction<A, B, C> combinator) {
return in -> in.zipWith(Mono.justOrEmpty(b), combinator);
}
public static <T> Function<Mono<T>, Mono<T>> precondition(Predicate<T> validator, Supplier<? extends Throwable> exceptionFactory) {
return in -> in.handle((t, sink) -> { if (validator.test(t)) sink.next(t); else sink.error(exceptionFactory.get()); });
}
public static <T, R, K> Function<Mono<T>, Flux<GroupedFlux<K, R>>> groupWith(Flux<K> keys, BiFunction<K, T, Mono<? extends R>> valueMapper) {
return in -> in.flux().transform(Fluxes.groupWith(keys, valueMapper));
}
}
| 42.772727 | 153 | 0.68119 |
8e80ebd77875fc4bfef9a9b300d09c47d18901bf | 295 | package com.argentumjk.client.utils;
/**
* Excepción que se lanza al querer leer y no hay datos disponibles en un buffer
*/
public class NotEnoughDataException extends Exception {
public NotEnoughDataException() {
super("No hay suficientes datos en el buffer para leer");
}
}
| 26.818182 | 80 | 0.728814 |
9cb34a12dc6bd4277c029942cad0992ddf1a8a5f | 135,822 | /*
* Copyright 2015 Midokura SARL
*
* 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.midonet.cluster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.midonet.cluster.data.AdRoute;
import org.midonet.cluster.data.BGP;
import org.midonet.cluster.data.Bridge;
import org.midonet.cluster.data.Chain;
import org.midonet.cluster.data.Converter;
import org.midonet.cluster.data.HostVersion;
import org.midonet.cluster.data.IpAddrGroup;
import org.midonet.cluster.data.Port;
import org.midonet.cluster.data.PortGroup;
import org.midonet.cluster.data.Route;
import org.midonet.cluster.data.Router;
import org.midonet.cluster.data.Rule;
import org.midonet.cluster.data.SystemState;
import org.midonet.cluster.data.TraceRequest;
import org.midonet.cluster.data.TunnelZone;
import org.midonet.cluster.data.VTEP;
import org.midonet.cluster.data.VtepBinding;
import org.midonet.cluster.data.WriteVersion;
import org.midonet.cluster.data.dhcp.Subnet;
import org.midonet.cluster.data.dhcp.Subnet6;
import org.midonet.cluster.data.dhcp.V6Host;
import org.midonet.cluster.data.host.Host;
import org.midonet.cluster.data.host.Interface;
import org.midonet.cluster.data.host.VirtualPortMapping;
import org.midonet.cluster.data.l4lb.HealthMonitor;
import org.midonet.cluster.data.l4lb.LoadBalancer;
import org.midonet.cluster.data.l4lb.Pool;
import org.midonet.cluster.data.l4lb.PoolMember;
import org.midonet.cluster.data.l4lb.VIP;
import org.midonet.cluster.data.ports.BridgePort;
import org.midonet.cluster.data.ports.VlanMacPort;
import org.midonet.cluster.data.ports.VxLanPort;
import org.midonet.cluster.data.rules.TraceRule;
import org.midonet.midolman.SystemDataProvider;
import org.midonet.midolman.cluster.zookeeper.ZkConnectionProvider;
import org.midonet.midolman.host.state.HostDirectory;
import org.midonet.midolman.host.state.HostZkManager;
import org.midonet.midolman.rules.RuleList;
import org.midonet.midolman.serialization.SerializationException;
import org.midonet.midolman.serialization.Serializer;
import org.midonet.midolman.state.Directory;
import org.midonet.midolman.state.DirectoryCallback;
import org.midonet.midolman.state.InvalidStateOperationException;
import org.midonet.midolman.state.Ip4ToMacReplicatedMap;
import org.midonet.midolman.state.MacPortMap;
import org.midonet.midolman.state.NoStatePathException;
import org.midonet.midolman.state.PathBuilder;
import org.midonet.midolman.state.PoolHealthMonitorMappingStatus;
import org.midonet.midolman.state.PortConfig;
import org.midonet.midolman.state.PortConfigCache;
import org.midonet.midolman.state.PortDirectory.VxLanPortConfig;
import org.midonet.midolman.state.StateAccessException;
import org.midonet.midolman.state.ZkLeaderElectionWatcher;
import org.midonet.midolman.state.ZkManager;
import org.midonet.midolman.state.ZkUtil;
import org.midonet.midolman.state.ZookeeperConnectionWatcher;
import org.midonet.midolman.state.l4lb.LBStatus;
import org.midonet.midolman.state.l4lb.MappingStatusException;
import org.midonet.midolman.state.l4lb.MappingViolationException;
import org.midonet.midolman.state.zkManagers.AdRouteZkManager;
import org.midonet.midolman.state.zkManagers.BgpZkManager;
import org.midonet.midolman.state.zkManagers.BridgeDhcpV6ZkManager;
import org.midonet.midolman.state.zkManagers.BridgeDhcpZkManager;
import org.midonet.midolman.state.zkManagers.BridgeZkManager;
import org.midonet.midolman.state.zkManagers.BridgeZkManager.BridgeConfig;
import org.midonet.midolman.state.zkManagers.ChainZkManager;
import org.midonet.midolman.state.zkManagers.ConfigGetter;
import org.midonet.midolman.state.zkManagers.HealthMonitorZkManager;
import org.midonet.midolman.state.zkManagers.IpAddrGroupZkManager;
import org.midonet.midolman.state.zkManagers.LoadBalancerZkManager;
import org.midonet.midolman.state.zkManagers.PoolHealthMonitorZkManager.PoolHealthMonitorConfig;
import org.midonet.midolman.state.zkManagers.PoolHealthMonitorZkManager.PoolHealthMonitorConfig.HealthMonitorConfigWithId;
import org.midonet.midolman.state.zkManagers.PoolHealthMonitorZkManager.PoolHealthMonitorConfig.LoadBalancerConfigWithId;
import org.midonet.midolman.state.zkManagers.PoolHealthMonitorZkManager.PoolHealthMonitorConfig.PoolMemberConfigWithId;
import org.midonet.midolman.state.zkManagers.PoolHealthMonitorZkManager.PoolHealthMonitorConfig.VipConfigWithId;
import org.midonet.midolman.state.zkManagers.PoolMemberZkManager;
import org.midonet.midolman.state.zkManagers.PoolZkManager;
import org.midonet.midolman.state.zkManagers.PortGroupZkManager;
import org.midonet.midolman.state.zkManagers.PortZkManager;
import org.midonet.midolman.state.zkManagers.RouteZkManager;
import org.midonet.midolman.state.zkManagers.RouterZkManager;
import org.midonet.midolman.state.zkManagers.RuleZkManager;
import org.midonet.midolman.state.zkManagers.TenantZkManager;
import org.midonet.midolman.state.zkManagers.TraceRequestZkManager;
import org.midonet.midolman.state.zkManagers.TunnelZoneZkManager;
import org.midonet.midolman.state.zkManagers.VipZkManager;
import org.midonet.midolman.state.zkManagers.VtepZkManager;
import org.midonet.packets.IPv4Addr;
import org.midonet.packets.IPv4Subnet;
import org.midonet.packets.IPv6Subnet;
import org.midonet.packets.MAC;
import org.midonet.util.eventloop.Reactor;
import org.midonet.util.functors.CollectionFunctors;
import org.midonet.util.functors.Functor;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.midonet.cluster.data.Rule.RuleIndexOutOfBoundsException;
@SuppressWarnings("unused")
public class LocalDataClientImpl implements DataClient {
@Inject
private TenantZkManager tenantZkManager;
@Inject
private BridgeDhcpZkManager dhcpZkManager;
@Inject
private BridgeDhcpV6ZkManager dhcpV6ZkManager;
@Inject
private BgpZkManager bgpZkManager;
@Inject
private AdRouteZkManager adRouteZkManager;
@Inject
private BridgeZkManager bridgeZkManager;
@Inject
private ChainZkManager chainZkManager;
@Inject
private RouteZkManager routeZkManager;
@Inject
private RouterZkManager routerZkManager;
@Inject
private RuleZkManager ruleZkManager;
@Inject
private PortZkManager portZkManager;
@Inject
private PortConfigCache portCache;
@Inject
private RouteZkManager routeMgr;
@Inject
private PortGroupZkManager portGroupZkManager;
@Inject
private HostZkManager hostZkManager;
@Inject
private LoadBalancerZkManager loadBalancerZkManager;
@Inject
private HealthMonitorZkManager healthMonitorZkManager;
@Inject
private PoolMemberZkManager poolMemberZkManager;
@Inject
private PoolZkManager poolZkManager;
@Inject
private VipZkManager vipZkManager;
@Inject
private TunnelZoneZkManager zonesZkManager;
@Inject
private ZkManager zkManager;
@Inject
private PathBuilder pathBuilder;
@Inject
private ClusterRouterManager routerManager;
@Inject
private ClusterBridgeManager bridgeManager;
@Inject
private Serializer serializer;
@Inject
private SystemDataProvider systemDataProvider;
@Inject
private IpAddrGroupZkManager ipAddrGroupZkManager;
@Inject
private TraceRequestZkManager traceReqZkManager;
@Inject
private VtepZkManager vtepZkManager;
@Inject
@Named(ZkConnectionProvider.DIRECTORY_REACTOR_TAG)
private Reactor reactor;
private final static Logger log =
LoggerFactory.getLogger(LocalDataClientImpl.class);
@Override
public @CheckForNull AdRoute adRoutesGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
AdRoute adRoute = null;
if (adRouteZkManager.exists(id)) {
adRoute = Converter.fromAdRouteConfig(adRouteZkManager.get(id));
adRoute.setId(id);
}
log.debug("Exiting: adRoute={}", adRoute);
return adRoute;
}
@Override
public void adRoutesDelete(UUID id)
throws StateAccessException, SerializationException {
adRouteZkManager.delete(id);
}
@Override
public UUID adRoutesCreate(@Nonnull AdRoute adRoute)
throws StateAccessException, SerializationException {
return adRouteZkManager.create(Converter.toAdRouteConfig(adRoute));
}
@Override
public List<AdRoute> adRoutesFindByBgp(@Nonnull UUID bgpId)
throws StateAccessException, SerializationException {
List<UUID> adRouteIds = adRouteZkManager.list(bgpId);
List<AdRoute> adRoutes = new ArrayList<>();
for (UUID adRouteId : adRouteIds) {
adRoutes.add(adRoutesGet(adRouteId));
}
return adRoutes;
}
@Override
public void bgpSetStatus(@Nonnull UUID id, @Nonnull String status)
throws StateAccessException, SerializationException {
bgpZkManager.setStatus(id, status);
}
@Override
public @CheckForNull BGP bgpGet(@Nonnull UUID id)
throws StateAccessException, SerializationException {
return new BGP(id, bgpZkManager.get(id)).setStatus(bgpZkManager.getStatus(id));
}
@Override
public void bgpDelete(UUID id)
throws StateAccessException, SerializationException {
bgpZkManager.delete(id);
}
@Override
public UUID bgpCreate(@Nonnull BGP bgp)
throws StateAccessException, SerializationException {
return bgpZkManager.create(bgp);
}
@Override
public List<BGP> bgpFindByPort(UUID portId)
throws StateAccessException, SerializationException {
List<UUID> bgpIds = bgpZkManager.list(portId);
List<BGP> bgps = new ArrayList<>();
for (UUID bgpId : bgpIds) {
bgps.add(bgpGet(bgpId));
}
return bgps;
}
public List<Bridge> bridgesFindByTenant(String tenantId)
throws StateAccessException, SerializationException {
log.debug("bridgesFindByTenant entered: tenantId={}", tenantId);
List<Bridge> bridges = bridgesGetAll();
for (Iterator<Bridge> it = bridges.iterator(); it.hasNext();) {
if (!it.next().hasTenantId(tenantId)) {
it.remove();
}
}
log.debug("bridgesFindByTenant exiting: {} bridges found", bridges.size());
return bridges;
}
/**
* Returns a list of all MAC-port mappings for the specified bridge.
* @throws StateAccessException
*/
@Override
public List<VlanMacPort> bridgeGetMacPorts(@Nonnull UUID bridgeId)
throws StateAccessException {
// Get entries for the untagged VLAN.
List<VlanMacPort> allPorts = new LinkedList<>();
allPorts.addAll(bridgeGetMacPorts(bridgeId, Bridge.UNTAGGED_VLAN_ID));
// Get entries for the other VLANs.
short[] vlanIds = bridgeZkManager.getVlanIds(bridgeId);
for (short vlanId : vlanIds)
allPorts.addAll(bridgeGetMacPorts(bridgeId, vlanId));
return allPorts;
}
/**
* Gets MAC-port mappings for the specified bridge and VLAN.
* @param bridgeId Bridge whose MAC-port mappings are requested.
* @param vlanId VLAN whose MAC-port mappings are requested. The value
* Bridge.UNTAGGED_VLAN_ID indicates the untagged VLAN.
* @return List of MAC-port mappings.
* @throws StateAccessException
*/
@Override
public List<VlanMacPort> bridgeGetMacPorts(
@Nonnull UUID bridgeId, short vlanId)
throws StateAccessException {
Map<MAC, UUID> portsMap = MacPortMap.getAsMap(
bridgeZkManager.getMacPortMapDirectory(bridgeId, vlanId));
List<VlanMacPort> ports = new ArrayList<>(portsMap.size());
for (Map.Entry<MAC, UUID> e : portsMap.entrySet()) {
ports.add(new VlanMacPort(e.getKey(), e.getValue(), vlanId));
}
return ports;
}
@Override
public void ensureBridgeHasVlanDirectory(@Nonnull UUID bridgeId)
throws StateAccessException {
bridgeZkManager.ensureBridgeHasVlanDirectory(bridgeId);
}
@Override
public boolean bridgeHasMacTable(@Nonnull UUID bridgeId, short vlanId)
throws StateAccessException {
return bridgeZkManager.hasVlanMacTable(bridgeId, vlanId);
}
@Override
public MacPortMap bridgeGetMacTable(
@Nonnull UUID bridgeId, short vlanId, boolean ephemeral)
throws StateAccessException {
return new MacPortMap(
bridgeZkManager.getMacPortMapDirectory(bridgeId, vlanId),
ephemeral);
}
@Override
public void bridgeAddMacPort(@Nonnull UUID bridgeId, short vlanId,
@Nonnull MAC mac, @Nonnull UUID portId)
throws StateAccessException {
MacPortMap.addPersistentEntry(
bridgeZkManager.getMacPortMapDirectory(bridgeId, vlanId), mac, portId);
}
@Override
public boolean bridgeHasMacPort(@Nonnull UUID bridgeId, Short vlanId,
@Nonnull MAC mac, @Nonnull UUID portId)
throws StateAccessException {
return MacPortMap.hasPersistentEntry(
bridgeZkManager.getMacPortMapDirectory(bridgeId, vlanId), mac, portId);
}
@Override
public void bridgeDeleteMacPort(@Nonnull UUID bridgeId, Short vlanId,
@Nonnull MAC mac, @Nonnull UUID portId)
throws StateAccessException {
MacPortMap.deleteEntry(
bridgeZkManager.getMacPortMapDirectory(bridgeId, vlanId),
mac, portId);
}
@Override
public Ip4ToMacReplicatedMap bridgeGetArpTable(@Nonnull UUID bridgeId)
throws StateAccessException {
return new Ip4ToMacReplicatedMap(
bridgeZkManager.getIP4MacMapDirectory(bridgeId));
}
@Override
public Map<IPv4Addr, MAC> bridgeGetIP4MacPairs(@Nonnull UUID bridgeId)
throws StateAccessException {
return Ip4ToMacReplicatedMap.getAsMap(
bridgeZkManager.getIP4MacMapDirectory(bridgeId));
}
@Override
public void bridgeAddIp4Mac(
@Nonnull UUID bridgeId, @Nonnull IPv4Addr ip4, @Nonnull MAC mac)
throws StateAccessException {
// TODO: potential race conditions
// The following code fixes the unobvious behavior of
// replicated maps, but is still subject to potential race conditions
// See MN-2637
Directory dir = bridgeZkManager.getIP4MacMapDirectory(bridgeId);
if (Ip4ToMacReplicatedMap.hasPersistentEntry(dir, ip4, mac)) {
return;
}
MAC oldMac = Ip4ToMacReplicatedMap.getEntry(dir, ip4);
if (oldMac != null) {
Ip4ToMacReplicatedMap.deleteEntry(dir, ip4, oldMac);
}
Ip4ToMacReplicatedMap.addPersistentEntry(
bridgeZkManager.getIP4MacMapDirectory(bridgeId), ip4, mac);
}
@Override
public void bridgeAddLearnedIp4Mac(
@Nonnull UUID bridgeId, @Nonnull IPv4Addr ip4, @Nonnull MAC mac)
throws StateAccessException {
// TODO: potential race conditions (see MN-2637)
Directory dir = bridgeZkManager.getIP4MacMapDirectory(bridgeId);
MAC oldMac = Ip4ToMacReplicatedMap.getEntry(dir, ip4);
if (oldMac != null) {
if (mac.equals(oldMac) ||
Ip4ToMacReplicatedMap.hasPersistentEntry(dir, ip4, oldMac)) {
return;
}
Ip4ToMacReplicatedMap.deleteEntry(dir, ip4, oldMac);
}
Ip4ToMacReplicatedMap.addLearnedEntry(
bridgeZkManager.getIP4MacMapDirectory(bridgeId), ip4, mac);
}
@Override
public boolean bridgeHasIP4MacPair(@Nonnull UUID bridgeId,
@Nonnull IPv4Addr ip, @Nonnull MAC mac)
throws StateAccessException {
Directory dir = bridgeZkManager.getIP4MacMapDirectory(bridgeId);
return Ip4ToMacReplicatedMap.hasPersistentEntry(dir, ip, mac) ||
Ip4ToMacReplicatedMap.hasLearnedEntry(dir, ip, mac);
}
@Override
public void bridgeDeleteIp4Mac(
@Nonnull UUID bridgeId, @Nonnull IPv4Addr ip4, @Nonnull MAC mac)
throws StateAccessException {
Ip4ToMacReplicatedMap.deleteEntry(
bridgeZkManager.getIP4MacMapDirectory(bridgeId), ip4, mac);
}
@Override
public void bridgeDeleteLearnedIp4Mac(
@Nonnull UUID bridgeId, @Nonnull IPv4Addr ip4, @Nonnull MAC mac)
throws StateAccessException {
Ip4ToMacReplicatedMap.deleteLearnedEntry(
bridgeZkManager.getIP4MacMapDirectory(bridgeId), ip4, mac);
}
@Override
public Set<IPv4Addr> bridgeGetIp4ByMac(
@Nonnull UUID bridgeId, @Nonnull MAC mac)
throws StateAccessException {
return Ip4ToMacReplicatedMap.getByMacValue(
bridgeZkManager.getIP4MacMapDirectory(bridgeId), mac);
}
@Override
public UUID bridgesCreate(@Nonnull Bridge bridge)
throws StateAccessException, SerializationException {
log.debug("bridgesCreate entered: bridge={}", bridge);
if (bridge.getId() == null) {
bridge.setId(UUID.randomUUID());
}
BridgeZkManager.BridgeConfig bridgeConfig = Converter.toBridgeConfig(
bridge);
List<Op> ops =
bridgeZkManager.prepareBridgeCreate(bridge.getId(),
bridgeConfig);
// Create the top level directories for
String tenantId = bridge.getProperty(Bridge.Property.tenant_id);
if (!Strings.isNullOrEmpty(tenantId)) {
ops.addAll(tenantZkManager.prepareCreate(tenantId));
}
zkManager.multi(ops);
log.debug("bridgesCreate exiting: bridge={}", bridge);
return bridge.getId();
}
@Override
public void bridgesUpdate(@Nonnull Bridge b)
throws StateAccessException, SerializationException {
List<Op> ops = new ArrayList<>();
// Get the original data
Bridge oldBridge = bridgesGet(b.getId());
BridgeZkManager.BridgeConfig bridgeConfig = Converter.toBridgeConfig(b);
// Update the config
ops.addAll(bridgeZkManager.prepareUpdate(b.getId(), bridgeConfig));
if (!ops.isEmpty()) {
zkManager.multi(ops);
}
}
@Override
public List<Bridge> bridgesGetAll() throws StateAccessException,
SerializationException {
log.debug("bridgesGetAll entered");
List<Bridge> bridges = new ArrayList<>();
for (UUID id :
bridgeZkManager.getUuidList(pathBuilder.getBridgesPath())) {
Bridge bridge = bridgesGet(id);
if (bridge != null) {
bridges.add(bridge);
}
}
log.debug("bridgesGetAll exiting: {} bridges found", bridges.size());
return bridges;
}
@Override
public EntityIdSetMonitor<UUID> bridgesGetUuidSetMonitor(
ZookeeperConnectionWatcher zkConnection)
throws StateAccessException {
return new EntityIdSetMonitor<>(bridgeZkManager, zkConnection);
}
@Override
public boolean bridgeExists(UUID id) throws StateAccessException {
return bridgeZkManager.exists(id);
}
@Override
public @CheckForNull Bridge bridgesGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
Bridge bridge = null;
if (bridgeZkManager.exists(id)) {
BridgeConfig bridgeCfg = bridgeZkManager.get(id);
if (bridgeCfg.vxLanPortId != null) {
log.info("Migrating legacy vxlanPortId property to " +
"vxlanPortIds on bridge {}", id);
if (!bridgeCfg.vxLanPortIds.contains(bridgeCfg.vxLanPortId)) {
bridgeCfg.vxLanPortIds.add(0, bridgeCfg.vxLanPortId);
}
bridgeCfg.vxLanPortId = null;
bridgeZkManager.update(id, bridgeCfg);
bridgeCfg = bridgeZkManager.get(id);
}
bridge = Converter.fromBridgeConfig(bridgeCfg);
bridge.setId(id);
}
log.debug("Exiting: bridge={}", bridge);
return bridge;
}
@Override
public void bridgesDelete(UUID id)
throws StateAccessException, SerializationException {
Bridge bridge = bridgesGet(id);
if (bridge == null) {
return;
}
List<Op> ops = bridgeZkManager.prepareBridgeDelete(id);
zkManager.multi(ops);
}
@Override
public List<Chain> chainsGetAll() throws StateAccessException,
SerializationException {
log.debug("chainsGetAll entered");
List<Chain> chains = new ArrayList<>();
String path = pathBuilder.getChainsPath();
if (zkManager.exists(path)) {
Set<String> chainIds = zkManager.getChildren(path);
for (String id : chainIds) {
Chain chain = chainsGet(UUID.fromString(id));
if (chain != null) {
chains.add(chain);
}
}
}
log.debug("chainsGetAll exiting: {} chains found", chains.size());
return chains;
}
@Override
public @CheckForNull Chain chainsGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
Chain chain = null;
if (chainZkManager.exists(id)) {
chain = Converter.fromChainConfig(chainZkManager.get(id));
chain.setId(id);
}
log.debug("Exiting: chain={}", chain);
return chain;
}
@Override
public void chainsDelete(UUID id)
throws StateAccessException, SerializationException {
Chain chain = chainsGet(id);
if (chain == null) {
return;
}
List<Op> ops = chainZkManager.prepareDelete(id);
zkManager.multi(ops);
}
private UUID prepareChainsCreate(@Nonnull Chain chain, List<Op> ops)
throws StateAccessException, SerializationException {
if (chain.getId() == null) {
chain.setId(UUID.randomUUID());
}
ChainZkManager.ChainConfig chainConfig =
Converter.toChainConfig(chain);
ops.addAll(chainZkManager.prepareCreate(chain.getId(), chainConfig));
// Create the top level directories for
String tenantId = chain.getProperty(Chain.Property.tenant_id);
if (!Strings.isNullOrEmpty(tenantId)) {
ops.addAll(tenantZkManager.prepareCreate(tenantId));
}
return chain.getId();
}
@Override
public UUID chainsCreate(@Nonnull Chain chain)
throws StateAccessException, SerializationException {
log.debug("chainsCreate entered: chain={}", chain);
List<Op> ops = new ArrayList<Op>();
UUID chainId = prepareChainsCreate(chain, ops);
zkManager.multi(ops);
log.debug("chainsCreate exiting: chain={}", chain);
return chainId;
}
@Override
public UUID tunnelZonesCreate(@Nonnull TunnelZone zone)
throws StateAccessException, SerializationException {
return zonesZkManager.createZone(zone, null);
}
@Override
public void tunnelZonesDelete(UUID uuid)
throws StateAccessException {
zonesZkManager.deleteZone(uuid);
}
@Override
public boolean tunnelZonesExists(UUID uuid) throws StateAccessException {
return zonesZkManager.exists(uuid);
}
@Override
public @CheckForNull TunnelZone tunnelZonesGet(UUID uuid)
throws StateAccessException, SerializationException {
return zonesZkManager.getZone(uuid, null);
}
@Override
public List<TunnelZone> tunnelZonesGetAll()
throws StateAccessException, SerializationException {
Collection<UUID> ids = zonesZkManager.getZoneIds();
List<TunnelZone> tunnelZones = new ArrayList<>();
for (UUID id : ids) {
TunnelZone zone = tunnelZonesGet(id);
if (zone != null) {
tunnelZones.add(zone);
}
}
return tunnelZones;
}
@Override
public void tunnelZonesUpdate(@Nonnull TunnelZone zone)
throws StateAccessException, SerializationException {
zonesZkManager.updateZone(zone);
}
@Override
public @CheckForNull TunnelZone.HostConfig tunnelZonesGetMembership(UUID id,
UUID hostId)
throws StateAccessException, SerializationException {
return zonesZkManager.getZoneMembership(id, hostId, null);
}
@Override
public boolean tunnelZonesContainHost(UUID hostId)
throws StateAccessException, SerializationException {
List<TunnelZone> tunnelZones = tunnelZonesGetAll();
boolean hostExistsInTunnelZone = false;
for (TunnelZone tunnelZone : tunnelZones) {
if (zonesZkManager.membershipExists(tunnelZone.getId(), hostId)) {
hostExistsInTunnelZone = true;
break;
}
}
return hostExistsInTunnelZone;
}
@Override
public Set<TunnelZone.HostConfig> tunnelZonesGetMemberships(
final UUID uuid)
throws StateAccessException {
return CollectionFunctors.map(
zonesZkManager.getZoneMemberships(uuid, null),
new Functor<UUID, TunnelZone.HostConfig>() {
@Override
public TunnelZone.HostConfig apply(UUID arg0) {
try {
return zonesZkManager.getZoneMembership(uuid, arg0,
null);
} catch (StateAccessException e) {
//
return null;
} catch (SerializationException e) {
return null;
}
}
},
new HashSet<TunnelZone.HostConfig>()
);
}
@Override
public UUID tunnelZonesAddMembership(
@Nonnull UUID zoneId, @Nonnull TunnelZone.HostConfig hostConfig)
throws StateAccessException, SerializationException {
return zonesZkManager.addMembership(zoneId, hostConfig);
}
@Override
public void tunnelZonesDeleteMembership(UUID zoneId, UUID membershipId)
throws StateAccessException {
zonesZkManager.delMembership(zoneId, membershipId);
}
@Override
public EntityMonitor<UUID, TunnelZone.Data, TunnelZone> tunnelZonesGetMonitor(
ZookeeperConnectionWatcher zkConnection) {
return new EntityMonitor<>(
zonesZkManager, zkConnection,
new EntityMonitor.Transformer<UUID, TunnelZone.Data, TunnelZone> () {
@Override
public TunnelZone transform(UUID id, TunnelZone.Data data) {
return new TunnelZone(id, data);
}
});
}
@Override
public EntityIdSetMonitor<UUID> tunnelZonesGetUuidSetMonitor(
ZookeeperConnectionWatcher zkConnection)
throws StateAccessException {
return new EntityIdSetMonitor(zonesZkManager, zkConnection);
}
@Override
public EntityIdSetMonitor<UUID> tunnelZonesGetMembershipsMonitor(
@Nonnull final UUID zoneId, ZookeeperConnectionWatcher zkConnection)
throws StateAccessException {
return new EntityIdSetMonitor<>(
new WatchableZkManager<UUID, TunnelZone.HostConfig>() {
@Override
public List<UUID> getAndWatchIdList(Runnable watcher)
throws StateAccessException {
return zonesZkManager.getAndWatchMembershipsList(
zoneId, watcher);
}
@Override
public TunnelZone.HostConfig get(UUID id, Runnable watcher)
throws StateAccessException, SerializationException {
return null;
}
}, zkConnection);
}
@Override
public List<Chain> chainsFindByTenant(String tenantId)
throws StateAccessException, SerializationException {
log.debug("chainsFindByTenant entered: tenantId={}", tenantId);
List<Chain> chains = chainsGetAll();
for (Iterator<Chain> it = chains.iterator(); it.hasNext();) {
if (!it.next().hasTenantId(tenantId)) {
it.remove();
}
}
log.debug("chainsFindByTenant exiting: {} chains found",
chains.size());
return chains;
}
@Override
public void dhcpSubnetsCreate(@Nonnull UUID bridgeId,
@Nonnull Subnet subnet)
throws StateAccessException, SerializationException {
dhcpZkManager.createSubnet(bridgeId,
Converter.toDhcpSubnetConfig(subnet));
}
@Override
public void dhcpSubnetsUpdate(@Nonnull UUID bridgeId,
@Nonnull Subnet subnet)
throws StateAccessException, SerializationException {
Subnet oldSubnet = dhcpSubnetsGet(bridgeId, subnet.getSubnetAddr());
if (oldSubnet == null) {
return;
}
// If isEnabled was not specified in the request, just set it to the
// previous value.
if (subnet.isEnabled() == null) {
subnet.setEnabled(oldSubnet.isEnabled());
}
dhcpZkManager.updateSubnet(bridgeId,
Converter.toDhcpSubnetConfig(subnet));
}
@Override
public void dhcpSubnetsDelete(UUID bridgeId, IPv4Subnet subnetAddr)
throws StateAccessException {
dhcpZkManager.deleteSubnet(bridgeId, subnetAddr);
}
@Override
public @CheckForNull Subnet dhcpSubnetsGet(UUID bridgeId,
IPv4Subnet subnetAddr)
throws StateAccessException, SerializationException {
Subnet subnet = null;
if (dhcpZkManager.existsSubnet(bridgeId, subnetAddr)) {
BridgeDhcpZkManager.Subnet subnetConfig =
dhcpZkManager.getSubnet(bridgeId, subnetAddr);
subnet = Converter.fromDhcpSubnetConfig(subnetConfig);
subnet.setId(subnetAddr.toZkString());
}
return subnet;
}
@Override
public List<Subnet> dhcpSubnetsGetByBridge(UUID bridgeId)
throws StateAccessException, SerializationException {
List<IPv4Subnet> subnetConfigs = dhcpZkManager.listSubnets(bridgeId);
List<Subnet> subnets = new ArrayList<>(subnetConfigs.size());
for (IPv4Subnet subnetAddr : subnetConfigs) {
subnets.add(dhcpSubnetsGet(bridgeId, subnetAddr));
}
return subnets;
}
@Override
public List<Subnet> dhcpSubnetsGetByBridgeEnabled(UUID bridgeId)
throws StateAccessException, SerializationException {
List<BridgeDhcpZkManager.Subnet> subnetConfigs =
dhcpZkManager.getEnabledSubnets(bridgeId);
List<Subnet> subnets = new ArrayList<>(subnetConfigs.size());
for (BridgeDhcpZkManager.Subnet subnetConfig : subnetConfigs) {
subnets.add(dhcpSubnetsGet(bridgeId, subnetConfig.getSubnetAddr()));
}
return subnets;
}
@Override
public void dhcpHostsCreate(
@Nonnull UUID bridgeId, @Nonnull IPv4Subnet subnet,
org.midonet.cluster.data.dhcp.Host host)
throws StateAccessException, SerializationException {
dhcpZkManager.addHost(bridgeId, subnet,
Converter.toDhcpHostConfig(host));
}
@Override
public void dhcpHostsUpdate(
@Nonnull UUID bridgeId, @Nonnull IPv4Subnet subnet,
org.midonet.cluster.data.dhcp.Host host)
throws StateAccessException, SerializationException {
dhcpZkManager.updateHost(bridgeId, subnet,
Converter.toDhcpHostConfig(host));
}
@Override
public @CheckForNull org.midonet.cluster.data.dhcp.Host dhcpHostsGet(
UUID bridgeId, IPv4Subnet subnet, String mac)
throws StateAccessException, SerializationException {
org.midonet.cluster.data.dhcp.Host host = null;
if (dhcpZkManager.existsHost(bridgeId, subnet, mac)) {
BridgeDhcpZkManager.Host hostConfig =
dhcpZkManager.getHost(bridgeId, subnet, mac);
host = Converter.fromDhcpHostConfig(hostConfig);
host.setId(MAC.fromString(mac));
}
return host;
}
@Override
public void dhcpHostsDelete(UUID bridgId, IPv4Subnet subnet, String mac)
throws StateAccessException {
dhcpZkManager.deleteHost(bridgId, subnet, mac);
}
@Override
public
List<org.midonet.cluster.data.dhcp.Host> dhcpHostsGetBySubnet(
UUID bridgeId, IPv4Subnet subnet)
throws StateAccessException, SerializationException {
List<BridgeDhcpZkManager.Host> hostConfigs =
dhcpZkManager.getHosts(bridgeId, subnet);
List<org.midonet.cluster.data.dhcp.Host> hosts =
new ArrayList<>();
for (BridgeDhcpZkManager.Host hostConfig : hostConfigs) {
hosts.add(Converter.fromDhcpHostConfig(hostConfig));
}
return hosts;
}
@Override
public void dhcpSubnet6Create(@Nonnull UUID bridgeId,
@Nonnull Subnet6 subnet)
throws StateAccessException, SerializationException {
dhcpV6ZkManager.createSubnet6(bridgeId,
Converter.toDhcpSubnet6Config(subnet));
}
@Override
public void dhcpSubnet6Update(@Nonnull UUID bridgeId,
@Nonnull Subnet6 subnet)
throws StateAccessException, SerializationException {
dhcpV6ZkManager.updateSubnet6(bridgeId,
Converter.toDhcpSubnet6Config(subnet));
}
@Override
public void dhcpSubnet6Delete(UUID bridgeId, IPv6Subnet prefix)
throws StateAccessException {
dhcpV6ZkManager.deleteSubnet6(bridgeId, prefix);
}
public @CheckForNull Subnet6 dhcpSubnet6Get(UUID bridgeId,
IPv6Subnet prefix)
throws StateAccessException, SerializationException {
Subnet6 subnet = null;
if (dhcpV6ZkManager.existsSubnet6(bridgeId, prefix)) {
BridgeDhcpV6ZkManager.Subnet6 subnetConfig =
dhcpV6ZkManager.getSubnet6(bridgeId, prefix);
subnet = Converter.fromDhcpSubnet6Config(subnetConfig);
subnet.setPrefix(prefix);
}
return subnet;
}
@Override
public List<Subnet6> dhcpSubnet6sGetByBridge(UUID bridgeId)
throws StateAccessException, SerializationException {
List<IPv6Subnet> subnet6Configs =
dhcpV6ZkManager.listSubnet6s(bridgeId);
List<Subnet6> subnets = new ArrayList<>(subnet6Configs.size());
for (IPv6Subnet subnet6Config : subnet6Configs) {
subnets.add(dhcpSubnet6Get(bridgeId, subnet6Config));
}
return subnets;
}
@Override
public void dhcpV6HostCreate(
@Nonnull UUID bridgeId, @Nonnull IPv6Subnet prefix, V6Host host)
throws StateAccessException, SerializationException {
dhcpV6ZkManager.addHost(bridgeId, prefix,
Converter.toDhcpV6HostConfig(host));
}
@Override
public void dhcpV6HostUpdate(
@Nonnull UUID bridgeId, @Nonnull IPv6Subnet prefix, V6Host host)
throws StateAccessException, SerializationException {
dhcpV6ZkManager.updateHost(bridgeId, prefix,
Converter.toDhcpV6HostConfig(host));
}
@Override
public @CheckForNull V6Host dhcpV6HostGet(
UUID bridgeId, IPv6Subnet prefix, String clientId)
throws StateAccessException, SerializationException {
V6Host host = null;
if (dhcpV6ZkManager.existsHost(bridgeId, prefix, clientId)) {
BridgeDhcpV6ZkManager.Host hostConfig =
dhcpV6ZkManager.getHost(bridgeId, prefix, clientId);
host = Converter.fromDhcpV6HostConfig(hostConfig);
host.setId(clientId);
}
return host;
}
@Override
public void dhcpV6HostDelete(UUID bridgId, IPv6Subnet prefix,
String clientId)
throws StateAccessException {
dhcpV6ZkManager.deleteHost(bridgId, prefix, clientId);
}
@Override
public
List<V6Host> dhcpV6HostsGetByPrefix(
UUID bridgeId, IPv6Subnet prefix)
throws StateAccessException, SerializationException {
List<BridgeDhcpV6ZkManager.Host> hostConfigs =
dhcpV6ZkManager.getHosts(bridgeId, prefix);
List<V6Host> hosts = new ArrayList<>();
for (BridgeDhcpV6ZkManager.Host hostConfig : hostConfigs) {
hosts.add(Converter.fromDhcpV6HostConfig(hostConfig));
}
return hosts;
}
@Override
public @CheckForNull Host hostsGet(UUID hostId)
throws StateAccessException, SerializationException {
Host host = null;
if (hostsExists(hostId)) {
HostDirectory.Metadata hostMetadata = hostZkManager.get(hostId);
if (hostMetadata == null) {
log.error("Failed to fetch metadata for host {}", hostId);
return null;
}
Integer floodingProxyWeight =
hostZkManager.getFloodingProxyWeight(hostId);
host = Converter.fromHostConfig(hostMetadata);
host.setId(hostId);
host.setIsAlive(hostsIsAlive(hostId));
host.setInterfaces(interfacesGetByHost(hostId));
/* The flooding proxy weight might have not been initialized
* for this host; if so, leave the default value set by Host
* constructor; otherwise, set the stored value. */
if (floodingProxyWeight != null)
host.setFloodingProxyWeight(floodingProxyWeight);
}
return host;
}
@Override
public void hostsDelete(UUID hostId) throws StateAccessException {
hostZkManager.deleteHost(hostId);
}
@Override
public boolean hostsExists(UUID hostId) throws StateAccessException {
return hostZkManager.exists(hostId);
}
@Override
public boolean hostsIsAlive(UUID hostId) throws StateAccessException {
return hostZkManager.isAlive(hostId);
}
@Override
public boolean hostsIsAlive(UUID hostId, Watcher watcher)
throws StateAccessException {
return hostZkManager.isAlive(hostId, watcher);
}
@Override
public boolean hostsHasPortBindings(UUID hostId)
throws StateAccessException {
return hostZkManager.hasPortBindings(hostId);
}
@Override
public List<Host> hostsGetAll()
throws StateAccessException {
Collection<UUID> ids = hostZkManager.getHostIds();
List<Host> hosts = new ArrayList<>();
for (UUID id : ids) {
try {
Host host = hostsGet(id);
if (host != null) {
hosts.add(host);
}
} catch (StateAccessException | SerializationException e) {
log.warn("Cannot get host {} while enumerating hosts", id);
}
}
return hosts;
}
@Override
public EntityMonitor<UUID, HostDirectory.Metadata, Host> hostsGetMonitor(
ZookeeperConnectionWatcher zkConnection) {
return new EntityMonitor<>(
hostZkManager, zkConnection,
new EntityMonitor.Transformer<UUID, HostDirectory.Metadata, Host> () {
@Override
public Host transform(UUID id, HostDirectory.Metadata data) {
Host host = Converter.fromHostConfig(data);
host.setId(id);
Integer floodingProxyWeight = null;
try {
floodingProxyWeight =
hostZkManager.getFloodingProxyWeight(id);
} catch (StateAccessException | SerializationException e) {
log.warn("Failure getting flooding proxy weight", e);
}
try {
host.setIsAlive(hostsIsAlive(id));
} catch (StateAccessException e) {
log.warn("Failure getting host status", e);
}
if (floodingProxyWeight != null) {
host.setFloodingProxyWeight(floodingProxyWeight);
}
return host;
}
});
}
@Override
public EntityIdSetMonitor<UUID> hostsGetUuidSetMonitor(
ZookeeperConnectionWatcher zkConnection)
throws StateAccessException {
return new EntityIdSetMonitor<>(hostZkManager, zkConnection);
}
@Override
public List<Interface> interfacesGetByHost(UUID hostId)
throws StateAccessException, SerializationException {
List<Interface> interfaces = new ArrayList<>();
Collection<String> interfaceNames =
hostZkManager.getInterfaces(hostId);
for (String interfaceName : interfaceNames) {
try {
Interface anInterface = interfacesGet(hostId, interfaceName);
if (anInterface != null) {
interfaces.add(anInterface);
}
} catch (StateAccessException e) {
log.warn(
"An interface description went missing in action while "
+ "we were looking for it host: {}, interface: "
+ "{}.", hostId, interfaceName, e);
}
}
return interfaces;
}
@Override
public @CheckForNull Interface interfacesGet(UUID hostId,
String interfaceName)
throws StateAccessException, SerializationException {
Interface anInterface = null;
if (hostZkManager.existsInterface(hostId, interfaceName)) {
HostDirectory.Interface interfaceData =
hostZkManager.getInterfaceData(hostId, interfaceName);
anInterface = Converter.fromHostInterfaceConfig(interfaceData);
anInterface.setId(interfaceName);
}
return anInterface;
}
@Override
public List<VirtualPortMapping> hostsGetVirtualPortMappingsByHost(
UUID hostId) throws StateAccessException, SerializationException {
Set<HostDirectory.VirtualPortMapping> zkMaps =
hostZkManager.getVirtualPortMappings(hostId, null);
List<VirtualPortMapping> maps = new ArrayList<>(zkMaps.size());
for(HostDirectory.VirtualPortMapping zkMap : zkMaps) {
maps.add(Converter.fromHostVirtPortMappingConfig(zkMap));
}
return maps;
}
@Override
public boolean hostsVirtualPortMappingExists(UUID hostId, UUID portId)
throws StateAccessException {
return hostZkManager.virtualPortMappingExists(hostId, portId);
}
@Override
public @CheckForNull VirtualPortMapping hostsGetVirtualPortMapping(
UUID hostId, UUID portId)
throws StateAccessException, SerializationException {
HostDirectory.VirtualPortMapping mapping =
hostZkManager.getVirtualPortMapping(hostId, portId);
if (mapping == null) {
return null;
}
return Converter.fromHostVirtPortMappingConfig(mapping);
}
@Override
public boolean portsExists(UUID id) throws StateAccessException {
return portZkManager.exists(id);
}
@Override
public void portsDelete(UUID id)
throws StateAccessException, SerializationException {
portZkManager.delete(id);
}
@Override
public List<BridgePort> portsFindByBridge(UUID bridgeId)
throws StateAccessException, SerializationException {
Collection<UUID> ids = portZkManager.getBridgePortIDs(bridgeId);
List<BridgePort> ports = new ArrayList<>();
for (UUID id : ids) {
Port<?, ?> port = portsGet(id);
if (port instanceof BridgePort) {
// Skip the VxLanPort, since it's not really a
// BridgePort and is accessible in other ways.
ports.add((BridgePort) portsGet(id));
}
}
ids = portZkManager.getBridgeLogicalPortIDs(bridgeId);
for (UUID id : ids) {
ports.add((BridgePort) portsGet(id));
}
return ports;
}
@Override
public List<Port<?, ?>> portsFindPeersByBridge(UUID bridgeId)
throws StateAccessException, SerializationException {
Collection<UUID> ids = portZkManager.getBridgeLogicalPortIDs(bridgeId);
List<Port<?, ?>> ports = new ArrayList<>();
for (UUID id : ids) {
Port<?, ?> portData = portsGet(id);
if (portData.getPeerId() != null) {
ports.add(portsGet(portData.getPeerId()));
}
}
return ports;
}
@Override
public List<Port<?, ?>> portsFindByRouter(UUID routerId)
throws StateAccessException, SerializationException {
Collection<UUID> ids = portZkManager.getRouterPortIDs(routerId);
List<Port<?, ?>> ports = new ArrayList<>();
for (UUID id : ids) {
ports.add(portsGet(id));
}
return ports;
}
@Override
public List<Port<?, ?>> portsFindPeersByRouter(UUID routerId)
throws StateAccessException, SerializationException {
Collection<UUID> ids = portZkManager.getRouterPortIDs(routerId);
List<Port<?, ?>> ports = new ArrayList<>();
for (UUID id : ids) {
Port<?, ?> portData = portsGet(id);
if (portData.getPeerId() != null) {
ports.add(portsGet(portData.getPeerId()));
}
}
return ports;
}
@Override
public UUID portsCreate(@Nonnull final Port<?,?> port)
throws StateAccessException, SerializationException {
return portZkManager.create(Converter.toPortConfig(port));
}
@Override
public List<Port<?, ?>> portsGetAll()
throws StateAccessException, SerializationException {
log.debug("portsGetAll entered");
List<Port<?, ?>> ports = new ArrayList<>();
String path = pathBuilder.getPortsPath();
if (zkManager.exists(path)) {
Set<String> portIds = zkManager.getChildren(path);
for (String id : portIds) {
Port<?, ?> port = portsGet(UUID.fromString(id));
if (port != null) {
ports.add(port);
}
}
}
log.debug("portsGetAll exiting: {} routers found", ports.size());
return ports;
}
@Override
public @CheckForNull Port<?,?> portsGet(UUID id)
throws StateAccessException, SerializationException {
Port<?,?> port = null;
if (portZkManager.exists(id)) {
port = Converter.fromPortConfig(portZkManager.get(id));
port.setActive(portZkManager.isActivePort(id));
port.setId(id);
}
return port;
}
@Override
public void portsUpdate(@Nonnull Port<?,?> port)
throws StateAccessException, SerializationException {
log.debug("portsUpdate entered: port={}", port);
// Whatever sent is what gets stored.
portZkManager.update(UUID.fromString(port.getId().toString()),
Converter.toPortConfig(port));
log.debug("portsUpdate exiting");
}
@Override
public void portsLink(@Nonnull UUID portId, @Nonnull UUID peerPortId)
throws StateAccessException, SerializationException {
portZkManager.link(portId, peerPortId);
}
@Override
public void portsUnlink(@Nonnull UUID portId)
throws StateAccessException, SerializationException {
portZkManager.unlink(portId);
}
@Override
public List<Port<?, ?>> portsFindByPortGroup(UUID portGroupId)
throws StateAccessException, SerializationException {
Set<UUID> portIds = portZkManager.getPortGroupPortIds(portGroupId);
List<Port<?, ?>> ports = new ArrayList<>(portIds.size());
for (UUID portId : portIds) {
ports.add(portsGet(portId));
}
return ports;
}
@Override
public IpAddrGroup ipAddrGroupsGet(UUID id)
throws StateAccessException, SerializationException {
IpAddrGroup g = Converter.fromIpAddrGroupConfig(
ipAddrGroupZkManager.get(id));
g.setId(id);
return g;
}
@Override
public void ipAddrGroupsDelete(UUID id)
throws StateAccessException, SerializationException {
ipAddrGroupZkManager.delete(id);
}
@Override
public UUID ipAddrGroupsCreate(@Nonnull IpAddrGroup ipAddrGroup)
throws StateAccessException, SerializationException {
return ipAddrGroupZkManager.create(
Converter.toIpAddrGroupConfig(ipAddrGroup));
}
@Override
public boolean ipAddrGroupsExists(UUID id) throws StateAccessException {
return ipAddrGroupZkManager.exists(id);
}
@Override
public List<IpAddrGroup> ipAddrGroupsGetAll()
throws StateAccessException, SerializationException {
Set<UUID> ids = ipAddrGroupZkManager.getAllIds();
List<IpAddrGroup> groups = new ArrayList<>();
for (UUID id : ids) {
IpAddrGroupZkManager.IpAddrGroupConfig config =
ipAddrGroupZkManager.get(id);
IpAddrGroup group = Converter.fromIpAddrGroupConfig(config);
group.setId(id);
groups.add(group);
}
return groups;
}
@Override
public boolean ipAddrGroupHasAddr(UUID id, String addr)
throws StateAccessException {
return ipAddrGroupZkManager.isMember(id, addr);
}
@Override
public void ipAddrGroupAddAddr(@Nonnull UUID id, @Nonnull String addr)
throws StateAccessException, SerializationException {
ipAddrGroupZkManager.addAddr(id, addr);
}
@Override
public void ipAddrGroupRemoveAddr(UUID id, String addr)
throws StateAccessException, SerializationException {
ipAddrGroupZkManager.removeAddr(id, addr);
}
@Override
public Set<String> getAddrsByIpAddrGroup(UUID id)
throws StateAccessException, SerializationException {
return ipAddrGroupZkManager.getAddrs(id);
}
@Override
public List<PortGroup> portGroupsFindByTenant(String tenantId)
throws StateAccessException, SerializationException {
log.debug("portGroupsFindByTenant entered: tenantId={}", tenantId);
List<PortGroup> portGroups = portGroupsGetAll();
for (Iterator<PortGroup> it = portGroups.iterator(); it.hasNext();) {
if (!it.next().hasTenantId(tenantId)) {
it.remove();
}
}
log.debug("portGroupsFindByTenant exiting: {} portGroups found",
portGroups.size());
return portGroups;
}
@Override
public List<PortGroup> portGroupsFindByPort(UUID portId)
throws StateAccessException, SerializationException {
log.debug("portGroupsFindByPort entered: portId={}", portId);
List<PortGroup> portGroups = new ArrayList<>();
if (portsExists(portId)) {
for (UUID portGroupId : portsGet(portId).getPortGroups()) {
PortGroup portGroup = portGroupsGet(portGroupId);
if (portGroup != null) {
portGroups.add(portGroup);
}
}
}
log.debug("portGroupsFindByPort exiting: {} portGroups found",
portGroups.size());
return portGroups;
}
@Override
public boolean portGroupsIsPortMember(@Nonnull UUID id,
@Nonnull UUID portId)
throws StateAccessException {
return portGroupZkManager.portIsMember(id, portId);
}
@Override
public void portGroupsAddPortMembership(@Nonnull UUID id,
@Nonnull UUID portId)
throws StateAccessException, SerializationException {
portGroupZkManager.addPortToPortGroup(id, portId);
}
@Override
public void portGroupsRemovePortMembership(UUID id, UUID portId)
throws StateAccessException, SerializationException {
portGroupZkManager.removePortFromPortGroup(id, portId);
}
@Override
public UUID portGroupsCreate(@Nonnull PortGroup portGroup)
throws StateAccessException, SerializationException {
log.debug("portGroupsCreate entered: portGroup={}", portGroup);
if (portGroup.getId() == null) {
portGroup.setId(UUID.randomUUID());
}
PortGroupZkManager.PortGroupConfig portGroupConfig =
Converter.toPortGroupConfig(portGroup);
List<Op> ops =
portGroupZkManager.prepareCreate(portGroup.getId(),
portGroupConfig);
String tenantId = portGroup.getProperty(PortGroup.Property.tenant_id);
if (!Strings.isNullOrEmpty(tenantId)) {
ops.addAll(tenantZkManager.prepareCreate(tenantId));
}
zkManager.multi(ops);
log.debug("portGroupsCreate exiting: portGroup={}", portGroup);
return portGroup.getId();
}
@Override
public void portGroupsUpdate(@Nonnull PortGroup portGroup)
throws StateAccessException, SerializationException {
PortGroupZkManager.PortGroupConfig pgConfig =
Converter.toPortGroupConfig(portGroup);
List<Op> ops = new ArrayList<>();
// Update the config
ops.addAll(portGroupZkManager.prepareUpdate(portGroup.getId(), pgConfig));
if (!ops.isEmpty()) {
zkManager.multi(ops);
}
}
@Override
public boolean portGroupsExists(UUID id) throws StateAccessException {
return portGroupZkManager.exists(id);
}
@Override
public List<PortGroup> portGroupsGetAll() throws StateAccessException,
SerializationException {
log.debug("portGroupsGetAll entered");
List<PortGroup> portGroups = new ArrayList<>();
String path = pathBuilder.getPortGroupsPath();
if (zkManager.exists(path)) {
Set<String> portGroupIds = zkManager.getChildren(path);
for (String id : portGroupIds) {
PortGroup portGroup = portGroupsGet(UUID.fromString(id));
if (portGroup != null) {
portGroups.add(portGroup);
}
}
}
log.debug("portGroupsGetAll exiting: {} port groups found",
portGroups.size());
return portGroups;
}
@Override
@CheckForNull
public PortGroup portGroupsGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
PortGroup portGroup = null;
if (portGroupZkManager.exists(id)) {
portGroup = Converter.fromPortGroupConfig(
portGroupZkManager.get(id));
portGroup.setId(id);
}
log.debug("Exiting: portGroup={}", portGroup);
return portGroup;
}
@Override
public void portGroupsDelete(UUID id)
throws StateAccessException, SerializationException {
PortGroup portGroup = portGroupsGet(id);
if (portGroup == null) {
return;
}
List<Op> ops = portGroupZkManager.prepareDelete(id);
zkManager.multi(ops);
}
@Override
public UUID hostsCreate(@Nonnull UUID hostId, @Nonnull Host host)
throws StateAccessException, SerializationException {
hostZkManager.createHost(hostId, Converter.toHostConfig(host));
return hostId;
}
@Override
public void hostsAddVrnPortMapping(@Nonnull UUID hostId, @Nonnull UUID portId,
@Nonnull String localPortName)
throws StateAccessException, SerializationException {
hostZkManager.addVirtualPortMapping(
hostId, new HostDirectory.VirtualPortMapping(portId, localPortName));
}
/**
* Does the same thing as @hostsAddVrnPortMapping(),
* except this returns the updated port object.
*/
@Override
public Port<?,?> hostsAddVrnPortMappingAndReturnPort(
@Nonnull UUID hostId, @Nonnull UUID portId,
@Nonnull String localPortName)
throws StateAccessException, SerializationException {
return
hostZkManager.addVirtualPortMapping(
hostId,
new HostDirectory.VirtualPortMapping(portId, localPortName));
}
@Override
public void hostsDelVrnPortMapping(UUID hostId, UUID portId)
throws StateAccessException, SerializationException {
hostZkManager.delVirtualPortMapping(hostId, portId);
}
@Override
public void hostsSetFloodingProxyWeight(UUID hostId, int weight)
throws StateAccessException, SerializationException {
hostZkManager.setFloodingProxyWeight(hostId, weight);
}
/* load balancer related methods */
@Override
@CheckForNull
public LoadBalancer loadBalancerGet(UUID id)
throws StateAccessException, SerializationException {
LoadBalancer loadBalancer = null;
if (loadBalancerZkManager.exists(id)) {
loadBalancer = Converter.fromLoadBalancerConfig(
loadBalancerZkManager.get(id));
loadBalancer.setId(id);
}
return loadBalancer;
}
@Override
public void loadBalancerDelete(UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
List<Op> ops = new ArrayList<>();
Set<UUID> poolIds = loadBalancerZkManager.getPoolIds(id);
for (UUID poolId : poolIds) {
buildPoolMapDeleteOps(ops, poolId);
}
LoadBalancerZkManager.LoadBalancerConfig loadBalancerConfig =
loadBalancerZkManager.get(id);
if (loadBalancerConfig.routerId != null) {
ops.addAll(
routerZkManager.prepareClearRefsToLoadBalancer(
loadBalancerConfig.routerId, id));
}
ops.addAll(loadBalancerZkManager.prepareDelete(id));
zkManager.multi(ops);
}
@Override
public UUID loadBalancerCreate(@Nonnull LoadBalancer loadBalancer)
throws StateAccessException, SerializationException,
InvalidStateOperationException {
if (loadBalancer.getId() == null) {
loadBalancer.setId(UUID.randomUUID());
}
LoadBalancerZkManager.LoadBalancerConfig loadBalancerConfig =
Converter.toLoadBalancerConfig(loadBalancer);
loadBalancerZkManager.create(loadBalancer.getId(),
loadBalancerConfig);
return loadBalancer.getId();
}
@Override
public void loadBalancerUpdate(@Nonnull LoadBalancer loadBalancer)
throws StateAccessException, SerializationException,
InvalidStateOperationException {
LoadBalancerZkManager.LoadBalancerConfig loadBalancerConfig =
Converter.toLoadBalancerConfig(loadBalancer);
loadBalancerZkManager.update(loadBalancer.getId(),
loadBalancerConfig);
}
@Override
public List<LoadBalancer> loadBalancersGetAll()
throws StateAccessException, SerializationException {
List<LoadBalancer> loadBalancers = new ArrayList<>();
String path = pathBuilder.getLoadBalancersPath();
if (zkManager.exists(path)) {
Set<String> loadBalancerIds = zkManager.getChildren(path);
for (String id : loadBalancerIds) {
LoadBalancer loadBalancer =
loadBalancerGet(UUID.fromString(id));
if (loadBalancer != null) {
loadBalancers.add(loadBalancer);
}
}
}
return loadBalancers;
}
@Override
public List<Pool> loadBalancerGetPools(UUID id)
throws StateAccessException, SerializationException {
Set<UUID> poolIds = loadBalancerZkManager.getPoolIds(id);
List<Pool> pools = new ArrayList<>(poolIds.size());
for (UUID poolId : poolIds) {
Pool pool = Converter.fromPoolConfig(poolZkManager.get(poolId));
pool.setId(poolId);
pools.add(pool);
}
return pools;
}
@Override
public List<VIP> loadBalancerGetVips(UUID id)
throws StateAccessException, SerializationException {
Set<UUID> vipIds = loadBalancerZkManager.getVipIds(id);
List<VIP> vips = new ArrayList<>(vipIds.size());
for (UUID vipId : vipIds) {
VIP vip = Converter.fromVipConfig(vipZkManager.get(vipId));
vip.setId(vipId);
vips.add(vip);
}
return vips;
}
private void validatePoolConfigMappingStatus(UUID poolId)
throws MappingStatusException, StateAccessException,
SerializationException {
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
if (poolConfig.isImmutable()) {
throw new MappingStatusException(
poolConfig.mappingStatus.toString());
}
}
/*
* Returns the pair of the mapping path and the mapping config. If the
* given pool is not associated with any health monitor, it returns `null`.
*/
private MutablePair<String, PoolHealthMonitorConfig>
preparePoolHealthMonitorMappings(
@Nonnull UUID poolId,
@Nonnull PoolZkManager.PoolConfig poolConfig,
ConfigGetter<UUID, PoolMemberZkManager.PoolMemberConfig> poolMemberConfigGetter,
ConfigGetter<UUID, VipZkManager.VipConfig> vipConfigGetter)
throws MappingStatusException, SerializationException,
StateAccessException {
UUID healthMonitorId = poolConfig.healthMonitorId;
// If the health monitor ID is null, the mapping should not be created
// and therefore `null` is returned.
if (healthMonitorId == null) {
return null;
}
// If `mappingStatus` property of Pool is in PENDING_*, it throws the
// exception and prevent the mapping from being updated.
validatePoolConfigMappingStatus(poolId);
String mappingPath = pathBuilder.getPoolHealthMonitorMappingsPath(
poolId, healthMonitorId);
assert poolConfig.loadBalancerId != null;
UUID loadBalancerId = checkNotNull(
poolConfig.loadBalancerId, "LoadBalancer ID is null.");
LoadBalancerConfigWithId loadBalancerConfig =
new LoadBalancerConfigWithId(
loadBalancerZkManager.get(loadBalancerId));
List<UUID> memberIds = poolZkManager.getMemberIds(poolId);
List<PoolMemberConfigWithId> memberConfigs =
new ArrayList<>(memberIds.size());
for (UUID memberId : memberIds) {
PoolMemberZkManager.PoolMemberConfig config =
poolMemberConfigGetter.get(memberId);
if (config != null) {
config.id = memberId;
memberConfigs.add(new PoolMemberConfigWithId(config));
}
}
List<UUID> vipIds = poolZkManager.getVipIds(poolId);
List<VipConfigWithId> vipConfigs =
new ArrayList<>(vipIds.size());
for (UUID vipId : vipIds) {
VipZkManager.VipConfig config = vipConfigGetter.get(vipId);
if (config != null) {
config.id = vipId;
vipConfigs.add(new VipConfigWithId(config));
}
}
HealthMonitorConfigWithId healthMonitorConfig =
new HealthMonitorConfigWithId(
healthMonitorZkManager.get(healthMonitorId));
PoolHealthMonitorConfig mappingConfig = new PoolHealthMonitorConfig(
loadBalancerConfig, vipConfigs, memberConfigs, healthMonitorConfig);
return new MutablePair<>(mappingPath, mappingConfig);
}
private List<Op> preparePoolHealthMonitorMappingUpdate(
Pair<String, PoolHealthMonitorConfig> pair)
throws SerializationException {
List<Op> ops = new ArrayList<>();
if (pair != null) {
String mappingPath = pair.getLeft();
PoolHealthMonitorConfig mappingConfig = pair.getRight();
ops.add(Op.setData(mappingPath,
serializer.serialize(mappingConfig), -1));
}
return ops;
}
/* health monitors related methods */
private List<Pair<String, PoolHealthMonitorConfig>>
buildPoolHealthMonitorMappings(UUID healthMonitorId,
@Nullable HealthMonitorZkManager.HealthMonitorConfig config)
throws MappingStatusException, SerializationException,
StateAccessException {
List<UUID> poolIds = healthMonitorZkManager.getPoolIds(healthMonitorId);
List<Pair<String, PoolHealthMonitorConfig>> pairs = new ArrayList<>();
for (UUID poolId : poolIds) {
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
MutablePair<String, PoolHealthMonitorConfig> pair =
preparePoolHealthMonitorMappings(poolId, poolConfig,
poolMemberZkManager,
vipZkManager);
if (pair != null) {
// Update health monitor config, which can be null
PoolHealthMonitorConfig updatedMappingConfig = pair.getRight();
updatedMappingConfig.healthMonitorConfig =
new HealthMonitorConfigWithId(config);
pair.setRight(updatedMappingConfig);
pairs.add(pair);
}
}
return pairs;
}
@Override
@CheckForNull
public HealthMonitor healthMonitorGet(UUID id)
throws StateAccessException, SerializationException {
HealthMonitor healthMonitor = null;
if (healthMonitorZkManager.exists(id)) {
healthMonitor = Converter.fromHealthMonitorConfig(
healthMonitorZkManager.get(id));
healthMonitor.setId(id);
}
return healthMonitor;
}
@Override
public void healthMonitorDelete(UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
List<Op> ops = new ArrayList<>();
List<UUID> poolIds = healthMonitorZkManager.getPoolIds(id);
for (UUID poolId : poolIds) {
validatePoolConfigMappingStatus(poolId);
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
ops.add(Op.setData(pathBuilder.getPoolPath(poolId),
serializer.serialize(poolConfig), -1));
// Pool-HealthMonitor mappings
ops.add(Op.delete(pathBuilder.getPoolHealthMonitorMappingsPath(
poolId, id), -1));
poolConfig.healthMonitorId = null;
// Indicate the mapping is being deleted.
poolConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_DELETE;
ops.addAll(poolZkManager.prepareUpdate(poolId, poolConfig));
ops.addAll(healthMonitorZkManager.prepareRemovePool(id, poolId));
}
ops.addAll(healthMonitorZkManager.prepareDelete(id));
zkManager.multi(ops);
}
@Override
public UUID healthMonitorCreate(@Nonnull HealthMonitor healthMonitor)
throws StateAccessException, SerializationException {
if (healthMonitor.getId() == null) {
healthMonitor.setId(UUID.randomUUID());
}
HealthMonitorZkManager.HealthMonitorConfig config =
Converter.toHealthMonitorConfig(healthMonitor);
zkManager.multi(
healthMonitorZkManager.prepareCreate(
healthMonitor.getId(), config));
return healthMonitor.getId();
}
@Override
public void healthMonitorUpdate(@Nonnull HealthMonitor healthMonitor)
throws MappingStatusException, StateAccessException,
SerializationException {
HealthMonitorZkManager.HealthMonitorConfig newConfig =
Converter.toHealthMonitorConfig(healthMonitor);
HealthMonitorZkManager.HealthMonitorConfig oldConfig =
healthMonitorZkManager.get(healthMonitor.getId());
UUID id = healthMonitor.getId();
if (newConfig.equals(oldConfig)) {
return;
}
List<Op> ops = new ArrayList<>();
ops.addAll(healthMonitorZkManager.prepareUpdate(id, newConfig));
// Pool-HealthMonitor mappings
for (Pair<String, PoolHealthMonitorConfig> pair :
buildPoolHealthMonitorMappings(id, newConfig)) {
List<UUID> poolIds = healthMonitorZkManager.getPoolIds(id);
for (UUID poolId : poolIds) {
validatePoolConfigMappingStatus(poolId);
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
// Indicate the mapping is being updated.
poolConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_UPDATE;
ops.add(Op.setData(pathBuilder.getPoolPath(poolId),
serializer.serialize(poolConfig), -1));
}
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
}
zkManager.multi(ops);
}
@Override
public List<HealthMonitor> healthMonitorsGetAll()
throws StateAccessException, SerializationException {
List<HealthMonitor> healthMonitors = new ArrayList<>();
String path = pathBuilder.getHealthMonitorsPath();
if (zkManager.exists(path)) {
Set<String> healthMonitorIds = zkManager.getChildren(path);
for (String id : healthMonitorIds) {
HealthMonitor healthMonitor
= healthMonitorGet(UUID.fromString(id));
if (healthMonitor != null) {
healthMonitors.add(healthMonitor);
}
}
}
return healthMonitors;
}
@Override
public List<Pool> healthMonitorGetPools(@Nonnull UUID id)
throws StateAccessException, SerializationException {
List<UUID> poolIds = healthMonitorZkManager.getPoolIds(id);
List<Pool> pools = new ArrayList<>(poolIds.size());
for (UUID poolId : poolIds) {
Pool pool = Converter.fromPoolConfig(poolZkManager.get(poolId));
pool.setId(poolId);
pools.add(pool);
}
return pools;
}
/* pool member related methods */
private Pair<String, PoolHealthMonitorConfig>
buildPoolHealthMonitorMappings(final UUID poolMemberId,
final @Nonnull PoolMemberZkManager.PoolMemberConfig config,
final boolean deletePoolMember)
throws MappingStatusException, SerializationException,
StateAccessException {
UUID poolId = checkNotNull(config.poolId, "Pool ID is null.");
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
// Since we haven't deleted/updated this PoolMember in Zookeeper yet,
// preparePoolHealthMonitorMappings() will get an outdated version of
// this PoolMember when it fetches the Pool's members. The ConfigGetter
// intercepts the request for this PoolMember and returns the updated
// PoolMemberConfig, or null if it's been deleted.
ConfigGetter<UUID, PoolMemberZkManager.PoolMemberConfig> configGetter =
new ConfigGetter<UUID, PoolMemberZkManager.PoolMemberConfig>() {
@Override
public PoolMemberZkManager.PoolMemberConfig get(UUID key)
throws StateAccessException, SerializationException {
if (key.equals(poolMemberId)) {
return deletePoolMember ? null : config;
}
return poolMemberZkManager.get(key);
}
};
return preparePoolHealthMonitorMappings(
poolId, poolConfig, configGetter, vipZkManager);
}
private List<Op> buildPoolMappingStatusUpdate(
PoolMemberZkManager.PoolMemberConfig poolMemberConfig)
throws StateAccessException, SerializationException {
UUID poolId = poolMemberConfig.poolId;
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
// Indicate the mapping is being updated.
poolConfig.mappingStatus = PoolHealthMonitorMappingStatus.PENDING_UPDATE;
return Arrays.asList(Op.setData(pathBuilder.getPoolPath(poolId),
serializer.serialize(poolConfig), -1));
}
@Override
@CheckForNull
public boolean poolMemberExists(UUID id)
throws StateAccessException {
return poolMemberZkManager.exists(id);
}
@Override
@CheckForNull
public PoolMember poolMemberGet(UUID id)
throws StateAccessException, SerializationException {
PoolMember poolMember = null;
if (poolMemberZkManager.exists(id)) {
poolMember =
Converter.fromPoolMemberConfig(poolMemberZkManager.get(id));
poolMember.setId(id);
}
return poolMember;
}
@Override
public void poolMemberDelete(UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
List<Op> ops = new ArrayList<>();
PoolMemberZkManager.PoolMemberConfig
config =
poolMemberZkManager.get(id);
if (config.poolId != null) {
ops.addAll(poolZkManager.prepareRemoveMember(config.poolId, id));
}
ops.addAll(poolMemberZkManager.prepareDelete(id));
// Pool-HealthMonitor mappings
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, config, true);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(config));
}
zkManager.multi(ops);
}
@Override
public UUID poolMemberCreate(@Nonnull PoolMember poolMember)
throws MappingStatusException, StateAccessException,
SerializationException {
validatePoolConfigMappingStatus(poolMember.getPoolId());
if (poolMember.getId() == null) {
poolMember.setId(UUID.randomUUID());
}
UUID id = poolMember.getId();
PoolMemberZkManager.PoolMemberConfig config =
Converter.toPoolMemberConfig(poolMember);
List<Op> ops = new ArrayList<>();
ops.addAll(poolMemberZkManager.prepareCreate(id, config));
ops.addAll(poolZkManager.prepareAddMember(config.poolId, id));
// Flush the pool member create ops first
zkManager.multi(ops);
ops.clear();
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, config, false);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(config));
}
zkManager.multi(ops);
return id;
}
@Override
public void poolMemberUpdate(@Nonnull PoolMember poolMember)
throws MappingStatusException, StateAccessException,
SerializationException {
validatePoolConfigMappingStatus(poolMember.getPoolId());
UUID id = poolMember.getId();
PoolMemberZkManager.PoolMemberConfig newConfig =
Converter.toPoolMemberConfig(poolMember);
PoolMemberZkManager.PoolMemberConfig oldConfig =
poolMemberZkManager.get(id);
boolean isPoolIdChanged =
!com.google.common.base.Objects.equal(newConfig.poolId,
oldConfig.poolId);
if (newConfig.equals(oldConfig)) {
return;
}
List<Op> ops = new ArrayList<>();
if (isPoolIdChanged) {
ops.addAll(poolZkManager.prepareRemoveMember(oldConfig.poolId, id));
ops.addAll(poolZkManager.prepareAddMember(newConfig.poolId, id));
}
ops.addAll(poolMemberZkManager.prepareUpdate(id, newConfig));
// Flush the update of the pool members first
zkManager.multi(ops);
ops.clear();
if (isPoolIdChanged) {
// Remove pool member from its old owner's mapping node.
Pair<String, PoolHealthMonitorConfig> oldPair =
buildPoolHealthMonitorMappings(id, oldConfig, true);
ops.addAll(preparePoolHealthMonitorMappingUpdate(oldPair));
}
// Update the pool's pool-HM mapping with the new member.
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, newConfig, false);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(newConfig));
}
zkManager.multi(ops);
}
@Override
public void poolMemberUpdateStatus(UUID poolMemberId, LBStatus status)
throws StateAccessException, SerializationException {
PoolMemberZkManager.PoolMemberConfig config =
poolMemberZkManager.get(poolMemberId);
if (config == null) {
log.error("pool member does not exist" + poolMemberId.toString());
return;
}
config.status = status;
List<Op> ops = poolMemberZkManager.prepareUpdate(poolMemberId, config);
zkManager.multi(ops);
}
@Override
public List<PoolMember> poolMembersGetAll()
throws StateAccessException, SerializationException {
List<PoolMember> poolMembers = new ArrayList<>();
String path = pathBuilder.getPoolMembersPath();
if (zkManager.exists(path)) {
Set<String> poolMemberIds = zkManager.getChildren(path);
for (String id : poolMemberIds) {
PoolMember poolMember = poolMemberGet(UUID.fromString(id));
if (poolMember != null) {
poolMembers.add(poolMember);
}
}
}
return poolMembers;
}
/* pool related methods */
private List<Op> prepareDeletePoolHealthMonitorMappingOps(UUID poolId)
throws SerializationException, StateAccessException {
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
List<Op> ops = new ArrayList<>();
if (poolConfig.healthMonitorId != null) {
ops.add(Op.delete(pathBuilder.getPoolHealthMonitorMappingsPath(
poolId, poolConfig.healthMonitorId), -1));
}
return ops;
}
@Override
@CheckForNull
public Pool poolGet(UUID id)
throws StateAccessException, SerializationException {
Pool pool = null;
if (poolZkManager.exists(id)) {
pool = Converter.fromPoolConfig(poolZkManager.get(id));
pool.setId(id);
}
return pool;
}
private List<Op> buildPoolDeleteOps(UUID id)
throws StateAccessException, SerializationException {
List<Op> ops = new ArrayList<>();
PoolZkManager.PoolConfig config = poolZkManager.get(id);
List<UUID> memberIds = poolZkManager.getMemberIds(id);
for (UUID memberId : memberIds) {
ops.addAll(poolZkManager.prepareRemoveMember(id, memberId));
ops.addAll(poolMemberZkManager.prepareDelete(memberId));
}
List<UUID> vipIds = poolZkManager.getVipIds(id);
for (UUID vipId : vipIds) {
ops.addAll(poolZkManager.prepareRemoveVip(id, vipId));
ops.addAll(vipZkManager.prepareDelete(vipId));
ops.addAll(loadBalancerZkManager.prepareRemoveVip(
config.loadBalancerId, vipId));
}
if (config.healthMonitorId != null) {
ops.addAll(healthMonitorZkManager.prepareRemovePool(
config.healthMonitorId, id));
}
ops.addAll(loadBalancerZkManager.prepareRemovePool(
config.loadBalancerId, id));
ops.addAll(poolZkManager.prepareDelete(id));
return ops;
}
private void buildPoolMapDeleteOps(List<Op> ops, UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
ops.addAll(buildPoolDeleteOps(id));
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(id);
validatePoolConfigMappingStatus(id);
if (poolConfig.healthMonitorId != null) {
ops.add(Op.delete(pathBuilder.getPoolHealthMonitorMappingsPath(
id, poolConfig.healthMonitorId), -1));
}
}
@Override
public void poolDelete(UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
List<Op> ops = new ArrayList<>();
buildPoolMapDeleteOps(ops, id);
zkManager.multi(ops);
}
@Override
public UUID poolCreate(@Nonnull Pool pool)
throws MappingStatusException, StateAccessException,
SerializationException {
if (pool.getId() == null) {
pool.setId(UUID.randomUUID());
}
UUID id = pool.getId();
PoolZkManager.PoolConfig config = Converter.toPoolConfig(pool);
List<Op> ops = new ArrayList<>();
ops.addAll(poolZkManager.prepareCreate(id, config));
if (config.loadBalancerId != null) {
ops.addAll(loadBalancerZkManager.prepareAddPool(
config.loadBalancerId, id));
}
if (config.healthMonitorId != null) {
ops.addAll(healthMonitorZkManager.prepareAddPool(
config.healthMonitorId, id));
}
// Flush the pool create ops first.
zkManager.multi(ops);
ops.clear();
// Pool-HealthMonitor mappings
Pair<String, PoolHealthMonitorConfig> pair =
preparePoolHealthMonitorMappings(
id, config, poolMemberZkManager, vipZkManager);
if (pair != null) {
String mappingPath = pair.getLeft();
PoolHealthMonitorConfig mappingConfig = pair.getRight();
ops.add(Op.create(mappingPath,
serializer.serialize(mappingConfig),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT));
config.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_CREATE;
ops.addAll(poolZkManager.prepareUpdate(id, config));
}
zkManager.multi(ops);
return id;
}
@Override
public void poolUpdate(@Nonnull Pool pool)
throws MappingStatusException, MappingViolationException,
SerializationException, StateAccessException {
UUID id = pool.getId();
PoolZkManager.PoolConfig newConfig = Converter.toPoolConfig(pool);
PoolZkManager.PoolConfig oldConfig = poolZkManager.get(id);
boolean isHealthMonitorChanged =
!com.google.common.base.Objects.equal(newConfig.healthMonitorId,
oldConfig.healthMonitorId);
if (newConfig.equals(oldConfig)) {
return;
}
// Set the internal status for the Pool-HealthMonitor mapping with the
// previous value.
newConfig.mappingStatus = oldConfig.mappingStatus;
List<Op> ops = new ArrayList<>();
if (isHealthMonitorChanged) {
if (oldConfig.healthMonitorId != null) {
ops.addAll(healthMonitorZkManager.prepareRemovePool(
oldConfig.healthMonitorId, id));
}
if (newConfig.healthMonitorId != null) {
ops.addAll(healthMonitorZkManager.prepareAddPool(
newConfig.healthMonitorId, id));
}
}
if (!com.google.common.base.Objects.equal(oldConfig.loadBalancerId,
newConfig.loadBalancerId)) {
// Move the pool from the previous load balancer to the new one.
ops.addAll(loadBalancerZkManager.prepareRemovePool(
oldConfig.loadBalancerId, id));
ops.addAll(loadBalancerZkManager.prepareAddPool(
newConfig.loadBalancerId, id));
// Move the VIPs belong to the pool from the previous load balancer
// to the new one.
List<UUID> vipIds = poolZkManager.getVipIds(id);
for (UUID vipId : vipIds) {
ops.addAll(loadBalancerZkManager.prepareRemoveVip(
oldConfig.loadBalancerId, vipId));
ops.addAll(loadBalancerZkManager.prepareAddVip(
newConfig.loadBalancerId, vipId));
VipZkManager.VipConfig vipConfig = vipZkManager.get(vipId);
// Update the load balancer ID of the VIPs with the pool's one.
vipConfig.loadBalancerId = newConfig.loadBalancerId;
ops.addAll(vipZkManager.prepareUpdate(vipId, vipConfig));
}
}
// Pool-HealthMonitor mappings
// If the reference to the health monitor is changed, the previous
// entries are deleted and the new entries are created.
if (isHealthMonitorChanged) {
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(id);
// Indicate the mapping is being deleted and once it's confirmed
// by the health monitor, it's replaced with INACTIVE.
if (pool.getHealthMonitorId() == null) {
validatePoolConfigMappingStatus(id);
newConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_DELETE;
// Delete the old entry
ops.add(Op.delete(pathBuilder.getPoolHealthMonitorMappingsPath(
id, poolConfig.healthMonitorId), -1));
}
// Throws an exception if users try to update the health monitor ID
// with another one even if the pool is already associated with
// another health monitor.
if (poolConfig.healthMonitorId != null
&& pool.getHealthMonitorId() != null) {
throw new MappingViolationException();
}
Pair<String, PoolHealthMonitorConfig> pair =
preparePoolHealthMonitorMappings(
id, newConfig, poolMemberZkManager, vipZkManager);
if (pair != null) {
String mappingPath = pair.getLeft();
PoolHealthMonitorConfig mappingConfig = pair.getRight();
ops.add(Op.create(mappingPath,
serializer.serialize(mappingConfig),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT));
// Indicate the update is being processed and once it's confirmed
// by the health monitor, it's replaced with ACTIVE.
if (com.google.common.base.Objects.equal(
oldConfig.mappingStatus,
PoolHealthMonitorMappingStatus.INACTIVE)) {
newConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_CREATE;
} else {
newConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_UPDATE;
}
}
}
ops.addAll(poolZkManager.prepareUpdate(id, newConfig));
zkManager.multi(ops);
}
@Override
public List<Pool> poolsGetAll() throws StateAccessException,
SerializationException {
List<Pool> pools = new ArrayList<>();
String path = pathBuilder.getPoolsPath();
if (zkManager.exists(path)) {
Set<String> poolIds = zkManager.getChildren(path);
for (String id : poolIds) {
Pool pool = poolGet(UUID.fromString(id));
if (pool != null) {
pools.add(pool);
}
}
}
return pools;
}
@Override
public List<PoolMember> poolGetMembers(@Nonnull UUID id)
throws StateAccessException, SerializationException {
List<UUID> memberIds = poolZkManager.getMemberIds(id);
List<PoolMember> members = new ArrayList<>(memberIds.size());
for (UUID memberId : memberIds) {
PoolMember member = Converter.fromPoolMemberConfig(
poolMemberZkManager.get(memberId));
member.setId(memberId);
members.add(member);
}
return members;
}
@Override
public List<VIP> poolGetVips(@Nonnull UUID id)
throws StateAccessException, SerializationException {
List<UUID> vipIds = poolZkManager.getVipIds(id);
List<VIP> vips = new ArrayList<>(vipIds.size());
for (UUID vipId : vipIds) {
VIP vip = Converter.fromVipConfig(vipZkManager.get(vipId));
vip.setId(vipId);
vips.add(vip);
}
return vips;
}
@Override
public void poolSetMapStatus(UUID id,
PoolHealthMonitorMappingStatus status)
throws StateAccessException, SerializationException {
PoolZkManager.PoolConfig pool = poolZkManager.get(id);
if (pool == null) {
return;
}
pool.mappingStatus = status;
zkManager.multi(poolZkManager.prepareUpdate(id, pool));
}
private Pair<String, PoolHealthMonitorConfig>
buildPoolHealthMonitorMappings(final UUID vipId,
final @Nonnull VipZkManager.VipConfig config,
final boolean deleteVip)
throws MappingStatusException, SerializationException,
StateAccessException {
UUID poolId = checkNotNull(config.poolId, "Pool ID is null.");
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
// Since we haven't deleted/updated this VIP in Zookeeper yet,
// preparePoolHealthMonitorMappings() will get an outdated version of
// this VIP when it fetches the Pool's vips. The ConfigGetter
// intercepts the request for this VIP and returns the updated
// VipConfig, or null if it's been deleted.
ConfigGetter<UUID, VipZkManager.VipConfig> configGetter =
new ConfigGetter<UUID, VipZkManager.VipConfig>() {
@Override
public VipZkManager.VipConfig get(UUID key)
throws StateAccessException, SerializationException {
if (key.equals(vipId)) {
return deleteVip ? null : config;
}
return vipZkManager.get(key);
}
};
return preparePoolHealthMonitorMappings(
poolId, poolConfig, poolMemberZkManager, configGetter);
}
private List<Op> buildPoolMappingStatusUpdate(
VipZkManager.VipConfig vipConfig)
throws StateAccessException, SerializationException {
UUID poolId = vipConfig.poolId;
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(poolId);
// Indicate the mapping is being updated.
poolConfig.mappingStatus =
PoolHealthMonitorMappingStatus.PENDING_UPDATE;
return Arrays.asList(Op.setData(pathBuilder.getPoolPath(poolId),
serializer.serialize(poolConfig), -1));
}
@Override
@CheckForNull
public VIP vipGet(UUID id)
throws StateAccessException, SerializationException {
VIP vip = null;
if (vipZkManager.exists(id)) {
vip = Converter.fromVipConfig(vipZkManager.get(id));
vip.setId(id);
}
return vip;
}
@Override
public void vipDelete(UUID id)
throws MappingStatusException, StateAccessException,
SerializationException {
List<Op> ops = new ArrayList<>();
VipZkManager.VipConfig config = vipZkManager.get(id);
if (config.loadBalancerId != null) {
ops.addAll(loadBalancerZkManager.prepareRemoveVip(
config.loadBalancerId, id));
}
if (config.poolId != null) {
ops.addAll(poolZkManager.prepareRemoveVip(config.poolId, id));
}
ops.addAll(vipZkManager.prepareDelete(id));
// Pool-HealthMonitor mappings
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, config, true);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(config));
}
zkManager.multi(ops);
}
@Override
public UUID vipCreate(@Nonnull VIP vip)
throws MappingStatusException, StateAccessException,
SerializationException {
validatePoolConfigMappingStatus(vip.getPoolId());
if (vip.getId() == null) {
vip.setId(UUID.randomUUID());
}
UUID id = vip.getId();
// Get the VipConfig and set its loadBalancerId from the PoolConfig.
VipZkManager.VipConfig config = Converter.toVipConfig(vip);
PoolZkManager.PoolConfig poolConfig = poolZkManager.get(config.poolId);
config.loadBalancerId = poolConfig.loadBalancerId;
List<Op> ops = new ArrayList<>();
ops.addAll(vipZkManager.prepareCreate(id, config));
ops.addAll(poolZkManager.prepareAddVip(config.poolId, id));
ops.addAll(loadBalancerZkManager.prepareAddVip(
config.loadBalancerId, id));
// Flush the VIP first.
zkManager.multi(ops);
ops.clear();
// Pool-HealthMonitor mappings
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, config, false);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(config));
}
zkManager.multi(ops);
return id;
}
@Override
public void vipUpdate(@Nonnull VIP vip)
throws MappingStatusException, StateAccessException,
SerializationException {
validatePoolConfigMappingStatus(vip.getPoolId());
// See if new config is different from old config.
UUID id = vip.getId();
VipZkManager.VipConfig newConfig = Converter.toVipConfig(vip);
VipZkManager.VipConfig oldConfig = vipZkManager.get(id);
// User can't set loadBalancerId directly because we get it from
// from the pool indicated by poolId.
newConfig.loadBalancerId = oldConfig.loadBalancerId;
if (newConfig.equals(oldConfig)) {
return;
}
List<Op> ops = new ArrayList<>();
boolean poolIdChanged =
!com.google.common.base.Objects.equal(newConfig.poolId,
oldConfig.poolId);
if (poolIdChanged) {
ops.addAll(poolZkManager.prepareRemoveVip(oldConfig.poolId, id));
ops.addAll(loadBalancerZkManager.prepareRemoveVip(
oldConfig.loadBalancerId, id));
PoolZkManager.PoolConfig
newPoolConfig =
poolZkManager.get(newConfig.poolId);
newConfig.loadBalancerId = newPoolConfig.loadBalancerId;
ops.addAll(poolZkManager.prepareAddVip(newConfig.poolId, id));
ops.addAll(loadBalancerZkManager.prepareAddVip(
newPoolConfig.loadBalancerId, id));
}
ops.addAll(vipZkManager.prepareUpdate(id, newConfig));
zkManager.multi(ops);
ops.clear();
if (poolIdChanged) {
// Remove the VIP from the old pool-HM mapping.
Pair<String, PoolHealthMonitorConfig> oldPair =
buildPoolHealthMonitorMappings(id, oldConfig, true);
ops.addAll(preparePoolHealthMonitorMappingUpdate(oldPair));
}
// Update the appropriate pool-HM mapping with the new VIP config.
Pair<String, PoolHealthMonitorConfig> pair =
buildPoolHealthMonitorMappings(id, newConfig, false);
ops.addAll(preparePoolHealthMonitorMappingUpdate(pair));
if (pair != null) {
ops.addAll(buildPoolMappingStatusUpdate(newConfig));
}
zkManager.multi(ops);
}
@Override
public List<VIP> vipGetAll()
throws StateAccessException, SerializationException {
List<VIP> vips = new ArrayList<>();
String path = pathBuilder.getVipsPath();
if (zkManager.exists(path)) {
Set<String> vipIds = zkManager.getChildren(path);
for (String id : vipIds) {
VIP vip = vipGet(UUID.fromString(id));
if (vip != null) {
vips.add(vip);
}
}
}
return vips;
}
@Override
public Integer hostsGetFloodingProxyWeight(UUID hostId, Watcher watcher)
throws StateAccessException, SerializationException {
return hostZkManager.getFloodingProxyWeight(hostId, watcher);
}
@Override
public @CheckForNull Route routesGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
Route route = null;
if (routeZkManager.exists(id)) {
route = Converter.fromRouteConfig(routeZkManager.get(id));
route.setId(id);
}
log.debug("Exiting: route={}", route);
return route;
}
@Override
public void routesDelete(UUID id)
throws StateAccessException, SerializationException {
routeZkManager.delete(id);
}
@Override
public UUID routesCreate(@Nonnull Route route)
throws StateAccessException, SerializationException {
return routeZkManager.create(Converter.toRouteConfig(route));
}
@Override
public UUID routesCreateEphemeral(@Nonnull Route route)
throws StateAccessException, SerializationException {
return routeZkManager.create(Converter.toRouteConfig(route), false);
}
@Override
public List<Route> routesFindByRouter(UUID routerId)
throws StateAccessException, SerializationException {
List<UUID> routeIds = routeZkManager.list(routerId);
List<Route> routes = new ArrayList<>();
for (UUID id : routeIds) {
routes.add(routesGet(id));
}
return routes;
}
@Override
public boolean routerExists(UUID id) throws StateAccessException {
return routerZkManager.exists(id);
}
@Override
public List<Router> routersGetAll() throws StateAccessException,
SerializationException {
log.debug("routersGetAll entered");
List<Router> routers = new ArrayList<>();
String path = pathBuilder.getRoutersPath();
if (zkManager.exists(path)) {
Set<String> routerIds = zkManager.getChildren(path);
for (String id : routerIds) {
Router router = routersGet(UUID.fromString(id));
if (router != null) {
routers.add(router);
}
}
}
log.debug("routersGetAll exiting: {} routers found", routers.size());
return routers;
}
@Override
public @CheckForNull Router routersGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
Router router = null;
if (routerZkManager.exists(id)) {
router = Converter.fromRouterConfig(routerZkManager.get(id));
router.setId(id);
}
log.debug("Exiting: router={}", router);
return router;
}
@Override
public void routersDelete(UUID id)
throws StateAccessException, SerializationException {
Router router = routersGet(id);
if (router == null) {
return;
}
List<Op> ops = routerZkManager.prepareRouterDelete(id);
zkManager.multi(ops);
}
@Override
public UUID routersCreate(@Nonnull Router router)
throws StateAccessException, SerializationException {
log.debug("routersCreate entered: router={}", router);
if (router.getId() == null) {
router.setId(UUID.randomUUID());
}
RouterZkManager.RouterConfig routerConfig =
Converter.toRouterConfig(router);
List<Op> ops =
routerZkManager.prepareRouterCreate(router.getId(),
routerConfig);
// Create the top level directories
String tenantId = router.getProperty(Router.Property.tenant_id);
if (!Strings.isNullOrEmpty(tenantId)) {
ops.addAll(tenantZkManager.prepareCreate(tenantId));
}
zkManager.multi(ops);
log.debug("routersCreate ex.ing: router={}", router);
return router.getId();
}
@Override
public void routersUpdate(@Nonnull Router router) throws
StateAccessException, SerializationException {
// Get the original data
Router oldRouter = routersGet(router.getId());
RouterZkManager.RouterConfig routerConfig = Converter.toRouterConfig(
router);
List<Op> ops = new ArrayList<>();
// Update the config
ops.addAll(routerZkManager.prepareUpdate(router.getId(), routerConfig));
if (!ops.isEmpty()) {
zkManager.multi(ops);
}
}
@Override
public List<Router> routersFindByTenant(String tenantId) throws StateAccessException,
SerializationException {
log.debug("routersFindByTenant entered: tenantId={}", tenantId);
List<Router> routers = routersGetAll();
for (Iterator<Router> it = routers.iterator(); it.hasNext();) {
if (!it.next().hasTenantId(tenantId)) {
it.remove();
}
}
log.debug("routersFindByTenant exiting: {} routers found",
routers.size());
return routers;
}
@Override
public @CheckForNull Rule<?, ?> rulesGet(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered: id={}", id);
Rule<?,?> rule = null;
if (ruleZkManager.exists(id)) {
rule = Converter.fromRuleConfig(ruleZkManager.get(id));
rule.setId(id);
// Find position of rule in chain
RuleList ruleList = ruleZkManager.getRuleList(rule.getChainId());
int position = ruleList.getRuleList().indexOf(id) + 1;
rule.setPosition(position);
}
log.debug("Exiting: rule={}", rule);
return rule;
}
@Override
public void rulesDelete(UUID id)
throws StateAccessException, SerializationException {
ruleZkManager.delete(id);
}
@Override
public UUID rulesCreate(@Nonnull Rule<?, ?> rule)
throws StateAccessException, RuleIndexOutOfBoundsException,
SerializationException {
return ruleZkManager.create(rule.getId(), Converter.toRuleConfig(rule),
rule.getPosition());
}
@Override
public List<Rule<?, ?>> rulesFindByChain(UUID chainId)
throws StateAccessException, SerializationException {
List<UUID> ruleIds = ruleZkManager.getRuleList(chainId).getRuleList();
List<Rule<?, ?>> rules = new ArrayList<>();
int position = 1;
for (UUID id : ruleIds) {
Rule<?,?> rule = rulesGet(id);
rule.setPosition(position);
position++;
rules.add(rule);
}
return rules;
}
@Override
public Set<String> tenantsGetAll() throws StateAccessException {
return tenantZkManager.list();
}
public WriteVersion writeVersionGet()
throws StateAccessException {
WriteVersion writeVersion = new WriteVersion();
String version = systemDataProvider.getWriteVersion();
writeVersion.setVersion(version);
return writeVersion;
}
/**
* Overwrites the current write version with the string supplied
* @param newVersion The new version to set the write version to.
*/
public void writeVersionUpdate(WriteVersion newVersion)
throws StateAccessException {
systemDataProvider.setWriteVersion(newVersion.getVersion());
}
/**
* Get the system state info.
*
* @return System State info.
* @throws StateAccessException
*/
public SystemState systemStateGet()
throws StateAccessException {
SystemState systemState = new SystemState();
boolean upgrade = systemDataProvider.systemUpgradeStateExists();
boolean readonly = systemDataProvider.configReadOnly();
String writeVersion = systemDataProvider.getWriteVersion();
systemState.setState(upgrade ? SystemState.State.UPGRADE.toString()
: SystemState.State.ACTIVE.toString());
systemState.setAvailability(
readonly ? SystemState.Availability.READONLY.toString()
: SystemState.Availability.READWRITE.toString());
systemState.setWriteVersion(writeVersion);
return systemState;
}
/**
* Update the system state info.
*
* @param systemState the new system state
* @throws StateAccessException
*/
public void systemStateUpdate(SystemState systemState)
throws StateAccessException {
systemDataProvider.setOperationState(systemState.getState());
systemDataProvider.setConfigState(systemState.getAvailability());
systemDataProvider.setWriteVersion(systemState.getWriteVersion());
}
/**
* Get the Host Version info
*
* @return A list containing HostVersion objects, each of which
* contains version information about a specific host.
* @throws StateAccessException
*/
public List<HostVersion> hostVersionsGet()
throws StateAccessException {
List<HostVersion> hostVersionList = new ArrayList<>();
List<String> versions = systemDataProvider.getVersionsInDeployment();
for (String version : versions) {
List<String> hosts = systemDataProvider.getHostsWithVersion(version);
for (String host : hosts) {
HostVersion hostVersion = new HostVersion();
hostVersion.setHostId(UUID.fromString(host));
hostVersion.setVersion(version);
hostVersionList.add(hostVersion);
}
}
return hostVersionList;
}
/**
* Trace request methods
*/
@Override
@CheckForNull
public TraceRequest traceRequestGet(UUID id)
throws StateAccessException, SerializationException {
if (traceReqZkManager.exists(id)) {
TraceRequestZkManager.TraceRequestConfig config
= traceReqZkManager.get(id);
if (config != null) {
return Converter.fromTraceRequestConfig(config).setId(id);
}
}
return null;
}
@Override
public void traceRequestDelete(UUID id)
throws StateAccessException, SerializationException {
List<Op> ops = new ArrayList<Op>();
TraceRequest request = traceRequestGet(id);
if (request == null) {
throw new StateAccessException("Trace does not exist");
}
ops.addAll(traceReqZkManager.prepareDelete(id));
zkManager.multi(ops);
}
private boolean checkTraceRequestDeviceExists(TraceRequest traceRequest)
throws StateAccessException, SerializationException {
switch (traceRequest.getDeviceType()) {
case ROUTER:
return routersGet(traceRequest.getDeviceId()) != null;
case BRIDGE:
return bridgesGet(traceRequest.getDeviceId()) != null;
case PORT:
return portsGet(traceRequest.getDeviceId()) != null;
}
return false;
}
@Override
public UUID traceRequestCreate(@Nonnull TraceRequest traceRequest)
throws StateAccessException, SerializationException,
RuleIndexOutOfBoundsException {
return traceRequestCreate(traceRequest, false);
}
@Override
public UUID traceRequestCreate(@Nonnull TraceRequest traceRequest,
boolean enabled)
throws StateAccessException, SerializationException,
RuleIndexOutOfBoundsException {
if (traceRequest.getId() == null) {
traceRequest.setId(UUID.randomUUID());
}
// check device exists
if (!checkTraceRequestDeviceExists(traceRequest)) {
throw new StateAccessException(
"Device " + traceRequest.getDeviceId()
+ " of type " + traceRequest.getDeviceType()
+ " does not exist");
}
UUID id = traceRequest.getId();
TraceRequestZkManager.TraceRequestConfig config
= Converter.toTraceRequestConfig(traceRequest);
List<Op> ops = new ArrayList<Op>();
ops.addAll(traceReqZkManager.prepareCreate(id, config));
if (enabled) {
ops.addAll(traceRequestPrepareEnable(traceRequest));
}
zkManager.multi(ops);
// device may have been deleted after we checked, but before
// we created the trace, if so, the trace is no longer valid,
// delete
if (!checkTraceRequestDeviceExists(traceRequest)) {
traceRequestDelete(traceRequest.getId());
throw new StateAccessException(
"Device " + traceRequest.getDeviceId() + " deleted");
}
return id;
}
@Override
public List<TraceRequest> traceRequestGetAll()
throws StateAccessException, SerializationException {
List<TraceRequest> traceRequests = new ArrayList<>();
String path = pathBuilder.getTraceRequestsPath();
if (zkManager.exists(path)) {
Set<String> trIds = zkManager.getChildren(path);
for (String id : trIds) {
TraceRequest tr = traceRequestGet(UUID.fromString(id));
if (tr != null) {
traceRequests.add(tr);
}
}
}
return traceRequests;
}
@Override
public List<TraceRequest> traceRequestFindByTenant(String tenantId)
throws StateAccessException, SerializationException {
List<TraceRequest> traceRequests = traceRequestGetAll();
Iterator<TraceRequest> iter = traceRequests.iterator();
while (iter.hasNext()) {
TraceRequest t = iter.next();
String ownerId = null;
switch (t.getDeviceType()) {
case ROUTER:
Router r = routersGet(t.getDeviceId());
if (r == null
|| !r.hasTenantId(tenantId)) {
iter.remove();
}
break;
case BRIDGE:
Bridge b = bridgesGet(t.getDeviceId());
if (b == null
|| !b.hasTenantId(tenantId)) {
iter.remove();
}
break;
case PORT:
Port p = portsGet(t.getDeviceId());
if (p == null) {
iter.remove();
} else {
UUID portDevice = p.getDeviceId();
Bridge bridge = bridgesGet(portDevice);
Router router = routersGet(portDevice);
if (bridge != null) {
if (!bridge.hasTenantId(tenantId)) {
iter.remove();
}
} else if (router != null) {
if (!router.hasTenantId(tenantId)) {
iter.remove();
}
} else {
// port doesn't have a device, so can't belong
// to a tenant
iter.remove();
}
}
break;
default:
// no device, so no owner
iter.remove();
}
}
return traceRequests;
}
/**
* If the agent crashes after this is called but before it
* is assigned to a device, a chain will be orphaned.
*/
private UUID traceFindOrCreateChain(TraceRequest request)
throws StateAccessException, SerializationException {
String name = traceReqZkManager.traceRequestChainName(
request.getId());
for (Chain chain : chainsGetAll()) {
if (chain.getName().equals(name)) {
return chain.getId();
}
}
Chain chain = new Chain().setName(name);
chainsCreate(chain);
return chain.getId();
}
private UUID traceFindOrCreateRule(UUID chainId, TraceRequest request,
List<Op> ops)
throws StateAccessException, SerializationException,
RuleIndexOutOfBoundsException {
for (Rule<?,?> r : rulesFindByChain(chainId)) {
if (r instanceof TraceRule) {
TraceRule rule = (TraceRule)r;
if (Objects.equals(rule.getRequestId(), request.getId())) {
return rule.getId(); // only one rule per request for now
}
}
}
TraceRule rule = new TraceRule(request.getId(),
request.getCondition(),
request.getLimit());
rule.setChainId(chainId).setPosition(1).setId(UUID.randomUUID());
ops.addAll(ruleZkManager.prepareInsertPositionOrdering(
rule.getId(), Converter.toRuleConfig(rule), 1));
return rule.getId();
}
private List<Op> traceRequestPrepareEnable(TraceRequest request)
throws StateAccessException, SerializationException,
RuleIndexOutOfBoundsException {
List<Op> ops = new ArrayList<Op>();
if (request.getEnabledRule() != null) {
return ops; // already enabled
}
UUID id = request.getId();
UUID deviceId = request.getDeviceId();
UUID ruleId = null;
switch (request.getDeviceType()) {
case BRIDGE:
Bridge bridge = bridgesGet(deviceId);
if (bridge != null) {
UUID chainId = bridge.getInboundFilter();
if (chainId == null) {
chainId = traceFindOrCreateChain(request);
bridge.setInboundFilter(chainId);
ops.addAll(bridgeZkManager.prepareUpdate(bridge.getId(),
Converter.toBridgeConfig(bridge)));
}
ruleId = traceFindOrCreateRule(chainId, request, ops);
} else {
throw new IllegalStateException("Bridge device does not exist");
}
break;
case PORT:
Port port = portsGet(deviceId);
if (port != null) {
UUID chainId = port.getInboundFilter();
if (chainId == null) {
chainId = traceFindOrCreateChain(request);
port.setInboundFilter(chainId);
ops.addAll(portZkManager.prepareUpdate(deviceId,
Converter.toPortConfig(port)));
}
ruleId = traceFindOrCreateRule(chainId, request, ops);
} else {
throw new IllegalStateException("Port device does not exist");
}
break;
case ROUTER:
Router router = routersGet(deviceId);
if (router != null) {
UUID chainId = router.getInboundFilter();
if (chainId == null) {
chainId = traceFindOrCreateChain(request);
router.setInboundFilter(chainId);
ops.addAll(routerZkManager.prepareUpdate(router.getId(),
Converter.toRouterConfig(router)));
}
ruleId = traceFindOrCreateRule(chainId, request, ops);
} else {
throw new IllegalStateException("Router device does not exist");
}
break;
default:
throw new IllegalStateException(
"Unknown device type " + request.getDeviceType());
}
request.setEnabledRule(ruleId);
ops.addAll(traceReqZkManager.prepareUpdate(request.getId(),
Converter
.toTraceRequestConfig(
request)));
return ops;
}
@Override
public void traceRequestEnable(UUID id)
throws StateAccessException, SerializationException,
RuleIndexOutOfBoundsException {
log.debug("Entered(traceRequestEnable): id={}", id);
TraceRequest request = traceRequestGet(id);
if (request == null) {
throw new IllegalStateException("Trace request does not exist");
}
zkManager.multi(traceRequestPrepareEnable(request));
log.debug("Exited(traceRequestEnable): id={}", id);
}
private List<Op> traceRequestPrepareDisable(TraceRequest request)
throws StateAccessException, SerializationException {
return traceReqZkManager.prepareDisable(request.getId());
}
public void traceRequestDisable(UUID id)
throws StateAccessException, SerializationException {
log.debug("Entered(traceRequestEnable): id={}", id);
TraceRequest request = traceRequestGet(id);
if (request == null) {
throw new IllegalStateException("Trace request does not exist");
}
zkManager.multi(traceRequestPrepareDisable(request));
log.debug("Exited(traceRequestDisable): id={}", id);
}
@Override
public Integer getPrecedingHealthMonitorLeader(Integer myNode)
throws StateAccessException {
String path = pathBuilder.getHealthMonitorLeaderDirPath();
Set<String> set = zkManager.getChildren(path);
String seqNumPath
= ZkUtil.getNextLowerSequenceNumberPath(set, myNode);
return seqNumPath == null ? null :
ZkUtil.getSequenceNumberFromPath(seqNumPath);
}
@Override
public Integer registerAsHealthMonitorNode(
ZkLeaderElectionWatcher.ExecuteOnBecomingLeader cb)
throws StateAccessException {
String path = pathBuilder.getHealthMonitorLeaderDirPath();
return ZkLeaderElectionWatcher.registerLeaderNode(cb, path, zkManager);
}
@Override
public void removeHealthMonitorLeaderNode(Integer node)
throws StateAccessException {
if (node == null)
return;
String path = pathBuilder.getHealthMonitorLeaderDirPath() + "/" +
StringUtils.repeat("0", 10 - node.toString().length()) +
node.toString();
zkManager.delete(path);
}
@Override
public void vtepCreate(VTEP vtep)
throws StateAccessException, SerializationException {
VtepZkManager.VtepConfig config = Converter.toVtepConfig(vtep);
zkManager.multi(vtepZkManager.prepareCreate(vtep.getId(), config));
}
@Override
public VTEP vtepGet(IPv4Addr ipAddr)
throws StateAccessException, SerializationException {
if (!vtepZkManager.exists(ipAddr))
return null;
VTEP vtep = Converter.fromVtepConfig(vtepZkManager.get(ipAddr));
vtep.setId(ipAddr);
return vtep;
}
@Override
public List<VTEP> vtepsGetAll()
throws StateAccessException, SerializationException {
List<VTEP> vteps = new ArrayList<>();
String path = pathBuilder.getVtepsPath();
if (zkManager.exists(path)) {
Set<String> vtepIps = zkManager.getChildren(path);
for (String vtepIp : vtepIps) {
VTEP vtep = vtepGet(IPv4Addr.fromString(vtepIp));
if (vtep != null) {
vteps.add(vtep);
}
}
}
return vteps;
}
@Override
public void vtepDelete(IPv4Addr ipAddr)
throws StateAccessException, SerializationException {
List<Op> deleteNoOwner = new ArrayList<>(
vtepZkManager.prepareDelete(ipAddr));
List<Op> deleteOwner = new ArrayList<>(
vtepZkManager.prepareDeleteOwner(ipAddr));
deleteOwner.addAll(deleteNoOwner);
try {
zkManager.multi(deleteOwner);
} catch (NoStatePathException e) {
zkManager.multi(deleteNoOwner);
}
}
@Override
public void vtepUpdate(VTEP vtep)
throws StateAccessException, SerializationException {
VtepZkManager.VtepConfig config = Converter.toVtepConfig(vtep);
zkManager.multi(vtepZkManager.prepareUpdate(vtep.getId(), config));
}
@Override
public void vtepAddBinding(@Nonnull IPv4Addr ipAddr,
@Nonnull String portName, short vlanId,
@Nonnull UUID networkId)
throws StateAccessException {
zkManager.multi(vtepZkManager.prepareCreateBinding(ipAddr, portName,
vlanId, networkId));
}
@Override
public void vtepDeleteBinding(@Nonnull IPv4Addr ipAddr,
@Nonnull String portName, short vlanId)
throws StateAccessException {
zkManager.multi(
vtepZkManager.prepareDeleteBinding(ipAddr, portName, vlanId));
}
@Override
public List<VtepBinding> vtepGetBindings(@Nonnull IPv4Addr ipAddr)
throws StateAccessException {
return vtepZkManager.getBindings(ipAddr);
}
@Override
public List<VtepBinding> bridgeGetVtepBindings(@Nonnull UUID bridgeId,
IPv4Addr vtepMgmtIp)
throws StateAccessException, SerializationException {
List<VtepBinding> bindings = new ArrayList<>();
Bridge br = bridgesGet(bridgeId);
if (br == null || br.getVxLanPortIds() == null) {
return bindings;
}
for (UUID id : br.getVxLanPortIds()) { // NPE safe
VxLanPort vxLanPort = (VxLanPort)portsGet(id);
if (vxLanPort == null) {
continue;
}
IPv4Addr portMgmtIp = vxLanPort.getMgmtIpAddr();
if (vtepMgmtIp != null &&
!portMgmtIp.equals(vtepMgmtIp)) {
continue;
}
List<VtepBinding> all = vtepZkManager.getBindings(portMgmtIp);
for (VtepBinding b : all) {
if (b.getNetworkId().equals(bridgeId)) {
bindings.add(b);
}
}
}
return bindings;
}
@Override
public VtepBinding vtepGetBinding(@Nonnull IPv4Addr ipAddr,
@Nonnull String portName, short vlanId)
throws StateAccessException {
return vtepZkManager.getBinding(ipAddr, portName, vlanId);
}
@Override
public int getNewVni() throws StateAccessException {
return vtepZkManager.getNewVni();
}
@Override
public IPv4Addr vxlanTunnelEndpointFor(UUID bridgePort)
throws SerializationException, StateAccessException {
BridgePort port = (BridgePort) portsGet(bridgePort);
if (port == null) {
return null;
}
if (!port.isExterior()) {
throw new IllegalArgumentException("Port " + port.getId() + " is " +
"not exterior");
}
Bridge b = bridgesGet(port.getDeviceId());
if (null == b) {
log.warn("Bridge {} for port {} does not exist anymore",
port.getDeviceId(), port.getId());
return null;
}
return vxlanTunnelEndpointForInternal(b, port);
}
/*
* Utility method to use internaly. It assumes that the caller has verified
* that both the bridge and port are non-null.
*
* It's convenient to slice this out so other methods can fetch the
* parameters as they prefer, and then use this to retrieve the vxlan
* tunnel endpoint. The method returns a null IP if the endpoint cannot
* be retrieved for any reason (bridge unbound, etc.)
*
* Note that this method will return null if the bridge is not bound to
* any VTEP. This is because we won't be able to figure out the tunnel zone
* from which to extract the host's IP.
*
* @param b a bridge, expected to exist, be bound to a VTEP, and contain the
* given port.
* @param port a bridge port on the given bridge, that must be exterior
* @return the IP address of the bound host's membership in the VTEP's
* tunnel zone.
*/
private IPv4Addr vxlanTunnelEndpointForInternal(Bridge b, BridgePort port)
throws SerializationException, StateAccessException {
// We can take a random vxlan port, since all are forced to be in the
// same tz
if (b.getVxLanPortIds() == null) {
return null;
}
VxLanPort vxlanPort = null;
int i = 0;
while (vxlanPort == null && i < b.getVxLanPortIds().size()) {
vxlanPort = (VxLanPort)portsGet(b.getVxLanPortIds().get(i++));
if (vxlanPort == null) {
log.warn("VxLanPort {} at bridge {} does not exist anymore",
b.getVxLanPortIds(), b.getId());
}
}
if (vxlanPort == null) {
log.warn("Can't find VTEP tunnel zone on bridge {} - is it even " +
"bound to a VTEP?", b.getId());
return null;
}
IPv4Addr vtepMgmtIp = vxlanPort.getMgmtIpAddr();
log.debug("Port's bridge {} is bound to one or more VTEPs", b.getId());
// We will need the host where the given BridgePort is bound
UUID hostId = port.getHostId();
if (hostId == null) {
log.error("Port {} is not bound to a host", port.getId());
return null;
}
// Let's get the tunnel zone this host should be in, and get the IP of
// the host in that tunnel zone.
VTEP vtep = vtepGet(vtepMgmtIp);
if (vtep == null) {
log.warn("Vtep {} bound to bridge {} does not exist anymore",
vtepMgmtIp, b.getId());
return null;
}
UUID tzId = vtep.getTunnelZoneId();
TunnelZone.HostConfig hostCfg =
this.tunnelZonesGetMembership(tzId, hostId);
if (hostCfg == null) {
log.error("Port {} on bridge {} bount to an interface in host {} " +
"was expected to belong to tunnel zone {} through " +
"binding to VTEP {}", port.getId(), b.getId(), hostId,
tzId, vtepMgmtIp);
return null;
}
return hostCfg.getIp();
}
@Override
public VxLanPort bridgeCreateVxLanPort(
UUID bridgeId, IPv4Addr mgmtIp, int mgmtPort, int vni,
IPv4Addr tunnelIp, UUID tunnelZoneId)
throws StateAccessException, SerializationException {
// the get below migrates from legacy schema if needed
BridgeConfig bridgeConfig = bridgeZkManager.get(bridgeId);
if (bridgeConfig.vxLanPortIds == null) { // should not happen but might
// on first read from ZK
bridgeConfig.vxLanPortIds = new ArrayList<>(2);
}
// migrate legacy data
if (bridgeConfig.vxLanPortId != null) {
if (!bridgeConfig.vxLanPortIds.contains(bridgeConfig.vxLanPortId)) {
bridgeConfig.vxLanPortIds.add(0, bridgeConfig.vxLanPortId);
log.debug("Lazy update of Bridge schema: existing VTEP"
+ "binding migrated to new schema in {}", bridgeId);
}
}
for (UUID id : bridgeConfig.vxLanPortIds) { // NPE safe
VxLanPort p = (VxLanPort) portsGet(id);
if (p.getMgmtIpAddr().equals(mgmtIp)) {
throw new IllegalStateException(
"Not expected to find a port for vtep " + mgmtIp);
}
}
VxLanPort port = new VxLanPort(bridgeId, mgmtIp, mgmtPort, vni,
tunnelIp, tunnelZoneId);
PortConfig portConfig = Converter.toPortConfig(port);
List<Op> ops = new ArrayList<>();
ops.addAll(portZkManager.prepareCreate(port.getId(), portConfig));
bridgeConfig.vxLanPortIds.add(port.getId());
ops.addAll(bridgeZkManager.prepareUpdate(bridgeId, bridgeConfig));
zkManager.multi(ops);
return port;
}
@Override
public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp)
throws SerializationException, StateAccessException {
Bridge b = bridgesGet(bridgeId);
if (b == null || b.getVxLanPortIds() == null) {
return;
}
for (UUID portId : b.getVxLanPortIds()) {
VxLanPort p = (VxLanPort)portsGet(portId);
if (p.getMgmtIpAddr().equals(mgmtIp)) {
bridgeDeleteVxLanPort(p);
return;
}
}
}
@Override
public void bridgeDeleteVxLanPort(@Nonnull VxLanPort port)
throws SerializationException, StateAccessException {
// Make sure the bridge has a VXLAN port.
BridgeConfig bridgeCfg = bridgeZkManager.get(port.getDeviceId());
UUID vxlanPortId = port.getId();
List<Op> ops = new ArrayList<>();
// Let's locate this id in the legacy or new vxlanPortIds of the bridge
if (bridgeCfg.vxLanPortId != null &&
bridgeCfg.vxLanPortId.equals(vxlanPortId)) {
bridgeCfg.vxLanPortId = null;
}
if (bridgeCfg.vxLanPortIds.contains(vxlanPortId)) {
bridgeCfg.vxLanPortIds.remove(vxlanPortId);
}
ops.addAll(bridgeZkManager.prepareUpdate(bridgeCfg.id, bridgeCfg));
// Delete the port.
VxLanPortConfig portConfig =
(VxLanPortConfig)portZkManager.get(vxlanPortId);
ops.addAll(portZkManager.prepareDelete(vxlanPortId));
// Delete its bindings in Zookeeper.
ops.addAll(vtepZkManager.prepareDeleteAllBindings(
IPv4Addr.fromString(portConfig.mgmtIpAddr),
portConfig.device_id));
zkManager.multi(ops);
}
@Override
public UUID tryOwnVtep(IPv4Addr mgmtIp, UUID ownerId)
throws SerializationException, StateAccessException {
return vtepZkManager.tryOwnVtep(mgmtIp, ownerId);
}
@Override
public Bridge bridgeGetAndWatch(UUID id, Directory.TypedWatcher watcher)
throws StateAccessException, SerializationException {
try {
BridgeConfig bc = bridgeZkManager.get(id, watcher);
Bridge b = Converter.fromBridgeConfig(bc);
b.setId(id);
return b;
} catch (NoStatePathException e) {
return null;
}
}
@Override
public void vxLanPortIdsAsyncGet(DirectoryCallback<Set<UUID>> callback,
Directory.TypedWatcher watcher)
throws StateAccessException {
portZkManager.getVxLanPortIdsAsync(callback, watcher);
}
@Override
public Ip4ToMacReplicatedMap getIp4MacMap(UUID bridgeId)
throws StateAccessException {
return new Ip4ToMacReplicatedMap(
bridgeZkManager.getIP4MacMapDirectory(bridgeId)
);
}
}
| 36.325756 | 122 | 0.621335 |
bc6ca397b5218e3eced3a5857db77bc28d83a883 | 588 | package bms.stream.receiver.parser;
import bms.stream.receiver.model.BatteryAttribute;
/**
* Temperature and change rate (TCR) parser.
*
* @author Shrinidhi Muralidhar Karanam on 2021-06-25
*/
public class TCRBatteryAttributeParser implements BatteryAttributeParser<BatteryAttribute> {
@Override
public BatteryAttribute parseToObject(String str) {
String[] parameters = str.split(", ");
return new BatteryAttribute(
Double.parseDouble(parameters[0].split(":")[1]),
Double.parseDouble(parameters[1].split(":")[1])
);
}
}
| 26.727273 | 92 | 0.683673 |
a8fd9604ea6ab92c98b634f269e3cbf00e746530 | 787 | package us.ihmc.commonWalkingControlModules.desiredFootStep;
import us.ihmc.humanoidRobotics.communication.controllerAPI.command.FootstepDataCommand;
import us.ihmc.humanoidRobotics.communication.packets.walking.FootstepDataMessage;
import us.ihmc.robotics.robotSide.RobotSide;
public interface DesiredFootstepCalculator
{
public abstract FootstepDataMessage updateAndGetDesiredFootstep(RobotSide supportLegSide);
public abstract void initializeDesiredFootstep(RobotSide supportLegSide, double stepDuration);
public abstract FootstepDataMessage predictFootstepAfterDesiredFootstep(RobotSide supportLegSide, FootstepDataMessage desiredFootstep, double timeFromNow,
double stepDuration);
public abstract void initialize();
public abstract boolean isDone();
}
| 39.35 | 157 | 0.850064 |
84ce316972c11a25c400d41cfac9a90f054e9e0f | 1,845 | /**
* Licensed to the RxJava Connector HTTP under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.hekonsek.rxjava.connector.http;
import com.github.hekonsek.rxjava.event.ReplyHandler;
import io.reactivex.Completable;
import io.vertx.reactivex.core.http.HttpServerRequest;
import static com.github.hekonsek.rxjava.connector.http.HttpResponse.httpResponse;
import static io.reactivex.Completable.complete;
public class VertxHttpReplyHandler implements ReplyHandler {
private final HttpServerRequest request;
public VertxHttpReplyHandler(HttpServerRequest request) {
this.request = request;
}
@Override public Completable reply(Object response) {
if(response instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse) response;
request.response().setStatusCode(httpResponse.code()).end(httpResponse.body());
return complete();
} else {
HttpResponse httpResponse = httpResponse(response);
request.response().setStatusCode(httpResponse.code()).end(httpResponse.body());
return complete();
}
}
} | 40.108696 | 91 | 0.736043 |
a5ece628fe7df349bc87a699d7d7a8ee9f61583d | 6,332 | package com.alibaba.alink.operator.batch.linearprogramming;
import com.alibaba.alink.common.comqueue.IterativeComQueue;
import com.alibaba.alink.common.comqueue.communication.AllReduce;
import com.alibaba.alink.common.comqueue.communication.AllReduce.SerializableBiConsumer;
import com.alibaba.alink.operator.batch.BatchOperator;
import com.alibaba.alink.operator.common.linearprogramming.InteriorPoint.*;
import com.alibaba.alink.params.linearprogramming.LPParams;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.ml.api.misc.param.Params;
import org.apache.flink.types.Row;
/**
* The *interior-point* method uses the primal-dual path following algorithm
* outlined in [1]_. Interior point methods are a type of algorithm that are
* used in solving both linear and nonlinear convex optimization problems
* that contain inequalities as constraints. The LP Interior-Point method
* relies on having a linear programming model with the objective function
* and all constraints being continuous and twice continuously differentiable.
* <p>
* References
* ----------
* .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
* optimizer for linear programming: an implementation of the
* homogeneous algorithm." High performance optimization. Springer US,
* 2000. 197-232.
*/
public class InteriorPointBatchOp extends BatchOperator<InteriorPointBatchOp> implements LPParams<InteriorPointBatchOp> {
public static final String MATRIX = "matrix";
public static final String VECTOR = "vector";
public static final String UPPER_BOUNDS = "upperBounds";
public static final String LOWER_BOUNDS = "lowerBounds";
public static final String UN_BOUNDS = "unBounds";
public static final String STATIC_A = "staticA";// (m,n)
public static final String STATIC_B = "staticB";// (m,)
public static final String STATIC_C = "staticC";// (n,)
public static final String STATIC_C0 = "staticC0";// constant
public static final String LOCAL_X = "localX";// (n+2,)
public static final String LOCAL_Y = "localY";// (m+2,)
public static final String LOCAL_Z = "localZ";// (n+2,)
public static final String LOCAL_MU = "localMu";// constant
public static final String LOCAL_TAU = "localTau";// constant
public static final String LOCAL_KAPPA = "localKappa";// constant
public static final String LOCAL_GAMMA = "localGamma";// constant
public static final String LOCAL_M = "localM";// (m*m+2,) row major 1D matrix
public static final String LOCAL_M_INV = "localMInv";//
public static final String LOCAL_X_DIV_Z = "localXDivZ";// (n,)
public static final String LOCAL_R_HAT_XS = "localRHatXs";
public static final String LOCAL_X_HAT = "localXHat";
public static final String R_P = "r_P";// (m+2,)
public static final String R_D = "r_D";// (n+2,)
public static final String R_G = "r_G";// constant
public static final String D_X = "d_x";
public static final String D_Y = "d_y";
public static final String D_Z = "d_z";
public static final String D_TAU = "d_tau";
public static final String D_KAPPA = "d_kappa";
public static final String N = "n";
public static final String R_P0 = "r_p0";
public static final String R_D0 = "r_d0";
public static final String R_G0 = "r_g0";
public static final String MU_0 = "mu_0";
public static final String CONDITION_GO = "go";
/**
* null constructor.
*/
public InteriorPointBatchOp() {
this(null);
}
/**
* constructor.
* * @param params the parameters set.
*/
public InteriorPointBatchOp(Params params) {
super(params);
}
static DataSet<Row> iterateICQ(DataSet<Row> inputMatrix,
DataSet<Row> inputVec,
DataSet<Row> upperBounds,
DataSet<Row> lowerBounds,
DataSet<Row> unBounds,
int iter) {
return new IterativeComQueue()
.initWithBroadcastData(MATRIX, inputMatrix)
.initWithBroadcastData(VECTOR, inputVec)
.initWithBroadcastData(UPPER_BOUNDS, upperBounds)
.initWithBroadcastData(LOWER_BOUNDS, lowerBounds)
.initWithBroadcastData(UN_BOUNDS, unBounds)
.add(new GetDelta())
.add(new AllReduce(R_D, null, new mergeVectorReduceFunc()))
.add(new AllReduce(R_P, null, new mergeVectorReduceFunc()))
.add(new AllReduce(LOCAL_M, null, new mergeVectorReduceFunc()))
.add(new GetAlpha(0))
.add(new GetAlpha(1))
.add(new UpdateData())
.setCompareCriterionOfNode0(new InteriorPointIterTermination())
.closeWith(new InteriorPointComplete())
.setMaxIter(iter)
.exec();
}
@Override
public InteriorPointBatchOp linkFrom(BatchOperator<?>... inputs) {
DataSet<Row> inputM = inputs[0].getDataSet();
DataSet<Row> inputV = inputs[1].getDataSet();
DataSet<Row> UpperBoundsDataSet = inputs[2].getDataSet();
DataSet<Row> LowerBoundsDataSet = inputs[3].getDataSet();
DataSet<Row> UnBoundsDataSet = inputs[4].getDataSet();
int iter = getMaxIter();
DataSet<Row> Input = iterateICQ(inputM, inputV,
UpperBoundsDataSet,
LowerBoundsDataSet,
UnBoundsDataSet,
iter)
.map((MapFunction<Row, Row>) row -> {
return row;
})
.returns(new RowTypeInfo(Types.DOUBLE));
this.setOutput(Input, new String[]{"result"});
return this;
}
private static class mergeVectorReduceFunc implements SerializableBiConsumer<double[], double[]> {
@Override
public void accept(double[] doubles, double[] doubles2) {
int s = (int) doubles2[0];
int t = (int) doubles2[1];
System.arraycopy(doubles2, s + 2, doubles, s + 2, t - s);
}
}
}
| 45.228571 | 121 | 0.653664 |
fb2fc1f6fbb99ea27f93aae38c98d5eafda3acf4 | 233 | package cn.gyw.backend.system.dao;
import cn.gyw.backend.system.model.entity.RoleResourceRelation;
import cn.gyw.components.web.base.mgb.BaseDao;
public interface RoleResourceRelationMapper extends BaseDao<RoleResourceRelation> {
} | 33.285714 | 83 | 0.841202 |
f783f14f6578a79d16dad5258a59fae705600b55 | 2,072 | /*
* Copyright 2019 Scott Logic Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scottlogic.datahelix.generator.core.profile.constraints.atomic;
import com.scottlogic.datahelix.generator.common.ValidationException;
import com.scottlogic.datahelix.generator.common.profile.Field;
import com.scottlogic.datahelix.generator.common.profile.InSetRecord;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static com.scottlogic.datahelix.generator.common.profile.FieldBuilder.createField;
import static com.scottlogic.datahelix.generator.core.builders.TestAtomicConstraintBuilder.inSetRecordsFrom;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
public class InSetConstraintTests
{
@Test
public void testConstraintThrowsIfGivenEmptySet(){
Field field1 = createField("TestField");
Assertions.assertThrows(
ValidationException.class,
() -> new InSetConstraint(field1, emptyList()));
}
@Test
public void testConstraintThrowsIfGivenNullInASet(){
Field field1 = createField("TestField");
Assertions.assertThrows(
ValidationException.class,
() -> new InSetConstraint(field1, singletonList(new InSetRecord(null))));
}
@Test
public void testConstraintThrowsNothingIfGivenAValidSet(){
Field field1 = createField("TestField");
Assertions.assertDoesNotThrow(
() -> new InSetConstraint(field1, inSetRecordsFrom("foo")));
}
}
| 35.724138 | 108 | 0.743726 |
bdb280b486e53a363860bb1d57f22635825a3808 | 2,126 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.sergiostorino.model.service.util.sms;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smslib.AGateway;
import org.smslib.ICallNotification;
/**
* Classe Responsavel por notificar Chamadas para o SIM
* @author Junior
*/
public class CallNotification implements ICallNotification {
private Properties modem1 = new Properties();
private Properties modem2 = new Properties();
private static final Log log = LogFactory.getLog(CallNotification.class);
public CallNotification() {
try {
modem1.load(getClass().getResourceAsStream("/serialModem.properties"));
modem2.load(getClass().getResourceAsStream("/serialModem.properties"));
} catch (IOException ex) {
Logger.getLogger(CallNotification.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Metodo Responsável por receber por parametro a porta de entrada da
* chamada, e o numero que esta realizando a chamada para o chip SIM.
*
* faz a verificando estando entre as condições abaixo realiza a
* persistencia e notifica o remetente da ligação com SMS
*
* @param gateway
* @param numero
*/
@Override
public void process(AGateway gateway, String numero) {
if (gateway.getGatewayId().equalsIgnoreCase(modem1.getProperty("sms1.service.modem"))) {
log.info("SMS Informativo sobre o SIM Encaminhado para o Remetente da Chamada ".concat(numero));
} else if (gateway.getGatewayId().equalsIgnoreCase(modem2.getProperty("sms2.service.modem"))) {
log.info("SMS Informativo sobre o SIM Encaminhado para o Remetente da Chamada ".concat(numero));
}
}
}
| 33.746032 | 109 | 0.682032 |
be9d6c2c364592a8803650711e0e0adc87ec3d18 | 531 | /*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/
// line 24 "GeographicalInformationSystem.ump"
// line 106 "GeographicalInformationSystem.ump"
public class Point
{
//------------------------
// MEMBER VARIABLES
//------------------------
//------------------------
// CONSTRUCTOR
//------------------------
public Point()
{}
//------------------------
// INTERFACE
//------------------------
public void delete()
{}
} | 18.310345 | 75 | 0.442561 |
81ac9d34298ad97867d0f0cd198f90fbcb6789f0 | 3,822 | /*
* Copyright © 2021 ProStore
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.arenadata.dtm.query.execution.plugin.adqm.calcite;
import io.arenadata.dtm.calcite.adqm.configuration.AdqmCalciteConfiguration;
import io.arenadata.dtm.query.calcite.core.framework.DtmCalciteFramework;
import io.arenadata.dtm.query.execution.plugin.adqm.calcite.configuration.CalciteConfiguration;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.tools.FrameworkConfig;
import org.apache.calcite.tools.Planner;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class SqlEddlParserTest {
private static final CalciteConfiguration calciteConfiguration = new CalciteConfiguration();
private static final SqlDialect SQL_DIALECT = new SqlDialect(SqlDialect.EMPTY_CONTEXT);
private final AdqmCalciteConfiguration calciteCoreConfiguration = new AdqmCalciteConfiguration();
private final SqlParser.Config parserConfig = calciteConfiguration.configDdlParser(
calciteCoreConfiguration.eddlParserImplFactory()
);
@Test
void parseSelectWithAliasFinal() throws SqlParseException {
String expectedResult = "SELECT *\n" +
"FROM test.pso AS t FINAL";
DtmCalciteFramework.ConfigBuilder configBuilder = DtmCalciteFramework.newConfigBuilder();
FrameworkConfig frameworkConfig = configBuilder.parserConfig(parserConfig).build();
Planner planner = DtmCalciteFramework.getPlanner(frameworkConfig);
SqlSelect sqlNode = (SqlSelect) planner.parse("select * from test.pso t FINAL");
assertNotNull(sqlNode);
assertThat(sqlNode.toSqlString(SQL_DIALECT).toString()).isEqualToNormalizingNewlines(expectedResult);
}
@Test
void parseSelectWithoutAliasFinal() throws SqlParseException {
String expectedResult = "SELECT *\n" +
"FROM test.pso FINAL";
DtmCalciteFramework.ConfigBuilder configBuilder = DtmCalciteFramework.newConfigBuilder();
FrameworkConfig frameworkConfig = configBuilder.parserConfig(parserConfig).build();
Planner planner = DtmCalciteFramework.getPlanner(frameworkConfig);
SqlSelect sqlNode = (SqlSelect) planner.parse("select * from test.pso FINAL");
assertNotNull(sqlNode);
assertThat(sqlNode.toSqlString(SQL_DIALECT).toString()).isEqualToNormalizingNewlines(expectedResult);
}
@Test
void parseSelectWithASFinal() throws SqlParseException {
String expectedResult = "SELECT *\n" +
"FROM test.pso AS t FINAL";
DtmCalciteFramework.ConfigBuilder configBuilder = DtmCalciteFramework.newConfigBuilder();
FrameworkConfig frameworkConfig = configBuilder.parserConfig(parserConfig).build();
Planner planner = DtmCalciteFramework.getPlanner(frameworkConfig);
SqlSelect sqlNode = (SqlSelect) planner.parse("select * from test.pso as t FINAL");
assertNotNull(sqlNode);
assertThat(sqlNode.toSqlString(SQL_DIALECT).toString()).isEqualToNormalizingNewlines(expectedResult);
}
}
| 48.379747 | 109 | 0.758503 |
0e30612514c794a303d25ef320389e7fed1f224b | 723 | package leetCode.easy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class HappyNumberTest {
@Test
void isHappy() {
HappyNumber happyNumber = new HappyNumber();
assertTrue(happyNumber.isHappy(1));
assertFalse(happyNumber.isHappy(2));
assertFalse(happyNumber.isHappy(3));
assertFalse(happyNumber.isHappy(4));
assertFalse(happyNumber.isHappy(5));
assertTrue(happyNumber.isHappy(7));
assertTrue(happyNumber.isHappy(10));
assertFalse(happyNumber.isHappy(11));
assertTrue(happyNumber.isHappy(13));
assertTrue(happyNumber.isHappy(19));
assertFalse(happyNumber.isHappy(111));
}
} | 30.125 | 52 | 0.676349 |
443f1575a4c00d5cbec8ee86d957d9cc3bf91c6f | 337 | package com.example.lottery.service;
import com.example.random.service.RandomNumberService;
import java.util.List;
/**
* @author Binnur Kurt <binnur.kurt@gmail.com>
*/
public interface LotteryService {
List<Integer> draw();
List<List<Integer>> draw(int column);
void setRandomNumberService(RandomNumberService rns);
}
| 19.823529 | 57 | 0.744807 |
1ebb85ad742e59584d32291d2c0f1c928538296f | 1,383 | package com.athaydes.osgiaas.javac;
import java.util.Collection;
import static java.util.Collections.emptyList;
/**
* Representation of a Java code snippet.
* <p>
* Instances of types implementing this interface can be used to run
* Java code using the {@link JavacService} implementations.
* <p>
* A trivial implementation of this class is provided with the nested {@link Builder} class.
*/
public interface JavaSnippet {
/**
* @return the executable code. This is the code that will go in the body of the runnable method.
*/
String getExecutableCode();
/**
* @return class imports. Eg. ['java.util.*', 'com.acme']
*/
Collection<String> getImports();
class Builder implements JavaSnippet {
private String code = "";
private Collection<String> imports = emptyList();
private Builder() {
}
public static Builder withCode( String code ) {
Builder b = new Builder();
b.code = code;
return b;
}
public Builder withImports( Collection<String> imports ) {
this.imports = imports;
return this;
}
@Override
public String getExecutableCode() {
return code;
}
@Override
public Collection<String> getImports() {
return imports;
}
}
} | 23.844828 | 101 | 0.60376 |
1577654d08c22f4a768c67f3240437aedcd90ab9 | 1,574 | package example;
import com.amazonaws.internal.CRC32MismatchException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.zip.CRC32;
class ChecksumChecker extends InputStream {
public static final int NO_EXPECTED_CRC = -1;
private final InputStream stream;
private final long expectedCrc32;
private final CRC32 crc = new CRC32();
private final CRC32 newCrc = new CRC32();
private ByteBuffer buffer;
public ChecksumChecker(InputStream stream, long expectedCrc32) {
this.stream = stream;
this.expectedCrc32 = expectedCrc32;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (buffer != null) {
newCrc.update(buffer);
}
if (newCrc.getValue() != crc.getValue()) {
throw new CRC32MismatchException("CRC does not match expected value.");
}
var size = stream.read(b, off, len);
if (size == -1) {
if (expectedCrc32 != NO_EXPECTED_CRC && expectedCrc32 != crc.getValue()) {
throw new CRC32MismatchException("CRC does not match expected value. " + crc.getValue());
}
} else {
buffer = ByteBuffer.wrap(b, off, size);
crc.update(buffer);
buffer.position(off);
}
return size;
}
@Override
public int read() {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
stream.close();
}
}
| 26.233333 | 105 | 0.619441 |
dd24823600c312f0654e779d3e7b80a8cfb2c276 | 971 | package net.minecraft.src;
public class SEAItemFoodBowl extends SEAItemFood
{
public SEAItemFoodBowl(int iItemID, int iHungerHealed, float fSaturationModifier, boolean bWolfMeat, String sItemName, String[] eatingTextures) {
super(iItemID, iHungerHealed, fSaturationModifier, bWolfMeat, sItemName, eatingTextures);
}
public SEAItemFoodBowl(int iItemID, int iHungerHealed, float fSaturationModifier, String sItemName, String[] eatingTextures) {
super(iItemID, iHungerHealed, fSaturationModifier, sItemName, eatingTextures);
}
@Override
public ItemStack onEaten( ItemStack stack, World world, EntityPlayer player )
{
super.onEaten( stack, world, player );
ItemStack bowlStack = new ItemStack( Item.bowlEmpty );
if ( !player.inventory.addItemStackToInventory( bowlStack ) )
{
player.dropPlayerItem( bowlStack );
}
return stack;
}
}
| 34.678571 | 150 | 0.68898 |
3e4e9cb34f13532f1e6c267134b9e9c2046fbebe | 1,067 | package company;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
/**
* @Author: Wenhang Chen
* @Description:给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
* <p>
* 示例 1:
* <p>
* 输入: coins = [1, 2, 5], amount = 11
* 输出: 3
* 解释: 11 = 5 + 5 + 1
* 示例 2:
* <p>
* 输入: coins = [2], amount = 3
* 输出: -1
* @Date: Created in 19:11 2/18/2020
* @Modified by:
*/
public class CoinChange {
public int coinChange(int[] coins, int amount) {
// 动态规划
// dp[i] = x 表示,当目标金额为 i 时,至少需要 x 枚硬币。
int[] dp = new int[amount + 1];
// 相当于初始化为正无穷,便于后续取最小值
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int i = 0; i < dp.length; i++) {
for (int coin : coins) {
// 子问题无解,跳过
if (i - coin < 0) continue;
dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
}
}
return (dp[amount] == amount + 1) ? -1 : dp[amount];
}
}
| 16.415385 | 98 | 0.511715 |
e9f4aaca97c8f9b32717a09f5826ae501974e68e | 1,177 | package com.dev.reactive.app.stream;
import java.util.ArrayList;
import java.util.List;
public class ParallelStream {
public static void main(String...strings) {
List<Employee> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 100; i++) {
list.add(new Employee("John", 20000));
list.add(new Employee("Rohn", 3000));
list.add(new Employee("Tom", 15000));
list.add(new Employee("Bheem", 8000));
list.add(new Employee("Shiva", 200));
list.add(new Employee("Krishna", 50000));
}
startTime = System.currentTimeMillis();
long listEmployee = list.stream()
.filter((e) -> e.getSalary() > 1000)
.count();
System.out.println(listEmployee);
endTime = System.currentTimeMillis();
System.out.println("Time taken with Sequential: " + (endTime - startTime));
startTime = System.currentTimeMillis();
long listEmployeeParallel = list.parallelStream()
.filter(e -> e.getSalary() > 1000)
.count();
System.out.println(listEmployeeParallel);
endTime = System.currentTimeMillis();
System.out.println("Time taken with parallel stream: " + (endTime - startTime));
}
}
| 28.02381 | 82 | 0.661003 |
f909c910348b2eb0930a5104613e14708d327e76 | 6,517 | /* Reemplazo de Crud.java */
package main.service;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import main.api.CrudService;
import main.dao.DeportesDao;
import main.dao.DeportesDaoI;
import main.dao.EstadosDao;
import main.dao.EstadosDaoI;
import main.dao.MunicipiosDao;
import main.dao.MunicipiosDaoI;
import main.dao.PersonasDao;
import main.dao.PersonasDaoI;
import main.dao.SexosDao;
import main.dao.SexosDaoI;
import main.dao.excepciones.RegistroExistenteException;
import main.datos.Deporte;
import main.datos.Estado;
import main.datos.Municipio;
import main.datos.Persona;
import main.datos.Sexo;
import main.modelo.Validaciones;
import main.modelo.excepciones.ApellidoIncorrectoException;
import main.modelo.excepciones.CamposIncompletosException;
import main.modelo.excepciones.DeportesVaciosException;
import main.modelo.excepciones.NombreIncorrectoException;
import main.utilidades.Par;
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public class CrudServiceImpl implements CrudService {
private final EstadosDaoI estadosDao = new EstadosDao();
private final DeportesDaoI deportesDao = new DeportesDao();
private final MunicipiosDaoI municipiosDao = new MunicipiosDao();
private final PersonasDaoI personasDao = new PersonasDao();
private final SexosDaoI sexosDao = new SexosDao();
@Override
public void finalize() throws Throwable {
estadosDao.cerrarConexion();
deportesDao.cerrarConexion();
municipiosDao.cerrarConexion();
personasDao.cerrarConexion();
sexosDao.cerrarConexion();
super.finalize();
}
@Override
@GET
@Path("/obtenerEstados")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerEstados() {
Response.ResponseBuilder responseBuilder;
ArrayList<Estado> catalogoEstados = estadosDao.obtenerEstados();
responseBuilder = Response.ok(catalogoEstados, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@GET
@Path("/obtenerSexos")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerSexos() {
Response.ResponseBuilder responseBuilder;
ArrayList<Sexo> catalogoSexos = sexosDao.obtenerSexos();
responseBuilder = Response.ok(catalogoSexos, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@GET
@Path("/obtenerDeportes")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerDeportes() {
Response.ResponseBuilder responseBuilder;
ArrayList<Deporte> catalogoDeportes = deportesDao.obtenerDeportes();
responseBuilder = Response.ok(catalogoDeportes, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@GET
@Path("/obtenerMunicipios/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerMunicipios(@PathParam("id") int idEstado) {
Response.ResponseBuilder responseBuilder;
Estado estado = new Estado();
estado.setIdEstado(idEstado);
ArrayList<Municipio> catalogoMunicipios = municipiosDao.obtenerMunicipios(estado);
responseBuilder = Response.ok(catalogoMunicipios, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@GET
@Path("/obtenerPersonas/{min}/{max}")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerPersonas(@PathParam("min") int minimo,
@PathParam("max") int maximo, @QueryParam("query") String consulta) {
consulta = (consulta == null) ? "" : consulta;
Response.ResponseBuilder responseBuilder;
Par<Integer, ArrayList<Persona>> personas
= personasDao.obtenerPersonas(minimo, maximo, consulta);
responseBuilder = Response.ok(personas, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@GET
@Path("/obtenerPersona/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response obtenerPersona(@PathParam("id") int idUsuario) {
Response.ResponseBuilder responseBuilder;
Persona persona = personasDao.obtenerPersona(idUsuario);
responseBuilder = Response.ok(persona, "application/json;charset=UTF-8");
return responseBuilder.build();
}
@Override
@POST
@Path("/colocarPersona")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public Response colocarPersona(Persona persona) {
System.out.println("DEBUG: " + persona);
Response.ResponseBuilder responseBuilder;
int codigo;
try {
Validaciones.validarPersona(persona);
personasDao.insertarPersona(persona);
codigo = 1;
} catch (NombreIncorrectoException e) {
codigo = 2;
} catch (ApellidoIncorrectoException e) {
codigo = 3;
} catch (CamposIncompletosException e) {
codigo = 4;
} catch (RegistroExistenteException e) {
codigo = 5;
} catch (DeportesVaciosException e) {
codigo = 4;
} catch (Exception e) {
codigo = 6;
}
responseBuilder = Response.ok("" + codigo, "text/plain;charset=UTF-8");
return responseBuilder.build();
}
@Override
@PUT
@Path("/actualizarPersona")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public Response actualizarPersona(Persona persona) {
Response.ResponseBuilder responseBuilder;
int codigo;
try {
Validaciones.validarPersona(persona);
personasDao.actualizarPersona(persona);
codigo = 1;
} catch (NombreIncorrectoException e) {
codigo = 2;
} catch (ApellidoIncorrectoException e) {
codigo = 3;
} catch (CamposIncompletosException e) {
codigo = 4;
} catch (DeportesVaciosException e) {
codigo = 4;
} catch (Exception e) {
codigo = 6;
}
responseBuilder = Response.ok("" + codigo, "text/plain;charset=UTF-8");
return responseBuilder.build();
}
@Override
@DELETE
@Path("/borrarPersona/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response borrarPersona(@PathParam("id") int idUsuario) {
Response.ResponseBuilder responseBuilder;
Persona persona = new Persona();
persona.setIdPersona(idUsuario);
personasDao.borrarPersona(persona);
responseBuilder = Response.ok("Borrado exitoso", "text/plain;charset=UTF-8");
return responseBuilder.build();
}
}
| 30.032258 | 88 | 0.730858 |
928b78c007f10ea691846418bc73b9ffff7aa78d | 1,032 | package com.estafet.boostcd.gateway.api.service;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.estafet.boostcd.gateway.api.dto.EnvironmentDTO;
import com.estafet.boostcd.gateway.api.model.EnvState;
import com.estafet.boostcd.gateway.api.util.ENV;
import com.estafet.openshift.boost.messages.environments.Environment;
@Service
public class EnvironmentService extends BaseService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private StateService stateService;
public EnvironmentDTO doAction(String productId, String env, String action) {
Environment environment = restTemplate.postForObject(ENV.ENVIRONMENT_SERVICE_API +
"/environment/" + productId + "/" + env + "/" + action, null, Environment.class);
Map<String, EnvState> states = stateService.getStates(productId);
return convertToDTO(states, environment);
}
}
| 33.290323 | 86 | 0.77907 |
bb3e948b6dc3cbb742c52acd4edf21b680e04666 | 1,356 | package com.github.jiangxch.mybatis.autoconfig.test.daotest;
import java.util.Date;
import com.github.jiangxch.mybatis.autoconfig.test.dao.BlogMapper;
import com.github.jiangxch.mybatis.autoconfig.test.dao.entity.Blog;
import org.junit.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;
/**
* @author: jiangxch
* @date: 2020/7/16 下午11:30
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class BlogMapperTest {
static {
System.setProperty("driverClassName", "org.h2.Driver");
System.setProperty("username", "sa");
System.setProperty("password", "");
System.setProperty("url", "jdbc:h2:mem:blog;DB_CLOSE_DELAY=-1");
System.setProperty("configLocation", "com.github.jiangxch.mybatis.autoconfig.test.dao");
}
@Autowired
private BlogMapper blogMapper;
@Test
public void test(){
blogMapper.createTable();
System.out.println(blogMapper.findAll());
Blog blog = new Blog();
blog.setId(0);
blog.setAuthor("aa");
blog.setContent("bbb");
blog.setAccessDate(new Date());
blogMapper.insert(blog);
System.out.println(blogMapper.findAll());
}
}
| 30.818182 | 96 | 0.698378 |
1afb66120ebfef166d0c448112a551f04b3b17a6 | 248 | package com.polimorfismo;
public class Pilot implements Caneta {
@Override
public void escreve() {
System.out.println("escreve pilot");
}
// overload
public void escreve(Integer cor) {
System.out.println("escreve pilot" + cor);
}
}
| 15.5 | 44 | 0.697581 |
cc7a9df428ad58a19f12cad31e53be1625b867d2 | 284 | package jpuppeteer.cdp.client.entity.overlay;
/**
* experimental
*/
public class SetShowAdHighlightsRequest {
/**
* True for showing ad highlights
*/
public final Boolean show;
public SetShowAdHighlightsRequest(Boolean show) {
this.show = show;
}
} | 16.705882 | 53 | 0.672535 |
9a107150d832b360f0e17f80fb795095d5e1a174 | 1,287 | package github.banana.view;
/**
* 深拷贝和浅拷贝
* <p>
* 浅拷贝
* 被复制对象的所有变量都含有与原来的对象相同的值, 而所有的对其它对象的引用仍然指向原来的对象
* 浅拷贝仅仅复制所考虑的对象, 而不复制它所引用的对象
* <p>
* 深拷贝
* 被复制的所有变量都含有与原来的对象相同的值, 而那些引用其它对象的变量将指向被复制过来的新对象, 而不再是原有的那些被引用的对象
* 深拷贝把要复制的对象所引用的对象都复制了一遍
* <p>
* Java数据类型
*
* <pre><code>
* |--------------------------------|
* | 类型 | 位数 | 字节数 |
* |--------------------------------|
* | short | 2 | 16 |
* |--------------------------------|
* | char | 2 | 16 |
* |--------------------------------|
* | int | 4 | 32 |
* |--------------------------------|
* | float | 4 | 32 |
* |--------------------------------|
* | long | 8 | 64 |
* |--------------------------------|
* | double | 8 | 64 |
* |--------------------------------|
* <code/><pre/>
*
* {@link System#gc()} 通知 GC 开始工作, 但是什么时候开始进行垃圾回收不确定
*/
public class CopyTest {
public static void main(String[] args) {
int i = 0xFFFFFFFF;
System.out.println(i);
char c = '\u0571';
System.out.println(c);
byte b = 01;
System.out.println(b);
int j = 'a';
System.out.println(j);
long k = 455555666666L;
System.out.println(k);
}
}
| 25.235294 | 67 | 0.379176 |
653f5e6fd6905cf25ec345c5521849571914d248 | 2,176 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.cascade;
import java.util.HashSet;
import java.util.Set;
public class A
{
// Constants -----------------------------------------------------------------------------------
// Static --------------------------------------------------------------------------------------
// Attributes ----------------------------------------------------------------------------------
private long id;
private String data;
// A 1 - * H
private Set hs;
// A 1 - 1 G
private G g;
// Constructors --------------------------------------------------------------------------------
public A()
{
hs = new HashSet();
}
public A(String data)
{
this();
this.data = data;
}
// Public --------------------------------------------------------------------------------------
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public void setData(String data)
{
this.data = data;
}
public String getData()
{
return data;
}
public void setHs(Set hs)
{
this.hs = hs;
}
public Set getHs()
{
return hs;
}
public void setG(G g)
{
this.g = g;
}
public G getG()
{
return g;
}
public void addH(H h)
{
hs.add(h);
h.setA(this);
}
public String toString()
{
return "A[" + id + ", " + data + "]";
}
// Package protected ---------------------------------------------------------------------------
// Protected -----------------------------------------------------------------------------------
// Private -------------------------------------------------------------------------------------
// Inner classes -------------------------------------------------------------------------------
}
| 20.72381 | 100 | 0.331342 |
853296fbede8012fc71d35e9d2929ea2e2b46159 | 1,394 | package org.tigergrab.javapooh.view.impl;
import org.tigergrab.javapooh.Item;
public class Element {
protected String type;
protected String item;
protected byte[] bytes;
protected int size = -1;
protected String comment = "";
public Element(final String typeName, final String itemName,
final byte[] bt, final String commentStr) {
this(typeName, itemName, bt);
comment = commentStr;
}
public Element(final Item it) {
type = it.type();
item = it.name();
size = it.size();
}
public Element(final String typeName, final String itemName, final byte[] bt) {
type = typeName;
item = itemName;
bytes = bt;
}
public Element(final String typeName, final String itemName, final int sz) {
type = typeName;
item = itemName;
size = sz;
}
public Element(Element element) {
type = element.getType();
item = element.getItem();
size = element.getSize();
bytes = element.getBytes();
comment = element.getComment();
}
public String getType() {
return type;
}
public String getItem() {
return item;
}
public int getSize() {
return size;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(final byte[] bt) {
bytes = bt;
}
public boolean hasComment() {
return 0 < comment.length() ? true : false;
}
public String getComment() {
return comment;
}
public void setComment(String str) {
comment = str;
}
}
| 18.103896 | 80 | 0.672884 |
cdc8d2fa954135d32638391c8267de9854e51b18 | 801 | package com.avereon.zenna.icon;
import com.avereon.zarra.image.RenderedIcon;
public class QuestionIcon extends RenderedIcon {
@Override
protected void render() {
// Squiggle
startPath();
moveTo( g( 9 ), g( 10 ) );
addArc( g( 12 ), g( 10 ), g( 3 ), g( 2 ), 180, 180 );
addArc( g( 16 ), g( 10 ), g( 1 ), g( 1 ), 180, -180 );
curveTo( g( 17 ), g( 14 ), g( 13 ), g( 12 ), g( 13 ), g( 18 ) );
addArc( g( 16 ), g( 18 ), g( 3 ), g( 2 ), 180, 180 );
curveTo( g( 19 ), g( 14 ), g( 23 ), g( 14 ), g( 23 ), g( 10 ) );
addArc( g( 16 ), g( 10 ), g( 7 ), g( 6 ), 0, 180 );
closePath();
fill();
// Dot
startPath();
addArc( g( 16 ), g( 26 ), g( 3 ), g( 3 ), 0, 360 );
closePath();
fill();
}
public static void main( String[] commands ) {
proof( new QuestionIcon() );
}
}
| 23.558824 | 66 | 0.510612 |
6eafcd555b11b4f3684878e0b1cfc6c516c68165 | 5,102 | package mrnerdy42.keywizard.gui;
import java.util.Arrays;
import mrnerdy42.keywizard.util.KeybindUtils;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.GuiScrollingList;
public class GuiBindingList extends GuiScrollingList {
private GuiKeyWizard parent;
private KeyBinding[] bindings;
private String searchText;
private String selectedCategory;
private KeyBinding selectedKeybind;
private int selectedKeybindId;
public GuiBindingList(GuiKeyWizard parent, int left, int bottom, int width, int height, int entryHeight) {
//Minecraft client, int width, int height, int top, int bottom, int left, int entryHeight, int screenWidth, int screenHeight
super(parent.getClient(), width, height, bottom - height, bottom, left, entryHeight, parent.width, parent.height);
this.parent = parent;
this.bindings = Arrays.copyOf(KeybindUtils.ALL_BINDINGS, KeybindUtils.ALL_BINDINGS.length);
this.searchText = this.parent.getSearchText();
this.selectedCategory = this.parent.getSelectedCategory();
this.selectKeybind(0);
}
@Override
protected int getSize() {
return bindings.length;
}
@Override
protected void elementClicked(int index, boolean doubleClick) {
this.selectKeybind(index);
}
@Override
protected boolean isSelected(int index) {
return this.selectedKeybindId == index;
}
@Override
protected void drawBackground() {
}
@Override
protected void drawSlot(int slotIdx, int entryRight, int slotTop, int slotBuffer, Tessellator tess) {
FontRenderer fontRender = this.parent.getFontRenderer();
KeyBinding currentBinding = this.bindings[slotIdx];
fontRender.drawStringWithShadow(I18n.format(currentBinding.getKeyDescription()), this.left + 3 , slotTop, 0xFFFFFF);
fontRender.drawStringWithShadow("("+I18n.format(currentBinding.getKeyCategory())+")", this.left + 3, slotTop + fontRender.FONT_HEIGHT + 2, 0x444444);
int color = 0;
if ( currentBinding.getKeyCode() == 0 || KeybindUtils.getNumConficts(currentBinding) > 0) {
color = 0x993333;
} else if(!currentBinding.isSetToDefaultValue()){
color = 0x339933;
} else {
color = 0x999999;
}
//int len = (I18n.format("gui.key")+": ").length() * 5;
//fontRender.drawStringWithShadow(I18n.format("gui.key")+": ", this.left + 3 , slotTop + fontRender.FONT_HEIGHT * 2 + 3, 0x999999);
fontRender.drawStringWithShadow(currentBinding.getDisplayName(), this.left + 3, slotTop + fontRender.FONT_HEIGHT * 2 + 3, color);
}
protected void updateList(){
if ( !this.searchText.equals(this.parent.getSearchText()) || !this.selectedCategory.equals(this.parent.getSelectedCategory()) ) {
this.searchText = this.parent.getSearchText();
this.selectedCategory = this.parent.getSelectedCategory();
KeyBinding[] bindingsNew = bindingsByCategory(this.selectedCategory);
String[] words = this.searchText.split("\\s+");
if (words.length != 0) {
if (words[0].length()>0 && words[0].charAt(0) == '@') {
bindingsNew = filterBindingsByKey(bindingsNew, words[0].substring(1, words[0].length()));
words[0] = "";
}
bindingsNew = filterBindingsByName(bindingsNew, words);
}
this.bindings = bindingsNew;
if (this.bindings.length != 0)
this.selectKeybind(0);
}
Arrays.sort(this.bindings, this.parent.sortType);
}
private void selectKeybind(int id){
this.selectedKeybindId = id;
this.selectedKeybind = this.bindings[id];
this.parent.setSelectedKeybind(this.selectedKeybind);
}
private KeyBinding[] bindingsByCategory(String category) {
KeyBinding[] bindings = Arrays.copyOf(KeybindUtils.ALL_BINDINGS, KeybindUtils.ALL_BINDINGS.length);
switch (category) {
case "categories.all":
return bindings;
case "categories.conflicts":
return Arrays.stream(bindings).filter(binding -> KeybindUtils.getNumConficts(binding) >= 1 && binding.getKeyCode() != 0).toArray(KeyBinding[]::new);
case "categories.unbound":
return Arrays.stream(bindings).filter(binding -> binding.getKeyCode() == 0).toArray(KeyBinding[]::new);
default:
return Arrays.stream(bindings).filter(binding -> binding.getKeyCategory() == category).toArray(KeyBinding[]::new);
}
}
private KeyBinding[] filterBindingsByName(KeyBinding[] bindings, String[] words){
KeyBinding[] filtered = {};
filtered = Arrays.stream(bindings).filter(binding -> {
boolean flag = true;
for (String w:words) {
flag = flag && I18n.format(binding.getKeyDescription()).toLowerCase().contains(w.toLowerCase());
}
return flag;
}).toArray(KeyBinding[]::new);
return filtered;
}
private KeyBinding[] filterBindingsByKey(KeyBinding[] bindings, String keyName) {
KeyBinding[] filtered = {};
filtered = Arrays.stream(bindings).filter(binding -> binding.getDisplayName().toLowerCase().contains(keyName.toLowerCase())).toArray(KeyBinding[]::new);
return filtered;
}
public KeyBinding getSelectedKeybind(){
return this.selectedKeybind;
}
}
| 36.184397 | 154 | 0.732066 |
fc04f9066b2fbc5fca644fc2a538728030fad99b | 2,457 | package com.rent.service.impl;
import com.rent.common.CommonEnum;
import com.rent.dao.HouseMapper;
import com.rent.dao.PhotoMapper;
import com.rent.entity.House;
import com.rent.entity.Photo;
import com.rent.entity.PhotoExample;
import com.rent.service.PhotoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class PhotoServiceImpl implements PhotoService {
private Logger logger= LoggerFactory.getLogger(this.getClass());
@Autowired
private PhotoMapper photoMapper;
@Autowired
private HouseMapper houseMapper;
@Override
public Map<String, Object> insertPhoto(Photo record) {
Map<String,Object> map=new HashMap<String,Object>();
int num = photoMapper.insertSelective(record);
//失败
if (num==0)
{
map.put("rescode", CommonEnum.REQUEST_FAILED.getCode());
map.put("resmsg",CommonEnum.REQUEST_FAILED.getMsg());
return map;
}
//成功
map.put("rescode", CommonEnum.REQUEST_SUCCESS.getCode());
map.put("resmsg",CommonEnum.REQUEST_SUCCESS.getMsg());
PhotoExample suithouse = new PhotoExample();
List<Photo> list = photoMapper.selectByExample(suithouse);
Photo newphoto = list.get(list.size()-1);
map.put("photoId",newphoto.getPhotoid());
House newhouse = houseMapper.selectByPrimaryKey(newphoto.getHouseid());
int photonum = newhouse.getPhotonum() + 1;
newhouse.setPhotonum(photonum);
houseMapper.updateByPrimaryKeySelective(newhouse);
return map;
}
@Override
public int deletePhoto(Integer photoid) {
Photo newphoto = photoMapper.selectByPrimaryKey(photoid);
House newhouse = houseMapper.selectByPrimaryKey(newphoto.getHouseid());
int photonum = newhouse.getPhotonum() - 1;
newhouse.setPhotonum(photonum);
houseMapper.updateByPrimaryKeySelective(newhouse);
return photoMapper.deleteByPrimaryKey(photoid);
}
@Override
public List<Photo> queryHouse(int houseId, int start, int end) {
PhotoExample suitphoto = new PhotoExample();
suitphoto.or().andHouseidEqualTo(houseId);
return photoMapper.selectByExample(suitphoto).subList(start,end);
}
}
| 34.605634 | 79 | 0.701262 |
613386101c87749fd31fc043af7afe66b0bf8073 | 1,356 | package org.apache.jmeter.protocol.aws;
/**
* Message Attribute class.
* @author JoseLuisSR
* @since 01/27/2021
* @see "https://github.com/JoseLuisSR/awsmeter"
*/
public class MessageAttribute {
/**
* Message attribute name.
*/
private String name;
/**
* Message attribute type.
*/
private String type;
/**
* Message attribute value.
*/
private String value;
/**
* Get Message Attribute Name.
* @return name.
*/
public String getName() {
return name;
}
/**
* Set Message Attribute Name.
* @param name
* Message Attribute Name.
*/
public void setName(String name){
this.name = name;
}
/**
* Get Message Attribute Type.
* @return type.
*/
public String getType() {
return type;
}
/**
* Set Message Attribute Type.
* @param type
* Message Attribute Type.
*/
public void setType(String type) {
this.type = type;
}
/**
* Message Attribute Value.
* @return value.
*/
public String getValue() {
return value;
}
/**
* Message Attribute Value.
* @param value
* Message Attribute Value.
*/
public void setValue(String value) {
this.value = value;
}
}
| 17.61039 | 48 | 0.532448 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.