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 |
|---|---|---|---|---|---|
a3daf63b9561d8c2b41008370774dea376fd528c | 1,227 | package saaadel.linkedin.crawler.web.selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public enum WebDriverFactory {
INSTANCE;
private WebDriver webDriver;
WebDriverFactory() {
}
public WebDriver getWebDriver() {
if (this.webDriver == null) {
// final HtmlUnitDriver webDriver = new HtmlUnitDriver() {
// @Override
// protected WebClient newWebClient(BrowserVersion version) {
// final WebClient webClient = super.newWebClient(version);
// webClient.getOptions().setThrowExceptionOnScriptError(false);
// webClient.getOptions().setPopupBlockerEnabled(true);
// webClient.getOptions().setCssEnabled(false);
// webClient.getOptions().setRedirectEnabled(true);
// webClient.getOptions().setUseInsecureSSL(true);
// return webClient;
// }
// };
// webDriver.setJavascriptEnabled(true);
final ChromeDriver webDriver_ = new ChromeDriver();
this.webDriver = webDriver_;
}
return this.webDriver;
}
}
| 35.057143 | 83 | 0.598207 |
3bc715d967c9d429d8d4d09847d4f22ea6a99d36 | 3,842 | package tech.salroid.filmy.custom_adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import tech.salroid.filmy.R;
import tech.salroid.filmy.data_classes.CastDetailsData;
/*
* Filmy Application for Android
* Copyright (c) 2016 Sajal Gupta (http://github.com/salroid).
*
* 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.
*/
public class CastAdapter extends RecyclerView.Adapter<CastAdapter.Ho> {
private final Boolean ret_size;
private List<CastDetailsData> cast = new ArrayList<>();
private Context context;
private ClickListener clickListener;
public CastAdapter(Context context, List<CastDetailsData> cast, Boolean size) {
this.context = context;
this.cast = cast;
this.ret_size = size;
}
@Override
public Ho onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.cast_custom_row, parent, false);
return new Ho(view);
}
@Override
public void onBindViewHolder(Ho holder, int position) {
String ct_name = cast.get(position).getCast_name();
String ct_desc = cast.get(position).getCast_character();
String ct_profile = cast.get(position).getCast_profile();
String ct_id = cast.get(position).getCast_id();
holder.cast_name.setText(ct_name);
holder.cast_description.setText(ct_desc);
try {
Glide.with(context)
.load(ct_profile)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.fitCenter()
.into(holder.cast_poster);
} catch (Exception e){
}
}
@Override
public int getItemCount() {
if (ret_size)
return (cast.size() >= 5) ? 5 : cast.size();
else
return cast.size();
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
public interface ClickListener {
void itemClicked(CastDetailsData setterGetter, int position, View view);
}
class Ho extends RecyclerView.ViewHolder {
@BindView(R.id.cast_name)
TextView cast_name;
@BindView(R.id.cast_description)
TextView cast_description;
@BindView(R.id.cast_poster)
CircularImageView cast_poster;
Ho(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.itemClicked(cast.get(getPosition()), getPosition(),view);
}
}
});
}
}
} | 29.782946 | 115 | 0.665539 |
6cb4286fb4d52a2076ab1b374c2cce8f6b014ead | 2,534 | /**
*
* Copyright 2009 Robin Collier
*
* 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.jivesoftware.smackx.pubsub.test;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.test.SmackTestCase;
import org.jivesoftware.smackx.pubsub.AccessModel;
import org.jivesoftware.smackx.pubsub.ConfigureForm;
import org.jivesoftware.smackx.pubsub.FormType;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PubSubManager;
/**
*
* @author Robin Collier
*
*/
abstract public class PubSubTestCase extends SmackTestCase
{
private PubSubManager[] manager;
public PubSubTestCase(String arg0)
{
super(arg0);
}
public PubSubTestCase()
{
super("PubSub Test Case");
}
protected LeafNode getRandomPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload) throws XMPPException
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setPersistentItems(persistItems);
form.setDeliverPayloads(deliverPayload);
form.setAccessModel(AccessModel.open);
return (LeafNode)pubMgr.createNode("/test/Pubnode" + System.currentTimeMillis(), form);
}
protected LeafNode getPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload, String nodeId) throws XMPPException
{
LeafNode node = null;
try
{
node = (LeafNode)pubMgr.getNode(nodeId);
}
catch (XMPPException e)
{
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setPersistentItems(persistItems);
form.setDeliverPayloads(deliverPayload);
form.setAccessModel(AccessModel.open);
node = (LeafNode)pubMgr.createNode(nodeId, form);
}
return node;
}
protected PubSubManager getManager(int idx)
{
if (manager == null)
{
manager = new PubSubManager[getMaxConnections()];
for(int i=0; i<manager.length; i++)
{
manager[i] = new PubSubManager(getConnection(i), getService());
}
}
return manager[idx];
}
protected String getService()
{
return "pubsub." + getXMPPServiceDomain();
}
}
| 27.247312 | 134 | 0.750987 |
b62486f5ce0c62ce01a0f1fbdd90ede1bdc596ed | 4,334 | /*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jserver.gameserver.model.actor.instance;
import com.l2jserver.gameserver.model.L2Skill;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.actor.L2Playable;
import com.l2jserver.gameserver.model.actor.L2Trap;
import com.l2jserver.gameserver.model.olympiad.Olympiad;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.templates.chars.L2NpcTemplate;
public class L2TrapInstance extends L2Trap
{
private L2PcInstance _owner;
private int _level;
private boolean _isInArena = false;
/**
* @param objectId
* @param template
* @param owner
*/
public L2TrapInstance(int objectId, L2NpcTemplate template,
L2PcInstance owner, int lifeTime, L2Skill skill)
{
super(objectId, template, lifeTime, skill);
setInstanceType(InstanceType.L2TrapInstance);
setInstanceId(owner.getInstanceId());
_owner = owner;
_level = owner.getLevel();
}
@Override
public int getLevel()
{
return _level;
}
@Override
public L2PcInstance getOwner()
{
return _owner;
}
@Override
public L2PcInstance getActingPlayer()
{
return _owner;
}
@Override
public void onSpawn()
{
super.onSpawn();
_isInArena = isInsideZone(ZONE_PVP) && !isInsideZone(ZONE_SIEGE);
}
@Override
public void deleteMe()
{
if (_owner != null)
{
_owner.setTrap(null);
_owner = null;
}
super.deleteMe();
}
@Override
public void unSummon()
{
if (_owner != null)
{
_owner.setTrap(null);
_owner = null;
}
super.unSummon();
}
@Override
public int getKarma()
{
return _owner != null ? _owner.getKarma() : 0;
}
@Override
public byte getPvpFlag()
{
return _owner != null ? _owner.getPvpFlag() : 0;
}
@Override
public void sendDamageMessage(L2Character target, int damage, boolean mcrit, boolean pcrit, boolean miss)
{
if (miss || _owner == null)
return;
if (_owner.isInOlympiadMode() &&
target instanceof L2PcInstance &&
((L2PcInstance)target).isInOlympiadMode() &&
((L2PcInstance)target).getOlympiadGameId() == _owner.getOlympiadGameId())
{
Olympiad.getInstance().notifyCompetitorDamage(getOwner(), damage, getOwner().getOlympiadGameId());
}
final SystemMessage sm;
if (target.isInvul() && !(target instanceof L2NpcInstance))
sm = new SystemMessage(SystemMessageId.ATTACK_WAS_BLOCKED);
else
{
sm = new SystemMessage(SystemMessageId.C1_GAVE_C2_DAMAGE_OF_S3);
sm.addCharName(this);
sm.addCharName(target);
sm.addNumber(damage);
}
_owner.sendPacket(sm);
}
@Override
public boolean canSee(L2Character cha)
{
if (_owner == null || cha == null)
return false;
if (cha == _owner)
return true;
if (_owner.isInParty()
&& cha.isInParty()
&& _owner.getParty().getPartyLeaderOID() == cha.getParty().getPartyLeaderOID())
return true;
return false;
}
@Override
public void setDetected(L2Character detector)
{
if (_isInArena)
{
super.setDetected(detector);
return;
}
if (_owner == null || (_owner.getPvpFlag() == 0 && _owner.getKarma() == 0))
return;
super.setDetected(detector);
}
@Override
protected boolean checkTarget(L2Character target)
{
if (!L2Skill.checkForAreaOffensiveSkills(this, target, getSkill(), _isInArena))
return false;
if (_isInArena)
return true;
// trap not attack non-flagged players
if (target instanceof L2Playable)
{
final L2PcInstance player = target.getActingPlayer();
if (player == null || (player.getPvpFlag() == 0 && player.getKarma() == 0))
return false;
}
return true;
}
}
| 23.053191 | 106 | 0.707891 |
80f0e7ec07437bb32703162d7f0705f6683ba9bd | 402 | package com.mindtree.staffmanagement.model.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({ "error" })
public class ErrorDto {
@JsonProperty("error")
private String error;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| 19.142857 | 59 | 0.721393 |
5d21ffcae3163ff895b8fea94bf50cd045634230 | 2,510 | package org.spongycastle.pqc.crypto.xmss;
import org.spongycastle.crypto.Digest;
/**
* XMSS^MT Parameters.
*/
public final class XMSSMTParameters
{
private final XMSSOid oid;
private final XMSSParameters xmssParams;
private final int height;
private final int layers;
/**
* XMSSMT constructor...
*
* @param height Height of tree.
* @param layers Amount of layers.
* @param digest Digest to use.
*/
public XMSSMTParameters(int height, int layers, Digest digest)
{
super();
this.height = height;
this.layers = layers;
this.xmssParams = new XMSSParameters(xmssTreeHeight(height, layers), digest);
oid = DefaultXMSSMTOid.lookup(getDigest().getAlgorithmName(), getDigestSize(), getWinternitzParameter(),
getLen(), getHeight(), layers);
/*
* if (oid == null) { throw new InvalidParameterException(); }
*/
}
private static int xmssTreeHeight(int height, int layers)
throws IllegalArgumentException
{
if (height < 2)
{
throw new IllegalArgumentException("totalHeight must be > 1");
}
if (height % layers != 0)
{
throw new IllegalArgumentException("layers must divide totalHeight without remainder");
}
if (height / layers == 1)
{
throw new IllegalArgumentException("height / layers must be greater than 1");
}
return height / layers;
}
/**
* Getter height.
*
* @return XMSSMT height.
*/
public int getHeight()
{
return height;
}
/**
* Getter layers.
*
* @return XMSSMT layers.
*/
public int getLayers()
{
return layers;
}
protected XMSSParameters getXMSSParameters()
{
return xmssParams;
}
protected WOTSPlus getWOTSPlus()
{
return xmssParams.getWOTSPlus();
}
protected Digest getDigest()
{
return xmssParams.getDigest();
}
/**
* Getter digest size.
*
* @return Digest size.
*/
public int getDigestSize()
{
return xmssParams.getDigestSize();
}
/**
* Getter Winternitz parameter.
*
* @return Winternitz parameter.
*/
public int getWinternitzParameter()
{
return xmssParams.getWinternitzParameter();
}
protected int getLen()
{
return xmssParams.getWOTSPlus().getParams().getLen();
}
}
| 22.017544 | 112 | 0.584462 |
4dd70316109dd012d57cf0f53cafeb2e1bfe3d28 | 1,617 | /*
* 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 vo;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author 2info2021
*/
@Entity
public class Professor {
@Id
@GeneratedValue
private int codigo = 0;
private String nome;
@Temporal(TemporalType.DATE)
private Calendar datanasc;
private String formacao;
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the datanasc
*/
public Calendar getDatanasc() {
return datanasc;
}
/**
* @param datanasc the datanasc to set
*/
public void setDatanasc(Calendar datanasc) {
this.datanasc = datanasc;
}
/**
* @return the formacao
*/
public String getFormacao() {
return formacao;
}
/**
* @param formacao the formacao to set
*/
public void setFormacao(String formacao) {
this.formacao = formacao;
}
}
| 18.802326 | 79 | 0.602968 |
33091274d4a0acc1199c5569b20fb8e0c1a13487 | 8,604 | package de.metas.material.dispo.commons.candidate;
import de.metas.common.util.CoalesceUtil;
import de.metas.material.dispo.commons.candidate.businesscase.BusinessCaseDetail;
import de.metas.material.dispo.commons.candidate.businesscase.DemandDetail;
import de.metas.material.event.commons.EventDescriptor;
import de.metas.material.event.commons.MaterialDescriptor;
import de.metas.material.event.commons.MinMaxDescriptor;
import de.metas.material.event.pporder.MaterialDispoGroupId;
import de.metas.organization.ClientAndOrgId;
import de.metas.organization.OrgId;
import de.metas.util.Check;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.Singular;
import lombok.Value;
import lombok.With;
import org.adempiere.warehouse.WarehouseId;
import org.compiere.Adempiere;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
/*
* #%L
* metasfresh-manufacturing-dispo
* %%
* Copyright (C) 2017 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@With
@Value
@EqualsAndHashCode(doNotUseGetters = true)
public class Candidate
{
public static CandidateBuilder builderForEventDescr(@NonNull final EventDescriptor eventDescr)
{
return Candidate.builder()
.clientAndOrgId(eventDescr.getClientAndOrgId());
}
public static CandidateBuilder builderForClientAndOrgId(@NonNull final ClientAndOrgId clientAndOrgId)
{
return Candidate.builder()
.clientAndOrgId(clientAndOrgId);
}
ClientAndOrgId clientAndOrgId;
CandidateType type;
/**
* Should be {@code null} for stock candidates.
*/
CandidateBusinessCase businessCase;
CandidateId id;
/**
* A supply candidate has a stock candidate as its parent. A demand candidate has a stock candidate as its child.
* We have this for historic reasons.
* On the longer run, stock-candidates will be merged into "normal" candidates and we won't need the parent-id anymore.
*/
CandidateId parentId;
/**
* The different supply candidate(s) and their corresponding demand candidate(s)
* that make up one business case are associated by a common group id.
* Note that {@link CandidateBusinessCase#PRODUCTION} and {@link CandidateBusinessCase#DISTRIBUTION} have multiple candidates in one group,
* Others like {@link CandidateBusinessCase#PURCHASE} have just one candidate in a group.
*/
MaterialDispoGroupId groupId;
int seqNo;
MaterialDescriptor materialDescriptor;
MinMaxDescriptor minMaxDescriptor;
BusinessCaseDetail businessCaseDetail;
DemandDetail additionalDemandDetail;
List<TransactionDetail> transactionDetails;
@Builder(toBuilder = true)
private Candidate(
@NonNull final ClientAndOrgId clientAndOrgId,
@NonNull final CandidateType type,
final CandidateBusinessCase businessCase,
final CandidateId id,
final CandidateId parentId,
final MaterialDispoGroupId groupId,
final int seqNo,
@NonNull final MaterialDescriptor materialDescriptor,
final MinMaxDescriptor minMaxDescriptor,
final BusinessCaseDetail businessCaseDetail,
final DemandDetail additionalDemandDetail,
@Singular @NonNull final List<TransactionDetail> transactionDetails)
{
this.clientAndOrgId = clientAndOrgId;
this.type = type;
this.businessCase = businessCase;
this.id = CoalesceUtil.coalesce(id, CandidateId.NULL);
Check.errorIf(this.id.isUnspecified(), "The given id may be null or CandidateId.NULL, but not unspecified");
this.parentId = CoalesceUtil.coalesce(parentId, CandidateId.NULL);
Check.errorIf(this.parentId.isUnspecified(), "The given parentId may be null or CandidateId.NULL, but not unspecified");
this.groupId = groupId;
this.seqNo = seqNo;
this.materialDescriptor = materialDescriptor;
this.minMaxDescriptor = CoalesceUtil.coalesce(minMaxDescriptor, MinMaxDescriptor.ZERO);
this.businessCaseDetail = businessCaseDetail;
this.additionalDemandDetail = additionalDemandDetail;
this.transactionDetails = transactionDetails;
if (type != CandidateType.STOCK
&& !Adempiere.isUnitTestMode() /* TODO create unit test candidates such that they are always valid and remove this */)
{
validateNonStockCandidate();
}
}
public static class CandidateBuilder
{
public CandidateBuilder quantity(final BigDecimal quantity)
{
Check.assumeNotNull(materialDescriptor, "Parameter materialDescriptor is not null");
return materialDescriptor(materialDescriptor.withQuantity(quantity));
}
}
// TODO always validate on construction, then make this method private
public Candidate validateNonStockCandidate()
{
switch (type)
{
case DEMAND:
case STOCK_UP:
Check.errorIf(
businessCaseDetail == null,
"If type={}, then the given businessCaseDetail may not be null; this={}",
type, this);
break;
case SUPPLY: // supply candidates can be created without businessCaseDetail if the request was made but no response from the planner came in yet
case INVENTORY_UP:
case INVENTORY_DOWN:
break;
case UNEXPECTED_INCREASE:
case UNEXPECTED_DECREASE:
Check.errorIf(
transactionDetails == null || transactionDetails.isEmpty(),
"If type={}, then the given transactionDetails may not be null or empty; this={}",
type, this);
break;
case ATTRIBUTES_CHANGED_FROM:
case ATTRIBUTES_CHANGED_TO:
break;
default:
Check.errorIf(true, "Unexpected candidateType={}; this={}", type, this);
}
for (final TransactionDetail transactionDetail : transactionDetails)
{
Check.errorIf(
!transactionDetail.isComplete(),
"Every element from the given parameter transactionDetails needs to have iscomplete==true; transactionDetail={}; this={}",
transactionDetail, this);
}
Check.errorIf((businessCase == null) != (businessCaseDetail == null),
"The given paramters businessCase and businessCaseDetail need to be both null or both not-null; businessCase={}; businessCaseDetail={}; this={}",
businessCase, businessCaseDetail, this);
Check.errorIf(
businessCase != null && !businessCase.getDetailClass().isAssignableFrom(businessCaseDetail.getClass()),
"The given paramters businessCase and businessCaseDetail don't match; businessCase={}; businessCaseDetail={}; this={}",
businessCase, businessCaseDetail, this);
return this;
}
public OrgId getOrgId()
{
return getClientAndOrgId().getOrgId();
}
public Candidate withNegatedQuantity()
{
return withQuantity(getQuantity().negate());
}
public BigDecimal getQuantity()
{
return materialDescriptor.getQuantity();
}
public Candidate withQuantity(@NonNull final BigDecimal quantity)
{
return withMaterialDescriptor(materialDescriptor.withQuantity(quantity));
}
public Candidate withDate(@NonNull final Instant date)
{
return withMaterialDescriptor(materialDescriptor.withDate(date));
}
public Candidate withWarehouseId(final WarehouseId warehouseId)
{
return withMaterialDescriptor(materialDescriptor.withWarehouseId(warehouseId));
}
@Nullable
public MaterialDispoGroupId getEffectiveGroupId()
{
if (type == CandidateType.STOCK)
{
return null;
}
else if (groupId != null)
{
return groupId;
}
else
{
return MaterialDispoGroupId.ofIdOrNull(id);
}
}
public Instant getDate()
{
return materialDescriptor.getDate();
}
public int getProductId()
{
return materialDescriptor.getProductId();
}
public WarehouseId getWarehouseId()
{
return materialDescriptor.getWarehouseId();
}
public BigDecimal computeActualQty()
{
return getTransactionDetails()
.stream()
.map(TransactionDetail::getQuantity)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public DemandDetail getDemandDetail()
{
return CoalesceUtil.coalesce(DemandDetail.castOrNull(businessCaseDetail), additionalDemandDetail);
}
public BigDecimal getBusinessCaseDetailQty()
{
if (businessCaseDetail == null)
{
return BigDecimal.ZERO;
}
return businessCaseDetail.getQty();
}
}
| 29.771626 | 149 | 0.762087 |
c143ff44f546c3f1ae103f917d02b3a45ff732fc | 87 | /**
*
*/
/**
* @author Administrator
*
*/
package com.nju.oawork.controller.file; | 10.875 | 39 | 0.597701 |
74c34adcd5261818e15b2f3c6555805efa571e0d | 4,084 | package net.ninjacat.omg.bytecode.reference;
import io.vavr.collection.List;
import net.ninjacat.omg.bytecode.AsmPatternCompiler;
import net.ninjacat.omg.conditions.ConditionMethod;
import net.ninjacat.omg.conditions.InCondition;
import net.ninjacat.omg.conditions.PropertyCondition;
import net.ninjacat.omg.errors.CompilerException;
import net.ninjacat.omg.patterns.PropertyPattern;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class DoubleCompilerTest {
@Test
public void shouldMatchSimpleEqPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.EQ, 42);
final PropertyPattern<DoubleTest> pattern = AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
assertThat(pattern.matches(new DoubleTest(42)), is(true));
assertThat(pattern.matches(new DoubleTest(24)), is(false));
}
@Test
public void shouldMatchSimpleNeqPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.NEQ, 42);
final PropertyPattern<DoubleTest> pattern = AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
assertThat(pattern.matches(new DoubleTest(42)), is(false));
assertThat(pattern.matches(new DoubleTest(24)), is(true));
}
@Test
public void shouldMatchSimpleGtPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.GT, 42);
final PropertyPattern<DoubleTest> pattern = AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
assertThat(pattern.matches(new DoubleTest(42)), is(false));
assertThat(pattern.matches(new DoubleTest(84)), is(true));
}
@Test
public void shouldMatchSimpleLtPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.LT, 42);
final PropertyPattern<DoubleTest> pattern = AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
assertThat(pattern.matches(new DoubleTest(42)), is(false));
assertThat(pattern.matches(new DoubleTest(21)), is(true));
}
@Test
public void shouldMatchInPattern() {
final InCondition<Double> condition = new InCondition<>("doubleField", List.of(42.0, 43.0).asJava());
final PropertyPattern<DoubleTest> pattern = AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
assertThat(pattern.matches(new DoubleTest(42)), is(true));
assertThat(pattern.matches(new DoubleTest(21)), is(false));
}
@Test(expected = CompilerException.class)
public void shouldFailMatchPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.MATCH, 42);
AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
}
@Test(expected = CompilerException.class)
public void shouldFailRegexPattern() {
final PropertyCondition<Double> condition = createPropertyCondition(ConditionMethod.REGEX, 42);
AsmPatternCompiler.forClass(DoubleTest.class).build(condition);
}
private static PropertyCondition<Double> createPropertyCondition(final ConditionMethod method, final double value) {
return new PropertyCondition<Double>() {
@Override
public String repr(final int level) {
return "";
}
@Override
public ConditionMethod getMethod() {
return method;
}
@Override
public String getProperty() {
return "doubleField";
}
@Override
public Double getValue() {
return value;
}
};
}
public static class DoubleTest {
private final Double doubleField;
DoubleTest(final double doubleField) {
this.doubleField = doubleField;
}
public Double getDoubleField() {
return doubleField;
}
}
} | 34.610169 | 120 | 0.690989 |
e48abf6c11f9e41c55a376fbf1f7708945056da5 | 4,296 | /*
* 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.cassandra.db.streaming;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import org.junit.Test;
import org.apache.cassandra.cql3.statements.schema.CreateTableStatement;
import org.apache.cassandra.db.SerializationHeader;
import org.apache.cassandra.db.streaming.CassandraStreamHeader.CassandraStreamHeaderSerializer;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.format.SSTableFormat;
import org.apache.cassandra.io.sstable.format.big.BigFormat;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.serializers.SerializationUtils;
import org.apache.cassandra.utils.ByteBufferUtil;
public class CassandraStreamHeaderTest
{
@Test
public void serializerTest()
{
String ddl = "CREATE TABLE tbl (k INT PRIMARY KEY, v INT)";
TableMetadata metadata = CreateTableStatement.parse(ddl, "ks").build();
CassandraStreamHeader header =
CassandraStreamHeader.builder()
.withSSTableFormat(SSTableFormat.Type.BIG)
.withSSTableVersion(BigFormat.latestVersion)
.withSSTableLevel(0)
.withEstimatedKeys(0)
.withSections(Collections.emptyList())
.withSerializationHeader(SerializationHeader.makeWithoutStats(metadata).toComponent())
.withTableId(metadata.id)
.build();
SerializationUtils.assertSerializationCycle(header, CassandraStreamHeader.serializer);
}
@Test
public void serializerTest_EntireSSTableTransfer()
{
String ddl = "CREATE TABLE tbl (k INT PRIMARY KEY, v INT)";
TableMetadata metadata = CreateTableStatement.parse(ddl, "ks").build();
ComponentManifest manifest = new ComponentManifest(new LinkedHashMap<Component, Long>() {{ put(Component.DATA, 100L); }});
CassandraStreamHeader header =
CassandraStreamHeader.builder()
.withSSTableFormat(SSTableFormat.Type.BIG)
.withSSTableVersion(BigFormat.latestVersion)
.withSSTableLevel(0)
.withEstimatedKeys(0)
.withSections(Collections.emptyList())
.withSerializationHeader(SerializationHeader.makeWithoutStats(metadata).toComponent())
.withComponentManifest(manifest)
.isEntireSSTable(true)
.withFirstKey(Murmur3Partitioner.instance.decorateKey(ByteBufferUtil.EMPTY_BYTE_BUFFER))
.withTableId(metadata.id)
.build();
SerializationUtils.assertSerializationCycle(header, new TestableCassandraStreamHeaderSerializer());
}
private static class TestableCassandraStreamHeaderSerializer extends CassandraStreamHeaderSerializer
{
@Override
public CassandraStreamHeader deserialize(DataInputPlus in, int version) throws IOException
{
return deserialize(in, version, tableId -> Murmur3Partitioner.instance);
}
}
}
| 46.193548 | 130 | 0.663175 |
b1678c6639cf4dae63c353e0d0c7e6f18a0406cc | 324 | package com.mana_wars.model.repository;
import java.util.List;
public interface UserLevelExperienceRepository {
int getUserLevel();
List<Integer> getUserLevelRequiredExperience();
void setUserLevel(int level);
int getCurrentUserExperience();
void setCurrentUserExperience(int currentUserExperience);
}
| 27 | 61 | 0.787037 |
b5f12d03220185dc964f5cb849cfd1fc1b4a2acb | 6,078 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.groovy.template;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import javax.annotation.PostConstruct;
import javax.servlet.Servlet;
import groovy.text.markup.MarkupTemplateEngine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.template.TemplateLocation;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver;
/**
* Auto-configuration support for Groovy templates in MVC. By default creates a
* {@link MarkupTemplateEngine} configured from {@link GroovyTemplateProperties}, but you
* can override that by providing your own {@link GroovyMarkupConfig} or even a
* {@link MarkupTemplateEngine} of a different type.
*
* @author Dave Syer
* @author Andy Wilkinson
* @author Brian Clozel
* @since 1.1.0
*/
@Configuration
@ConditionalOnClass(MarkupTemplateEngine.class)
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(GroovyTemplateProperties.class)
public class GroovyTemplateAutoConfiguration {
private static final Log logger = LogFactory.getLog(GroovyTemplateAutoConfiguration.class);
@Configuration
@ConditionalOnClass(GroovyMarkupConfigurer.class)
public static class GroovyMarkupConfiguration {
private final ApplicationContext applicationContext;
private final GroovyTemplateProperties properties;
private final MarkupTemplateEngine templateEngine;
public GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTemplateProperties properties,
ObjectProvider<MarkupTemplateEngine> templateEngine) {
this.applicationContext = applicationContext;
this.properties = properties;
this.templateEngine = templateEngine.getIfAvailable();
}
@PostConstruct
public void checkTemplateLocationExists() {
if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) {
TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath());
if (!location.exists(this.applicationContext)) {
logger.warn("Cannot find template location: " + location
+ " (please add some templates, check your Groovy "
+ "configuration, or set spring.groovy.template." + "check-template-location=false)");
}
}
}
/**
* MarkupTemplateEngine could be loaded from groovy-templates or groovy-all.
* Unfortunately it's quite common for people to use groovy-all and not actually
* need templating support. This method check attempts to check the source jar so
* that we can skip the {@code /template} folder check for such cases.
* @return true if the groovy-all jar is used
*/
private boolean isUsingGroovyAllJar() {
try {
ProtectionDomain domain = MarkupTemplateEngine.class.getProtectionDomain();
CodeSource codeSource = domain.getCodeSource();
if (codeSource != null && codeSource.getLocation().toString().contains("-all")) {
return true;
}
return false;
}
catch (Exception ex) {
return false;
}
}
@Bean
@ConditionalOnMissingBean(GroovyMarkupConfig.class)
@ConfigurationProperties(prefix = "spring.groovy.template.configuration")
public GroovyMarkupConfigurer groovyMarkupConfigurer() {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath(this.properties.getResourceLoaderPath());
configurer.setCacheTemplates(this.properties.isCache());
if (this.templateEngine != null) {
configurer.setTemplateEngine(this.templateEngine);
}
return configurer;
}
}
@Configuration
@ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, UrlBasedViewResolver.class })
@ConditionalOnWebApplication
@ConditionalOnProperty(name = "spring.groovy.template.enabled", matchIfMissing = true)
public static class GroovyWebConfiguration {
private final GroovyTemplateProperties properties;
public GroovyWebConfiguration(GroovyTemplateProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean(name = "groovyMarkupViewResolver")
public GroovyMarkupViewResolver groovyMarkupViewResolver() {
GroovyMarkupViewResolver resolver = new GroovyMarkupViewResolver();
this.properties.applyToViewResolver(resolver);
return resolver;
}
}
}
| 39.212903 | 110 | 0.797631 |
24c16e713dd53e90ba3cd974e1d50e6d37f2b846 | 883 | package com.justserver.apocalypse.commands;
import com.justserver.apocalypse.Apocalypse;
import com.justserver.apocalypse.dungeons.Dungeon;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public record DungeonCommand(Apocalypse plugin) implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
sender.sendMessage(ChatColor.RED + "У вас недостаточно прав, чтобы тестировать данжи :( Подождите немного, и данжи выйдут в открытый доступ");
if (sender instanceof Player && sender.isOp()) {
new Dungeon((Player) sender);
}
return true;
}
}
| 35.32 | 150 | 0.755379 |
5bac6ed1bdc625e365c52e870be973f1867fcfd2 | 252 | package hu.uni.eszterhazy.framework.service;
import hu.uni.eszterhazy.framework.model.Address;
import java.util.Collection;
public interface AddressService {
Collection<Address> listAll();
Collection<Address> listAllByCity(String city);
}
| 19.384615 | 51 | 0.781746 |
143c271c97c816358bb9bc292f0dd89993c2c702 | 8,367 | package org.cneo.hotornotapp;
import org.cneo.hotornotapp.AboutDialog.onSubmitListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements onSubmitListener {
private String nickname;
private String HOTURL = "http://www.hotornot.de/index.php";
private TextView textView;
final Context context = this;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
onClickMaybe();
return true;
case R.id.check_female:
HOTURL = "http://www.hotornot.de/index.php/?changegender=w";
item.setChecked(true);
Toast.makeText(getApplicationContext(),
"Female Selected",
Toast.LENGTH_LONG).show();
return true;
case R.id.check_male:
HOTURL = "http://www.hotornot.de/index.php/?changegender=m";
item.setChecked(true);
Toast.makeText(getApplicationContext(),
"Male Selected",
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView1);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { HOTURL });
}
public String cutBack(String txt, String teil, int number) {
for (int i = 0; i < number; i++) {
txt = txt.substring(0, txt.lastIndexOf(teil));
}
return txt;
}
public String cutFront(String txt, String teil, int number) {
for (int i = 0; i < number; i++) {
txt = txt.substring(txt.indexOf(teil) + 1, txt.length());
}
return txt;
}
private class PostAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
// pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "successfully logged", Toast.LENGTH_SHORT).show();
}
@SuppressWarnings("unused")
public void postData(String valueIWantToSend) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://webershandwick.de/receiver.py");
try {
// create a list to store HTTP variables and their values
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
// add an HTTP variable and value pair
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// send the variable and value, in other words post, to the URL
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// process exception
} catch (IOException e) {
// process exception
}
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "","Download ...", true);
}
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
String pix_url = "";
nickname = "";
Pattern p = Pattern.compile("(<title.*?>)(.+?)(</title>)");
Matcher m = p.matcher(result);
if (m.find())
{
String codeGroup = m.group();
nickname = nickname + cutFront(codeGroup, "u", 1);
nickname = cutBack(nickname, "?", 1);
}
p = Pattern.compile("<div style=\"(.+?)\">");
m = p.matcher(result);
if (m.find())
{
String codeGroup = m.group();
pix_url = pix_url + cutFront(codeGroup, "'", 1);
pix_url = cutBack(pix_url, "'", 1);
textView.setText("Nickname:" + nickname);
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(pix_url);
}
progressDialog.dismiss();
}
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { HOTURL });
Timestamp timestamp = new Timestamp(new Date().getTime());
new PostAsyncTask().execute(timestamp.toString() + "," + nickname + "\n");
}
public void onClickMaybe() {
AboutDialog fragment1 = new AboutDialog();
fragment1.mListener = MainActivity.this;
fragment1.show(getFragmentManager(), "");
}
@Override
public void setOnSubmitListener(String arg) {
// TODO Auto-generated method stub
}
} | 33.202381 | 109 | 0.607028 |
3d771f850bed0d2d823a6faf5c50da4d5d3b25ff | 1,675 | package codeine.issues;
import codeine.issues.Issue.State;
import codeine.utils.ExceptionUtils;
import codeine.utils.TextFileUtils;
import codeine.utils.network.HttpUtils;
import com.google.gson.Gson;
public class Issues {
public static void main(String[] args) {
for (int i = 1; i < 121; i++) {
try {
String file = "C:\\Users\\oshai\\Documents\\GitHub\\codeine\\issues\\" + (i + ".json");
String file2 = "C:\\Users\\oshai\\Documents\\GitHub\\codeine\\issues\\";
String text = TextFileUtils.getContents(file);
Issue issue = new Gson().fromJson(text, Issue.class);
if (issue.state == State.open){
file2 += "open\\";
} else if (issue.state == State.closed){
file2 += "closed\\";
} else {
System.out.println("failed to fetch state for " + i);
continue;
}
file2 += i + "." + HttpUtils.specialEncode(issue.title) + ".json";
TextFileUtils.setContents(file2, text);
} catch (Exception e) {
System.out.println(ExceptionUtils.getRootCauseMessage(e));
}
}
}
public static void fetchFromGithub() {
System.setProperty("https.proxyHost", "proxy.iil.intel.com");
System.setProperty("https.proxyPort", "911");
for (int i = 61; i < 121; i++) {
try {
System.out.println(i);
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
String url = "https://api.github.com/repos/oshai/codeine/issues/" + i;
String text = HttpUtils.doGET(url);
String file = "C:\\Users\\oshai\\Documents\\GitHub\\codeine\\issues\\" + i + ".json";
TextFileUtils.setContents(file, text);
} catch (Exception e) {
System.out.println(ExceptionUtils.getRootCauseMessage(e));
}
}
}
}
| 31.018519 | 91 | 0.650746 |
ca326f7a76b1ebf3451d186d3c2b4cb6af76fe96 | 582 | package com.jmsr.Sc4mmb4r.rest.controller;
import java.util.List;
import org.springframework.http.ResponseEntity;
import com.jmsr.Sc4mmb4r.rest.entity.RestaurantRest;
public interface RestaurantController {
ResponseEntity<List<RestaurantRest>> retrieveRestaurants();
ResponseEntity<RestaurantRest> retrieveRestaurant(Long restaurantId) throws Exception;
ResponseEntity<RestaurantRest> createRestaurant(RestaurantRest restaurantRest) throws Exception;
ResponseEntity<RestaurantRest> updateRestaurant(Long restaurantId, RestaurantRest restaurantRest) throws Exception;
}
| 29.1 | 116 | 0.848797 |
3b417a1f598918afaaf756d528074282d19dfe7c | 256 | package com.issue.management.entity.dto;
import lombok.Data;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class CreateProjectRequest {
private Long id;
private String projectName;
private String projectCode;
}
| 19.692308 | 40 | 0.796875 |
1966a42eb0d9a57de9fdbca792db4940b333dc57 | 3,065 | package com.jlife.abon.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jlife.abon.enumeration.Country;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.format.annotation.DateTimeFormat;
/**
* @author Dzmitry Misiuk
*/
public class AbstractUserData extends BaseData {
private String name;
private String lastName;
private String middleName;
private String phone;
private Country country = Country.BELARUS;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
@DateTimeFormat(pattern = "dd.MM.yyyy")
private DateTime birthday;
private String logoPath;
private MediaData logoMedia;
private String logoMediaId;
private String vehicleRegistrationPlate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public DateTime getBirthday() {
return birthday;
}
public void setBirthday(DateTime birthday) {
this.birthday = birthday;
}
public String getLogoPath() {
return logoPath;
}
public void setLogoPath(String logoPath) {
this.logoPath = logoPath;
}
public MediaData getLogoMedia() {
return logoMedia;
}
public void setLogoMedia(MediaData logoMedia) {
this.logoMedia = logoMedia;
}
public String getLogoMediaId() {
return logoMediaId;
}
public void setLogoMediaId(String logoMediaId) {
this.logoMediaId = logoMediaId;
}
public String getVehicleRegistrationPlate() {
return vehicleRegistrationPlate;
}
public void setVehicleRegistrationPlate(String vehicleRegistrationPlate) {
this.vehicleRegistrationPlate = vehicleRegistrationPlate;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public int getDaysBeforeBirthday() {
if (getBirthday() != null) {
DateTime now = DateTime.now().withTimeAtStartOfDay();
DateTime birthdayCurrentYear = getBirthday().withYear(now.getYear()).withTimeAtStartOfDay();
if (birthdayCurrentYear.isBefore(now)) {
birthdayCurrentYear = birthdayCurrentYear.withYear(now.getYear() + 1);
return Days.daysBetween(now, birthdayCurrentYear).getDays();
} else {
return Days.daysBetween(now, birthdayCurrentYear).getDays();
}
} else {
return 999;
}
}
}
| 23.945313 | 104 | 0.646982 |
4683fc1b805500c77012bbb86dd85a07cbaec5de | 8,997 | package org.iplantc.service.common.dao;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.CacheMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.iplantc.service.common.Settings;
import org.iplantc.service.common.exceptions.EntityEventPersistenceException;
import org.iplantc.service.common.model.AgaveEntityEvent;
import org.iplantc.service.common.persistence.HibernateUtil;
import org.iplantc.service.common.persistence.TenancyHelper;
import java.util.List;
/**
* Model class for interacting with {@link AgaveEntityEvent}. {@link AgaveEntityEvent}s are
* persisted independently of the parent object for async management.
*
* @author dooley
*
*/
public abstract class AbstractEntityEventDao<T extends AgaveEntityEvent, V extends Enum> implements EntityEventDao<T, V> {
/**
* Default no-args constructor
*/
public AbstractEntityEventDao() {}
protected abstract Class<?> getEntityEventClass();
/**
* Returns name of the tenant filter to apply when looking things up.
* Tenant filters should be the name of the {@link AgaveEntityEvent}
* concrete class and "TenantFilter". First letter lowercase.
*
* @return
*/
protected String getTenantFilterName() {
return Character.toLowerCase(getEntityEventClass().getSimpleName().charAt(0)) +
getEntityEventClass().getSimpleName().substring(1) + "TenantFilter";
}
/**
* Creates a hibernate session and resolves the tenancy filter for the domain
* object by default.
*
* @return
*/
protected Session getSession() {
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
session.enableFilter(getTenantFilterName())
.setParameter("tenantId", TenancyHelper.getCurrentTenantId());
session.clear();
return session;
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#getEntityEventByUuid(java.lang.String)
*/
@Override
@SuppressWarnings("unchecked")
public T getEntityEventByUuid(String uuid)
throws EntityEventPersistenceException
{
if (StringUtils.isEmpty(uuid))
throw new EntityEventPersistenceException("Event id cannot be null");
try
{
Session session = getSession();
T event = (T)session.createQuery("FROM " + getEntityEventClass().getSimpleName() + " WHERE uuid = :uuid")
.setString("uuid", uuid)
.setMaxResults(1)
.uniqueResult();
session.flush();
return event;
}
catch (HibernateException ex)
{
throw new EntityEventPersistenceException(ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#getEntityEventByEntityUuid(java.lang.String)
*/
@Override
public List<T> getEntityEventByEntityUuid(String uuid)
throws EntityEventPersistenceException
{
return getEntityEventByEntityUuid(uuid, Settings.DEFAULT_PAGE_SIZE, 0);
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#getEntityEventByEntityUuid(java.lang.String, int, int)
*/
@Override
@SuppressWarnings("unchecked")
public List<T> getEntityEventByEntityUuid(String uuid, int limit, int offset)
throws EntityEventPersistenceException
{
if (StringUtils.isEmpty(uuid))
throw new EntityEventPersistenceException("Entity id cannot be null");
try
{
Session session = getSession();
String sql = "FROM " + getEntityEventClass().getSimpleName() +
" where entity = :uuid order by id asc";
List<T> events = session.createQuery(sql)
.setString("uuid", uuid)
.setFirstResult(offset)
.setMaxResults(limit)
.list();
session.flush();
return events;
}
catch (HibernateException ex)
{
throw new EntityEventPersistenceException(ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#getByEntityUuidAndEntityEventUuid(java.lang.String, java.lang.String)
*/
@Override
@SuppressWarnings("unchecked")
public T getByEntityUuidAndEntityEventUuid(String entityUuid, String entityEventUuid)
throws EntityEventPersistenceException
{
if (StringUtils.isEmpty(entityUuid))
throw new EntityEventPersistenceException("Entity uuid cannot be null");
if (StringUtils.isEmpty(entityEventUuid))
throw new EntityEventPersistenceException("Event uuid cannot be null");
try
{
Session session = getSession();
String sql = "FROM " + getEntityEventClass().getSimpleName()
+ " WHERE entity = :entityUuid and uuid = :entityEventUuid";
T event = (T)session.createQuery(sql)
.setString("entityUuid", entityUuid)
.setString("entityEventUuid", entityEventUuid)
.setMaxResults(1)
.uniqueResult();
session.flush();
return event;
}
catch (HibernateException ex)
{
throw new EntityEventPersistenceException(ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#getAllEntityEventWithStatusForEntityUuid(java.lang.String, V)
*/
@Override
@SuppressWarnings("unchecked")
public List<T> getAllEntityEventWithStatusForEntityUuid(String eventUuid, V eventType)
throws EntityEventPersistenceException
{
if (eventType == null)
throw new EntityEventPersistenceException("Entity event status cannot be null");
if (StringUtils.isEmpty(eventUuid))
throw new EntityEventPersistenceException("Event uuid cannot be null");
try
{
Session session = getSession();
String hql = "FROM " + getEntityEventClass().getSimpleName()
+ " WHERE entity = :uuid "
+ " AND status = :status "
+ " ORDER BY id ASC";
List<T> events = session.createQuery(hql)
.setString("status", eventType.name())
.setString("uuid", eventUuid)
.list();
session.flush();
return events;
}
catch (HibernateException ex)
{
throw new EntityEventPersistenceException(ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#persist(T)
*/
@Override
public void persist(T event) throws EntityEventPersistenceException
{
if (event == null)
throw new EntityEventPersistenceException("Event cannot be null");
try
{
Session session = getSession();
session.saveOrUpdate(event);
session.flush();
}
catch (HibernateException ex)
{
try
{
if (HibernateUtil.getSession().isOpen()) {
HibernateUtil.rollbackTransaction();
}
}
catch (Exception ignored) {}
throw new EntityEventPersistenceException("Failed to save entity event.", ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#delete(T)
*/
@Override
public void delete(T event) throws EntityEventPersistenceException
{
if (event == null)
throw new EntityEventPersistenceException("Event cannot be null");
try
{
Session session = getSession();
session.delete(event);
session.flush();
}
catch (HibernateException ex)
{
try
{
if (HibernateUtil.getSession().isOpen()) {
HibernateUtil.rollbackTransaction();
}
}
catch (Exception ignored) {}
throw new EntityEventPersistenceException("Failed to delete entity event.", ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
/* (non-Javadoc)
* @see org.iplantc.service.common.dao.EntityEventDao#deleteBySoftwareId(java.lang.String)
*/
@Override
public void deleteByEntityId(String entityUuid) throws EntityEventPersistenceException
{
if (StringUtils.isEmpty(entityUuid)) {
throw new EntityEventPersistenceException("Event uuid cannot be null");
}
try
{
Session session = getSession();
String hql = "DELETE FROM " + getEntityEventClass().getSimpleName() +
" WHERE entity = :uuid";
session.createQuery(hql)
.setString("uuid", entityUuid)
.setCacheMode(CacheMode.IGNORE)
.setCacheable(false)
.executeUpdate();
session.flush();
}
catch (HibernateException ex)
{
try
{
if (HibernateUtil.getSession().isOpen()) {
HibernateUtil.rollbackTransaction();
}
}
catch (Exception ignored) {}
throw new EntityEventPersistenceException("Failed to delete events for uuid " + entityUuid, ex);
}
finally {
try { HibernateUtil.commitTransaction(); } catch (Exception ignored) {}
}
}
}
| 27.513761 | 124 | 0.685895 |
be882f0b9d201ac8d0ff046abf5ee26662508bf6 | 2,614 | /*
* 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.inatel.projeto.dao;
import br.inatel.projeto.model.Editora;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Moises Delmoro
*/
public class EditoraDAO extends ConexaoBD {
public Editora buscarEditora(int idBusca) {
super.connectToDb();
Editora ed = new Editora();
ed.setIdEditora(idBusca);
//Comando em SQL:
String sql = "SELECT * FROM Editora WHERE idEditora = ?";
//O comando NÃO recebe parâmetros -> consulta estática (st)
try {
super.pst = super.con.prepareStatement(sql);
super.pst.setInt(1, idBusca);
super.rs = super.pst.executeQuery();
while (rs.next()) {
ed.setIdEditora(idBusca);
ed.setNome(rs.getString("nome"));
ed.setEndereco(rs.getString("endereco"));
ed.setQualidadeServico(rs.getFloat("qualidadeServico"));
}
} catch (SQLException ex) {
System.out.println("Erro = " + ex.getMessage());
} finally {
try {
super.con.close();
super.pst.close();
} catch (SQLException ex) {
System.out.println("Erro = " + ex.getMessage());
}
}
return ed;
}
public ArrayList<Editora> buscarIdEditora() {
super.connectToDb();
ArrayList<Editora> edt = new ArrayList<>();
//Comando em SQL:
String sql = "SELECT * FROM Editora";
//O comando NÃO recebe parâmetros -> consulta estática (st)
try {
super.pst = super.con.prepareStatement(sql);
super.rs = super.pst.executeQuery();
while (rs.next()) {
Editora e = new Editora();
e.setIdEditora(rs.getInt("idEditora"));
e.setNome(rs.getString("nome"));
e.setEndereco(rs.getString("endereco"));
e.setQualidadeServico(rs.getFloat("qualidadeServico"));
edt.add(e);
}
} catch (SQLException ex) {
System.out.println("Erro = " + ex.getMessage());
} finally {
try {
super.con.close();
super.pst.close();
} catch (SQLException ex) {
System.out.println("Erro = " + ex.getMessage());
}
}
return edt;
}
}
| 29.704545 | 79 | 0.53596 |
2430162ebb0b16c4cbaf3020817a6c700d913969 | 2,013 | package com.example.service;/**
* @author : Mr.Gao
* @date : 2021/3/23 下午10:15
*/
import com.example.dao.GraduateStudentDao;
import com.example.model.GraduateStudent;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
/**
* @ClassName ProfessionService
* @Author Mr.Gao
* @Date 2021/3/23 下午10:15
* @Description TODO |
*/
@Service
public class GraduateStudentService {
@Resource
private GraduateStudentDao GraduateStudentDao;
public PageInfo<GraduateStudent> getGraduateStudentList( Integer page, Integer limit, Integer year,String type) {
PageHelper.startPage(page, limit);
List<GraduateStudent> pageList = GraduateStudentDao.getGraduateStudentPageListBySearch(year,type);
return new PageInfo<>(pageList);
}
public List<GraduateStudent> getGraduateStudentList() {
List<GraduateStudent> GraduateStudents = GraduateStudentDao.getGraduateStudentPageList();
return GraduateStudents ;
}
public GraduateStudent getGraduateStudentById(Integer id) {
return GraduateStudentDao.getGraduateStudentById(id);
}
public void updateGraduateStudent(GraduateStudent GraduateStudent) {
// Calendar cale = null;
// cale = Calendar.getInstance();
// int year = cale.get(Calendar.YEAR);
// int month = cale.get(Calendar.MONTH) + 1;
// if (month < 9) {
// year--;
// }
//
// GraduateStudent.setYear(String.valueOf(year));
if (GraduateStudent.getId() == null || GraduateStudent.getId().equals(0)) {
GraduateStudentDao.insertGraduateStudent(GraduateStudent);
} else {
GraduateStudentDao.updateGraduateStudentById(GraduateStudent);
}
}
public void deleteGraduateStudentById(Integer id) {
GraduateStudentDao.deleteGraduateStudentById(id);
}
}
| 28.757143 | 117 | 0.700447 |
a13d8a1f788765c0302f50a99e13f4eebdbfca67 | 729 | package com.dandelion.cool.order.controller;
import com.dandelion.cool.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author: Mr.QinJiang
* @create: 2019-03-08 16:15
* @description: 订单 控制器
**/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private IOrderService orderService;
@RequestMapping("/index")
public List index(){
return orderService.getConfig();
}
@RequestMapping("/index1")
public String index1(){
return "index1";
}
}
| 21.441176 | 62 | 0.725652 |
4dafdedd2382db5283251069c969a3a17a0a3604 | 477 | package ru.job4j.set;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class SimpleHashSetTest {
@Test
public void whenAddItemToHashSetThenContainsIt() {
SimpleHashSet<Integer> shs = new SimpleHashSet<>();
assertThat(shs.add(1), is(true));
assertThat(shs.contains(1), is(true));
assertThat(shs.remove(1), is(true));
assertThat(shs.contains(1), is(false));
}
} | 28.058824 | 59 | 0.677149 |
ef27c659a3c4c6a686f2863d825df6d86eecdb5d | 17,293 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|aegis
operator|.
name|type
package|;
end_package
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Array
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|GenericArrayType
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|ParameterizedType
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Type
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|logging
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|namespace
operator|.
name|QName
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|stream
operator|.
name|XMLStreamReader
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|aegis
operator|.
name|AegisContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|aegis
operator|.
name|util
operator|.
name|NamespaceHelper
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|common
operator|.
name|logging
operator|.
name|LogUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|common
operator|.
name|xmlschema
operator|.
name|XmlSchemaUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|ws
operator|.
name|commons
operator|.
name|schema
operator|.
name|XmlSchema
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|ws
operator|.
name|commons
operator|.
name|schema
operator|.
name|constants
operator|.
name|Constants
import|;
end_import
begin_comment
comment|/** * Static methods/constants for Aegis. */
end_comment
begin_class
specifier|public
specifier|final
class|class
name|TypeUtil
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LogUtils
operator|.
name|getL7dLogger
argument_list|(
name|TypeUtil
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
name|TypeUtil
parameter_list|()
block|{
comment|//utility class
block|}
specifier|public
specifier|static
name|AegisType
name|getReadType
parameter_list|(
name|XMLStreamReader
name|xsr
parameter_list|,
name|AegisContext
name|context
parameter_list|,
name|AegisType
name|baseType
parameter_list|)
block|{
if|if
condition|(
operator|!
name|context
operator|.
name|isReadXsiTypes
argument_list|()
condition|)
block|{
if|if
condition|(
name|baseType
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type reading disabled, and no type available for "
operator|+
name|xsr
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
block|}
return|return
name|baseType
return|;
block|}
name|String
name|overrideType
init|=
name|xsr
operator|.
name|getAttributeValue
argument_list|(
name|Constants
operator|.
name|URI_2001_SCHEMA_XSI
argument_list|,
literal|"type"
argument_list|)
decl_stmt|;
if|if
condition|(
name|overrideType
operator|!=
literal|null
condition|)
block|{
name|QName
name|overrideName
init|=
name|NamespaceHelper
operator|.
name|createQName
argument_list|(
name|xsr
operator|.
name|getNamespaceContext
argument_list|()
argument_list|,
name|overrideType
argument_list|)
decl_stmt|;
if|if
condition|(
name|baseType
operator|==
literal|null
operator|||
operator|!
name|overrideName
operator|.
name|equals
argument_list|(
name|baseType
operator|.
name|getSchemaType
argument_list|()
argument_list|)
condition|)
block|{
name|AegisType
name|improvedType
init|=
literal|null
decl_stmt|;
name|TypeMapping
name|tm
decl_stmt|;
if|if
condition|(
name|baseType
operator|!=
literal|null
condition|)
block|{
name|tm
operator|=
name|baseType
operator|.
name|getTypeMapping
argument_list|()
expr_stmt|;
name|improvedType
operator|=
name|tm
operator|.
name|getType
argument_list|(
name|overrideName
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|improvedType
operator|==
literal|null
condition|)
block|{
name|improvedType
operator|=
name|context
operator|.
name|getRootType
argument_list|(
name|overrideName
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|improvedType
operator|!=
literal|null
condition|)
block|{
return|return
name|improvedType
return|;
block|}
block|}
if|if
condition|(
name|baseType
operator|!=
literal|null
condition|)
block|{
name|LOG
operator|.
name|finest
argument_list|(
literal|"xsi:type=\""
operator|+
name|overrideName
operator|+
literal|"\" was specified, but no corresponding AegisType was registered; defaulting to "
operator|+
name|baseType
operator|.
name|getSchemaType
argument_list|()
argument_list|)
expr_stmt|;
return|return
name|baseType
return|;
block|}
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type=\""
operator|+
name|overrideName
operator|+
literal|"\" was specified, but no corresponding AegisType was registered; no default."
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
if|if
condition|(
name|baseType
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type absent, and no type available for "
operator|+
name|xsr
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
block|}
return|return
name|baseType
return|;
block|}
comment|/** * getReadType cannot just look up the xsi:type in the mapping. This function must be * called instead at the root where there is no initial mapping to start from, as from * a part or an element of some containing item. * @param xsr * @param context * @return */
specifier|public
specifier|static
name|AegisType
name|getReadTypeStandalone
parameter_list|(
name|XMLStreamReader
name|xsr
parameter_list|,
name|AegisContext
name|context
parameter_list|,
name|AegisType
name|baseType
parameter_list|)
block|{
if|if
condition|(
name|baseType
operator|!=
literal|null
condition|)
block|{
return|return
name|getReadType
argument_list|(
name|xsr
argument_list|,
name|context
argument_list|,
name|baseType
argument_list|)
return|;
block|}
if|if
condition|(
operator|!
name|context
operator|.
name|isReadXsiTypes
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type reading disabled, and no type available for "
operator|+
name|xsr
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
name|String
name|typeNameString
init|=
name|xsr
operator|.
name|getAttributeValue
argument_list|(
name|Constants
operator|.
name|URI_2001_SCHEMA_XSI
argument_list|,
literal|"type"
argument_list|)
decl_stmt|;
if|if
condition|(
name|typeNameString
operator|!=
literal|null
condition|)
block|{
name|QName
name|schemaTypeName
init|=
name|NamespaceHelper
operator|.
name|createQName
argument_list|(
name|xsr
operator|.
name|getNamespaceContext
argument_list|()
argument_list|,
name|typeNameString
argument_list|)
decl_stmt|;
name|TypeMapping
name|tm
decl_stmt|;
name|tm
operator|=
name|context
operator|.
name|getTypeMapping
argument_list|()
expr_stmt|;
name|AegisType
name|type
init|=
name|tm
operator|.
name|getType
argument_list|(
name|schemaTypeName
argument_list|)
decl_stmt|;
if|if
condition|(
name|type
operator|==
literal|null
condition|)
block|{
name|type
operator|=
name|context
operator|.
name|getRootType
argument_list|(
name|schemaTypeName
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|type
operator|!=
literal|null
condition|)
block|{
return|return
name|type
return|;
block|}
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type=\""
operator|+
name|schemaTypeName
operator|+
literal|"\" was specified, but no corresponding AegisType was registered; no default."
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
name|LOG
operator|.
name|warning
argument_list|(
literal|"xsi:type was not specified for top-level element "
operator|+
name|xsr
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
return|return
literal|null
return|;
block|}
specifier|public
specifier|static
name|AegisType
name|getWriteType
parameter_list|(
name|AegisContext
name|globalContext
parameter_list|,
name|Object
name|value
parameter_list|,
name|AegisType
name|type
parameter_list|)
block|{
if|if
condition|(
name|value
operator|!=
literal|null
operator|&&
name|type
operator|!=
literal|null
operator|&&
name|type
operator|.
name|getTypeClass
argument_list|()
operator|!=
name|value
operator|.
name|getClass
argument_list|()
condition|)
block|{
name|AegisType
name|overrideType
init|=
name|globalContext
operator|.
name|getRootType
argument_list|(
name|value
operator|.
name|getClass
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|overrideType
operator|!=
literal|null
condition|)
block|{
return|return
name|overrideType
return|;
block|}
block|}
return|return
name|type
return|;
block|}
specifier|public
specifier|static
name|AegisType
name|getWriteTypeStandalone
parameter_list|(
name|AegisContext
name|globalContext
parameter_list|,
name|Object
name|value
parameter_list|,
name|AegisType
name|type
parameter_list|)
block|{
if|if
condition|(
name|type
operator|!=
literal|null
condition|)
block|{
return|return
name|getWriteType
argument_list|(
name|globalContext
argument_list|,
name|value
argument_list|,
name|type
argument_list|)
return|;
block|}
name|TypeMapping
name|tm
decl_stmt|;
name|tm
operator|=
name|globalContext
operator|.
name|getTypeMapping
argument_list|()
expr_stmt|;
comment|// don't use this for null!
name|type
operator|=
name|tm
operator|.
name|getType
argument_list|(
name|value
operator|.
name|getClass
argument_list|()
argument_list|)
expr_stmt|;
return|return
name|type
return|;
block|}
comment|/** * Allow writing of collections when the type of the collection object is known via * an {@link java.lang.reflect.Type} object. * @param globalContext the context * @param value the object to write. * @param reflectType the type to use in writing the object. * @return */
specifier|public
specifier|static
name|AegisType
name|getWriteTypeStandalone
parameter_list|(
name|AegisContext
name|globalContext
parameter_list|,
name|Object
name|value
parameter_list|,
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Type
name|reflectType
parameter_list|)
block|{
if|if
condition|(
name|reflectType
operator|==
literal|null
condition|)
block|{
return|return
name|getWriteTypeStandalone
argument_list|(
name|globalContext
argument_list|,
name|value
argument_list|,
operator|(
name|AegisType
operator|)
literal|null
argument_list|)
return|;
block|}
return|return
name|globalContext
operator|.
name|getTypeMapping
argument_list|()
operator|.
name|getTypeCreator
argument_list|()
operator|.
name|createType
argument_list|(
name|reflectType
argument_list|)
return|;
block|}
specifier|public
specifier|static
name|void
name|setAttributeAttributes
parameter_list|(
name|QName
name|name
parameter_list|,
name|AegisType
name|type
parameter_list|,
name|XmlSchema
name|root
parameter_list|)
block|{
name|String
name|ns
init|=
name|type
operator|.
name|getSchemaType
argument_list|()
operator|.
name|getNamespaceURI
argument_list|()
decl_stmt|;
name|XmlSchemaUtils
operator|.
name|addImportIfNeeded
argument_list|(
name|root
argument_list|,
name|ns
argument_list|)
expr_stmt|;
block|}
comment|/** * Utility function to cast a Type to a Class. This throws an unchecked exception if the Type is * not a Class. The idea here is that these Type references should have been checked for * reasonableness before the point of calls to this function. * @param type Reflection type. * @param throwForNonClass whether to throw (true) or return null (false) if the Type * is not a class. * @return the Class */
specifier|public
specifier|static
name|Class
argument_list|<
name|?
argument_list|>
name|getTypeClass
parameter_list|(
name|Type
name|type
parameter_list|,
name|boolean
name|throwForNonClass
parameter_list|)
block|{
if|if
condition|(
name|type
operator|instanceof
name|Class
condition|)
block|{
return|return
operator|(
name|Class
argument_list|<
name|?
argument_list|>
operator|)
name|type
return|;
block|}
elseif|else
if|if
condition|(
name|throwForNonClass
condition|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Attempt to derive Class from reflection Type "
operator|+
name|type
argument_list|)
throw|;
block|}
else|else
block|{
return|return
literal|null
return|;
block|}
block|}
comment|/** * Insist that a Type is a parameterized type of one parameter. * This is used to decompose Holders, for example. * @param type the type * @return the parameter, or null if the type is not what we want. */
specifier|public
specifier|static
name|Type
name|getSingleTypeParameter
parameter_list|(
name|Type
name|type
parameter_list|)
block|{
return|return
name|getSingleTypeParameter
argument_list|(
name|type
argument_list|,
literal|0
argument_list|)
return|;
block|}
comment|/** * Insist that a Type is a parameterized type of one parameter. * This is used to decompose Holders, for example. * @param type the type * @param index which parameter * @return the parameter, or null if the type is not what we want. */
specifier|public
specifier|static
name|Type
name|getSingleTypeParameter
parameter_list|(
name|Type
name|type
parameter_list|,
name|int
name|index
parameter_list|)
block|{
if|if
condition|(
name|type
operator|instanceof
name|ParameterizedType
condition|)
block|{
name|ParameterizedType
name|pType
init|=
operator|(
name|ParameterizedType
operator|)
name|type
decl_stmt|;
name|Type
index|[]
name|params
init|=
name|pType
operator|.
name|getActualTypeArguments
argument_list|()
decl_stmt|;
if|if
condition|(
name|params
operator|.
name|length
operator|>
name|index
condition|)
block|{
return|return
name|params
index|[
name|index
index|]
return|;
block|}
block|}
return|return
literal|null
return|;
block|}
comment|/** * If a Type is a class, return it as a class. * If it is a ParameterizedType, return the raw type as a class. * Otherwise return null. * @param type * @return */
specifier|public
specifier|static
name|Class
argument_list|<
name|?
argument_list|>
name|getTypeRelatedClass
parameter_list|(
name|Type
name|type
parameter_list|)
block|{
name|Class
argument_list|<
name|?
argument_list|>
name|directClass
init|=
name|getTypeClass
argument_list|(
name|type
argument_list|,
literal|false
argument_list|)
decl_stmt|;
if|if
condition|(
name|directClass
operator|!=
literal|null
condition|)
block|{
return|return
name|directClass
return|;
block|}
if|if
condition|(
name|type
operator|instanceof
name|ParameterizedType
condition|)
block|{
name|ParameterizedType
name|pType
init|=
operator|(
name|ParameterizedType
operator|)
name|type
decl_stmt|;
return|return
name|getTypeRelatedClass
argument_list|(
name|pType
operator|.
name|getRawType
argument_list|()
argument_list|)
return|;
block|}
if|if
condition|(
name|type
operator|instanceof
name|GenericArrayType
condition|)
block|{
name|GenericArrayType
name|gat
init|=
operator|(
name|GenericArrayType
operator|)
name|type
decl_stmt|;
name|Type
name|compType
init|=
name|gat
operator|.
name|getGenericComponentType
argument_list|()
decl_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|arrayBaseType
init|=
name|getTypeRelatedClass
argument_list|(
name|compType
argument_list|)
decl_stmt|;
comment|// believe it or not, this seems to be the only way to get the
comment|// Class object for an array of primitive type.
name|Object
name|instance
init|=
name|Array
operator|.
name|newInstance
argument_list|(
name|arrayBaseType
argument_list|,
literal|0
argument_list|)
decl_stmt|;
return|return
name|instance
operator|.
name|getClass
argument_list|()
return|;
block|}
return|return
literal|null
return|;
block|}
block|}
end_class
end_unit
| 15.551259 | 810 | 0.783323 |
905a6c8e97f268e1045bd10d41bfb87bd1641e33 | 21,717 | package io.branch;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.jar.JarFile;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.app.Activity;
import android.os.Bundle;
import java.util.Set;
public class BranchDevice extends CordovaPlugin {
public static final String BLANK = "bnc_no_value";
private static boolean isRealHardwareId;
private static String linkClickIdentifier;
private static String pushLinkIdentifier;
private static String appLinkIdentifier;
private static String externalIntent;
private static String externalIntentExtras;
private static final int STATE_FRESH_INSTALL = 0;
private static final int STATE_UPDATE = 2;
private static final int STATE_NO_CHANGE = 1;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
readAndStripParam(cordova.getActivity());
}
private void readAndStripParam(Activity activity) {
Uri data = null;
if (activity.getIntent() != null) {
data = activity.getIntent().getData();
}
// Capture the intent URI and extra for analytics in case started by external intents such as google app search
try {
if (data != null) {
externalIntent = data.toString();
}
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
Bundle bundle = activity.getIntent().getExtras();
Set<String> extraKeys = bundle.keySet();
if (extraKeys.size() > 0) {
JSONObject extrasJson = new JSONObject();
for (String key : extraKeys) {
extrasJson.put(key, bundle.get(key));
}
externalIntentExtras = extrasJson.toString();
}
}
} catch (Exception ignore) { }
// Check for any push identifier in case app is launched by a push notification
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
String pushIdentifier = activity.getIntent().getExtras().getString("branch");
if (pushIdentifier != null && pushIdentifier.length() > 0) {
pushLinkIdentifier = pushIdentifier;
return;
}
}
// Check for link click id or app link
if (data != null && data.isHierarchical() && activity != null) {
if (data.getQueryParameter("link_click_id") != null) {
linkClickIdentifier = data.getQueryParameter("link_click_id");
String paramString = "link_click_id=" + data.getQueryParameter("link_click_id");
String uriString = activity.getIntent().getDataString();
if (data.getQuery().length() == paramString.length()) {
paramString = "\\?" + paramString;
} else if ((uriString.length() - paramString.length()) == uriString.indexOf(paramString)) {
paramString = "&" + paramString;
} else {
paramString = paramString + "&";
}
Uri newData = Uri.parse(uriString.replaceFirst(paramString, ""));
activity.getIntent().setData(newData);
} else {
// Check if the clicked url is an app link pointing to this app
String scheme = data.getScheme();
if (scheme != null) {
if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
&& data.getHost() != null && data.getHost().length() > 0) {
appLinkIdentifier = data.toString();
}
}
}
}
}
@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Log.d("BranchDevice", "Action: " + action + " Args: " + args);
if ("getInstallData".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
getInstallData(args, callbackContext);
}
});
} else if ("getOpenData".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
getOpenData(args, callbackContext);
}
});
} else {
return false;
}
return true;
}
private void getInstallData(JSONArray args, CallbackContext callbackContext) {
JSONObject installPost = new JSONObject();
try {
boolean debug = args.optBoolean(0);
Log.d("BranchDevice", "getInstallData debug value is " + debug);
int isReferrable = args.optInt(1, -1);
Log.d("BranchDevice", "getInstallData isReferrable value is " + isReferrable);
String idStr = getUniqueID(debug);
installPost.put("debug_set", debug);
if (!idStr.equals(BLANK)) {
installPost.put("hardware_id", idStr);
installPost.put("is_hardware_id_real", hasRealHardwareId());
}
if (!getAppVersion().equals(BLANK))
installPost.put("app_version", getAppVersion());
if (!getCarrier().equals(BLANK))
installPost.put("carrier", getCarrier());
installPost.put("bluetooth", getBluetoothPresent());
if (!getBluetoothVersion().equals(BLANK))
installPost.put("bluetooth_version", getBluetoothVersion());
installPost.put("has_nfc", getNFCPresent());
installPost.put("has_telephone", getTelephonePresent());
if (!getPhoneBrand().equals(BLANK))
installPost.put("brand", getPhoneBrand());
if (!getPhoneModel().equals(BLANK))
installPost.put("model", getPhoneModel());
if (!getOS().equals(BLANK))
installPost.put("os", getOS());
String uriScheme = getURIScheme();
if (!uriScheme.equals(BLANK))
installPost.put("uri_scheme", uriScheme);
installPost.put("os_version", getOSVersion());
DisplayMetrics dMetrics = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
installPost.put("screen_dpi", dMetrics.densityDpi);
installPost.put("screen_height", dMetrics.heightPixels);
installPost.put("screen_width", dMetrics.widthPixels);
installPost.put("wifi", getWifiConnected());
if (isReferrable < 0) {
installPost.put("is_referrable", (getUpdateState(false) == 0)?1:0);
} else {
installPost.put("is_referrable", isReferrable);
}
installPost.put("update", getUpdateState(true));
if (linkClickIdentifier != null) {
installPost.put("link_identifier", linkClickIdentifier);
linkClickIdentifier = null;
}
if (pushLinkIdentifier != null) {
installPost.put("push_identifier", pushLinkIdentifier);
pushLinkIdentifier = null;
}
if (appLinkIdentifier != null) {
installPost.put("android_app_link_url", appLinkIdentifier);
appLinkIdentifier = null;
}
if (externalIntent != null) {
installPost.put("external_intent_uri", externalIntent);
externalIntent = null;
}
if (externalIntentExtras != null) {
installPost.put("external_intent_extra", externalIntentExtras);
externalIntentExtras = null;
}
Log.d("BranchDevice", "data: " + installPost.toString());
callbackContext.success(installPost);
} catch (JSONException ex) {
Log.e("BranchDevice", "Exception creatin install data: " + ex.getMessage());
callbackContext.error(ex.getMessage());
}
}
private void getOpenData(JSONArray args, CallbackContext callbackContext) {
JSONObject openPost = new JSONObject();
try {
int isReferrable = args.optInt(0, -1);
Log.d("BranchDevice", "getOpenData isReferrable value is " + isReferrable);
if (isReferrable < 0) {
openPost.put("is_referrable", 0);
} else {
openPost.put("is_referrable", isReferrable);
}
if (!getAppVersion().equals(BLANK))
openPost.put("app_version", getAppVersion());
openPost.put("os_version", getOSVersion());
String uriScheme = getURIScheme();
if (!uriScheme.equals(BLANK))
openPost.put("uri_scheme", uriScheme);
if (!getOS().equals(BLANK))
openPost.put("os", getOS());
if (linkClickIdentifier != null) {
openPost.put("link_identifier", linkClickIdentifier);
linkClickIdentifier = null;
}
if (pushLinkIdentifier != null) {
openPost.put("push_identifier", pushLinkIdentifier);
pushLinkIdentifier = null;
}
if (appLinkIdentifier != null) {
openPost.put("android_app_link_url", appLinkIdentifier);
appLinkIdentifier = null;
}
if (externalIntent != null) {
openPost.put("external_intent_uri", externalIntent);
externalIntent = null;
}
if (externalIntentExtras != null) {
openPost.put("external_intent_extra", externalIntentExtras);
externalIntentExtras = null;
}
callbackContext.success(openPost);
} catch (JSONException ex) {
Log.e("BranchDevice", "Exception creatin open data: " + ex.getMessage());
callbackContext.error(ex.getMessage());
}
}
public String getUniqueID(boolean debug) {
if (cordova.getActivity() != null) {
String androidID = null;
if (!debug) {
androidID = Secure.getString(cordova.getActivity().getContentResolver(), Secure.ANDROID_ID);
}
if (androidID == null) {
androidID = UUID.randomUUID().toString();
isRealHardwareId = false;
}
return androidID;
} else
return BLANK;
}
public boolean hasRealHardwareId() {
return isRealHardwareId;
}
public String getURIScheme() {
return getURIScheme(cordova.getActivity().getPackageName());
}
public String getURIScheme(String packageName) {
String scheme = BLANK;
if (!isLowOnMemory()) {
PackageManager pm = cordova.getActivity().getPackageManager();
try {
ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
String sourceApk = ai.publicSourceDir;
JarFile jf = null;
InputStream is = null;
byte[] xml = null;
try {
jf = new JarFile(sourceApk);
is = jf.getInputStream(jf.getEntry("AndroidManifest.xml"));
xml = new byte[is.available()];
is.read(xml);
scheme = new ApkParser().decompressXML(xml);
} catch (Exception ignored) {
} catch (OutOfMemoryError ignored) {
} finally {
xml = null;
try {
if (is != null) {
is.close();
is = null;
}
if (jf != null) {
jf.close();
jf = null;
}
} catch (IOException ignored) {}
}
} catch (NameNotFoundException ignored) {
}
}
return scheme;
}
private boolean isLowOnMemory() {
ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
activityManager.getMemoryInfo(mi);
return mi.lowMemory;
}
public String getAppVersion() {
try {
PackageInfo packageInfo = cordova.getActivity().getPackageManager().getPackageInfo(cordova.getActivity().getPackageName(), 0);
if (packageInfo.versionName != null)
return packageInfo.versionName;
else
return BLANK;
} catch (NameNotFoundException ignored ) {
}
return BLANK;
}
public String getCarrier() {
TelephonyManager telephonyManager = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
String ret = telephonyManager.getNetworkOperatorName();
if (ret != null)
return ret;
}
return BLANK;
}
public boolean getBluetoothPresent() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
return bluetoothAdapter.isEnabled();
}
} catch (SecurityException ignored ) {
}
return false;
}
public String getBluetoothVersion() {
if (android.os.Build.VERSION.SDK_INT >= 8) {
if(android.os.Build.VERSION.SDK_INT >= 18 &&
cordova.getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return "ble";
} else if(cordova.getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
return "classic";
}
}
return BLANK;
}
public boolean getNFCPresent() {
try {
return cordova.getActivity().getPackageManager().hasSystemFeature("android.hardware.nfc");
} catch (Exception ignored ) {
}
return false;
}
public boolean getTelephonePresent() {
try {
return cordova.getActivity().getPackageManager().hasSystemFeature("android.hardware.telephony");
} catch (Exception ignored ) {
}
return false;
}
public String getPhoneBrand() {
return android.os.Build.MANUFACTURER;
}
public String getPhoneModel() {
return android.os.Build.MODEL;
}
public String getOS() {
return "Android";
}
public String getOSVersion() {
return String.valueOf(android.os.Build.VERSION.SDK_INT);
}
public boolean isSimulator() {
return android.os.Build.FINGERPRINT.contains("generic");
}
@SuppressLint("NewApi")
public int getUpdateState(boolean updatePrefs) {
Context context = cordova.getActivity().getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences("cordova_prefs", Context.MODE_PRIVATE);
String currAppVersion = getAppVersion();
String storedAppVersion = prefs.getString("bnc_app_version", "");
if (storedAppVersion.isEmpty()) {
// if no app version is in storage, this must be the first time Branch is here
if (updatePrefs) {
Editor editor = prefs.edit();
editor.putString("bnc_app_version", currAppVersion);
editor.commit();
}
if (android.os.Build.VERSION.SDK_INT >= 9) {
// if we can access update/install time, use that to check if it's a fresh install or update
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if (packageInfo.lastUpdateTime != packageInfo.firstInstallTime) {
return STATE_UPDATE;
}
return STATE_FRESH_INSTALL;
} catch (NameNotFoundException ignored ) { }
}
// otherwise, just register an install
return STATE_FRESH_INSTALL;
} else if (!storedAppVersion.equals(currAppVersion)) {
// if the current app version doesn't match the stored, it's an update
if (updatePrefs) {
Editor editor = prefs.edit();
editor.putString("bnc_app_version", currAppVersion);
editor.commit();
}
return STATE_UPDATE;
}
// otherwise it's an open
return STATE_NO_CHANGE;
}
public boolean getWifiConnected() {
if (PackageManager.PERMISSION_GRANTED == cordova.getActivity().checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)) {
ConnectivityManager connManager = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifiInfo.isConnected();
}
return false;
}
public String getAdvertisingId() {
String advertisingId = null;
try {
Class<?> AdvertisingIdClientClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient");
Method getAdvertisingIdInfoMethod = AdvertisingIdClientClass.getMethod("getAdvertisingIdInfo", Context.class);
Object adInfoObj = getAdvertisingIdInfoMethod.invoke(null, cordova.getActivity());
Method getIdMethod = adInfoObj.getClass().getMethod("getId");
advertisingId = (String) getIdMethod.invoke(adInfoObj);
} catch(IllegalStateException ex) {
ex.printStackTrace();
} catch(Exception ignore) {
}
return advertisingId;
}
public class ApkParser {
// decompressXML -- Parse the 'compressed' binary form of Android XML docs
// such as for AndroidManifest.xml in .apk files
public static final int endDocTag = 0x00100101;
public static final int startTag = 0x00100102;
public static final int endTag = 0x00100103;
public String decompressXML(byte[] xml) {
// Compressed XML file/bytes starts with 24x bytes of data,
// 9 32 bit words in little endian order (LSB first):
// 0th word is 03 00 08 00
// 3rd word SEEMS TO BE: Offset at then of StringTable
// 4th word is: Number of strings in string table
// WARNING: Sometime I indiscriminently display or refer to word in
// little endian storage format, or in integer format (ie MSB first).
int numbStrings = LEW(xml, 4*4);
// StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
// of the length/string data in the StringTable.
int sitOff = 0x24; // Offset of start of StringIndexTable
// StringTable, each string is represented with a 16 bit little endian
// character count, followed by that number of 16 bit (LE) (Unicode) chars.
int stOff = sitOff + numbStrings*4; // StringTable follows StrIndexTable
// XMLTags, The XML tag tree starts after some unknown content after the
// StringTable. There is some unknown data after the StringTable, scan
// forward from this point to the flag for the start of an XML start tag.
int xmlTagOff = LEW(xml, 3*4); // Start from the offset in the 3rd word.
// Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
for (int ii=xmlTagOff; ii<xml.length-4; ii+=4) {
if (LEW(xml, ii) == startTag) {
xmlTagOff = ii; break;
}
} // end of hack, scanning for start of first start tag
// XML tags and attributes:
// Every XML start and end tag consists of 6 32 bit words:
// 0th word: 02011000 for startTag and 03011000 for endTag
// 1st word: a flag?, like 38000000
// 2nd word: Line of where this tag appeared in the original source file
// 3rd word: FFFFFFFF ??
// 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
// 5th word: StringIndex of Element Name
// (Note: 01011000 in 0th word means end of XML document, endDocTag)
// Start tags (not end tags) contain 3 more words:
// 6th word: 14001400 meaning??
// 7th word: Number of Attributes that follow this tag(follow word 8th)
// 8th word: 00000000 meaning??
// Attributes consist of 5 words:
// 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
// 1st word: StringIndex of Attribute Name
// 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
// 3rd word: Flags?
// 4th word: str ind of attr value again, or ResourceId of value
// Step through the XML tree element tags and attributes
int off = xmlTagOff;
int indent = 0;
int startTagLineNo = -2;
while (off < xml.length) {
int tag0 = LEW(xml, off);
int lineNo = LEW(xml, off+2*4);
int nameSi = LEW(xml, off+5*4);
if (tag0 == startTag) { // XML START TAG
int numbAttrs = LEW(xml, off+7*4); // Number of Attributes to follow
off += 9*4; // Skip over 6+3 words of startTag data
startTagLineNo = lineNo;
// Look for the Attributes
for (int ii=0; ii<numbAttrs; ii++) {
int attrNameSi = LEW(xml, off+1*4); // AttrName String Index
int attrValueSi = LEW(xml, off+2*4); // AttrValue Str Ind, or FFFFFFFF
int attrResId = LEW(xml, off+4*4); // AttrValue ResourceId or dup AttrValue StrInd
off += 5*4; // Skip over the 5 words of an attribute
String attrName = compXmlString(xml, sitOff, stOff, attrNameSi);
String attrValue = attrValueSi!=-1 ? compXmlString(xml, sitOff, stOff, attrValueSi) : "resourceID 0x"+Integer.toHexString(attrResId);
if (attrName.equals("scheme")) {
return attrValue;
}
}
indent++;
} else if (tag0 == endTag) { // XML END TAG
indent--;
off += 6*4; // Skip over 6 words of endTag data
String name = compXmlString(xml, sitOff, stOff, nameSi);
prtIndent(indent, "</"+name+"> (line "+startTagLineNo+"-"+lineNo+")");
} else if (tag0 == endDocTag) { // END OF XML DOC TAG
break;
} else {
break;
}
} // end of while loop scanning tags and attributes of XML tree
Log.d("BranchAPKParser", " end at offset "+off);
return BLANK;
} // end of decompressXML
public String compXmlString(byte[] xml, int sitOff, int stOff, int strInd) {
if (strInd < 0) return null;
int strOff = stOff + LEW(xml, sitOff+strInd*4);
return compXmlStringAt(xml, strOff);
}
public static final String spaces = " ";
public void prtIndent(int indent, String str) {
Log.d("BranchAPKParser", (spaces.substring(0, Math.min(indent*2, spaces.length()))+str));
}
// compXmlStringAt -- Return the string stored in StringTable format at
// offset strOff. This offset points to the 16 bit string length, which
// is followed by that number of 16 bit (Unicode) chars.
public String compXmlStringAt(byte[] arr, int strOff) {
int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
byte[] chars = new byte[strLen];
for (int ii=0; ii<strLen; ii++) {
chars[ii] = arr[strOff+2+ii*2];
}
return new String(chars); // Hack, just use 8 byte chars
} // end of compXmlStringAt
// LEW -- Return value of a Little Endian 32 bit word from the byte array
// at offset off.
public int LEW(byte[] arr, int off) {
return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000 | arr[off+1]<<8&0xff00 | arr[off]&0xFF;
} // end of LEW
}
}
| 35.485294 | 139 | 0.694341 |
0f5d8834ebb9758dec0c2f9cf40146c09c8b47b4 | 1,115 | package com.example.android.miwok;
public class Word {
/** Default translational of the word */
private String mDefaultTranslation;
/** Miwok translational of the word */
private String mMiwokTranslaton;
private int mMediaAudio;
/**Image of the word */
private int mImageResourceId = No_IMAGE_PROVIDE;
private static final int No_IMAGE_PROVIDE = -1;
// Constructor that take 2 inputs
public Word(String defaultTranslation, String miwokTranslaton, int imageResourceId, int mediaAudio){
mDefaultTranslation = defaultTranslation;
mMiwokTranslaton = miwokTranslaton;
mImageResourceId = imageResourceId;
mMediaAudio = mediaAudio;
}
/**methods */
public String getDefaultTranslation(){
return mDefaultTranslation;
}
public String getMiwokTranslaton(){
return mMiwokTranslaton;
}
public int getmImage() {
return mImageResourceId;
}
public int getmMediaAudio() {
return mMediaAudio;
}
public boolean hasImage(){
return mImageResourceId != No_IMAGE_PROVIDE;
}
}
| 22.755102 | 103 | 0.685202 |
5e1405497156d52a1c745291073303334a9f9a1a | 3,459 | /*
...@Author Hisham Maged
*/
import javax.swing.JFileChooser;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Collections;
public class WordFrequency
{
private HashMap<String,Integer> uniqueWords;
private int maxWordCount;
private int totalWordsCount;
public WordFrequency()
{
fillUniqueWords(getFile());
this.maxWordCount=findMaxValue();
}
public WordFrequency(File file)
{
fillUniqueWords(file);
this.maxWordCount=findMaxValue();
}
public WordFrequency(String path)
{
fillUniqueWords((new File(path)).isFile()?new File(path):getFile());
this.maxWordCount=findMaxValue();
}
public int getTotalWordsCount()
{
return this.totalWordsCount;
}
public void printTotalWordsCount()
{
System.out.println("Total words in the file: "+getTotalWordsCount());
}
public int getCountOfMaxWord()
{
return this.maxWordCount;
}
public String getMaxWord()
{
for(String e:uniqueWords.keySet())
if(uniqueWords.get(e)==this.maxWordCount)
return e;
return null;
}
public int getUniqueWordsCount()
{
return this.uniqueWords.size();
}
public void printUniqueWordsCount()
{
System.out.println("Number of Unique words in file: "+getUniqueWordsCount());
}
public void printUniqueWordsAndCount()
{
for(String e:uniqueWords.keySet())
System.out.println(uniqueWords.get(e)+ " "+e);
}
public void printMaxWord()
{
System.out.println("The word that occurs most often and its count are: "+getMaxWord()+" "+getCountOfMaxWord());
}
private File getFile()
{
JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
try{
do
{
System.out.println("Please choose a file");
chooser.showOpenDialog(null);
}while(chooser.getSelectedFile() == null);
}catch(NullPointerException ex){System.out.println("Incorrect Response!"); return getFile();}
return chooser.getSelectedFile();
}
private String[] getWords(File source)
{
ArrayList<String> words=new ArrayList<>();
try(BufferedReader input=new BufferedReader(new FileReader(source)))
{
String line=null;
while((line=input.readLine())!=null)
{
//String[] tokens=removeNonLetters(line.trim().split("\\W+"));
String[] tokens=line.trim().split(" ");
this.totalWordsCount=words.size();
words.addAll(Arrays.asList(tokens));
}
}catch(IOException ex){ex.printStackTrace();}
return words.toArray(new String[words.size()]);
}
private String[] removeNonLetters(String[] tokens)
{
int j=0;
for(String e:tokens)tokens[j++]=removePunctuation(e);
return tokens;
}
private String removePunctuation(String str)
{
StringBuilder sb=new StringBuilder();
for(int i=0,n=str.length();i<n;i++)
{
if(Character.isLetter(str.charAt(i)))
sb.append(str.charAt(i));
else continue;
}
return sb.toString();
}
private void fillUniqueWords(File file)
{
String[] words=getWords(file);
uniqueWords=new HashMap<String,Integer>();
for(String e:words)
{
if(e.equals("") || e.equals(" "))continue;
if(!uniqueWords.containsKey(e.toLowerCase()))
uniqueWords.put(e.toLowerCase(),1);
else
uniqueWords.put(e.toLowerCase(),uniqueWords.get(e.toLowerCase())+1);
}
}
public int findMaxValue()
{
return Collections.max(uniqueWords.values());
}
} | 25.433824 | 113 | 0.711766 |
fd81af58da648bd09eb3384a8ac7b2c0c7cba15f | 627 | package com.vine.jdk8.lambda;
import java.util.function.Function;
/**
* @author hekai
* @create 2018-04-10 上午11:16
*/
public class FunctionTest {
public static void main(String[] args) {
FunctionTest functionTest = new FunctionTest();
System.out.println(functionTest.compute(1, value -> 5 + value));
System.out.println(functionTest.convert(100, String::valueOf));
}
public int compute(int a, Function<Integer, Integer> function){
return function.apply(a);
}
public String convert(int x, Function<Integer, String> function){
return function.apply(x);
}
}
| 24.115385 | 72 | 0.665072 |
7b317d1f6dfcc48fcf66b8fd8d7a519a5a3b5735 | 4,228 | package com.example.song.seoulapp_fm.Game;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.example.song.seoulapp_fm.MainActivity;
import com.example.song.seoulapp_fm.PreferencesUtil;
import com.example.song.seoulapp_fm.R;
import java.util.Timer;
/*
* AR 공통 레이아웃
* (카메라 뷰)
*/
public class ARBaseActivity extends GameBaseActivity {
// 카메라 객체
private Camera camera_main;
private CameraPreview preview;
private FrameLayout frame; // 카메라 미리보기 frame 뷰
// 타이머 객체 - 스레드 이용 위해
public Timer mTimer;
protected FrameLayout ar_base_content; // 상속받을 activity의 base layout
private ARGuideDialog guideDialog = null;
// 가이드 팝업이 보여지고 있으면 1, 아니면 0
public static int isGuideShow = 0;
@Override
public void setContentView(int layoutResID) {
super.setContentView(R.layout.activity_ar_base);
/*
// ar 실행 시 service 일시 정지
// service stop
intent = new Intent(ARBaseActivity.this, FMService.class);
stopService(intent);
*/
if (!pref.getValue(PreferencesUtil.PREF_AR_GUIDE, "D").equals("N"))
onArBaseBtnListner(null);
// camera
Log.e("===========", "ARBaseActivity camera start");
camera_main = getCameraInstance();
// 카메라 미리보기를 하는 CameraPreview 객체 생성
Log.e("===========", "ARBaseActivity camera preview");
preview = new CameraPreview(this, camera_main);
Log.e("===========", "ARBaseActivity camera set");
// frameLayout을 미리보기 스크린으로 사용하기 위해
frame = (FrameLayout) findViewById(R.id.ar_base_preview);
// CameraPreview 객체를 FrameLayout의 내용으로 넣어서 FrameLayout을 카메라 미리보기 스크린으로 사용
frame.addView(preview);
// base frame
ar_base_content = (FrameLayout) findViewById(R.id.ar_base_content);
ar_base_content.addView(LayoutInflater.from(this).inflate(layoutResID, null));
}
@Override
public void setContentView(View view) {
super.setContentView(R.layout.activity_ar_base);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
super.setContentView(R.layout.activity_ar_base);
}
// Camera 객체 생성하는 메소드
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
// 이미지 회전 함수
public Bitmap rotateImage(Bitmap src, float degree) {
// Matrix 객체 생성
Matrix matrix = new Matrix();
// 회전 각도 셋팅
matrix.postRotate(degree);
// 이미지와 Matrix 를 셋팅해서 Bitmap 객체 생성
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTimer != null) mTimer.cancel();
// if (dialog != null && dialog.isShowing()) dialog.dismiss();
if (guideDialog != null && guideDialog.isVisible()) guideDialog.dismiss();
/*
if (pref.getValue(PreferencesUtil.PREF_NOTIFICATION, true)) {
// ar 종료 시 설정 on 상태 이면 service start
intent = new Intent(ARBaseActivity.this, FMService.class);
startService(intent);
}
*/
}
public void onArBaseBtnListner(View view) {
// 게임 가이드 보기
if (isGuideShow == 0) {
isGuideShow = 1;
guideDialog = new ARGuideDialog();
guideDialog.setCancelable(false); // back key 막기
guideDialog.show(getSupportFragmentManager(), "ArGuide");
}
}
@Override
public void onBackPressed() {
// back 버튼 클릭
if (place_num == -1 || place_num == 12) {
intent = new Intent(ARBaseActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
} else
super.onBackPressed();
}
} | 29.361111 | 93 | 0.630322 |
049b680765b765698cc93ed32e2583301dfaddc1 | 1,710 | /*
* Created on Aug 23, 2008
*
* 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.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.swing.driver;
import static org.fest.swing.driver.JTreeChildOfPathCountQuery.childCount;
import static org.fest.util.Strings.concat;
import javax.annotation.Nonnull;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.timing.Condition;
/**
* Verifies that the children of a node in a {@code JTree} are displayed.
*
* @author Alex Ruiz
*/
class JTreeChildrenShowUpCondition extends Condition {
private JTree tree;
private TreePath path;
static @Nonnull JTreeChildrenShowUpCondition untilChildrenShowUp(@Nonnull JTree tree, @Nonnull TreePath path) {
return new JTreeChildrenShowUpCondition(tree, path);
}
private JTreeChildrenShowUpCondition(@Nonnull JTree tree, @Nonnull TreePath path) {
super(concat(path.toString(), " to show"));
this.tree = tree;
this.path = path;
}
@Override @RunsInEDT
public boolean test() {
return childCount(tree, path) != 0;
}
@Override protected void done() {
tree = null;
path = null;
}
} | 31.090909 | 118 | 0.740351 |
20bd81c9cdd3f8c6e1393a0643ec546192b0a5a4 | 5,106 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.world.gen;
import org.spongepowered.api.world.biome.BiomeType;
import java.util.List;
/**
* Represents the world generator of a world. This interface contains all
* settings for the world generator, like which populators are in use, but also
* the world seed.
*
* <p>The generation process for chunks is divided into two phases, generation
* and population. The generation phase is in charge of creating the base
* terrain shape and generating large terrain features. All operations during
* the generation phase act upon a BlockBuffer rather than a live chunk
* object.</p>
*
* <p>Conversely the population phase operates against a live chunk object and
* has the guarantee that all immediately surrounding chunks have at least
* passed the generation phase. The population phase is typically used for the
* placement of small features and objects placed may cross chunk
* boundaries.</p>
*
* <ol><strong>The generation phase:</strong> <li>Create a BlockBuffer
* representing the chunk's area</li> <li>Call the
* {@link #getBaseGeneratorPopulator() base GeneratorPopulator} from the
* WorldGenerator to create the base terrain shape.</li> <li>Call each of the
* {@link BiomeType#getGeneratorPopulators() GeneratorPopulators} registered to
* the BiomeType.</li> <li>Call each of the {@link #getGeneratorPopulators()
* GeneratorPopulators} registered to the WorldGenerator.</li> <li>Build the
* final Chunk object from the contents of the BlockBuffer.</li> </ol>
*
* <ol><strong>The population phase:</strong> <li>Validate surrounding
* chunks.</li> <li>Using the biome at an arbitrary point within the chunk ({16,
* 0, 16} in the vanilla game), pass the chunk to each of the
* {@link BiomeType#getPopulators() Populators} registered to the chosen
* biome.</li> <li>Pass the chunk to each of the {@link #getPopulators()
* Populators} registered to the WorldGenerator.</li> </ol>
*/
public interface WorldGenerator {
/**
* Gets the main {@link GeneratorPopulator}. This generator populator is
* responsible for generating the base terrain of the chunk.
*
* @return The {@link GeneratorPopulator}.
* @see #setBaseGeneratorPopulator(GeneratorPopulator)
*/
GeneratorPopulator getBaseGeneratorPopulator();
/**
* Sets the {@link GeneratorPopulator}. This generator populator is
* responsible for generating the base terrain of the chunk.
*
* @param generator The generator.
*/
void setBaseGeneratorPopulator(GeneratorPopulator generator);
/**
* Gets a mutable list of {@link GeneratorPopulator}s. These populators work
* strictly on a single chunk. They will be executed directly after the
* {@link BiomeType#getGroundCover() biome ground cover layers} and the
* {@link BiomeType#getGeneratorPopulators() biome generator populators}
* have been called. These generator populators are typically used to
* generate large terrain features, like caves and ravines.
*
* <p>This list does not include {@link #getBaseGeneratorPopulator() the
* base generator}.</p>
*
* @return The generator populators
*/
List<GeneratorPopulator> getGeneratorPopulators();
/**
* Gets a mutable list of {@link Populator}s which are applied globally (in
* the whole world).
*
* @see BiomeType#getPopulators()
* @return The populators
*/
List<Populator> getPopulators();
/**
* Gets the {@link BiomeGenerator} for this world generator.
*
* @return The biome generator
*/
BiomeGenerator getBiomeGenerator();
/**
* Sets the {@link BiomeGenerator} for this world generator.
*
* @param biomeGenerator The new biome generator
*/
void setBiomeGenerator(BiomeGenerator biomeGenerator);
}
| 41.852459 | 80 | 0.724442 |
6d224e4cd3105512c6ec2de18894c00d21e7762e | 3,752 | /*
* 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.accumulo.test.functional;
import static java.util.Collections.singletonMap;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.admin.NewTableConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.junit.Test;
public class TabletIT extends AccumuloClusterHarness {
private static final int N = 1000;
@Override
public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
Map<String,String> siteConfig = cfg.getSiteConfig();
siteConfig.put(Property.TSERV_MAXMEM.getKey(), "128M");
cfg.setSiteConfig(siteConfig);
}
@Override
protected int defaultTimeoutSeconds() {
return 2 * 60;
}
@Test
public void createTableTest() throws Exception {
try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
String tableName = getUniqueNames(1)[0];
createTableTest(client, tableName, false);
createTableTest(client, tableName, true);
}
}
public void createTableTest(AccumuloClient accumuloClient, String tableName, boolean readOnly)
throws Exception {
// create the test table within accumulo
if (!readOnly) {
TreeSet<Text> keys = new TreeSet<>();
for (int i = N / 100; i < N; i += N / 100) {
keys.add(new Text(String.format("%05d", i)));
}
// presplit
accumuloClient.tableOperations().create(tableName,
new NewTableConfiguration()
.setProperties(singletonMap(Property.TABLE_SPLIT_THRESHOLD.getKey(), "200"))
.withSplits(keys));
try (BatchWriter b = accumuloClient.createBatchWriter(tableName)) {
// populate
for (int i = 0; i < N; i++) {
Mutation m = new Mutation(new Text(String.format("%05d", i)));
m.put("col" + ((i % 3) + 1), "qual", "junk");
b.addMutation(m);
}
}
}
try (Scanner scanner = accumuloClient.createScanner(tableName, Authorizations.EMPTY)) {
int count = 0;
for (Entry<Key,Value> elt : scanner) {
String expected = String.format("%05d", count);
assert (elt.getKey().getRow().toString().equals(expected));
count++;
}
assertEquals(N, count);
}
}
}
| 35.396226 | 96 | 0.709222 |
74d186a643eb8e61c8d9a9be00a3d29a48f824b7 | 3,545 | package one.jodi.base.model;
import one.jodi.base.error.ErrorWarningMessageJodi;
import one.jodi.base.service.annotation.AnnotationService;
import one.jodi.base.service.metadata.DataModelDescriptor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ApplicationBase implements ModelNode {
private static final Logger logger = LogManager.getLogger(ApplicationBase.class);
private static final String ERROR_MSG =
"Schema '%1$s' already exists in application.";
private final Map<String, SchemaBase> schemas = new HashMap<>();
private final AnnotationService annotationService;
private final ErrorWarningMessageJodi errorWarningMessages;
public ApplicationBase(final AnnotationService annotationService,
final ErrorWarningMessageJodi errorWarningMessages) {
super();
this.annotationService = annotationService;
this.errorWarningMessages = errorWarningMessages;
}
@Override
public String getName() {
return "root";
}
@Override
public ModelNode getParent() {
return null;
}
//
// factory methods
//
protected SchemaBase createSchemaInstance(final DataModelDescriptor model,
final DatabaseBase database) {
return new SchemaBase(this, model.getSchemaName(), model.getDataServerName(),
model.getModelCode(), database,
this.annotationService, this.errorWarningMessages);
}
protected DatabaseBase createDatabaseInstance(final DataModelDescriptor model) {
return new DatabaseBase(model.getDataServerName(),
model.getDataBaseServiceName(),
model.getDataBaseServicePort(),
model.getDataServerName());
}
public SchemaBase addSchema(final DataModelDescriptor model,
final String initExpression)
throws MalformedModelException {
SchemaBase schema = createSchemaInstance(model, createDatabaseInstance(model));
// validate after schema instance has been created that
// its name does not exist already
if (schemas.get(schema.getName()) != null) {
String msg = String.format(ERROR_MSG, model.getSchemaName());
logger.debug(msg);
throw new MalformedModelException(schemas.get(model.getSchemaName()), msg);
}
schemas.put(model.getSchemaName(), schema);
return schema;
}
public Map<String, ? extends SchemaBase> getSchemaMap() {
return Collections.unmodifiableMap(this.schemas);
}
public List<? extends SchemaBase> getSchemas() {
return Collections.unmodifiableList(new ArrayList<>(this.schemas.values()));
}
public Optional<? extends TableBase> findTable(final String schemaName,
final String tableName) {
assert (schemaName != null && !schemaName.trim().isEmpty() &&
tableName != null && !tableName.trim().isEmpty());
SchemaBase found = schemas.get(schemaName.trim());
if (found == null) {
// schema with the given name does not exist
return Optional.empty();
}
return Optional.ofNullable(found.getTable(tableName.trim()));
}
}
| 35.45 | 87 | 0.660085 |
165f0556f36dc702fe1e7dfae6987294deb5d188 | 14,829 | package org.aries.common;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
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.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.aries.adapter.BooleanAdapter;
import org.aries.adapter.DateTimeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmailMessage", namespace = "http://www.aries.org/common", propOrder = {
"id",
"content",
"subject",
"timestamp",
"sourceId",
"smtpHost",
"smtpPort",
"fromAddress",
"toAddresses",
"bccAddresses",
"ccAddresses",
"replytoAddresses",
"adminAddresses",
"attachments",
"sendAsHtml"
})
@XmlRootElement(name = "emailMessage", namespace = "http://www.aries.org/common")
public class EmailMessage implements Comparable<EmailMessage>, Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "id", namespace = "http://www.aries.org/common")
private Long id;
@XmlElement(name = "content", namespace = "http://www.aries.org/common")
private String content;
@XmlElement(name = "subject", namespace = "http://www.aries.org/common")
private String subject;
@XmlElement(name = "timestamp", namespace = "http://www.aries.org/common", type = String.class)
@XmlJavaTypeAdapter(DateTimeAdapter.class)
@XmlSchemaType(name = "dateTime")
private Date timestamp;
@XmlElement(name = "sourceId", namespace = "http://www.aries.org/common")
private String sourceId;
@XmlElement(name = "smtpHost", namespace = "http://www.aries.org/common")
private String smtpHost;
@XmlElement(name = "smtpPort", namespace = "http://www.aries.org/common")
private String smtpPort;
@XmlElement(name = "fromAddress", namespace = "http://www.aries.org/common", required = true, nillable = true)
private EmailAddress fromAddress;
@XmlElement(name = "toAddresses", namespace = "http://www.aries.org/common", nillable = true)
private List<EmailAddressList> toAddresses;
@XmlElement(name = "bccAddresses", namespace = "http://www.aries.org/common", nillable = true)
private List<EmailAddressList> bccAddresses;
@XmlElement(name = "ccAddresses", namespace = "http://www.aries.org/common", nillable = true)
private List<EmailAddressList> ccAddresses;
@XmlElement(name = "replytoAddresses", namespace = "http://www.aries.org/common", nillable = true)
private List<EmailAddressList> replytoAddresses;
@XmlElement(name = "adminAddresses", namespace = "http://www.aries.org/common", nillable = true)
private List<EmailAddressList> adminAddresses;
@XmlElement(name = "attachments", namespace = "http://www.aries.org/common", nillable = true)
private List<Attachment> attachments;
@XmlElement(name = "sendAsHtml", namespace = "http://www.aries.org/common", type = String.class)
@XmlJavaTypeAdapter(BooleanAdapter.class)
@XmlSchemaType(name = "boolean")
private Boolean sendAsHtml;
public EmailMessage() {
toAddresses = new ArrayList<EmailAddressList>();
bccAddresses = new ArrayList<EmailAddressList>();
ccAddresses = new ArrayList<EmailAddressList>();
replytoAddresses = new ArrayList<EmailAddressList>();
adminAddresses = new ArrayList<EmailAddressList>();
attachments = new ArrayList<Attachment>();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpPort() {
return smtpPort;
}
public void setSmtpPort(String smtpPort) {
this.smtpPort = smtpPort;
}
public EmailAddress getFromAddress() {
return fromAddress;
}
public void setFromAddress(EmailAddress emailAddress) {
this.fromAddress = emailAddress;
}
public List<EmailAddressList> getToAddresses() {
synchronized (toAddresses) {
return toAddresses;
}
}
public void setToAddresses(Collection<EmailAddressList> emailAddressListList) {
if (emailAddressListList == null) {
this.toAddresses = null;
} else {
synchronized (this.toAddresses) {
this.toAddresses = new ArrayList<EmailAddressList>();
addToToAddresses(emailAddressListList);
}
}
}
public void addToToAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.toAddresses) {
this.toAddresses.add(emailAddressList);
}
}
}
public void addToToAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null && !emailAddressListCollection.isEmpty()) {
synchronized (this.toAddresses) {
this.toAddresses.addAll(emailAddressListCollection);
}
}
}
public void removeFromToAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.toAddresses) {
this.toAddresses.remove(emailAddressList);
}
}
}
public void removeFromToAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null ) {
synchronized (this.toAddresses) {
this.toAddresses.removeAll(emailAddressListCollection);
}
}
}
public void clearToAddresses() {
synchronized (toAddresses) {
toAddresses.clear();
}
}
public List<EmailAddressList> getBccAddresses() {
synchronized (bccAddresses) {
return bccAddresses;
}
}
public void setBccAddresses(Collection<EmailAddressList> emailAddressListList) {
if (emailAddressListList == null) {
this.bccAddresses = null;
} else {
synchronized (this.bccAddresses) {
this.bccAddresses = new ArrayList<EmailAddressList>();
addToBccAddresses(emailAddressListList);
}
}
}
public void addToBccAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.bccAddresses) {
this.bccAddresses.add(emailAddressList);
}
}
}
public void addToBccAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null && !emailAddressListCollection.isEmpty()) {
synchronized (this.bccAddresses) {
this.bccAddresses.addAll(emailAddressListCollection);
}
}
}
public void removeFromBccAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.bccAddresses) {
this.bccAddresses.remove(emailAddressList);
}
}
}
public void removeFromBccAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null ) {
synchronized (this.bccAddresses) {
this.bccAddresses.removeAll(emailAddressListCollection);
}
}
}
public void clearBccAddresses() {
synchronized (bccAddresses) {
bccAddresses.clear();
}
}
public List<EmailAddressList> getCcAddresses() {
synchronized (ccAddresses) {
return ccAddresses;
}
}
public void setCcAddresses(Collection<EmailAddressList> emailAddressListList) {
if (emailAddressListList == null) {
this.ccAddresses = null;
} else {
synchronized (this.ccAddresses) {
this.ccAddresses = new ArrayList<EmailAddressList>();
addToCcAddresses(emailAddressListList);
}
}
}
public void addToCcAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.ccAddresses) {
this.ccAddresses.add(emailAddressList);
}
}
}
public void addToCcAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null && !emailAddressListCollection.isEmpty()) {
synchronized (this.ccAddresses) {
this.ccAddresses.addAll(emailAddressListCollection);
}
}
}
public void removeFromCcAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.ccAddresses) {
this.ccAddresses.remove(emailAddressList);
}
}
}
public void removeFromCcAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null ) {
synchronized (this.ccAddresses) {
this.ccAddresses.removeAll(emailAddressListCollection);
}
}
}
public void clearCcAddresses() {
synchronized (ccAddresses) {
ccAddresses.clear();
}
}
public List<EmailAddressList> getReplytoAddresses() {
synchronized (replytoAddresses) {
return replytoAddresses;
}
}
public void setReplytoAddresses(Collection<EmailAddressList> emailAddressListList) {
if (emailAddressListList == null) {
this.replytoAddresses = null;
} else {
synchronized (this.replytoAddresses) {
this.replytoAddresses = new ArrayList<EmailAddressList>();
addToReplytoAddresses(emailAddressListList);
}
}
}
public void addToReplytoAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.replytoAddresses) {
this.replytoAddresses.add(emailAddressList);
}
}
}
public void addToReplytoAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null && !emailAddressListCollection.isEmpty()) {
synchronized (this.replytoAddresses) {
this.replytoAddresses.addAll(emailAddressListCollection);
}
}
}
public void removeFromReplytoAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.replytoAddresses) {
this.replytoAddresses.remove(emailAddressList);
}
}
}
public void removeFromReplytoAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null ) {
synchronized (this.replytoAddresses) {
this.replytoAddresses.removeAll(emailAddressListCollection);
}
}
}
public void clearReplytoAddresses() {
synchronized (replytoAddresses) {
replytoAddresses.clear();
}
}
public List<EmailAddressList> getAdminAddresses() {
synchronized (adminAddresses) {
return adminAddresses;
}
}
public void setAdminAddresses(Collection<EmailAddressList> emailAddressListList) {
if (emailAddressListList == null) {
this.adminAddresses = null;
} else {
synchronized (this.adminAddresses) {
this.adminAddresses = new ArrayList<EmailAddressList>();
addToAdminAddresses(emailAddressListList);
}
}
}
public void addToAdminAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.adminAddresses) {
this.adminAddresses.add(emailAddressList);
}
}
}
public void addToAdminAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null && !emailAddressListCollection.isEmpty()) {
synchronized (this.adminAddresses) {
this.adminAddresses.addAll(emailAddressListCollection);
}
}
}
public void removeFromAdminAddresses(EmailAddressList emailAddressList) {
if (emailAddressList != null ) {
synchronized (this.adminAddresses) {
this.adminAddresses.remove(emailAddressList);
}
}
}
public void removeFromAdminAddresses(Collection<EmailAddressList> emailAddressListCollection) {
if (emailAddressListCollection != null ) {
synchronized (this.adminAddresses) {
this.adminAddresses.removeAll(emailAddressListCollection);
}
}
}
public void clearAdminAddresses() {
synchronized (adminAddresses) {
adminAddresses.clear();
}
}
public List<Attachment> getAttachments() {
synchronized (attachments) {
return attachments;
}
}
public void setAttachments(Collection<Attachment> attachmentList) {
if (attachmentList == null) {
this.attachments = null;
} else {
synchronized (this.attachments) {
this.attachments = new ArrayList<Attachment>();
addToAttachments(attachmentList);
}
}
}
public void addToAttachments(Attachment attachment) {
if (attachment != null ) {
synchronized (this.attachments) {
this.attachments.add(attachment);
}
}
}
public void addToAttachments(Collection<Attachment> attachmentCollection) {
if (attachmentCollection != null && !attachmentCollection.isEmpty()) {
synchronized (this.attachments) {
this.attachments.addAll(attachmentCollection);
}
}
}
public void removeFromAttachments(Attachment attachment) {
if (attachment != null ) {
synchronized (this.attachments) {
this.attachments.remove(attachment);
}
}
}
public void removeFromAttachments(Collection<Attachment> attachmentCollection) {
if (attachmentCollection != null ) {
synchronized (this.attachments) {
this.attachments.removeAll(attachmentCollection);
}
}
}
public void clearAttachments() {
synchronized (attachments) {
attachments.clear();
}
}
public Boolean isSendAsHtml() {
return sendAsHtml != null && sendAsHtml;
}
public Boolean getSendAsHtml() {
return sendAsHtml != null && sendAsHtml;
}
public void setSendAsHtml(Boolean sendAsHtml) {
this.sendAsHtml = sendAsHtml;
}
protected <T extends Comparable<T>> int compare(T value1, T value2) {
if (value1 == null && value2 == null) return 0;
if (value1 != null && value2 == null) return 1;
if (value1 == null && value2 != null) return -1;
int status = value1.compareTo(value2);
return status;
}
@Override
public int compareTo(EmailMessage other) {
int status = compare(timestamp, other.timestamp);
if (status != 0)
return status;
status = compare(sourceId, other.sourceId);
if (status != 0)
return status;
return 0;
}
@Override
public boolean equals(Object object) {
if (object == null)
return false;
if (!object.getClass().isAssignableFrom(this.getClass()))
return false;
EmailMessage other = (EmailMessage) object;
if (id != null)
return id.equals(other.id);
int status = compareTo(other);
return status == 0;
}
@Override
public int hashCode() {
if (id != null)
return id.hashCode();
int hashCode = 0;
if (timestamp != null)
hashCode += timestamp.hashCode();
if (sourceId != null)
hashCode += sourceId.hashCode();
if (hashCode == 0)
return super.hashCode();
return hashCode;
}
@Override
public String toString() {
return "EmailMessage: timestamp="+timestamp+", sourceId="+sourceId;
}
}
| 26.386121 | 111 | 0.730528 |
d1b00a82b7325264696bb708ec3b961970d022f0 | 4,126 | package com.example.config;
import com.example.listener.PaymentProcessingJobExecutionListener;
import com.example.model.Payment;
import com.example.model.mapper.PaymentPrepareStatementSetter;
import com.example.model.mapper.PaymentRowMapper;
import com.example.processor.PaymentProcessingItemProcessor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.sql.DataSource;
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
private DataSource dataSource;
@Bean
public JdbcCursorItemReader<Payment> reader() {
JdbcCursorItemReader<Payment> reader = new JdbcCursorItemReader<>();
reader.setDataSource(dataSource);
reader.setSql("SELECT * FROM payments");
reader.setRowMapper(new PaymentRowMapper());
return reader;
}
@Bean
public PaymentProcessingItemProcessor processor(){
return new PaymentProcessingItemProcessor();
}
@Bean
public JdbcBatchItemWriter<Payment> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Payment>()
.itemSqlParameterSourceProvider(
new BeanPropertyItemSqlParameterSourceProvider<>()
)
.sql("UPDATE PAYMENTS SET paymentType = ?, " +
"paymentStatus = ?, " +
"description = ? " +
"WHERE paymentId = ?"
)
.itemPreparedStatementSetter(new PaymentPrepareStatementSetter())
.dataSource(dataSource)
.build();
}
@Bean
public Step updatePaymentStatusStep(
ItemReader<Payment> reader, ItemWriter<Payment> writer,
ItemProcessor<Payment, Payment> processor) {
return
stepBuilderFactory
.get("updatePaymentStatusStep")
.<Payment, Payment> chunk(10)
.reader(reader)
.processor(processor)
.writer(writer)
.taskExecutor(taskExecutor())
.build();
}
@Bean
public Job exportProcessAndUpdatePaymentJob(PaymentProcessingJobExecutionListener listener, Step updatePaymentStatusStep) {
return jobBuilderFactory.get("processAndUpdatePaymentJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(updatePaymentStatusStep)
.end()
.build();
}
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(2);
/*taskExecutor.execute(new Runnable() {
@Override
public void run() {
}
}, 8000);*/
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
} | 35.878261 | 129 | 0.69874 |
cce6df525bf35cf70c7b0cba3ef06f1f2f062411 | 4,248 | package com.likya.tlossw.web.definitions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.XmlOptions;
import org.primefaces.component.datatable.DataTable;
import com.likya.tlos.model.xmlbeans.swresourcens.ResourceListType;
import com.likya.tlos.model.xmlbeans.swresourcens.ResourceType;
import com.likya.tlossw.utils.xml.XMLNameSpaceTransformer;
import com.likya.tlossw.web.TlosSWBaseBean;
@ManagedBean(name = "resourceSearchPanelMBean")
@ViewScoped
public class ResourceSearchPanelMBean extends TlosSWBaseBean implements Serializable {
private static final long serialVersionUID = 7899903706759759225L;
private ResourceType resource;
private ArrayList<ResourceType> searchResourceList;
private transient DataTable searchResourceTable;
private ResourceType selectedRow;
private String resourceName;
private List<ResourceType> filteredResourceList;
public void dispose() {
resetResourceAction();
}
@PostConstruct
public void init() {
resetResourceAction();
}
public String getResourceXML() {
//QName qName = RNSEntryType.type.getName()OuterType().getDocumentElementName();
//QName qName = RNSEntryType.type.getName();
QName qName = ResourceType.type.getName();
//QName qName = new QName("http://schemas.ogf.org/rns/2009/12/rns", "RNSEntryType", "rns");
XmlOptions xmlOptions = XMLNameSpaceTransformer.transformXML(qName);
String resourceXML = resource.xmlText(xmlOptions);
return resourceXML;
}
public void resetResourceAction() {
resource = ResourceType.Factory.newInstance();
searchResourceList = new ArrayList<ResourceType>();
resourceName = "";
}
public void searchResourceAction(ActionEvent e) {
if (resourceName != null && !resourceName.equals("")) {
resource.setEntryName(resourceName);
}
ResourceListType resourceListType = getDbOperations().searchResource(getResourceXML());
searchResourceList = new ArrayList<ResourceType>();
for (ResourceType resourceType : resourceListType.getResourceArray()) {
searchResourceList.add(resourceType);
}
if (searchResourceList == null || searchResourceList.size() == 0) {
addMessage("searchResource", FacesMessage.SEVERITY_INFO, "tlos.info.search.noRecord", null);
}
}
public void deleteResourceAction(ActionEvent e) {
//resource = (ResourceType) searchResourceTable.getRowData();
resource = selectedRow;
if (getDbOperations().deleteResource(getResourceXML())) {
searchResourceList.remove(resource);
resource = ResourceType.Factory.newInstance();
addMessage("searchResource", FacesMessage.SEVERITY_INFO, "tlos.success.resource.delete", null);
} else {
addMessage("searchResource", FacesMessage.SEVERITY_ERROR, "tlos.error.resource.delete", null);
}
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public DataTable getSearchResourceTable() {
return searchResourceTable;
}
public void setSearchResourceTable(DataTable searchResourceTable) {
this.searchResourceTable = searchResourceTable;
}
public ResourceType getResource() {
return resource;
}
public void setResource(ResourceType resource) {
this.resource = resource;
}
public ArrayList<ResourceType> getSearchResourceList() {
return searchResourceList;
}
public void setSearchResourceList(ArrayList<ResourceType> searchResourceList) {
this.searchResourceList = searchResourceList;
}
public List<ResourceType> getFilteredResourceList() {
return filteredResourceList;
}
public void setFilteredResourceList(List<ResourceType> filteredResourceList) {
this.filteredResourceList = filteredResourceList;
}
public ResourceType getSelectedRow() {
return selectedRow;
}
public void setSelectedRow(ResourceType selectedRow) {
this.selectedRow = selectedRow;
}
}
| 29.915493 | 99 | 0.756121 |
89e34317cb1a6db473417fa975494166f17d62c1 | 331 | package org.txazo.java.serialization;
import java.io.Serializable;
public class IChildren extends IParent implements Serializable {
private static final long serialVersionUID = -6164532894214647621L;
private String name;
public IChildren(int id, String name) {
super(1);
this.name = name;
}
}
| 19.470588 | 71 | 0.70997 |
595fdbb48ac8a80148f19f273293f079945f78da | 10,853 | /*
* Aipo is a groupware program developed by Aimluck,Inc.
* Copyright (C) 2004-2011 Aimluck,Inc.
* http://www.aipo.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aimluck.eip.note;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.portlet.EipTNoteMap;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALData;
import com.aimluck.eip.common.ALEipGroup;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALEipPost;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.note.util.NoteUtils;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.ResultList;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;
import com.aimluck.eip.util.ALLocalizationUtils;
/**
* 伝言メモの送信先に指定できるグループの検索データを管理するためのクラスです。
*/
public class NoteGroupSelectData extends
ALAbstractSelectData<TurbineUser, TurbineUser> implements ALData {
/** logger */
private static final JetspeedLogger logger = JetspeedLogFactoryService
.getLogger(NoteGroupSelectData.class.getName());
/** 現在選択しているタブ */
private String currentTab;
private String userId = null;
private String userAliasName = null;
private List<ALEipGroup> myGroupList = null;
private int unreadReceivedNotesAllSum = 0;
/** 新着数 */
private int newNoteAllSum = 0;
/**
* 初期化処理を行います。
*
* @param action
* @param rundata
* @param context
*/
@Override
public void init(ALAction action, RunData rundata, Context context)
throws ALPageNotFoundException, ALDBErrorException {
ALEipUtils.removeTemp(rundata, context, NoteUtils.TARGET_USER_ID);
super.init(action, rundata, context);
// グループの初期値を取得する
try {
String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
if (filter == null || filter.equals("")) {
VelocityPortlet portlet = ALEipUtils.getPortlet(rundata, context);
String groupName =
portlet.getPortletConfig().getInitParameter("p3b-group");
if (groupName != null) {
ALEipUtils.setTemp(rundata, context, LIST_FILTER_STR, groupName);
ALEipUtils.setTemp(rundata, context, LIST_FILTER_TYPE_STR, "group");
}
}
} catch (Exception ex) {
logger.debug("Exception", ex);
}
}
/**
*
* @param rundata
* @param context
* @return
*/
@Override
protected ResultList<TurbineUser> selectList(RunData rundata, Context context) {
setCurrentTab(rundata, context);
try {
userId = Integer.toString(ALEipUtils.getUserId(rundata));
userAliasName =
ALEipUtils.getALEipUser(rundata).getAliasName().toString();
NoteUtils.getTargetGroupName(rundata, context);
List<ALEipGroup> myGroups = ALEipUtils.getMyGroups(rundata);
myGroupList = new ArrayList<ALEipGroup>();
for (ALEipGroup group : myGroups) {
myGroupList.add(group);
}
// 受信履歴の未読数と新着数をカウントアップする.
List<EipTNoteMap> list =
NoteUtils.getSelectQueryNoteList(rundata, context).fetchList();
if (list != null && list.size() > 0) {
String stat = null;
for (EipTNoteMap map : list) {
stat = map.getNoteStat();
if (NoteUtils.NOTE_STAT_NEW.equals(stat)) {
// 新着数をカウントアップする.
newNoteAllSum++;
} else if (NoteUtils.NOTE_STAT_UNREAD.equals(stat)) {
// 受信履歴の未読数をカウントアップする.
unreadReceivedNotesAllSum++;
}
}
}
String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
String filter_type =
ALEipUtils.getTemp(rundata, context, LIST_FILTER_TYPE_STR);
if (filter == null || filter_type == null || filter.equals("")) {
return new ResultList<TurbineUser>(new ArrayList<TurbineUser>());
} else {
SelectQuery<TurbineUser> query = getSelectQuery(rundata, context);
buildSelectQueryForListView(query);
buildSelectQueryForListViewSort(query, rundata, context);
return query.getResultList();
}
} catch (Exception ex) {
logger.error("note", ex);
return null;
}
}
/**
*
* @param rundata
* @param context
* @return
*/
@Override
protected TurbineUser selectDetail(RunData rundata, Context context) {
setCurrentTab(rundata, context);
return null;
}
/**
*
* @param user
* @return
*/
@Override
protected Object getResultData(TurbineUser user) {
try {
NoteGroupResultData rd = new NoteGroupResultData();
rd.initField();
rd.setUserId(user.getUserId().intValue());
rd.setUserName(user.getLastName() + " " + user.getFirstName());
return rd;
} catch (Exception ex) {
logger.error("note", ex);
return null;
}
}
/**
*
* @param obj
* @return
*/
@Override
protected Object getResultDataDetail(TurbineUser obj) {
return null;
}
/**
*
* @return
*/
@Override
protected Attributes getColumnMap() {
Attributes map = new Attributes();
map.putValue("src_user", TurbineUser.LAST_NAME_KANA_PROPERTY);
map.putValue("group", TurbineUser.TURBINE_USER_GROUP_ROLE_PROPERTY
+ "."
+ TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
+ "."
+ TurbineGroup.GROUP_NAME_PROPERTY);
map.putValue("userposition", TurbineUser.EIP_MUSER_POSITION_PROPERTY
+ "."
+ EipMUserPosition.POSITION_PROPERTY); // ユーザの順番
return map;
}
/**
* 検索条件を設定した SelectQuery を返します。
*
* @param rundata
* @param context
* @return
*/
private SelectQuery<TurbineUser> getSelectQuery(RunData rundata,
Context context) {
SelectQuery<TurbineUser> query = Database.query(TurbineUser.class);
Expression exp11 =
ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
.valueOf(1));
Expression exp12 =
ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
.valueOf(2));
Expression exp13 =
ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
.valueOf(3));
query.setQualifier(exp11.andExp(exp12).andExp(exp13));
Expression exp2 =
ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY, "F");
query.andQualifier(exp2);
Expression exp3 =
ExpressionFactory.noMatchDbExp(TurbineUser.USER_ID_PK_COLUMN, Integer
.valueOf(userId));
query.andQualifier(exp3);
return buildSelectQueryForFilter(query, rundata, context);
}
/**
* フィルタ用の <code>SelectQuery</code> を構築します。
*
* @param crt
* @param rundata
* @param context
* @return
*/
@Override
protected SelectQuery<TurbineUser> buildSelectQueryForFilter(
SelectQuery<TurbineUser> query, RunData rundata, Context context) {
String filter = ALEipUtils.getTemp(rundata, context, LIST_FILTER_STR);
String filter_type =
ALEipUtils.getTemp(rundata, context, LIST_FILTER_TYPE_STR);
String crt_key = null;
Attributes map = getColumnMap();
if (filter == null || filter_type == null || filter.equals("")) {
return query;
}
crt_key = map.getValue(filter_type);
if (crt_key == null) {
return query;
}
Expression exp = ExpressionFactory.matchExp(crt_key, filter);
query.andQualifier(exp);
current_filter = filter;
current_filter_type = filter_type;
return query;
}
/**
*
* @param rundata
* @param context
*/
private void setCurrentTab(RunData rundata, Context context) {
String tabParam = rundata.getParameters().getString("tab");
currentTab = ALEipUtils.getTemp(rundata, context, "tab");
if (tabParam == null && currentTab == null) {
ALEipUtils.setTemp(rundata, context, "tab", "received_notes");
currentTab = "received_notes";
} else if (tabParam != null) {
ALEipUtils.setTemp(rundata, context, "tab", tabParam);
currentTab = tabParam;
}
}
/**
* 現在選択されているタブを取得します。
*
* @return
*/
public String getCurrentTab() {
return currentTab;
}
/**
*
* @return
*/
public String getUserId() {
return userId;
}
/**
*
* @return
*/
public String getUserAliasName() {
return userAliasName;
}
public String getUserAliasNameText() {
return ALLocalizationUtils.getl10nFormat(
"NOTE_USER_ALIAS_NAME_TEXT",
userAliasName.toString());
}
/**
*
* @return
*/
public int getNewNoteAllSum() {
return newNoteAllSum;
}
public String getNewNoteAllSumText() {
return ALLocalizationUtils.getl10nFormat(
"NOTE_NEW_NOTE_ALL_SUM_TEXT",
newNoteAllSum);
}
/**
*
* @return
*/
public int getUnreadReceivedNotesAllSum() {
return unreadReceivedNotesAllSum;
}
/**
*
* @return
*/
public Map<Integer, ALEipPost> getPostMap() {
return ALEipManager.getInstance().getPostMap();
}
/**
*
* @return
*/
public List<ALEipGroup> getMyGroupList() {
return myGroupList;
}
}
| 28.71164 | 83 | 0.657975 |
66f7a900d0cca4fa37f9a4205cabdce0b991cab5 | 1,375 | package com.rox.redis_jedis.set_test;
import java.util.Set;
import org.junit.Test;
import redis.clients.jedis.Jedis;
/**
* 测试 SetAPI
* 是否属于
* 交集
* 并集
* 差集
*/
public class SetTest {
@Test
public void testSet() {
Jedis jedis = new Jedis("cs1", 6379);
jedis.sadd("bigdata:hadoop", "hdfs","maprduce","yarn","zookeeper");
jedis.sadd("bigdata:spark", "flume","kafka","redis","zookeeper");
// 判断一个成员是否属于指定的集合 sismember
Boolean isornot = jedis.sismember("bigdata:hadoop", "zookeeper");
System.out.println(isornot);
System.out.println("----------------华丽的分割线--------------------");
// 求两个集合的差集 sdiff
Set<String> diff = jedis.sdiff("bigdata:hadoop","bigdata:spark");
for(String mb:diff){
System.out.println(mb);
}
System.out.println("----------------华丽的分割线--------------------");
// 求两个集合的并集 sunion
Set<String> union = jedis.sunion("bigdata:hadoop","bigdata:spark");
for(String mb:union){
System.out.println(mb);
}
System.out.println("----------------华丽的分割线--------------------");
// 求两个集合的交集 sinter
Set<String> intersect = jedis.sinter("bigdata:hadoop","bigdata:spark");
//打印结果
for(String mb:intersect){
System.out.println(mb);
}
}
}
| 26.442308 | 79 | 0.533818 |
0213fa9f94141291298a29a1130c1644d3702167 | 541 | package org.colocation.qos;
import org.cloudbus.cloudsim.core.CloudSim;
import org.colocation.ServiceEntity;
/**
* Created by wkj on 2019/6/13.
*/
public class EntrypointAPI {
private String entrypoint;
private String APIName;
public EntrypointAPI( String APIName, String entrypoint) {
this.APIName = APIName;
this.entrypoint = entrypoint;
}
public String getEntrypoint() {
return entrypoint;
}
public String getAPIName() {
return APIName;
}
}
| 20.807692 | 63 | 0.639556 |
1f40b9968471da95d4f0bc881a55e0ce39c4ab60 | 3,400 | /*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.securitytoken.model.transform;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.services.securitytoken.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* StAX request marshaller for AssumeRoleRequest
*/
public class AssumeRoleRequestMarshaller implements
Marshaller<Request<AssumeRoleRequest>, AssumeRoleRequest> {
public Request<AssumeRoleRequest> marshall(AssumeRoleRequest assumeRoleRequest) {
if (assumeRoleRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(AssumeRoleRequest)");
}
Request<AssumeRoleRequest> request = new DefaultRequest<AssumeRoleRequest>(
assumeRoleRequest, "AWSSecurityTokenService");
request.addParameter("Action", "AssumeRole");
request.addParameter("Version", "2011-06-15");
String prefix;
if (assumeRoleRequest.getRoleArn() != null) {
prefix = "RoleArn";
String roleArn = assumeRoleRequest.getRoleArn();
request.addParameter(prefix, StringUtils.fromString(roleArn));
}
if (assumeRoleRequest.getRoleSessionName() != null) {
prefix = "RoleSessionName";
String roleSessionName = assumeRoleRequest.getRoleSessionName();
request.addParameter(prefix, StringUtils.fromString(roleSessionName));
}
if (assumeRoleRequest.getPolicy() != null) {
prefix = "Policy";
String policy = assumeRoleRequest.getPolicy();
request.addParameter(prefix, StringUtils.fromString(policy));
}
if (assumeRoleRequest.getDurationSeconds() != null) {
prefix = "DurationSeconds";
Integer durationSeconds = assumeRoleRequest.getDurationSeconds();
request.addParameter(prefix, StringUtils.fromInteger(durationSeconds));
}
if (assumeRoleRequest.getExternalId() != null) {
prefix = "ExternalId";
String externalId = assumeRoleRequest.getExternalId();
request.addParameter(prefix, StringUtils.fromString(externalId));
}
if (assumeRoleRequest.getSerialNumber() != null) {
prefix = "SerialNumber";
String serialNumber = assumeRoleRequest.getSerialNumber();
request.addParameter(prefix, StringUtils.fromString(serialNumber));
}
if (assumeRoleRequest.getTokenCode() != null) {
prefix = "TokenCode";
String tokenCode = assumeRoleRequest.getTokenCode();
request.addParameter(prefix, StringUtils.fromString(tokenCode));
}
return request;
}
}
| 41.463415 | 85 | 0.677647 |
b9b6baa27ef535108eb354db5c5f909eebd95dcd | 1,207 | package nyc.c4q.ac21;
import java.util.Scanner;
/**
* Created by c4q-Allison on 3/20/15.
*/
public class APrettyTitle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your favorite book title here to be prettified:");
String title = input.nextLine();
System.out.println(Capitalize(title));
System.out.println(PrettyTitle(title));
}
public static String PrettyTitle(String title) {
String prettify = "";
for (int i = 0; i < title.length(); i++) {
if (title.charAt(i) != ' ') {
prettify += "*"; }
else
prettify += " ";
}
return prettify;
}
public static String Capitalize(String title) {
String newTitle ="";
for (int i = 0; i < title.length(); i++) {
if (i == 0)
newTitle = title.substring(i, i+1).toUpperCase();
else if (title.charAt(i - 1) == ' ')
newTitle += title.substring(i, i+1).toUpperCase();
else
newTitle += title.charAt(i);
}
return newTitle;
}
}
| 21.175439 | 84 | 0.516984 |
80a693c915a2c6a58b9e069aa6eff839df54c9ad | 647 | package com.sendtomoon.eroica2.allergo.classloader;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import com.sendtomoon.eroica2.allergo.AllergoManager;
public class AllergoURLStreamHandler extends URLStreamHandler {
private AllergoManager manager;
public AllergoURLStreamHandler() {
manager = com.sendtomoon.eroica2.allergo.Allergo.getManager();
}
public AllergoURLStreamHandler(AllergoManager manager) {
this.manager = manager;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new AllergoURLConnection(u, manager);
}
}
| 23.107143 | 67 | 0.805255 |
45e3099c3312a0c3cab9ea43d651d9e9a2bcce34 | 2,013 | package Application.Services;
import Application.Entities.AllReader;
import Application.Entities.Information;
import Application.Entities.IssuedBook;
import java.util.Date;
import java.util.List;
import java.util.Map;
public interface IssuedBookService {
void save(IssuedBook issuedBook);
void delete(Long id_record);
IssuedBook update(IssuedBook issuedBook);
IssuedBook findById(Long id);
List<IssuedBook> findAll();
List<IssuedBook> findByIdReader(Long id_reader);
List<IssuedBook> findByIdEdition(Long id_edition);
List<IssuedBook> findByIdReaderAndIdEdition(Long id_reader, Long id_edition);
List<IssuedBook> findReturned();
List<IssuedBook> findNotReturned();
List<IssuedBook> findByIdReaderAndReturned(Long id_reader);
List<IssuedBook> findByIdReaderAndNotReturned(Long id_reader);
List<IssuedBook> findByIdLibrarian(Long id_librarian);
List<IssuedBook> findByIdLibrarianAndReturned(Long id_librarian);
List<IssuedBook> findByIdLibrarianAndNotReturned(Long id_librarian);
List<IssuedBook> findByIdEditionAndIdLibrarian(Long id_edition, Long id_librarian);
List<IssuedBook> findByMoreDateExtradition(Date dateExtradition);
List<IssuedBook> findByLessDateExtradition(Date dateExtradition);
List<IssuedBook> findByMoreDateReturn(Date dateReturn);
List<IssuedBook> findByLessDateReturn(Date dateReturn);
List<IssuedBook> findBetweenDates(Date dateExtradition, Date dateReturn);
boolean isReturned(Long id_edition);
List<AllReader> findReadersWithTitle(String title);
List<AllReader> findReadersWithType(String type);
boolean isRegistered(Long id_reader, Long id_edition);
List<IssuedBook> findReadyBooks();
List<AllReader> findReadersByIdLibraryAndPeriod(long idLibrarian, Date startDate, Date endDate);
List<AllReader> findReadersNotAttendingLibrary(Date startDate, Date endDate);
Map<AllReader, String> findReadersWithTitle(String composition, Date startDate, Date endDate);
}
| 36.6 | 100 | 0.79235 |
3a37662355a76f85490f31dac6a00bef14b8656e | 17,500 | /*
Copyright 2014 Georg Kohlweiss
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.github.gekoh.yagen.util;
import com.github.gekoh.yagen.hibernate.DDLEnhancer;
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import static com.github.gekoh.yagen.api.Constants.USER_NAME_LEN;
/**
* @author Georg Kohlweiss
*/
public class DBHelper {
enum DatabaseDialect {
ORACLE,
HSQLDB,
POSTGRESQL
}
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DBHelper.class);
public static final String PROPERTY_GENERATE_BYPASS = "yagen.generator.bypass.implement";
public static final String PROPERTY_BYPASS = "yagen.bypass";
public static final String PROPERTY_BYPASS_REGEX = "yagen.bypass.regex";
public static final String PROPERTY_SKIP_MODIFICATION = "yagen.skip-modification.regex";
private static Field FIELD_CONFIGURATION_VALUES;
static {
try {
FIELD_CONFIGURATION_VALUES = StandardServiceRegistryImpl.class.getDeclaredField("configurationValues");
FIELD_CONFIGURATION_VALUES.setAccessible(true);
} catch (NoSuchFieldException e) {
LOG.error("unable to get field via reflection", e);
}
}
public static String createUUID() {
return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); // replace "-" 36 -> 32 char
}
public static String getOsUser() {
// that's not necessarily the user logged in but one can change this value with env var USERNAME
// which is absolutely sufficient in this case
return System.getProperty("user.name");
}
public static boolean skipModificationOf(String objectName, Metadata metadata) {
Map configurationValues = DBHelper.getConfigurationValues(metadata);
if (objectName == null || configurationValues == null || !configurationValues.containsKey(PROPERTY_SKIP_MODIFICATION)) {
return false;
}
return objectName.matches((String) configurationValues.get(PROPERTY_SKIP_MODIFICATION));
}
public static boolean implementBypassFunctionality(Metadata metadata) {
Map configurationValues = metadata != null ? DBHelper.getConfigurationValues(metadata) : null;
return configurationValues != null && configurationValues.containsKey(PROPERTY_GENERATE_BYPASS) &&
Boolean.TRUE.equals(Boolean.valueOf((String) configurationValues.get(PROPERTY_GENERATE_BYPASS)));
}
public static void setBypass(String objectRegex, EntityManager em) {
if (objectRegex == null) {
objectRegex = "^.*$";
}
setSessionVariable(PROPERTY_BYPASS_REGEX, objectRegex, em);
}
public static void removeBypass(EntityManager em) {
removeSessionVariable(PROPERTY_BYPASS_REGEX, em);
}
public static void removeSessionVariable(DatabaseDialect dialect, Connection connection, String name) throws SQLException {
switch (dialect) {
case ORACLE:
case HSQLDB:
try (PreparedStatement stmtUpdate = connection.prepareStatement("delete from SESSION_VARIABLES where name=?")) {
stmtUpdate.setString(1, name);
stmtUpdate.executeUpdate();
}
break;
case POSTGRESQL:
try (CallableStatement callableStatement = connection.prepareCall("{call remove_session_variable(?)}")) {
callableStatement.setString(1, name);
callableStatement.execute();
}
break;
default:
throw new IllegalArgumentException("unknown dialect: " + dialect);
}
}
public static String getSessionVariable(DatabaseDialect dialect, Connection connection, String name) throws SQLException {
switch (dialect) {
case ORACLE:
case HSQLDB:
try (PreparedStatement stmtUpdate = connection.prepareStatement("select value from SESSION_VARIABLES where name=?")) {
stmtUpdate.setString(1, name);
try (ResultSet rs = stmtUpdate.executeQuery()) {
if (rs.next()) {
String ret = rs.getString(1);
return ret;
}
return null;
}
}
case POSTGRESQL:
try (CallableStatement callableStatement = connection.prepareCall("{? = call get_session_variable(?)}")) {
callableStatement.setString(2, name);
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.execute();
return callableStatement.getString(1);
}
default:
throw new IllegalArgumentException("unknown dialect: " + dialect);
}
}
public static void setSessionVariable(DatabaseDialect dialect, Connection connection, String name, String value) throws SQLException {
switch (dialect) {
case ORACLE:
case HSQLDB:
try (PreparedStatement stmtUpdate = connection.prepareStatement("update SESSION_VARIABLES set VALUE=? where NAME=?")) {
stmtUpdate.setString(1, value);
stmtUpdate.setString(2, name);
if (stmtUpdate.executeUpdate() < 1) {
try (PreparedStatement stmtInsert = connection.prepareStatement("insert into SESSION_VARIABLES (name, value) values (?, ?)")) {
stmtInsert.setString(1, name);
stmtInsert.setString(2, value);
stmtInsert.executeUpdate();
}
}
}
break;
case POSTGRESQL:
try (CallableStatement callableStatement = connection.prepareCall("{call set_session_variable(?, ?)}")) {
callableStatement.setString(1, name);
callableStatement.setString(2, value);
callableStatement.execute();
}
break;
default:
throw new IllegalArgumentException("unknown dialect: " + dialect);
}
}
public static void setSessionVariable(String name, String value, EntityManager em) {
// postgres drops the temporary table when the session closes, so probably we have to create it beforehand
if (isPostgres(getDialect(em))) {
em.unwrap(Session.class).doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
setSessionVariable(DatabaseDialect.POSTGRESQL, connection, name, value);
}
});
return;
}
int affected = em.createNativeQuery("update SESSION_VARIABLES set VALUE=:value where NAME=:name")
.setParameter("name", name)
.setParameter("value", value)
.executeUpdate();
if (affected < 1) {
em.createNativeQuery("insert into SESSION_VARIABLES (name, value) values (:name, :value)")
.setParameter("name", name)
.setParameter("value", value)
.executeUpdate();
}
}
public static String getSessionVariable(String name, EntityManager em) {
// postgres drops the temporary table when the session closes, so probably we have to create it beforehand
if (isPostgres(getDialect(em))) {
return em.unwrap(Session.class).doReturningWork(new ReturningWork<String>() {
@Override
public String execute(Connection connection) throws SQLException {
String ret = getSessionVariable(DatabaseDialect.POSTGRESQL, connection, name);
return ret;
}
});
}
String value = null;
try {
value = (String) em.createNativeQuery("select value from SESSION_VARIABLES where NAME=:name")
.setParameter("name", name)
.getSingleResult();
} catch (NoResultException noResult) {
// ignore
}
return value;
}
public static void removeSessionVariable(String name, EntityManager em) {
// postgres drops the temporary table when the session closes, so probably it's not even existing
if (isPostgres(getDialect(em))) {
em.unwrap(Session.class).doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
removeSessionVariable(DatabaseDialect.POSTGRESQL, connection, name);
}
});
return;
}
em.createNativeQuery("delete from SESSION_VARIABLES where name=:name")
.setParameter("name", name)
.executeUpdate();
}
public static boolean isStaticallyBypassed(String objectName) {
final String bypass = System.getProperty(PROPERTY_BYPASS);
if (bypass != null) {
return true;
}
final String bypassPattern = System.getProperty(PROPERTY_BYPASS_REGEX);
if (bypassPattern != null) {
return objectName.matches(bypassPattern);
}
return false;
}
public static String getSysContext(String namespace, String parameter) {
if ("USERENV".equals(namespace)) {
if ("DB_NAME".equals(parameter)) {
return "HSQLDB";
}
else if ("OS_USER".equals(parameter)) {
return getOsUser();
}
else if ("CLIENT_IDENTIFIER".equals(parameter)) {
return null;
}
}
return null;
}
public static boolean regexpLike(String value, String regexp) {
if (value == null) {
return false;
}
return Pattern.compile(regexp).matcher(value).find();
}
public static boolean regexpLikeFlags(String value, String regexp, String flags) {
if (value == null || flags == null) {
return false;
}
String f = flags.toLowerCase();
int opts = 0;
if (f.contains("i")) {
opts = opts | Pattern.CASE_INSENSITIVE;
}
if (f.contains("c")) {
opts = opts | Pattern.CANON_EQ;
}
if (f.contains("n")) {
opts = opts | Pattern.DOTALL;
}
if (f.contains("m")) {
opts = opts | Pattern.MULTILINE;
}
return Pattern.compile(regexp, opts).matcher(value).find();
}
public static String injectSessionUser(String user, EntityManager em) {
String prevUser;
if (isPostgres(getDialect(em))
|| isHsqlDb(getDialect(em))) {
prevUser = getSessionVariable("CLIENT_IDENTIFIER", em);
if (user == null) {
removeSessionVariable("CLIENT_IDENTIFIER", em);
} else {
setSessionVariable("CLIENT_IDENTIFIER", user, em);
}
}
else {
prevUser = em.unwrap(Session.class).doReturningWork(new SetUserWorkOracle(user));
}
return prevUser;
}
public static boolean isHsqlDb(EntityManager em) {
return isHsqlDb(getDialect(em));
}
public static boolean isHsqlDb(Dialect dialect) {
return dialectMatches(dialect, "hsql");
}
public static boolean isPostgres(EntityManager em) {
return isPostgres(getDialect(em));
}
public static boolean isPostgres(Dialect dialect) {
return dialectMatches(dialect, "postgres");
}
public static boolean isOracle(EntityManager em) {
return isOracle(getDialect(em));
}
public static boolean isOracle(Dialect dialect) {
return dialectMatches(dialect, "oracle");
}
private static boolean dialectMatches(Dialect dialect, String subStr) {
String driverClassName = getDriverClassName(dialect);
return driverClassName != null ? driverClassName.toLowerCase().contains(subStr) : dialect.getClass().getName().toLowerCase().contains(subStr);
}
public static Metadata getMetadata(Dialect dialect) {
Object metadataObj;
if (!(dialect instanceof DDLEnhancer) || (metadataObj = ((DDLEnhancer) dialect).getMetadata()) == null) {
return null;
}
return (Metadata) metadataObj;
}
public static String getDriverClassName(EntityManager em) {
return em.unwrap(Session.class).doReturningWork(new ReturningWork<String>() {
public String execute(Connection connection) throws SQLException {
return connection.getMetaData().getDriverName();
}
});
}
public static Dialect getDialect(EntityManager em) {
if (em.unwrap(Session.class) != null) {
final SessionFactoryImpl sessionFactory = em.unwrap(Session.class).getSessionFactory().unwrap(SessionFactoryImpl.class);
return sessionFactory != null ? sessionFactory.getJdbcServices().getDialect() : null;
}
return null;
}
public static String getDriverClassName(Dialect dialect) {
Metadata metadata = getMetadata(dialect);
if (metadata == null) {
return null;
}
Map configurationValues = getConfigurationValues(metadata);
if (configurationValues != null) {
return (String) configurationValues.get("hibernate.connection.driver_class");
}
LOG.warn("cannot detect jdbc driver name");
return null;
}
public static Map getConfigurationValues(Metadata metadata) {
ServiceRegistry serviceRegistry = metadata.getDatabase().getServiceRegistry();
try {
if (serviceRegistry instanceof StandardServiceRegistryImpl && FIELD_CONFIGURATION_VALUES != null) {
return (Map) FIELD_CONFIGURATION_VALUES.get(serviceRegistry);
}
} catch (Exception ignore) {
}
LOG.warn("cannot get configuration values");
return null;
}
public static Timestamp getCurrentTimestamp() {
return NanoAwareTimestampUtil.getCurrentTimestamp();
}
public static class SetUserWorkOracle implements ReturningWork<String> {
private String userName;
public SetUserWorkOracle(String userName) {
this.userName = userName;
}
public String execute(Connection connection) throws SQLException {
CallableStatement statement = connection.prepareCall(
"declare newUserValue varchar2(" + USER_NAME_LEN + ") := substr(?,1," + USER_NAME_LEN + "); " +
"begin ? := sys_context('USERENV','CLIENT_IDENTIFIER'); " +
"DBMS_SESSION.set_identifier(newUserValue); " +
"end;"
);
statement.setString(1, userName);
statement.registerOutParameter(2, Types.VARCHAR);
statement.execute();
String result = statement.getString(2);
statement.close();
LOG.info("set client_identifier in oracle session from '{}' to '{}'", result == null ? "" : result, userName == null ? "" : "<db_user> (" + userName + ")");
return result;
}
}
public static void executeProcedure(EntityManager em, String method, Object... args) {
Session session = em.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
try (CallableStatement callableStatement = connection.prepareCall(String.format("{call %s}", method))) {
if (args != null) {
for (int i = 0; i<args.length; i++) {
callableStatement.setObject(i+1, args[i]);
}
}
callableStatement.execute();
}
}
});
}
}
| 39.149888 | 168 | 0.609086 |
352b5417ee044f53684b1e890270ddc02b7546bb | 1,618 | package com.erlangshen.model.vo;
import com.erlangshen.model.bo.LoginLogBO;
/**
* @author https://github.com/shuli495/erlangshen
*/
public class LoginLogVO extends LoginLogBO {
private static final long serialVersionUID = 1L;
private String username;
private String nickname;
private String mail;
private String phone;
private String clientId;
private String clientName;
private String createdBy;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Override
public String toString() {
return super.toString() + " LoginLogVO{\"username\": \""+username+"\", \"nickname\": \""+nickname+"\", "
+ "\"mail\": \""+mail+"\", \"phone\": \""+phone+"\", \"clientId\": \""+clientId+"\", " +
"\"clientName\": \""+clientName+"\", \"createdBy\": \""+createdBy+"\"}";
}
} | 19.731707 | 106 | 0.681706 |
f12f2d5fbd1b3fe2df3bca9bf5eb51605bc65ba4 | 1,182 | package cla.edg.modelbean;
public class BeanRelation {
protected String memberName;
protected String fromBeanTypeName;
protected String toBeanTypeName;
protected String referFieldName;
protected boolean forwardReference;
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getFromBeanTypeName() {
return fromBeanTypeName;
}
public void setFromBeanTypeName(String fromBeanTypeName) {
this.fromBeanTypeName = fromBeanTypeName;
}
public String getToBeanTypeName() {
return toBeanTypeName;
}
public void setToBeanTypeName(String toBeanTypeName) {
this.toBeanTypeName = toBeanTypeName;
}
public boolean isForwardReference() {
return forwardReference;
}
public void setForwardReference(boolean referOne) {
this.forwardReference = referOne;
}
public String getReferFieldName() {
return referFieldName;
}
public void setReferFieldName(String referFieldName) {
this.referFieldName = referFieldName;
}
public String getKey() {
if (this.isForwardReference()) {
return getReferFieldName();
}else {
return "~"+getReferFieldName();
}
}
}
| 24.122449 | 59 | 0.76819 |
c6ac6fcb3b8584af64c1795a314d355ec74337ca | 568 | package top.bitmore.dax.sdk.openapi.spot.ccex.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* @author coinmex-sdk-team
* @date 2018/04/28
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class WithdrawalParam {
/**
* 提现金额
*/
private BigDecimal amount;
/**
* 币种
*/
private String currencyCode;
/**
* 地址
*/
private String address;
}
| 17.212121 | 53 | 0.684859 |
3d974580bef1a732858c91c0c733b95df108a114 | 1,508 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.jboss.netty.util;
/**
* A utility class that provides the convenient shutdown of
* {@link ExternalResourceReleasable}s.
*/
public final class ExternalResourceUtil {
/**
* Releases the specified {@link ExternalResourceReleasable}s.
*/
public static void release(ExternalResourceReleasable... releasables) {
ExternalResourceReleasable[] releasablesCopy =
new ExternalResourceReleasable[releasables.length];
for (int i = 0; i < releasables.length; i ++) {
if (releasables[i] == null) {
throw new NullPointerException("releasables[" + i + ']');
}
releasablesCopy[i] = releasables[i];
}
for (ExternalResourceReleasable e: releasablesCopy) {
e.releaseExternalResources();
}
}
private ExternalResourceUtil() {
}
}
| 32.782609 | 78 | 0.675729 |
c25f3103399acb9e9795cd29c9bc4dbcd6e6c04b | 731 | /*
* All content copyright http://www.j2eefast.com, unless
* otherwise indicated. All rights reserved.
* No deletion without permission
*/
package com.j2eefast.framework.sys.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
*
* @Description:公司与地区对应关系
* @author zhouzhou loveingowp@163.com
* @time 2018-12-05 15:46
*
*/
@Data
@TableName("sys_comp_dept")
public class SysCompDeptEntity implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 公司ID
*/
private Long compId;
/**
* 地区ID
*/
private Long deptId;
}
| 19.756757 | 57 | 0.738714 |
c2c59124405b4066daf4022142a3160b5a3bf65d | 4,170 | /*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.qa.upgrade.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.value.builder.SerializedObjectValueBuilder;
import org.camunda.bpm.qa.upgrade.DescribesScenario;
import org.camunda.bpm.qa.upgrade.ScenarioSetup;
import org.camunda.bpm.qa.upgrade.json.beans.ObjectList;
import org.camunda.bpm.qa.upgrade.json.beans.Order;
import org.camunda.bpm.qa.upgrade.json.beans.OrderDetails;
import org.camunda.bpm.qa.upgrade.json.beans.RegularCustomer;
import static org.camunda.bpm.engine.variable.Variables.serializedObjectValue;
import static org.junit.Assert.assertEquals;
public class CreateProcessInstanceWithJsonVariablesScenario {
@Deployment
public static String deployProcess() {
return "org/camunda/bpm/qa/upgrade/json/simpleProcess.bpmn20.xml";
}
@DescribesScenario("initProcessInstanceWithDifferentVariables")
public static ScenarioSetup initProcessInstance() {
return new ScenarioSetup() {
public void execute(ProcessEngine engine, String scenarioName) {
// given
ProcessInstance processInstance = engine.getRuntimeService().startProcessInstanceByKey("Process", "processWithJsonVariables");
// when
Execution execution = engine.getRuntimeService().createExecutionQuery().processInstanceId(processInstance.getId()).singleResult();
engine.getRuntimeService().setVariable(execution.getId(), "objectVariable", createObjectVariable());
engine.getRuntimeService().setVariable(execution.getId(), "plainTypeArrayVariable", createPlainTypeArray());
engine.getRuntimeService().setVariable(execution.getId(), "notGenericObjectListVariable", createNotGenericObjectList());
engine.getRuntimeService().setVariable(execution.getId(), "serializedMapVariable", createSerializedMap());
}
};
}
public static Object createObjectVariable() {
Order order = new Order();
order.setId(1234567890987654321L);
order.setOrder("order1");
order.setDueUntil(20150112);
order.setActive(true);
OrderDetails orderDetails = new OrderDetails();
orderDetails.setArticle("camundaBPM");
orderDetails.setPrice(32000.45);
orderDetails.setRoundedPrice(32000);
List<String> currencies = new ArrayList<String>();
currencies.add("euro");
currencies.add("dollar");
orderDetails.setCurrencies(currencies);
order.setOrderDetails(orderDetails);
List<RegularCustomer> customers = new ArrayList<RegularCustomer>();
customers.add(new RegularCustomer("Kermit", 1354539722));
customers.add(new RegularCustomer("Waldo", 1320325322));
customers.add(new RegularCustomer("Johnny", 1286110922));
order.setCustomers(customers);
return order;
}
public static int[] createPlainTypeArray() {
return new int[]{5, 10};
}
public static ObjectList createNotGenericObjectList() {
ObjectList customers = new ObjectList();
customers.add(new RegularCustomer("someCustomer", 5));
customers.add(new RegularCustomer("secondCustomer", 666));
return customers;
}
public static SerializedObjectValueBuilder createSerializedMap(){
return serializedObjectValue("{\"foo\": \"bar\"}").serializationDataFormat("application/json").objectTypeName(HashMap.class.getName());
}
}
| 40.096154 | 139 | 0.758753 |
ee6841378d9c2ec6406926261507b0f49b30a2a0 | 21,652 | /*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
enum TVPType {
ResultSet,
ISQLServerDataRecord,
SQLServerDataTable,
Null
}
/**
*
* Implementation of Table-valued parameters which provide an easy way to marshal multiple rows of data from a client
* application to SQL Server without requiring multiple round trips or special server-side logic for processing the
* data.
* <p>
* You can use table-valued parameters to encapsulate rows of data in a client application and send the data to the
* server in a single parameterized command. The incoming data rows are stored in a table variable that can then be
* operated on by using Transact-SQL.
* <p>
* Column values in table-valued parameters can be accessed using standard Transact-SQL SELECT statements. Table-valued
* parameters are strongly typed and their structure is automatically validated. The size of table-valued parameters is
* limited only by server memory.
* <p>
* You cannot return data in a table-valued parameter. Table-valued parameters are input-only; the OUTPUT keyword is not
* supported.
*/
class TVP {
String TVPName;
String TVP_owningSchema;
String TVP_dbName;
ResultSet sourceResultSet = null;
SQLServerDataTable sourceDataTable = null;
Map<Integer, SQLServerMetaData> columnMetadata = null;
Iterator<Entry<Integer, Object[]>> sourceDataTableRowIterator = null;
ISQLServerDataRecord sourceRecord = null;
TVPType tvpType = null;
Set<String> columnNames = null;
// MultiPartIdentifierState
enum MPIState {
MPI_Value,
MPI_ParseNonQuote,
MPI_LookForSeparator,
MPI_LookForNextCharOrSeparator,
MPI_ParseQuote,
MPI_RightQuote,
}
void initTVP(TVPType type, String tvpPartName) throws SQLServerException {
tvpType = type;
columnMetadata = new LinkedHashMap<>();
parseTypeName(tvpPartName);
}
TVP(String tvpPartName) throws SQLServerException {
initTVP(TVPType.Null, tvpPartName);
}
// Name used in CREATE TYPE
TVP(String tvpPartName, SQLServerDataTable tvpDataTable) throws SQLServerException {
if (tvpPartName == null) {
tvpPartName = tvpDataTable.getTvpName();
}
initTVP(TVPType.SQLServerDataTable, tvpPartName);
sourceDataTable = tvpDataTable;
sourceDataTableRowIterator = sourceDataTable.getIterator();
populateMetadataFromDataTable();
}
TVP(String tvpPartName, ResultSet tvpResultSet) throws SQLServerException {
initTVP(TVPType.ResultSet, tvpPartName);
sourceResultSet = tvpResultSet;
// Populate TVP metadata from ResultSetMetadata.
populateMetadataFromResultSet();
}
TVP(String tvpPartName, ISQLServerDataRecord tvpRecord) throws SQLServerException {
initTVP(TVPType.ISQLServerDataRecord, tvpPartName);
sourceRecord = tvpRecord;
columnNames = new HashSet<>();
// Populate TVP metadata from ISQLServerDataRecord.
populateMetadataFromDataRecord();
// validate sortOrdinal and throw all relevant exceptions before proceeding
validateOrderProperty();
}
boolean isNull() {
return (TVPType.Null == tvpType);
}
Object[] getRowData() throws SQLServerException {
if (TVPType.ResultSet == tvpType) {
int colCount = columnMetadata.size();
Object[] rowData = new Object[colCount];
for (int i = 0; i < colCount; i++) {
try {
/*
* for Time types, getting TimeStamp instead of Time, because this value will be converted to String
* later on. If the value is a time object, the millisecond would be removed.
*/
if (java.sql.Types.TIME == sourceResultSet.getMetaData().getColumnType(i + 1)) {
rowData[i] = sourceResultSet.getTimestamp(i + 1);
} else {
rowData[i] = sourceResultSet.getObject(i + 1);
}
} catch (SQLException e) {
throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
}
}
return rowData;
} else if (TVPType.SQLServerDataTable == tvpType) {
Map.Entry<Integer, Object[]> rowPair = sourceDataTableRowIterator.next();
return rowPair.getValue();
} else
return sourceRecord.getRowData();
}
boolean next() throws SQLServerException {
if (TVPType.ResultSet == tvpType) {
try {
return sourceResultSet.next();
} catch (SQLException e) {
throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
}
} else if (TVPType.SQLServerDataTable == tvpType) {
return sourceDataTableRowIterator.hasNext();
} else if (null != sourceRecord) {
return sourceRecord.next();
}
return false;
}
void populateMetadataFromDataTable() throws SQLServerException {
if (null != sourceDataTable) {
Map<Integer, SQLServerDataColumn> dataTableMetaData = sourceDataTable.getColumnMetadata();
if (null == dataTableMetaData || dataTableMetaData.isEmpty()) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null);
}
dataTableMetaData.entrySet()
.forEach(E -> columnMetadata.put(E.getKey(), new SQLServerMetaData(E.getValue().columnName,
E.getValue().javaSqlType, E.getValue().precision, E.getValue().scale)));
}
}
void populateMetadataFromResultSet() throws SQLServerException {
if (null != sourceResultSet) {
try {
ResultSetMetaData rsmd = sourceResultSet.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
SQLServerMetaData columnMetaData = new SQLServerMetaData(rsmd.getColumnName(i + 1),
rsmd.getColumnType(i + 1), rsmd.getPrecision(i + 1), rsmd.getScale(i + 1));
columnMetadata.put(i, columnMetaData);
}
} catch (SQLException e) {
throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveColMeta"), e);
}
}
}
void populateMetadataFromDataRecord() throws SQLServerException {
if (null != sourceRecord) {
if (0 >= sourceRecord.getColumnCount()) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null);
}
for (int i = 0; i < sourceRecord.getColumnCount(); i++) {
Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnNames);
// Make a copy here as we do not want to change user's metadata.
SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1));
columnMetadata.put(i, metaData);
}
}
}
void validateOrderProperty() throws SQLServerException {
int columnCount = columnMetadata.size();
boolean[] sortOrdinalSpecified = new boolean[columnCount];
int maxSortOrdinal = -1;
int sortCount = 0;
for (Entry<Integer, SQLServerMetaData> columnPair : columnMetadata.entrySet()) {
SQLServerSortOrder columnSortOrder = columnPair.getValue().sortOrder;
int columnSortOrdinal = columnPair.getValue().sortOrdinal;
if (SQLServerSortOrder.Unspecified != columnSortOrder) {
// check if there's no way sort order could be monotonically increasing
if (columnCount <= columnSortOrdinal) {
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_TVPSortOrdinalGreaterThanFieldCount"));
throw new SQLServerException(form.format(new Object[] {columnSortOrdinal, columnPair.getKey()}),
null, 0, null);
}
// Check to make sure we haven't seen this ordinal before
if (sortOrdinalSpecified[columnSortOrdinal]) {
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_TVPDuplicateSortOrdinal"));
throw new SQLServerException(form.format(new Object[] {columnSortOrdinal}), null, 0, null);
}
sortOrdinalSpecified[columnSortOrdinal] = true;
if (columnSortOrdinal > maxSortOrdinal)
maxSortOrdinal = columnSortOrdinal;
sortCount++;
}
}
if (0 < sortCount) {
// validate monotonically increasing sort order. watch for values outside of the sortCount range.
if (maxSortOrdinal >= sortCount) {
// there is at least one hole, find the first one
int i;
for (i = 0; i < sortCount; i++) {
if (!sortOrdinalSpecified[i])
break;
}
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPMissingSortOrdinal"));
throw new SQLServerException(form.format(new Object[] {i}), null, 0, null);
}
}
}
void parseTypeName(String name) throws SQLServerException {
String leftQuote = "[\"";
String rightQuote = "]\"";
char separator = '.';
int limit = 3; // DbName, SchemaName, table type name
String[] parsedNames = new String[limit];
int stringCount = 0; // index of current string in the buffer
if ((null == name) || (0 == name.length())) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidTVPName"));
Object[] msgArgs = {};
throw new SQLServerException(null, form.format(msgArgs), null, 0, false);
}
StringBuilder sb = new StringBuilder(name.length());
// String buffer to hold white space used when parsing non-quoted strings 'a b . c d' = 'a b' and 'c d'
StringBuilder whitespaceSB = null;
// Right quote character to use given the left quote character found.
char rightQuoteChar = ' ';
MPIState state = MPIState.MPI_Value;
for (int index = 0; index < name.length(); ++index) {
char testchar = name.charAt(index);
switch (state) {
case MPI_Value:
int quoteIndex;
if (Character.isWhitespace(testchar)) // skip the whitespace
continue;
else if (testchar == separator) {
// If separator was found, but no string was found, initialize the string we are parsing to
// Empty.
parsedNames[stringCount] = "";
stringCount++;
} else if (-1 != (quoteIndex = leftQuote.indexOf(testchar))) {
// If we are at left quote, record the corresponding right quote for the left quote
rightQuoteChar = rightQuote.charAt(quoteIndex);
sb.setLength(0);
state = MPIState.MPI_ParseQuote;
} else if (-1 != rightQuote.indexOf(testchar)) {
// If we shouldn't see a right quote
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
} else {
sb.setLength(0);
sb.append(testchar);
state = MPIState.MPI_ParseNonQuote;
}
break;
case MPI_ParseNonQuote:
if (testchar == separator) {
parsedNames[stringCount] = sb.toString(); // set the currently parsed string
stringCount = incrementStringCount(parsedNames, stringCount);
state = MPIState.MPI_Value;
}
// Quotes are not valid inside a non-quoted name
else if ((-1 != rightQuote.indexOf(testchar)) || (-1 != leftQuote.indexOf(testchar))) {
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
} else if (Character.isWhitespace(testchar)) {
// If it is Whitespace
parsedNames[stringCount] = sb.toString(); // Set the currently parsed string
if (null == whitespaceSB)
whitespaceSB = new StringBuilder();
whitespaceSB.setLength(0);
// start to record the white space, if we are parsing a name like "foo bar" we should return
// "foo bar"
whitespaceSB.append(testchar);
state = MPIState.MPI_LookForNextCharOrSeparator;
} else
sb.append(testchar);
break;
case MPI_LookForNextCharOrSeparator:
if (!Character.isWhitespace(testchar)) {
// If it is not whitespace
if (testchar == separator) {
stringCount = incrementStringCount(parsedNames, stringCount);
state = MPIState.MPI_Value;
} else {
// If its not a separator and not whitespace
sb.append(whitespaceSB);
sb.append(testchar);
// Need to set the name here in case the string ends here.
parsedNames[stringCount] = sb.toString();
state = MPIState.MPI_ParseNonQuote;
}
} else {
if (null == whitespaceSB) {
whitespaceSB = new StringBuilder();
}
whitespaceSB.append(testchar);
}
break;
case MPI_ParseQuote:
// if are on a right quote see if we are escaping the right quote or ending the quoted string
if (testchar == rightQuoteChar)
state = MPIState.MPI_RightQuote;
else
sb.append(testchar); // Append what we are currently parsing
break;
case MPI_RightQuote:
if (testchar == rightQuoteChar) {
// If the next char is a another right quote then we were escaping the right quote
sb.append(testchar);
state = MPIState.MPI_ParseQuote;
} else if (testchar == separator) {
// If its a separator then record what we've parsed
parsedNames[stringCount] = sb.toString();
stringCount = incrementStringCount(parsedNames, stringCount);
state = MPIState.MPI_Value;
} else if (!Character.isWhitespace(testchar)) {
// If it is not white space we got problems
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
} else {
// It is a whitespace character
// the following char should be whitespace, separator, or end of string anything else is bad
parsedNames[stringCount] = sb.toString();
state = MPIState.MPI_LookForSeparator;
}
break;
case MPI_LookForSeparator:
if (!Character.isWhitespace(testchar)) {
// If it is not whitespace
if (testchar == separator) {
// If it is a separator
stringCount = incrementStringCount(parsedNames, stringCount);
state = MPIState.MPI_Value;
} else {
// not a separator
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
}
break;
}
}
if (stringCount > limit - 1) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
// Resolve final states after parsing the string
switch (state) {
case MPI_Value: // These states require no extra action
case MPI_LookForSeparator:
case MPI_LookForNextCharOrSeparator:
break;
case MPI_ParseNonQuote: // Dump what ever was parsed
case MPI_RightQuote:
parsedNames[stringCount] = sb.toString();
break;
case MPI_ParseQuote: // Invalid Ending States
default:
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
if (parsedNames[0] == null) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
} else {
// Shuffle the parsed name, from left justification to right justification, i.e. [a][b][null][null] goes to
// [null][null][a][b]
int offset = limit - stringCount - 1;
if (offset > 0) {
for (int x = limit - 1; x >= offset; --x) {
parsedNames[x] = parsedNames[x - offset];
parsedNames[x - offset] = null;
}
}
}
this.TVPName = parsedNames[2];
this.TVP_owningSchema = parsedNames[1];
this.TVP_dbName = parsedNames[0];
}
/*
* Parsing the multi-part identifier string. parameters: name - string to parse left-quote: set of characters which
* are valid quoting characters to initiate a quote right-quote: set of characters which are valid to stop a quote,
* array index's correspond to the the left-quote array. separator: separator to use limit: number of names to parse
* out removequote:to remove the quotes on the returned string
*/
private int incrementStringCount(String[] ary, int position) throws SQLServerException {
++position;
int limit = ary.length;
if (position >= limit) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidThreePartName"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
ary[position] = new String();
return position;
}
String getTVPName() {
return TVPName;
}
String getDbNameTVP() {
return TVP_dbName;
}
String getOwningSchemaNameTVP() {
return TVP_owningSchema;
}
int getTVPColumnCount() {
return columnMetadata.size();
}
Map<Integer, SQLServerMetaData> getColumnMetadata() {
return columnMetadata;
}
}
| 45.775899 | 121 | 0.557039 |
18c37dc7d916a98ee6be2ddc66816145343301b0 | 685 | package xyz.nikitacartes.easywhitelist.mixin;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.OperatorList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(OperatorList.class)
public class OperatorListMixin {
@Inject(method = "toString(Lcom/mojang/authlib/GameProfile;)Ljava/lang/String;", at = @At("HEAD"), cancellable = true)
protected void toString(GameProfile gameProfile, CallbackInfoReturnable<String> cir) {
cir.setReturnValue(gameProfile.getName());
}
}
| 38.055556 | 122 | 0.794161 |
6c94c891a7e13e42aa71c1b00f5c313a7f36c0cf | 10,272 | // Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
// Last modified on Wed 12 Jul 2017 at 16:10:00 PST by ian morris nieves
// modified on Mon 30 Apr 2007 at 13:21:00 PST by lamport
// modified on Fri Sep 22 13:18:45 PDT 2000 by yuanyu
package tlc2.value.impl;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.EvalControl;
import tlc2.tool.EvalException;
import tlc2.tool.FingerprintException;
import tlc2.tool.impl.Tool;
import tlc2.value.IValue;
import tlc2.value.Values;
import util.Assert;
import util.Assert.TLCRuntimeException;
import util.WrongInvocationException;
public class MethodValue extends OpValue implements Applicable {
public static Value get(final Method md) {
return get(md, 0);
}
public static Value get(final Method md, int minLevel) {
final MethodValue mv = new MethodValue(md, minLevel);
// Eagerly evaluate the constant operator if possible (zero arity) to only
// evaluate once at startup and not during state exploration.
final int acnt = md.getParameterTypes().length;
final boolean isConstant = (acnt == 0) && Modifier.isFinal(md.getModifiers());
return isConstant ? mv.apply(Tool.EmptyArgs, EvalControl.Clear) : mv;
}
private final MethodHandle mh;
private final Method md;
private final int minLevel;
/* Constructor */
private MethodValue(final Method md, final int minLevel) {
this.md = md;
this.minLevel = minLevel;
try {
final int parameterCount = this.md.getParameterCount();
if (parameterCount > 0) {
// With more than one argument, we want to setup the method handle to use a
// spreader which essentially converts the Value[] into something that is
// accepted by the method handle. Without a spreader, passing a Value[] to
// MethodHandle#invoke does not work. Instead one has to use MethodHandle#invokeWithArguments.
// MethodHandle#invokeWithArguments internally creates a spreader on the fly
// which turns out to be costly (for the spec MongoRepl of the performance
// tests it resulted in a 20% performance drop).
this.mh = MethodHandles.publicLookup().unreflect(md).asSpreader(IValue[].class, parameterCount);
} else {
this.mh = MethodHandles.publicLookup().unreflect(md);
}
} catch (IllegalAccessException e) {
throw new TLCRuntimeException(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, MP.getMessage(
EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[] { md.toString(), e.getMessage() }));
}
}
@Override
public final byte getKind() { return METHODVALUE; }
@Override
public final IValue initialize() {
this.deepNormalize();
// Do not call fingerprint as a MethodValue has no fingerprint.
return this;
}
@Override
public final int compareTo(Object obj) {
try {
Assert.fail("Attempted to compare operator " + this.toString() +
" with value:\n" + obj == null ? "null" : Values.ppr(obj.toString()), getSource());
return 0; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
public final boolean equals(Object obj) {
try {
Assert.fail("Attempted to check equality of operator " + this.toString() +
" with value:\n" + obj == null ? "null" : Values.ppr(obj.toString()), getSource());
return false; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final boolean member(Value elem) {
try {
Assert.fail("Attempted to check if the value:\n" + elem == null ? "null" : Values.ppr(elem.toString()) +
"\nis an element of operator " + this.toString(), getSource());
return false; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final boolean isFinite() {
try {
Assert.fail("Attempted to check if the operator " + this.toString() +
" is a finite set.", getSource());
return false; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value apply(Value arg, int control) {
try {
throw new WrongInvocationException("It is a TLC bug: Should use the other apply method.");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value apply(Value[] args, int control) {
try {
Value res = null;
try
{
if (args.length == 0) {
res = (Value) this.mh.invokeExact();
} else {
res = (Value) this.mh.invoke(args);
}
} catch (Throwable e)
{
if (e instanceof InvocationTargetException)
{
Throwable targetException = ((InvocationTargetException)e).getTargetException();
throw new EvalException(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), targetException.getMessage()});
} else if (e instanceof NullPointerException) {
throw new EvalException(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), e.getMessage()});
} else if (e instanceof EvalException) {
// Do not wrap an EvalException below.
throw (EvalException) e;
} else
{
String message = e.getMessage();
if (message == null) {
// Try to pass some information along (i.e. the full stack-trace) in cases where
// message is null.
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
message = sw.toString();
}
Assert.fail(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), message});
}
}
return res;
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value select(Value arg) {
try {
throw new WrongInvocationException("It is a TLC bug: Attempted to call MethodValue.select().");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value takeExcept(ValueExcept ex) {
try {
Assert.fail("Attempted to appy EXCEPT construct to the operator " +
this.toString() + ".", getSource());
return null; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value takeExcept(ValueExcept[] exs) {
try {
Assert.fail("Attempted to apply EXCEPT construct to the operator " +
this.toString() + ".", getSource());
return null; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value getDomain() {
try {
Assert.fail("Attempted to compute the domain of the operator " +
this.toString() + ".", getSource());
return SetEnumValue.EmptySet; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final int size() {
try {
Assert.fail("Attempted to compute the number of elements in the operator " +
this.toString() + ".", getSource());
return 0; // make compiler happy
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
/* Should never normalize an operator. */
@Override
public final boolean isNormalized() {
try {
throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator.");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final Value normalize() {
try {
throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator.");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
@Override
public final boolean isDefined() { return true; }
@Override
public final IValue deepCopy() { return this; }
@Override
public final boolean assignable(Value val) {
try {
throw new WrongInvocationException("It is a TLC bug: Attempted to initialize an operator.");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
/* String representation of the value. */
@Override
public final StringBuffer toString(StringBuffer sb, int offset, boolean ignored) {
try {
return sb.append("<Java Method: " + this.md + ">");
}
catch (RuntimeException | OutOfMemoryError e) {
if (hasSource()) { throw FingerprintException.getNewHead(this, e); }
else { throw e; }
}
}
public final int getMinLevel() {
return minLevel;
}
}
| 33.568627 | 144 | 0.655763 |
fbfaa568cd25b59492b2533b76e75ed7c8bcf80c | 100 | package org.iii.ideas.catering_service.rest.api;
public class QueryOfferedListRequest {
}
| 14.285714 | 49 | 0.75 |
9b699f18248d72da85948c0f4716a2dc6ffad8e0 | 11,883 | import java.awt.EventQueue;
import java.awt.Image;
import java.sql.*;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import net.proteanit.sql.DbUtils;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.MatteBorder;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
public class Delete extends JFrame {
private JPanel contentPane;
private JTable table;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Delete frame = new Delete();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn=null;
PreparedStatement pst;
Statement stmt = null;
ResultSet rs = null;
private JTextField txtID;
private JTextField txtName;
private JTextField txtPrice;
private JTextField txtUnit;
public Delete() {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/newwin.wav")));
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
conn=Connectionz.getConnection();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000,600);
setResizable(false);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Image backg=new ImageIcon("res/leaves.jpg").getImage().getScaledInstance(1000, 600, java.awt.Image.SCALE_SMOOTH);
JLabel lblTipsClickOn = new JLabel("Tips: Click on the Item you want to Delete");
lblTipsClickOn.setForeground(Color.WHITE);
lblTipsClickOn.setFont(new Font("PrimusW00-Bold", Font.PLAIN, 13));
lblTipsClickOn.setBounds(723, 538, 251, 24);
contentPane.add(lblTipsClickOn);
JLabel lblItemDetails = new JLabel("Item Details");
lblItemDetails.setHorizontalAlignment(SwingConstants.CENTER);
lblItemDetails.setFont(new Font("PrimusW00-Bold", Font.BOLD, 24));
lblItemDetails.setForeground(Color.WHITE);
Border border = BorderFactory.createLineBorder(Color.white, 1);
lblItemDetails.setBorder(border);
lblItemDetails.setBounds(10, 100, 442, 46);
contentPane.add(lblItemDetails);
JLabel lblUpdate = new JLabel("Delete Item(s)");
lblUpdate.setForeground(Color.WHITE);
lblUpdate.setBounds(356, 9, 442, 80);
contentPane.add(lblUpdate);
lblUpdate.setFont(new Font("Trajan Pro", Font.BOLD, 50));
JButton btnUpdate = new JButton("Delete");
btnUpdate.setFont(new Font("PrimusW00-Bold", Font.PLAIN, 19));
btnUpdate.setBounds(56, 517, 111, 34);
contentPane.add(btnUpdate);
JButton btnBack = new JButton("Back");
btnBack.setFont(new Font("PrimusW00-Bold", Font.PLAIN, 19));
btnBack.setBounds(307, 517, 111, 34);
contentPane.add(btnBack);
JLabel lblId = new JLabel("ID :");
lblId.setForeground(Color.WHITE);
lblId.setFont(new Font("PrimusW00-Bold", Font.BOLD, 20));
lblId.setBounds(39, 182, 53, 34);
contentPane.add(lblId);
JLabel lblName = new JLabel("NAME :");
lblName.setForeground(Color.WHITE);
lblName.setFont(new Font("PrimusW00-Bold", Font.BOLD, 20));
lblName.setBounds(39, 267, 81, 34);
contentPane.add(lblName);
JLabel lblPrice = new JLabel("PRICE :");
lblPrice.setForeground(Color.WHITE);
lblPrice.setFont(new Font("PrimusW00-Bold", Font.BOLD, 20));
lblPrice.setBounds(39, 350, 81, 34);
contentPane.add(lblPrice);
JLabel lblUnit = new JLabel("UNIT(s) :");
lblUnit.setForeground(Color.WHITE);
lblUnit.setFont(new Font("PrimusW00-Bold", Font.BOLD, 20));
lblUnit.setBounds(39, 430, 92, 34);
contentPane.add(lblUnit);
txtUnit = new JTextField();
txtUnit.setFont(new Font("Bahnschrift", Font.BOLD, 16));
txtUnit.setBounds(209, 430, 209, 32);
contentPane.add(txtUnit);
txtUnit.setColumns(10);
txtPrice = new JTextField();
txtPrice.setFont(new Font("Bahnschrift", Font.BOLD, 16));
txtPrice.setBounds(209, 350, 209, 34);
contentPane.add(txtPrice);
txtPrice.setColumns(10);
txtName = new JTextField();
txtName.setFont(new Font("Bahnschrift", Font.BOLD, 16));
txtName.setBounds(209, 272, 209, 32);
contentPane.add(txtName);
txtName.setColumns(10);
txtID = new JTextField();
txtID.setFont(new Font("Bahnschrift", Font.BOLD, 16));
txtID.setBounds(209, 187, 209, 32);
contentPane.add(txtID);
txtID.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(477, 100, 497, 432);
contentPane.add(scrollPane);
table = new JTable();
table.setFont(new Font("Bahnschrift", Font.PLAIN, 16));
table.setRowHeight(30);
table.getTableHeader().setFont(new Font("Times New Roman", Font.CENTER_BASELINE, 20));
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
int i=table.getSelectedRow();
TableModel model=table.getModel();
txtID.setText(model.getValueAt(i,0).toString());
txtName.setText(model.getValueAt(i,1).toString());
txtPrice.setText(model.getValueAt(i,2).toString());
txtUnit.setText(model.getValueAt(i,3).toString());
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/mouseclick.wav")));
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
scrollPane.setViewportView(table);
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ID", "NAME", "PRICE", "Unit(s)"
}
));
JLabel label_1 = new JLabel("");
label_1.setForeground(Color.WHITE);
label_1.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE));
label_1.setBounds(10, 157, 442, 331);
contentPane.add(label_1);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("res/delete.png"));
label.setBounds(273, 11, 92, 78);
contentPane.add(label);
JLabel lblback = new JLabel("");
lblback.setBounds(0, 0, 994, 572);
lblback.setIcon(new ImageIcon(backg));
contentPane.add(lblback);
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/open.wav")));
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
Welcome welcome = new Welcome();
welcome.setVisible(true);
dispose();
}
});
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String id = txtID.getText();
User use=new User();
if(id.isEmpty()){
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/error1.wav")));
clip.start();
} catch (Exception ex) {
ex.printStackTrace();
}
JOptionPane.showMessageDialog(contentPane, "Please fill the required details to proceed!!!", "W A R N I N G !", JOptionPane.WARNING_MESSAGE);
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/open.wav")));
clip.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
else{
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/confirm.wav")));
clip.start();
} catch (Exception ex) {
ex.printStackTrace();
}
int ok = JOptionPane.showConfirmDialog(contentPane, "Confirm to delete", "Are you sure...", JOptionPane.YES_NO_OPTION);
if(ok==0){
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/confirm.wav")));
clip.start();
} catch (Exception ex) {
ex.printStackTrace();
}
use.delete(id);
JOptionPane.showMessageDialog(contentPane, "Data is deleted...Successfully", "Done...", 1);
txtID.setText(null);
txtName.setText(null);
txtPrice.setText(null);
txtUnit.setText(null);
load();
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("audio/open.wav")));
clip.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
});
load();
}
public void load(){
try{
String query="select Pdt_Id,Pdt_Name,Pdt_Price,Pdt_Unit from Items";
PreparedStatement pst=conn.prepareStatement(query);
rs=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
System.out.println(""+e);
}
}
}
| 37.60443 | 165 | 0.54498 |
e8cbf1374bece413aeafbb5c840b8b6e28112e27 | 2,085 | package com.toast.apocalypse.common.util;
import com.toast.apocalypse.common.event.CommonConfigReloadListener;
import com.toast.apocalypse.common.misc.ApocalypseDamageSources;
import com.toast.apocalypse.common.register.ApocalypseItems;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.event.TickEvent;
public class RainDamageTickHelper {
/**
* Variables for quick access.
*
* These are updated when the mod's
* common config loads/reloads.
*
* {@link CommonConfigReloadListener#updateInfo()}
*/
public static int RAIN_TICK_RATE;
public static float RAIN_DAMAGE;
/**
* Checks if it is time to apply rain tick damage,
* and applies the damage to the player if so.
*
* @see com.toast.apocalypse.common.event.PlayerEvents#onPlayerTick(TickEvent.PlayerTickEvent)
*/
public static void checkAndPerformRainDamageTick(PlayerEntity player) {
World world = player.getCommandSenderWorld();
if (EnchantmentHelper.hasAquaAffinity(player) || !world.isRainingAt(player.blockPosition()))
return;
if (CapabilityHelper.getRainTicks(player) >= RAIN_TICK_RATE) {
CapabilityHelper.clearRainTicks(player);
ItemStack headStack = player.getItemBySlot(EquipmentSlotType.HEAD);
if (!headStack.isEmpty()) {
if (headStack.getItem() == ApocalypseItems.BUCKET_HELM.get() || headStack.getItem().getMaxDamage(headStack) <= 0) {
return;
}
headStack.hurtAndBreak(player.getRandom().nextInt(2), player, (playerEntity) -> player.broadcastBreakEvent(EquipmentSlotType.HEAD));
}
else {
player.hurt(ApocalypseDamageSources.RAIN_DAMAGE, RAIN_DAMAGE);
}
}
else {
CapabilityHelper.addRainTick(player);
}
}
}
| 36.578947 | 148 | 0.682974 |
d3968ecf2996b56d30633bae8843118bcd598aa8 | 412 | package com.mplus.hsytrix.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "mplus-common",fallback = HelloFeignFallBack.class)
public interface HelloFeign {
@GetMapping(value = "/hello/{name}")
public String hello(@PathVariable("name") String name);
}
| 31.692308 | 72 | 0.800971 |
077a5113d4688765e2e35b66b7daadcdb9e1827f | 168 | package Ejercicio5CuentaPalabras;
public interface Informador {
public void anyadeInfo(String s);
public String obtenInfo();
public void quitarInfo(String s);
}
| 21 | 35 | 0.779762 |
d884b1cfe3cd28b1e0127d36c9e2f9d476d4b340 | 1,737 | package frc.robot.drivers;
import com.kauailabs.navx.frc.AHRS;
import com.kauailabs.navx.frc.AHRS.SerialDataType;
import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.SPI;
import edu.wpi.first.wpilibj.SerialPort;
import org.frcteam2910.common.drivers.Gyroscope;
import org.frcteam2910.common.math.*;
/**
* Add your docs here.
*/
public class NavX extends Gyroscope{
private AHRS navX;
/**
* @param updateRate should always be set to the max of 200
*/
public NavX(I2C.Port i2cport, byte updateRate) {
navX = new AHRS(i2cport, updateRate);
}
/**
* @param updateRate should always be set to the max of 200
*/
public NavX(SPI.Port spiport, byte updateRate) {
navX = new AHRS(spiport, updateRate);
}
/**
* @param updateRate should always be set to the max of 200
*/
public NavX(SerialPort.Port port, byte updateRate) {
navX = new AHRS(port, SerialDataType.kProcessedData, updateRate);
}
@Override
public void calibrate() {
navX.reset();
}
@Override
public Rotation2 getUnadjustedAngle() {
return Rotation2.fromRadians(getAxis(Axis.YAW));
}
@Override
public double getUnadjustedRate() {
return Math.toRadians(navX.getRate());
}
public double getAxis(Axis axis) {
switch (axis) {
case PITCH:
return Math.toRadians(navX.getPitch());
case ROLL:
return Math.toRadians(navX.getRoll());
case YAW:
return Math.toRadians(navX.getYaw());
default:
return 0.0;
}
}
public enum Axis {
PITCH,
ROLL,
YAW
}
} | 23.794521 | 73 | 0.606218 |
ed4787b0e9d9a6889ca676384e3daf5db00d4f7e | 1,779 | package {{java_package}};
import java.rmi.RemoteException;
import psdi.mbo.Mbo;
import psdi.mbo.MboServerInterface;
import psdi.mbo.MboSet;
import psdi.util.MXApplicationException;
import psdi.util.MXException;
/**
* Set of {{mbo_class_name}}} State objects
*
*/
public class {{mbo_class_name}}StateSet extends MboSet implements
{{mbo_class_name}}StateSetRemote {
/**
* Construct the set of record State.
*
* @param ms The MboServerInterface used to access internals of the
* MXServer.
*/
public {{mbo_class_name}}StateSet(MboServerInterface ms) throws MXException,
RemoteException {
super(ms);
}
/**
* Initialize the set.
*/
public void init() throws MXException, RemoteException {
// This set cannot be changed by outside users
setFlag(READONLY, true);
super.init();
}
/**
* Factory method to create Script State.
*
* @param ms the {{mbo_class_name}}State MboSet.
* @return a {{mbo_class_name}} State Mbo.
*/
protected Mbo getMboInstance(MboSet ms) throws MXException, RemoteException {
return new {{mbo_class_name}}State(ms);
}
/**
* In order to create new {{mbo_class_name}}State, this set needs to be owned by a
* {{mbo_class_name}} Mbo
*
* @exception MXApplicationException Thrown with "autoscr",
* "{{mbo_class_name}}StateNoAdd" if not owned by a {{mbo_class_name}} object.
*/
public void canAdd() throws MXException {
// Only way to add is when you have a VAE owning it
if (!(getOwner() instanceof {{mbo_class_name}})) {
throw new MXApplicationException("autoscr", "{{mbo_class_name}}StateNoAdd");
}
}
}
| 28.238095 | 93 | 0.636313 |
538a83d351e933161ea6c140cfa201d95b478e2a | 249 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/** Metric aggregators. */
@ParametersAreNonnullByDefault
package io.opentelemetry.sdk.metrics.aggregator;
import javax.annotation.ParametersAreNonnullByDefault;
| 22.636364 | 54 | 0.799197 |
6aef5b09cddc03960c93cc04ecf585ec35f9c772 | 220 | package se.l4.silo;
public interface StoreResult<ID, T>
{
/**
* Get the identifier of the stored object.
*
* @return
*/
ID getId();
/**
* Get the data that was stored.
*
* @return
*/
T getData();
}
| 11.578947 | 44 | 0.577273 |
05ecfb3a5bb810e5e808b677828495847edebe3b | 2,070 | package core.checker.checker;
import core.checker.util.OpUtil;
import core.checker.vo.Result;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Checks that a unique id generator actually emits unique IDs. Expects a
* history with :f :generate invocations matched by :ok responses with distinct
* IDs for their :values. IDs should be comparable
*/
public class UniqueIds implements Checker {
@Override
public Result check(Map test, List<Operation> history, Map opts) {
long attemptCount = history.stream()
.filter(OpUtil::isInvoke)
.filter(op -> op.getF().equals("generate"))
.count();
List<Long> acks = history.stream()
.filter(OpUtil::isOk)
.filter(op -> op.getF() == Operation.F.GENERATE)
.map(op -> (long) op.getValue()).collect(Collectors.toList());
Map<Object, Long> counts = new HashMap<>();
for (long id : acks) {
counts.put(id, counts.getOrDefault(id, 0L) + 1);
}
for (Object key : counts.keySet()) {
if (counts.get(key) <= 1) {
counts.remove(key);
}
}
TreeMap dups = new TreeMap(counts);
long lowest = acks.get(0);
long highest = lowest;
for (long id : acks) {
if (id < lowest) {
lowest = id;
} else if (highest < id) {
highest = id;
}
}
List range = List.of(lowest, highest);
Result result = new Result();
result.setValid(dups.isEmpty());
result.setRes(Map.of(
"valid?", dups.isEmpty(),
"attempted-count", attemptCount,
"acknowledged-count", acks.size(),
"duplicated-count", dups.size(),
"duplicated", dups,
"range", range
));
//TODO sort dups by value
return result;
}
}
| 27.972973 | 81 | 0.54058 |
9dfbaa49800258c77d367702d715ad1b353ea6cf | 460 | package com.cowlark.eventbus.events;
import com.cowlark.eventbus.Event;
public class KindletCreateEvent extends Event<KindletCreateEventHandler>
{
public static Type<KindletCreateEventHandler> TYPE =
new Type<KindletCreateEventHandler>();
@Override
public Type<KindletCreateEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(KindletCreateEventHandler handler)
{
handler.onKindletCreate();
}
}
| 21.904762 | 72 | 0.773913 |
6774459b4363e71781b861fe7466f7f33d1e31e0 | 813 | package kz.dorm.api.dorm.util.gson.shelters;
import com.google.gson.annotations.SerializedName;
import kz.dorm.utils.DataConfig;
public class Shelter {
/* Мама. */
@SerializedName(DataConfig.DB_DORM_SHELTER_PARENT_MOTHER)
public Parent mother;
/* Папа. */
@SerializedName(DataConfig.DB_DORM_SHELTER_PARENT_FATHER)
public Parent father;
/* Опекун. */
@SerializedName(DataConfig.DB_DORM_SHELTER_GUARDIAN)
public Guardian guardian;
/* Детский дом. */
@SerializedName(DataConfig.DB_DORM_SHELTER_ORPHANAGE)
public Orphanage orphanage;
public Shelter(Parent mother, Parent father, Guardian guardian, Orphanage orphanage) {
this.mother = mother;
this.father = father;
this.guardian = guardian;
this.orphanage = orphanage;
}
} | 27.1 | 90 | 0.712177 |
31f6646f3ebe70252772e67ee3b4272676420227 | 835 | package de.ust.skill.common.jforeign.internal.fieldTypes;
import java.io.IOException;
import java.util.Collection;
import de.ust.skill.common.jvm.streams.InStream;
import de.ust.skill.common.jvm.streams.OutStream;
public final class F64 extends FloatType<Double> {
private final static F64 instance = new F64();
public static F64 get() {
return instance;
}
private F64() {
super(13);
}
@Override
public Double readSingleField(InStream in) {
return in.f64();
}
@Override
public long calculateOffset(Collection<Double> xs) {
return 8 * xs.size();
}
@Override
public void writeSingleField(Double target, OutStream out) throws IOException {
out.f64(target);
}
@Override
public String toString() {
return "f64";
}
}
| 21.410256 | 83 | 0.653892 |
a91103a83d811a5e7a646a6ba65096d53d10121d | 1,842 | /*
* Copyright 2016 David Murphy
*
* 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.redhat.demo.kafka.workitem;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.redhat.demo.kafka.KafkaClient;
public class KafkaWorkItemHandler implements WorkItemHandler {
private static final Logger LOG = LoggerFactory.getLogger(KafkaWorkItemHandler.class);
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
String topic = (String)workItem.getParameter("Topic");
String key = (String)workItem.getParameter("Key");
String value = (String)workItem.getParameter("Value");
try {
KafkaClient client = (KafkaClient)new InitialContext().lookup("java:module/KafkaClientBean!com.redhat.demo.kafka.KafkaClient");
client.send(topic, key, value);
manager.completeWorkItem(workItem.getId(), null);
} catch (NamingException e) {
LOG.error("Could not find Kafka client", e);
manager.abortWorkItem(workItem.getId());
}
}
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
}
}
| 31.758621 | 130 | 0.761672 |
7618da8d1ab34aafe64af99b3b5353e70c91d4ec | 2,857 | /*
* Copyright 2021 Jeremy KUHN
*
* 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.inverno.mod.sql.vertx.internal;
import io.inverno.mod.sql.PreparedStatement;
import io.inverno.mod.sql.TransactionalSqlOperations;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Transaction;
import reactor.core.publisher.Mono;
/**
* <p>
* Transactional SQL operations executed on a single connection.
* </p>
*
* <p>
* Committing or rolling back the transaction also closes the underlying Vert.x
* connection.
* </p>
*
* @author <a href="mailto:jeremy.kuhn@inverno.io">Jeremy Kuhn</a>
* @since 1.2
*/
public class TransactionalSqlConnection extends AbstractSqlOperations implements TransactionalSqlOperations {
private final Transaction transaction;
private final boolean closeConnection;
/**
* <p>
* Creates transactional operations with the specified underlying Vert.x SQL
* connection and transaction.
* </p>
*
* @param connection a Vert.x SQL connection with an opened transaction
* @param transaction the transaction
* @param closeConnection true to close the connection on commit/rollback, false otherwise
*/
public TransactionalSqlConnection(SqlConnection connection, Transaction transaction, boolean closeConnection) {
super(connection);
this.transaction = transaction;
this.closeConnection = closeConnection;
}
@Override
public PreparedStatement preparedStatement(String sql) {
return new TransactionalPreparedStatement(((SqlConnection)this.client), sql);
}
@Override
public Mono<Void> commit() {
Mono<Void> result = Mono.fromCompletionStage(() -> this.transaction.commit().toCompletionStage());
if(this.closeConnection) {
result = Mono.usingWhen(result, ign -> Mono.empty(), ign -> this.close());
}
return result;
}
@Override
public Mono<Void> rollback() {
Mono<Void> result = Mono.fromCompletionStage(() -> this.transaction.rollback().toCompletionStage());
if(this.closeConnection) {
result = Mono.usingWhen(result, ign -> Mono.empty(), ign -> this.close());
}
return result;
}
/**
* <p>
* Closes the underlying SQL connection.
* </p>
*
* @return a Mono that completes when the connection is closed
*/
public Mono<Void> close() {
return Mono.fromCompletionStage(() -> this.client.close().toCompletionStage());
}
}
| 30.72043 | 112 | 0.733637 |
9a44e8262a6cb3d5a1a684996ef51ae73596d635 | 15,256 | /*
HostCanvasProfile.java
Copyright (c) 2015 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.host.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.deviceconnect.android.deviceplugin.host.R;
import org.deviceconnect.android.deviceplugin.host.canvas.CanvasDrawImageObject;
import org.deviceconnect.android.deviceplugin.host.canvas.CanvasDrawUtils;
/**
* Canvas Profile Activity.
*
* @author NTT DOCOMO, INC.
*/
public class CanvasProfileActivity extends Activity {
/**
* Defined a parameter name.
*/
private static final String PARAM_INTENT = "param_intent";
/**
* Defined a dialog type:{@value}.
*/
private static final String DIALOG_TYPE_OOM = "TYPE_OOM";
/**
* Defined a dialog type:{@value}.
*/
private static final String DIALOG_TYPE_NOT_FOUND = "TYPE_NOT_FOUND";
/**
* 画像リソース取得結果.
*/
private enum ResourceResult {
/**
* リソースの取得に成功.
*/
Success,
/**
* リソースの取得時にOut Of Memoryが発生.
*/
OutOfMemory,
/**
* リソースの取得に失敗.
*/
NotFoundResource
}
/**
* Canvas view object.
*/
private ImageView mCanvasView;
/**
* Argument that draw in canvas.
*/
private Intent mIntent;
/**
* Bitmap that was sent from web application.
*/
private Bitmap mBitmap;
/**
* Download start dialog.
*/
private StartingDialogFragment mDialog;
/**
* Download flag.
*/
private boolean mDownloadFlag = false;
/**
* フォアグラウンドフラグ.
*/
private boolean mForegroundFlag = false;
/**
* 表示用オブジェクト.
*/
private CanvasDrawImageObject mDrawImageObject;
/**
* Implementation of BroadcastReceiver.
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
String action = intent.getAction();
if (CanvasDrawImageObject.ACTION_DRAW_CANVAS.equals(action)) {
setDrawingArgument(intent);
refreshImage(intent);
} else if (CanvasDrawImageObject.ACTION_DELETE_CANVAS.equals(action)) {
finish();
}
}
};
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_canvas_profile);
mCanvasView = findViewById(R.id.canvasProfileView);
Button btn = findViewById(R.id.buttonClose);
btn.setOnClickListener((v) -> {
finish();
});
Intent intent = null;
if (savedInstanceState != null) {
intent = (Intent) savedInstanceState.get(PARAM_INTENT);
}
if (intent == null) {
intent = getIntent();
}
setDrawingArgument(intent);
}
@Override
protected void onResume() {
super.onResume();
mForegroundFlag = true;
IntentFilter filter = new IntentFilter();
filter.addAction(CanvasDrawImageObject.ACTION_DRAW_CANVAS);
filter.addAction(CanvasDrawImageObject.ACTION_DELETE_CANVAS);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
refreshImage(mIntent);
}
@Override
protected void onPause() {
mForegroundFlag = false;
dismissDownloadDialog();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onPause();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
if (mIntent != null) {
outState.putParcelable(PARAM_INTENT, mIntent);
}
}
/**
* Set a argument that draw in canvas.
*
* @param intent argument
*/
private void setDrawingArgument(final Intent intent) {
if (intent != null) {
mIntent = intent;
}
}
/**
* リソースが見つからない場合のエラーダイアログを表示します.
*/
private void openNotFoundDrawImage() {
AlertDialogFragment oomDialog = AlertDialogFragment.create(DIALOG_TYPE_NOT_FOUND,
getString(R.string.host_canvas_error_title),
getString(R.string.host_canvas_error_not_found_message),
getString(R.string.host_ok));
oomDialog.show(getFragmentManager(), DIALOG_TYPE_NOT_FOUND);
}
/**
* メモリ不足エラーダイアログを表示します.
*/
private void openOutOfMemory() {
AlertDialogFragment oomDialog = AlertDialogFragment.create(DIALOG_TYPE_OOM,
getString(R.string.host_canvas_error_title),
getString(R.string.host_canvas_error_oom_message),
getString(R.string.host_ok));
oomDialog.show(getFragmentManager(), DIALOG_TYPE_OOM);
}
/**
* ダウンロードダイアログを表示します.
*/
private synchronized void showDownloadDialog() {
if (mDialog != null) {
mDialog.dismiss();
}
mDialog = new StartingDialogFragment();
mDialog.show(getFragmentManager(), "dialog");
}
/**
* ダウンロードダイアログを非表示にします.
*/
private synchronized void dismissDownloadDialog() {
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
/**
* 画面に表示する画像を更新します.
* @param intent 更新する画像データが入ったintent
*/
private void refreshImage(final Intent intent) {
final CanvasDrawImageObject drawImageObject = CanvasDrawImageObject.create(intent);
if (drawImageObject == null) {
openNotFoundDrawImage();
return;
}
if (mDownloadFlag) {
return;
}
mDownloadFlag = true;
AsyncTask<Void, ResourceResult, ResourceResult> task = new AsyncTask<Void, ResourceResult, ResourceResult>() {
@Override
protected void onPreExecute() {
showDownloadDialog();
}
@Override
protected ResourceResult doInBackground(final Void... params) {
if (mBitmap != null) {
// 同じデータへのURIならば、すでに画像を読み込んでいるの表示する
if (mDrawImageObject != null && drawImageObject.getData().equals(mDrawImageObject.getData())) {
return ResourceResult.Success;
} else {
if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
mBitmap = null;
}
}
}
String uri = drawImageObject.getData();
byte[] data;
try {
if (uri.startsWith("http")) {
data = CanvasDrawUtils.getData(uri);
} else if (uri.startsWith("content")) {
data = CanvasDrawUtils.getContentData(CanvasProfileActivity.this, uri);
} else {
data = CanvasDrawUtils.getCacheData(uri);
}
mBitmap = CanvasDrawUtils.getBitmap(data);
if (mBitmap == null) {
return ResourceResult.NotFoundResource;
}
} catch (OutOfMemoryError e) {
return ResourceResult.OutOfMemory;
} catch (Exception e) {
return ResourceResult.NotFoundResource;
}
return ResourceResult.Success;
}
@Override
protected void onPostExecute(final ResourceResult result) {
mDrawImageObject = drawImageObject;
dismissDownloadDialog();
if (mForegroundFlag) {
switch (result) {
case Success:
showDrawObject(mDrawImageObject);
break;
case OutOfMemory:
openOutOfMemory();
break;
case NotFoundResource:
openNotFoundDrawImage();
break;
}
}
mDownloadFlag = false;
}
};
task.execute();
}
/**
* 画面を更新します.
* @param drawObj 更新する画像データ
*/
private void showDrawObject(final CanvasDrawImageObject drawObj) {
switch (drawObj.getMode()) {
default:
case NON_SCALE_MODE:
Matrix matrix = new Matrix();
matrix.postTranslate((float) drawObj.getX(), (float) drawObj.getY());
mCanvasView.setImageBitmap(mBitmap);
mCanvasView.setScaleType(ScaleType.MATRIX);
mCanvasView.setImageMatrix(matrix);
break;
case SCALE_MODE:
mCanvasView.setImageBitmap(mBitmap);
mCanvasView.setScaleType(ScaleType.FIT_CENTER);
mCanvasView.setTranslationX((int) drawObj.getX());
mCanvasView.setTranslationY((int) drawObj.getY());
break;
case FILL_MODE:
BitmapDrawable bd = new BitmapDrawable(getResources(), mBitmap);
bd.setTileModeX(Shader.TileMode.REPEAT);
bd.setTileModeY(Shader.TileMode.REPEAT);
mCanvasView.setImageDrawable(bd);
mCanvasView.setScaleType(ScaleType.FIT_XY);
mCanvasView.setTranslationX((int) drawObj.getX());
mCanvasView.setTranslationY((int) drawObj.getY());
break;
}
}
/**
* Show a dialog of dwnload image.
*/
public static class StartingDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
String title = getString(R.string.host_canvas_download_title);
String msg = getString(R.string.host_canvas_download_message);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_progress, null);
TextView titleView = v.findViewById(R.id.title);
TextView messageView = v.findViewById(R.id.message);
titleView.setText(title);
messageView.setText(msg);
builder.setView(v);
return builder.create();
}
@Override
public void onPause() {
dismiss();
super.onPause();
}
}
/**
* エラーダイアログ.
*/
public static class AlertDialogFragment extends DialogFragment {
/**
* タグのキーを定義します.
*/
private static final String KEY_TAG = "tag";
/**
* タイトルのキーを定義します.
*/
private static final String KEY_TITLE = "title";
/**
* メッセージのキーを定義します.
*/
private static final String KEY_MESSAGE = "message";
/**
* Positiveボタンのキーを定義します.
*/
private static final String KEY_POSITIVE = "yes";
/**
* Negativeボタンのキーを定義します.
*/
private static final String KEY_NEGATIVE = "no";
/**
* ボタン無しでAlertDialogを作成します.
* @param tag タグ
* @param title タイトル
* @param message メッセージ
* @return AlertDialogFragmentのインスタンス
*/
public static AlertDialogFragment create(final String tag, final String title, final String message) {
return create(tag, title, message, null, null);
}
/**
* PositiveボタンのみでAlertDialogを作成します.
* @param tag タグ
* @param title タイトル
* @param message メッセージ
* @param positive positiveボタン名
* @return AlertDialogFragmentのインスタンス
*/
public static AlertDialogFragment create(final String tag, final String title, final String message, final String positive) {
return create(tag, title, message, positive, null);
}
/**
* ボタン有りでAlertDialogを作成します.
* @param tag タグ
* @param title タイトル
* @param message メッセージ
* @param positive positiveボタン名
* @param negative negativeボタン名
* @return AlertDialogFragmentのインスタンス
*/
public static AlertDialogFragment create(final String tag, final String title, final String message,
final String positive, final String negative) {
Bundle args = new Bundle();
args.putString(KEY_TAG, tag);
args.putString(KEY_TITLE, title);
args.putString(KEY_MESSAGE, message);
if (positive != null) {
args.putString(KEY_POSITIVE, positive);
}
if (negative != null) {
args.putString(KEY_NEGATIVE, negative);
}
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.setArguments(args);
return dialog;
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getArguments().getString(KEY_TITLE));
builder.setMessage(getArguments().getString(KEY_MESSAGE));
if (getArguments().getString(KEY_POSITIVE) != null) {
builder.setPositiveButton(getArguments().getString(KEY_POSITIVE),
(dialog, which) -> {
Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
});
}
if (getArguments().getString(KEY_NEGATIVE) != null) {
builder.setNegativeButton(getArguments().getString(KEY_NEGATIVE), null);
}
return builder.create();
}
@Override
public void onCancel(final DialogInterface dialog) {
}
}
}
| 31.134694 | 133 | 0.572168 |
f0adf9aeca18485e9642918d762938bb5da12ade | 296 | package com.ibiz.excel.picture.support.event;
import com.ibiz.excel.picture.support.model.Sheet;
import com.ibiz.excel.picture.support.listener.ContentListener;
public interface WorkbookEvent<E extends ContentListener> {
WorkbookEvent registry(E listener);
void onEvent(Sheet sheet);
}
| 29.6 | 63 | 0.800676 |
749dd41c2157264c558766013f25406582efed08 | 624 | package websocket.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
public class OneOOne {
public static void main(String... args) throws IOException, NoSuchAlgorithmException {
ServerSocket server = new ServerSocket(80);
try {
System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
Socket client = server.accept();
System.out.println("A client connected.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| 31.2 | 101 | 0.660256 |
0615b62bb400db9eb4d6e6ca535ddcfaba3a78a6 | 9,791 | package com.o6.controller;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.o6.ApplicationConfig;
import com.o6.dao.UserContentRepository;
import com.o6.dto.BasicUserAuthInfo;
import com.o6.security.TokenAuthenticationService;
import com.o6.security.User;
import com.o6.security.UserAuthentication;
import com.o6.security.UserRepository;
import com.o6.security.UserRole;
import com.o6.service.UserProfilesService;
import com.o6.util.CommonUtils;
import com.o6.util.UserExistingException;
/*
* User controller.
*
* TODO: Currently, some service functionality is also in here, needs to be moved to separate
* service layer.
*/
@RestController
@ControllerAdvice
public class UserController {
private static final String EMAIL_CONFIRM_URL_BASE = "/api/register/confirmEmail";
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
ApplicationConfig appConfig;
@Autowired
JavaMailSender mailSender;
@Autowired
UserRepository userRepository;
@Autowired
private UserContentRepository userContentRepository;
@Autowired
TokenAuthenticationService tokenAuthenticationService;
@Autowired
UserProfilesService userProfilesService;
@RequestMapping(value = "/api/users/current", method = RequestMethod.GET)
public User getCurrent() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UserAuthentication) {
return ((UserAuthentication) authentication).getDetails();
}
return new User(authentication.getName()); // anonymous user support
}
@RequestMapping(value = "/api/register", method = RequestMethod.POST)
public ResponseEntity<String> register(@RequestBody BasicUserAuthInfo user,
HttpServletRequest request, HttpServletResponse response) throws UserExistingException {
if (user.getUserName().equalsIgnoreCase("Anonymous")) {
return new ResponseEntity<String>("User Anonymous not allowed",
HttpStatus.UNPROCESSABLE_ENTITY);
}
if (userRepository.findByEmail(user.getEmail()) != null) {
return new ResponseEntity<String>("User already present in the system",
HttpStatus.UNPROCESSABLE_ENTITY);
}
// Verify captcha
RestTemplate restTemplate = new RestTemplate();
String url =
String.format(
"https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s",
appConfig.recaptchaKey, user.getReCaptchaVal(), request.getRemoteAddr());
@SuppressWarnings("rawtypes")
ResponseEntity<Map> resp = restTemplate.postForEntity(url, null, Map.class);
if (!resp.getStatusCode().equals(HttpStatus.OK)) {
return new ResponseEntity<String>("Captcha check failure", HttpStatus.UNPROCESSABLE_ENTITY);
}
final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
User dbUser = new User();
dbUser.setUsername(user.getUserName());
dbUser.setEmail(user.getEmail());
dbUser.setEmailVerifyKey(UUID.randomUUID().toString());
dbUser.setPassword(pwEncoder.encode(user.getPassword()));
dbUser.grantRole(UserRole.USER);
userRepository.save(dbUser);
sendEmailConfirmationEmail(dbUser.getUsername(), dbUser.getEmail(), dbUser.getEmailVerifyKey());
final UserAuthentication userAuthentication = new UserAuthentication(dbUser);
// Add the custom token as HTTP header to the response
tokenAuthenticationService.addAuthentication(response, userAuthentication);
// Add the authentication to the Security context
SecurityContextHolder.getContext().setAuthentication(userAuthentication);
return new ResponseEntity<String>("User registered", HttpStatus.OK);
}
/*
* Confirm email, update database.
*/
@RequestMapping(value = EMAIL_CONFIRM_URL_BASE + "/{verifyKey}", method = RequestMethod.GET)
public ResponseEntity<String> confirmEmail(HttpServletResponse httpServletResponse,
@PathVariable("verifyKey") String verifyKey) {
final User currentUser = userRepository.findByEmailVerifyKey(verifyKey);
if (currentUser != null) {
currentUser.setEmailVerified(true);
userRepository.save(currentUser);
}
httpServletResponse.setHeader("Location", appConfig.appUrl);
return new ResponseEntity<String>("redirect:" + appConfig.appUrl, HttpStatus.TEMPORARY_REDIRECT);
}
/*
* Confirm email, update database.
*/
@RequestMapping(value = "/api/user/refreshToken", method = RequestMethod.GET)
public ResponseEntity<String> refreshToken(Principal principal) {
UserAuthentication ua = (UserAuthentication) principal;
final User currentUser = userRepository.findOne(ua.getDetails().getId());
return new ResponseEntity<String>(tokenAuthenticationService.getToken(currentUser),
HttpStatus.OK);
}
@RequestMapping(value = "/api/changePassword", method = RequestMethod.POST)
public ResponseEntity<String> changePassword(@RequestBody final BasicUserAuthInfo user) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final User currentUser =
userRepository.findByEmail(((UserAuthentication) authentication).getDetails().getEmail());
if (user.getNewPassword() == null || user.getNewPassword().length() < 4) {
return new ResponseEntity<String>("new password too short", HttpStatus.UNPROCESSABLE_ENTITY);
}
final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
if (!pwEncoder.matches(user.getPassword(), currentUser.getPassword())) {
return new ResponseEntity<String>("old password mismatch", HttpStatus.UNPROCESSABLE_ENTITY);
}
currentUser.setPassword(pwEncoder.encode(user.getNewPassword()));
userRepository.save(currentUser);
return new ResponseEntity<String>("password changed", HttpStatus.OK);
}
@RequestMapping(value = "/api/resetPassword", method = RequestMethod.POST)
public ResponseEntity<String> resetPassword(@RequestBody final BasicUserAuthInfo user) {
final User currentUser = userRepository.findByEmail(user.getEmail());
final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
String randomPassword = RandomStringUtils.randomAlphanumeric(8);
currentUser.setPassword(pwEncoder.encode(randomPassword));
userRepository.save(currentUser);
sendResetPasswordEmail(currentUser.getUsername(), currentUser.getEmail(), randomPassword);
return new ResponseEntity<String>("password changed", HttpStatus.OK);
}
@RequestMapping(value = "/admin/api/users", method = RequestMethod.GET)
public List<User> list() {
return userRepository.findAll();
}
/*
* Send password reset mail in a separate thread.
*/
private void sendResetPasswordEmail(String userName, String toAddress, String newPassword) {
String subject = "Your password reset request";
String message =
"Dear " + userName + ",\n\n"
+ "Your password reset request is processed. Your new password is: " + newPassword
+ "\n\nRegards\n--Support Staff.\n";
CommonUtils.commonExecService().execute(new Runnable() {
@Override
public void run() {
CommonUtils.sendEmail(mailSender, appConfig.senderName, appConfig.senderEmail, toAddress,
subject, message, false);
}
});
}
private void sendEmailConfirmationEmail(String userName, String email, String emailConfirmKey) {
String subject = "Thanks for registering, please confirm email";
String confirmUrl = appConfig.appUrl + EMAIL_CONFIRM_URL_BASE + "/" + emailConfirmKey;
String message =
"<html><body>"
+ "Dear "
+ userName
+ ",<br><br>"
+ "Thanks for registering to O6Escalate. One last step in this process is to confirm your email address. "
+ "To confirm, please click on " + "<a href='" + confirmUrl
+ "' target='_blank'>this link</a>, " + "or open this URL in a browser: " + confirmUrl
+ "<br> " + "<br><br>Regards<br>--Support Staff.<br>" + "</html></body>";
CommonUtils.commonExecService().execute(new Runnable() {
@Override
public void run() {
CommonUtils.sendEmail(mailSender, appConfig.senderName, appConfig.senderEmail, email,
subject, message, true);
}
});
}
/*
* General exception handling
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
logger.error("Exception caught:", e);
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(e.getMessage());
}
}
| 38.097276 | 118 | 0.744051 |
3ca27125862eface5cf62c363e1deaf2c6437d78 | 417 | package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
/** A complex auto command that drives forward, releases a hatch, and then drives backward. */
public class AutoElevator extends SequentialCommandGroup {
public AutoElevator() {
addCommands(
new ElevatorDownCommand(-0.6, 50),
new ReleaseArms(0.1),
new ElevatorUpCommand(0.3, 20)
);
}
}
| 26.0625 | 94 | 0.707434 |
003bf179e4671f767cd2e571035b6e9af772cd68 | 571 | public class Peca
{
private char tipo;
public Peca(char tipo)
{
setTipo(tipo);
}
public void setTipo(char tipo)
{
this.tipo = tipo;
}
public char getTipo()
{
return tipo;
}
public boolean promocao()
{
if(tipo=='o')
{
tipo = 'O';
return true;
}
if(tipo=='x')
{
tipo = 'X';
return true;
}
return false;
}
public String toString()
{
return "" + tipo;
}
} | 15.026316 | 34 | 0.401051 |
342fb98a4cbb47b546535748671c3289f66b06d9 | 293 | package com.sunzequn.srm.utils;
import java.text.DecimalFormat;
/**
* Created by Sloriac on 2016/11/22.
*/
public class NumUtil {
public static double m8(double d) {
DecimalFormat df = new DecimalFormat("#.00000000");
return Double.parseDouble(df.format(d));
}
}
| 18.3125 | 59 | 0.665529 |
f8610231e2abcd6201632973f5b2ae11f3d313b1 | 12,868 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.iot.v1;
import com.google.api.core.BetaApi;
import com.google.cloud.iot.v1.DeviceManagerGrpc.DeviceManagerImplBase;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.protobuf.Empty;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockDeviceManagerImpl extends DeviceManagerImplBase {
private ArrayList<GeneratedMessageV3> requests;
private Queue<Object> responses;
public MockDeviceManagerImpl() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
public List<GeneratedMessageV3> getRequests() {
return requests;
}
public void addResponse(GeneratedMessageV3 response) {
responses.add(response);
}
public void setResponses(List<GeneratedMessageV3> responses) {
this.responses = new LinkedList<Object>(responses);
}
public void addException(Exception exception) {
responses.add(exception);
}
public void reset() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
@Override
public void createDeviceRegistry(
CreateDeviceRegistryRequest request, StreamObserver<DeviceRegistry> responseObserver) {
Object response = responses.remove();
if (response instanceof DeviceRegistry) {
requests.add(request);
responseObserver.onNext((DeviceRegistry) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void getDeviceRegistry(
GetDeviceRegistryRequest request, StreamObserver<DeviceRegistry> responseObserver) {
Object response = responses.remove();
if (response instanceof DeviceRegistry) {
requests.add(request);
responseObserver.onNext((DeviceRegistry) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void updateDeviceRegistry(
UpdateDeviceRegistryRequest request, StreamObserver<DeviceRegistry> responseObserver) {
Object response = responses.remove();
if (response instanceof DeviceRegistry) {
requests.add(request);
responseObserver.onNext((DeviceRegistry) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void deleteDeviceRegistry(
DeleteDeviceRegistryRequest request, StreamObserver<Empty> responseObserver) {
Object response = responses.remove();
if (response instanceof Empty) {
requests.add(request);
responseObserver.onNext((Empty) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void listDeviceRegistries(
ListDeviceRegistriesRequest request,
StreamObserver<ListDeviceRegistriesResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListDeviceRegistriesResponse) {
requests.add(request);
responseObserver.onNext((ListDeviceRegistriesResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void createDevice(CreateDeviceRequest request, StreamObserver<Device> responseObserver) {
Object response = responses.remove();
if (response instanceof Device) {
requests.add(request);
responseObserver.onNext((Device) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void getDevice(GetDeviceRequest request, StreamObserver<Device> responseObserver) {
Object response = responses.remove();
if (response instanceof Device) {
requests.add(request);
responseObserver.onNext((Device) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void updateDevice(UpdateDeviceRequest request, StreamObserver<Device> responseObserver) {
Object response = responses.remove();
if (response instanceof Device) {
requests.add(request);
responseObserver.onNext((Device) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void deleteDevice(DeleteDeviceRequest request, StreamObserver<Empty> responseObserver) {
Object response = responses.remove();
if (response instanceof Empty) {
requests.add(request);
responseObserver.onNext((Empty) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void listDevices(
ListDevicesRequest request, StreamObserver<ListDevicesResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListDevicesResponse) {
requests.add(request);
responseObserver.onNext((ListDevicesResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void modifyCloudToDeviceConfig(
ModifyCloudToDeviceConfigRequest request, StreamObserver<DeviceConfig> responseObserver) {
Object response = responses.remove();
if (response instanceof DeviceConfig) {
requests.add(request);
responseObserver.onNext((DeviceConfig) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void listDeviceConfigVersions(
ListDeviceConfigVersionsRequest request,
StreamObserver<ListDeviceConfigVersionsResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListDeviceConfigVersionsResponse) {
requests.add(request);
responseObserver.onNext((ListDeviceConfigVersionsResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void listDeviceStates(
ListDeviceStatesRequest request, StreamObserver<ListDeviceStatesResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListDeviceStatesResponse) {
requests.add(request);
responseObserver.onNext((ListDeviceStatesResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void setIamPolicy(SetIamPolicyRequest request, StreamObserver<Policy> responseObserver) {
Object response = responses.remove();
if (response instanceof Policy) {
requests.add(request);
responseObserver.onNext((Policy) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void getIamPolicy(GetIamPolicyRequest request, StreamObserver<Policy> responseObserver) {
Object response = responses.remove();
if (response instanceof Policy) {
requests.add(request);
responseObserver.onNext((Policy) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void testIamPermissions(
TestIamPermissionsRequest request,
StreamObserver<TestIamPermissionsResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof TestIamPermissionsResponse) {
requests.add(request);
responseObserver.onNext((TestIamPermissionsResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void sendCommandToDevice(
SendCommandToDeviceRequest request,
StreamObserver<SendCommandToDeviceResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof SendCommandToDeviceResponse) {
requests.add(request);
responseObserver.onNext((SendCommandToDeviceResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void bindDeviceToGateway(
BindDeviceToGatewayRequest request,
StreamObserver<BindDeviceToGatewayResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof BindDeviceToGatewayResponse) {
requests.add(request);
responseObserver.onNext((BindDeviceToGatewayResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void unbindDeviceFromGateway(
UnbindDeviceFromGatewayRequest request,
StreamObserver<UnbindDeviceFromGatewayResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof UnbindDeviceFromGatewayResponse) {
requests.add(request);
responseObserver.onNext((UnbindDeviceFromGatewayResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
}
| 36.765714 | 99 | 0.73609 |
c7999412355bd5a4fc9ea05065ca452b97b1cb35 | 697 | package com.rollbar.notifier.util.json;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.rollbar.api.payload.data.body.Body;
import com.rollbar.api.payload.data.body.Message;
import java.lang.reflect.Type;
public class BodySerializer implements JsonSerializer<Body> {
@Override
public JsonElement serialize(Body src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
if(src.getContents() instanceof Message) {
jsonObject.add("message", context.serialize(src.getContents()));
}
return jsonObject;
}
}
| 30.304348 | 92 | 0.777618 |
8c79d1a60ae1580854c141c03568ccd1b5e3dbe3 | 37 | package de.pinsrq.sdk.corium.module;
| 18.5 | 36 | 0.810811 |
f1f74f324f09ff77bf70b72113b4b6864d0141c3 | 4,735 | package com.genesis.dao;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.genesis.entity.TimeSheetEntity;
import com.genesis.model.TimeSheet;
@Repository(value="timeSheetDAO")
public class TimeSheetDAOImpl implements TimeSheetDAO{
@Autowired
EntityManager entityManager;
@Override
public List<TimeSheet> getAllEmployeeTimeSheet() throws Exception {
String sql = "SELECT t FROM TimeSheetEntity t";
Query q = entityManager.createQuery(sql);
List<TimeSheetEntity> userTimeSheetList = q.getResultList();
List<TimeSheet> finalList = new ArrayList<>();
for(TimeSheetEntity timeSheetEntity:userTimeSheetList) {
TimeSheet timeSheet = new TimeSheet();
//System.out.println(customer.getDvd().getDvdType().equals(dvdType));
//System.out.println(customer.getDvd().getDvdType()+" "+dvdType);
timeSheet.setTimeId(timeSheetEntity.getTimeId());
timeSheet.setEmployeeId(timeSheetEntity.getEmployeeId());
timeSheet.setAttendanceDate(timeSheetEntity.getAttendanceDate());
timeSheet.setTimeIn(timeSheetEntity.getTimeIn());
timeSheet.setTimeOut(timeSheetEntity.getTimeOut());
timeSheet.setComment(timeSheetEntity.getComment());
finalList.add(timeSheet);
}
return finalList;
}
@Override
public TimeSheet getEmployeeTimeSheet(Integer employeeId, LocalDate date) throws Exception {
TimeSheet timeSheet = null;
String sql = "SELECT t FROM TimeSheetEntity t WHERE t.employeeId = ?1 AND date =?2";
Query q = entityManager.createQuery(sql);
q.setParameter(1, employeeId);
q.setParameter(2, date);
try {
TimeSheetEntity timeSheetEntity = (TimeSheetEntity) q.getSingleResult();
if(timeSheetEntity != null) {
timeSheet = new TimeSheet();
timeSheet.setTimeId(timeSheetEntity.getTimeId());
timeSheet.setEmployeeId(timeSheetEntity.getEmployeeId());
timeSheet.setAttendanceDate(timeSheetEntity.getAttendanceDate());
timeSheet.setTimeIn(timeSheetEntity.getTimeIn());
timeSheet.setTimeOut(timeSheetEntity.getTimeOut());
timeSheet.setComment(timeSheetEntity.getComment());
}
} catch (Exception NoResultException) {
//e.printStackTrace();
//System.out.println(e.getMessage());
throw new Exception("Dao.USER_TIMESHEET_DOES_NOT_EXIST");
}
return timeSheet;
}
@Override
public Integer clockIn(Integer employeeId, LocalDate date, LocalTime timeIn) throws Exception {
Integer updateCount = null;
/*
* get user time card using date and id
* then add time in information
* post it back
*/
try {
String sql = "UPDATE TimeSheetEntity t SET t.timeIn =?1 WHERE t.employeeId = ?2 AND date =?3 ";
Query q = entityManager.createQuery(sql);
q.setParameter(1, timeIn);
q.setParameter(2, employeeId);
q.setParameter(3, date);
updateCount = q.executeUpdate();//returns no. of entries updated
} catch (Exception e) {
System.out.println("Error in userLoginDAO: "+e.getMessage());
}
return updateCount;
}
@Override
public Integer clockOut(Integer employeeId, LocalDate date,LocalTime timeOut) throws Exception {
Integer updateCount = null;
/*
* get user time card using date and id
* then add time in information
* post it back
*/
try {
String sql = "UPDATE TimeSheetEntity t SET t.timeOut =?1 WHERE t.employeeId = ?2 AND date =?3 ";
Query q = entityManager.createQuery(sql);
q.setParameter(1, timeOut);
q.setParameter(2, employeeId);
q.setParameter(3, date);
updateCount = q.executeUpdate();
} catch (Exception e) {
System.out.println("Error in userLoginDAO: "+e.getMessage());
}
return updateCount;
}
@Override
public Integer addTimeSheet(TimeSheet timeSheet) throws Exception {
Integer retValue = null;
Integer timeId = null;
try {
TimeSheetEntity timeSheetEntity = new TimeSheetEntity();
timeSheetEntity.setEmployeeId(timeSheet.getEmployeeId());
timeSheetEntity.setAttendanceDate(timeSheet.getAttendanceDate());
timeSheetEntity.setTimeId(timeSheet.getTimeId());
timeSheetEntity.setComment(timeSheet.getComment());
timeSheetEntity.setTimeIn(timeSheet.getTimeIn());
timeSheetEntity.setTimeOut(timeSheet.getTimeOut());
entityManager.persist(timeSheetEntity);
timeId = timeSheetEntity.getTimeId();
retValue = timeId;
} catch (Exception e) {
System.out.println("Something went wrong while persisting to database: "+e.getMessage());
}
return retValue;
}
}
| 28.871951 | 100 | 0.729039 |
c1644a17af765e9975459419d2f35c6caa910ddd | 4,008 | package com.tango.cordova;
import android.app.Application;
import android.content.Context;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.Intent;
import android.util.Log;
import java.util.Set;
import java.util.HashSet;
import com.tango.core.Tango;
import com.tango.custom.trigger.TangoAutomation;
public class TangoPlugin extends CordovaPlugin {
private static final String TAG = "TangoPlugin";
private static final String KEY_CTA = "com.tangotargeting.intent.extra.CTA";
private static final String ACTION_CTA = "com.tangotargeting.intent.action.CUSTOM_CTA";
private BroadcastReceiver ctaReceiver;
public void initialize(CordovaInterface cordova, CordovaWebView webView){
super.initialize(cordova, webView);
ctaReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getStringExtra(KEY_CTA);
Log.d(TAG, "TangoPlugin Custom Action Received => " + action);
if (action != null) {
final String method = String.format("javascript:window.TangoPlugin.onCustomAction('%s');", action);
TangoPlugin.this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
TangoPlugin.this.webView.loadUrl(method);
Log.d(TAG, "TangoPlugin Custom Action Executed in WebView => " + action);
}
});
}
}
};
registerReceiver(ctaReceiver, new IntentFilter(ACTION_CTA));
}
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException{
Log.d(TAG, "TangoPlugin action => " + action);
if("initializeTango".equals(action)){
return true; // Tango is self initialized on Android
}else if("trigger".equals(action)){
String triggerPhrase = args.getString(0);
Log.d(TAG, "TangoPlugin trigger => " + triggerPhrase);
int result = TangoAutomation.trigger(triggerPhrase);
if(result == TangoAutomation.CAMPAIGN_TRIGGERED){
callbackContext.success("Campaign Triggered Successfully!");
return true;
}else{
callbackContext.error("Campaign Failed to trigger with code: " + result);
return false;
}
}else if("addSegments".equals(action)){
Set<String> tags;
JSONArray jsonTags = args.getJSONArray(0);
try{
tags = toStringSet(jsonTags);
}catch(JSONException e){
callbackContext.error(e.getMessage());
return false;
}
Tango.addTags(tags);
callbackContext.success(jsonTags);
}
return true;
}
protected void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
super.webView.getContext().registerReceiver(receiver, filter);
Log.d(TAG, "TangoPlugin Custom Call to Action Receiver registered!");
//LocalBroadcastManager.getInstance(super.webView.getContext()).registerReceiver(receiver, filter);
}
protected void unregisterReceiver(BroadcastReceiver receiver) {
super.webView.getContext().unregisterReceiver(receiver);
Log.d(TAG, "TangoPlugin Custom Call to Action Receiver unregistered!");
//LocalBroadcastManager.getInstance(super.webView.getContext()).unregisterReceiver(receiver);
}
public void onDestroy() {
unregisterReceiver(ctaReceiver);
}
private Set<String> toStringSet(JSONArray jsonArray) throws JSONException{
Set<String> tags = new HashSet<String>();
try {
for (int i = 0; i < jsonArray.length(); i++) {
tags.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return tags;
}
} | 31.3125 | 115 | 0.712824 |
011f32c023c98bfba334de2d5f34808f4233c81d | 2,797 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.machinelearning;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Defines values for ParameterType.
*/
public final class ParameterType {
/** Static value String for ParameterType. */
public static final ParameterType STRING = new ParameterType("String");
/** Static value Int for ParameterType. */
public static final ParameterType INT = new ParameterType("Int");
/** Static value Float for ParameterType. */
public static final ParameterType FLOAT = new ParameterType("Float");
/** Static value Enumerated for ParameterType. */
public static final ParameterType ENUMERATED = new ParameterType("Enumerated");
/** Static value Script for ParameterType. */
public static final ParameterType SCRIPT = new ParameterType("Script");
/** Static value Mode for ParameterType. */
public static final ParameterType MODE = new ParameterType("Mode");
/** Static value Credential for ParameterType. */
public static final ParameterType CREDENTIAL = new ParameterType("Credential");
/** Static value Boolean for ParameterType. */
public static final ParameterType BOOLEAN = new ParameterType("Boolean");
/** Static value Double for ParameterType. */
public static final ParameterType DOUBLE = new ParameterType("Double");
/** Static value ColumnPicker for ParameterType. */
public static final ParameterType COLUMN_PICKER = new ParameterType("ColumnPicker");
/** Static value ParameterRange for ParameterType. */
public static final ParameterType PARAMETER_RANGE = new ParameterType("ParameterRange");
/** Static value DataGatewayName for ParameterType. */
public static final ParameterType DATA_GATEWAY_NAME = new ParameterType("DataGatewayName");
private String value;
/**
* Creates a custom value for ParameterType.
* @param value the custom value
*/
public ParameterType(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return value;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ParameterType)) {
return false;
}
if (obj == this) {
return true;
}
ParameterType rhs = (ParameterType) obj;
if (value == null) {
return rhs.value == null;
} else {
return value.equals(rhs.value);
}
}
}
| 31.077778 | 95 | 0.676082 |
f2e5b5307bba1d2ecba1a10288ae574d240575ce | 380 | package visitor;
import controller.Game;
/**
* ChangeLevelVisitor is a {@link Visitor} to notify a Game that a level is over and must go to the next one
*
* @author José Astorga
*/
public class ChangeLevelVisitor extends Visitor {
/**
* ChangeLevelVisitor Constructor
*/
@Override
public void visitGame(Game game){
game.goNextLevel();
}
}
| 19 | 108 | 0.671053 |
20ef6eca4029c05014a0c1d33d886456d9ccc1b9 | 7,583 | /*
* 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.hadoop.fs.s3a.scale;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.contract.ContractTestUtils;
import org.apache.hadoop.fs.s3a.S3AFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.s3a.S3AInputStream;
import org.apache.hadoop.fs.s3a.S3AInstrumentation;
import org.apache.hadoop.fs.s3a.S3ATestUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.Locale;
import static org.junit.Assume.assumeTrue;
/**
* Base class for scale tests; here is where the common scale configuration
* keys are defined.
*/
public class S3AScaleTestBase extends Assert {
public static final String SCALE_TEST = "scale.test.";
public static final String S3A_SCALE_TEST = "fs.s3a.scale.test.";
@Rule
public TestName methodName = new TestName();
@BeforeClass
public static void nameThread() {
Thread.currentThread().setName("JUnit");
}
/**
* The number of operations to perform: {@value}.
*/
public static final String KEY_OPERATION_COUNT =
SCALE_TEST + "operation.count";
/**
* The readahead buffer: {@value}.
*/
public static final String KEY_READ_BUFFER_SIZE =
S3A_SCALE_TEST + "read.buffer.size";
public static final int DEFAULT_READ_BUFFER_SIZE = 16384;
/**
* Key for a multi MB test file: {@value}.
*/
public static final String KEY_CSVTEST_FILE =
S3A_SCALE_TEST + "csvfile";
/**
* Default path for the multi MB test file: {@value}.
*/
public static final String DEFAULT_CSVTEST_FILE
= "s3a://landsat-pds/scene_list.gz";
/**
* The default number of operations to perform: {@value}.
*/
public static final long DEFAULT_OPERATION_COUNT = 2005;
protected S3AFileSystem fs;
protected static final Logger LOG =
LoggerFactory.getLogger(S3AScaleTestBase.class);
private Configuration conf;
/**
* Configuration generator. May be overridden to inject
* some custom options.
* @return a configuration with which to create FS instances
*/
protected Configuration createConfiguration() {
return new Configuration();
}
/**
* Get the configuration used to set up the FS.
* @return the configuration
*/
public Configuration getConf() {
return conf;
}
@Before
public void setUp() throws Exception {
conf = createConfiguration();
LOG.debug("Scale test operation count = {}", getOperationCount());
fs = S3ATestUtils.createTestFileSystem(conf);
}
@After
public void tearDown() throws Exception {
ContractTestUtils.rm(fs, getTestPath(), true, true);
}
protected Path getTestPath() {
String testUniqueForkId = System.getProperty("test.unique.fork.id");
return testUniqueForkId == null ? new Path("/tests3a") :
new Path("/" + testUniqueForkId, "tests3a");
}
protected long getOperationCount() {
return getConf().getLong(KEY_OPERATION_COUNT, DEFAULT_OPERATION_COUNT);
}
/**
* Describe a test in the logs
* @param text text to print
* @param args arguments to format in the printing
*/
protected void describe(String text, Object... args) {
LOG.info("\n\n{}: {}\n",
methodName.getMethodName(),
String.format(text, args));
}
/**
* Get the input stream statistics of an input stream.
* Raises an exception if the inner stream is not an S3A input stream
* @param in wrapper
* @return the statistics for the inner stream
*/
protected S3AInstrumentation.InputStreamStatistics getInputStreamStatistics(
FSDataInputStream in) {
InputStream inner = in.getWrappedStream();
if (inner instanceof S3AInputStream) {
S3AInputStream s3a = (S3AInputStream) inner;
return s3a.getS3AStreamStatistics();
} else {
Assert.fail("Not an S3AInputStream: " + inner);
// never reached
return null;
}
}
/**
* Make times more readable, by adding a "," every three digits.
* @param nanos nanos or other large number
* @return a string for logging
*/
protected static String toHuman(long nanos) {
return String.format(Locale.ENGLISH, "%,d", nanos);
}
/**
* Log the bandwidth of a timer as inferred from the number of
* bytes processed.
* @param timer timer
* @param bytes bytes processed in the time period
*/
protected void bandwidth(NanoTimer timer, long bytes) {
LOG.info("Bandwidth = {} MB/S",
timer.bandwidthDescription(bytes));
}
/**
* Work out the bandwidth in MB/s
* @param bytes bytes
* @param durationNS duration in nanos
* @return the number of megabytes/second of the recorded operation
*/
public static double bandwidthMBs(long bytes, long durationNS) {
return (bytes * 1000.0 ) / durationNS;
}
/**
* A simple class for timing operations in nanoseconds, and for
* printing some useful results in the process.
*/
protected static class NanoTimer {
final long startTime;
long endTime;
public NanoTimer() {
startTime = now();
}
/**
* End the operation
* @return the duration of the operation
*/
public long end() {
endTime = now();
return duration();
}
/**
* End the operation; log the duration
* @param format message
* @param args any arguments
* @return the duration of the operation
*/
public long end(String format, Object... args) {
long d = end();
LOG.info("Duration of {}: {} nS",
String.format(format, args), toHuman(d));
return d;
}
long now() {
return System.nanoTime();
}
long duration() {
return endTime - startTime;
}
double bandwidth(long bytes) {
return S3AScaleTestBase.bandwidthMBs(bytes, duration());
}
/**
* Bandwidth as bytes per second
* @param bytes bytes in
* @return the number of bytes per second this operation timed.
*/
double bandwidthBytes(long bytes) {
return (bytes * 1.0 ) / duration();
}
/**
* How many nanoseconds per byte
* @param bytes bytes processed in this time period
* @return the nanoseconds it took each byte to be processed
*/
long nanosPerByte(long bytes) {
return duration() / bytes;
}
/**
* Get a description of the bandwidth, even down to fractions of
* a MB
* @param bytes bytes processed
* @return bandwidth
*/
String bandwidthDescription(long bytes) {
return String.format("%,.6f", bandwidth(bytes));
}
}
}
| 27.675182 | 78 | 0.676909 |
f401c768cdae73055dd08ec385b7e35c18a2cf0a | 998 | package org.datavec.api.util.files;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Lightweight utilities for converting files to URI.
*
* @author Justin Long (crockpotveggies)
*/
public class URIUtil {
public static URI fileToURI(File f) {
try {
// manually construct URI (this is faster)
String sp = slashify(f.getAbsoluteFile().getPath(), false);
if (!sp.startsWith("//"))
sp = "//" + sp;
return new URI("file", null, sp, null);
} catch (URISyntaxException x) {
throw new Error(x); // Can't happen
}
}
private static String slashify(String path, boolean isDirectory) {
String p = path;
if (File.separatorChar != '/')
p = p.replace(File.separatorChar, '/');
if (!p.startsWith("/"))
p = "/" + p;
if (!p.endsWith("/") && isDirectory)
p = p + "/";
return p;
}
}
| 26.263158 | 71 | 0.542084 |
fed2b21f8f6da82ef182a3e72041af8fea97f127 | 2,474 | package no.nav.aura.basta;
import no.nav.aura.basta.backend.fasit.payload.PlatformType;
import no.nav.aura.basta.domain.input.vm.Converters;
import no.nav.aura.basta.domain.input.vm.NodeType;
import no.nav.aura.envconfig.client.PlatformTypeDO;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class ConvertersTest {
@Test
public void platformTypeDOFromNodeTypeAndMiddleWareType() {
assertThat(Converters.platformTypeDOFrom(NodeType.BPM_NODES), equalTo(PlatformTypeDO.BPM));
assertThat(Converters.platformTypeDOFrom(NodeType.BPM86_NODES), equalTo(PlatformTypeDO.BPM86));
assertThat(Converters.platformTypeDOFrom(NodeType.WAS_NODES), equalTo(PlatformTypeDO.WAS));
assertThat(Converters.platformTypeDOFrom(NodeType.WAS9_NODES), equalTo(PlatformTypeDO.WAS9));
assertThat(Converters.platformTypeDOFrom(NodeType.LIBERTY), equalTo(PlatformTypeDO.LIBERTY));
assertThat(Converters.platformTypeDOFrom(NodeType.JBOSS), equalTo(PlatformTypeDO.JBOSS));
assertThat(Converters.platformTypeDOFrom(NodeType.OPENAM_SERVER), equalTo(PlatformTypeDO.OPENAM_SERVER));
}
@Test(expected = IllegalArgumentException.class)
public void illeagalNodeTypeConvertion() {
Converters.platformTypeDOFrom(NodeType.UNKNOWN);
}
@Test
public void convertsFromBastaNodeTypeToFasitPlatformType() {
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.BPM_NODES), equalTo(PlatformType.BPM));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.BPM86_NODES), equalTo(PlatformType.BPM86));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.WAS_NODES), equalTo(PlatformType.WAS));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.WAS9_NODES), equalTo(PlatformType.WAS9));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.LIBERTY), equalTo(PlatformType.LIBERTY));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.JBOSS), equalTo(PlatformType.JBOSS));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.WILDFLY), equalTo(PlatformType.JBOSS));
assertThat(Converters.fasitPlatformTypeEnumFrom(NodeType.OPENAM_SERVER), equalTo(PlatformType.OPENAM_SERVER));
}
@Test(expected = IllegalArgumentException.class)
public void throwsExceptionForUnknownNodetype(){
Converters.fasitPlatformTypeEnumFrom(NodeType.UNKNOWN);
}
}
| 52.638298 | 118 | 0.788601 |
83a397561de1dd2f28bee659e6294d480ad99ffd | 477 | package tools;
import javax.swing.*;
import java.awt.*;
public class Tools {
public static JButton createButton(String text, Color color) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.setBackground(color);
button.setForeground(Color.BLACK);
button.setFont(new Font("Arial", Font.BOLD, 25));
button.setPreferredSize(new Dimension(200, 80));
return button;
}
}
| 23.85 | 66 | 0.666667 |
fb0e28ee27a17e1fac3f88860b95a7f039a1345e | 12,446 | /*
* Copyright (c) 2002-2012 Alibaba Group Holding Limited.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.citrus.service.mail.session;
import static com.alibaba.citrus.test.TestUtil.*;
import static com.alibaba.citrus.util.CollectionUtil.*;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Store;
import javax.mail.internet.AddressException;
import com.alibaba.citrus.service.mail.MailException;
import com.alibaba.citrus.service.mail.MailService;
import com.alibaba.citrus.service.mail.mock.MyMockStore;
import com.alibaba.citrus.service.mail.support.DefaultMailStoreHandler;
import org.junit.Test;
import org.jvnet.mock_javamail.Mailbox;
public class MailStoreTests extends AbstractMailSessionTests<MailStore> {
@Test
public void config_stores() {
// normal store
MailStore store = mailService.getMailStore("mystore");
assertSame(mailService, store.getMailService());
assertFalse(store.isDebug());
assertFalse(store.isDefault()); // default flag is not copied
assertEquals("myhost", store.getHost());
assertEquals(110, store.getPort());
assertEquals("myname", store.getUser());
assertEquals("mypass", store.getPassword());
assertEquals("pop3", store.getProtocol());
assertEquals("INBOX2", store.getFolder());
assertEquals(1, store.getSessionProperties().size());
assertEquals("30000", store.getSessionProperties().get("mail.pop3.connectiontimeout"));
// default store
store = mailService.getMailStore();
assertDefaultStore(store);
store = mailService.getMailStore("mystore_default");
assertDefaultStore(store);
}
private void assertDefaultStore(MailStore store) {
assertSame(mailService, store.getMailService());
assertTrue(store.isDebug());
assertFalse(store.isDefault()); // default flag is not copied
assertEquals("alibaba.com", store.getHost());
assertEquals(-1, store.getPort());
assertEquals("aliren", store.getUser());
assertEquals(null, store.getPassword());
assertEquals("pop3", store.getProtocol());
assertEquals("INBOX", store.getFolder());
assertEquals(1, store.getSessionProperties().size());
assertEquals("true", store.getSessionProperties().get("mail.debug"));
}
@Test
public void setHandler() throws Exception {
// add handler1
MyHandler handler1 = new MyHandler();
session.setHandler(handler1);
assertSame(handler1, session.getHandler());
// add null - no effect
session.setHandler(null);
assertSame(handler1, session.getHandler());
// re-add handler1
session.setHandler(handler1);
assertSame(handler1, session.getHandler());
// add handler2
MyHandler handler2 = new MyHandler();
session.setHandler(handler2);
assertSame(handler2, session.getHandler());
}
@Test
public void connectAndClose() {
session.setProtocol("unknown");
// unknown protocol
try {
session.connect();
fail();
} catch (MailException e) {
assertThat(e, exception(NoSuchProviderException.class, "Could not find a provider of unknown protocol"));
}
// connect error
MyMockStore.setError(true);
session.setProtocol("pop3");
try {
session.connect();
fail();
} catch (MailException e) {
assertThat(e, exception(MessagingException.class, "Could not connect to the store"));
} finally {
MyMockStore.setError(false);
}
// close error: ignored
session.connect();
assertTrue(session.isConnected());
MyMockStore.setError(true);
try {
session.close();
} finally {
MyMockStore.setError(false);
}
}
@Test
public void receive() throws Exception {
addMail("hello");
session.setDebug(true);
session.setUser(ALIREN);
session.setHost(ALIBABA_COM);
// no handler
assertFalse(session.isConnected());
session.receive();
assertFalse(session.isConnected());
assertEquals(1, Mailbox.get(ALIREN_ALIBABA_COM).size());
// with handler - delete all
MyHandler handler = new MyHandler();
assertFalse(session.isConnected());
session.receive(handler);
assertFalse(session.isConnected());
assertEquals(0, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(1, handler.messageCount);
assertEquals(1, handler.msgs.size());
assertEquals("hello", handler.msgs.get(0).getSubject());
// with handler - delete partially
handler = new MyHandler(2, true);
addMail("111");
addMail("222");
addMail("333");
addMail("444");
assertFalse(session.isConnected());
session.receive(handler);
assertFalse(session.isConnected());
assertEquals(2, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(4, handler.messageCount);
assertEquals(2, handler.msgs.size());
assertEquals("111", handler.msgs.get(0).getSubject());
assertEquals("222", handler.msgs.get(1).getSubject());
// with handler - read all, do not delete
handler = new MyHandler(-1, false);
assertFalse(session.isConnected());
session.receive(handler);
assertFalse(session.isConnected());
assertEquals(2, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(2, handler.messageCount);
assertEquals(2, handler.msgs.size());
assertEquals("333", handler.msgs.get(0).getSubject());
assertEquals("444", handler.msgs.get(1).getSubject());
// connection failure
setError(ALIREN_ALIBABA_COM, true);
assertFalse(session.isConnected());
try {
session.receive();
fail();
} catch (MailException e) {
assertThat(e, exception(MessagingException.class, "Could not connect to the store"));
} finally {
setError(ALIREN_ALIBABA_COM, false);
}
assertFalse(session.isConnected());
// receive failure
assertFalse(session.isConnected());
handler = new MyHandler(-1, false) {
@Override
public void prepareConnection(Store store) throws MailException, MessagingException {
MyMockStore.setError(true);
}
};
try {
session.receive(handler);
fail();
} catch (MailException e) {
assertThat(e, exception(MessagingException.class, "Could not receive messages"));
} finally {
MyMockStore.setError(false);
}
assertFalse(session.isConnected());
}
@Test
public void receive_config() throws Exception {
session = mailService.getMailStore();
addMail("hello");
MyHandler handler = new MyHandler();
assertFalse(session.isConnected());
session.receive(handler);
assertFalse(session.isConnected());
assertEquals(0, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(1, handler.messageCount);
assertEquals(1, handler.msgs.size());
assertEquals("hello", handler.msgs.get(0).getSubject());
}
@Test
public void receive_batch_config() throws Exception {
session = mailService.getMailStore();
addMail("111");
addMail("222");
addMail("333");
MyHandler handler = new MyHandler(1, true); // 每次收一封信
try {
assertFalse(session.isConnected());
session.connect();
assertTrue(session.isConnected());
// 111
session.receive(handler);
assertTrue(session.isConnected());
assertEquals(2, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(3, handler.messageCount);
assertEquals(1, handler.msgs.size());
assertEquals("111", handler.msgs.remove(0).getSubject());
// 222
session.receive(handler);
assertTrue(session.isConnected());
assertEquals(1, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(2, handler.messageCount);
assertEquals(1, handler.msgs.size());
assertEquals("222", handler.msgs.remove(0).getSubject());
// 333
session.receive(handler);
assertTrue(session.isConnected());
assertEquals(0, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(1, handler.messageCount);
assertEquals(1, handler.msgs.size());
assertEquals("333", handler.msgs.remove(0).getSubject());
// no mail
session.receive(handler);
assertTrue(session.isConnected());
assertEquals(0, Mailbox.get(ALIREN_ALIBABA_COM).size());
assertEquals(0, handler.messageCount);
assertEquals(0, handler.msgs.size());
} finally {
session.close();
assertFalse(session.isConnected());
}
}
private void addMail(String text) throws AddressException {
Mailbox.get(ALIREN_ALIBABA_COM).add(createMessage(text, ALIREN_ALIBABA_COM));
}
@Override
protected void assertCopy(MailStore copy, Properties propsCopy) {
assertEquals("protocol", copy.getProtocol());
assertEquals("folder", copy.getFolder());
}
@Override
protected void assertToString(String str) {
assertThat(str, containsRegex("MailStore \\{"));
assertThat(str, containsRegex("folder\\s+= folder"));
assertThat(str, containsRegex("protocol\\s+= protocol"));
}
@Override
protected void prepareForSubclass(MailStore session) {
session.setProtocol("protocol");
session.setFolder("folder");
}
@Override
protected MailStore createMailSession(MailService service) {
MailStore store = new MailStore();
store.setMailService(service);
return store;
}
@Override
protected MailStore copyMailSession(MailStore session, Properties overrideProps) {
return new MailStore(session, overrideProps);
}
public static class MyHandler extends DefaultMailStoreHandler {
private final List<Message> msgs = createArrayList();
private int messageCount;
private final int receiveMax;
private final boolean delete;
private MyHandler() {
this(-1, true);
}
private MyHandler(int receiveMax, boolean delete) {
this.receiveMax = receiveMax;
this.delete = delete;
}
@Override
public int getMessageCount(int messageCount) throws MailException {
this.messageCount = messageCount;
if (receiveMax == -1) {
return messageCount;
} else {
return receiveMax;
}
}
@Override
public boolean processMessage(Message message) throws MailException, MessagingException {
msgs.add(message);
return delete;
}
}
}
| 33.820652 | 118 | 0.604853 |
10f33d2fbd6d1e74c3c0f8776b095bd0aaf47430 | 12,855 | /*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree.
*/
package org.fcrepo.kernel.impl.services;
import org.apache.jena.rdf.model.Model;
import org.fcrepo.kernel.api.RdfStream;
import org.fcrepo.kernel.api.Transaction;
import org.fcrepo.kernel.api.exception.CannotCreateResourceException;
import org.fcrepo.kernel.api.exception.InteractionModelViolationException;
import org.fcrepo.kernel.api.exception.ItemNotFoundException;
import org.fcrepo.kernel.api.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.api.identifiers.FedoraId;
import org.fcrepo.kernel.api.models.ExternalContent;
import org.fcrepo.kernel.api.models.ResourceHeaders;
import org.fcrepo.kernel.api.operations.CreateNonRdfSourceOperationBuilder;
import org.fcrepo.kernel.api.operations.NonRdfSourceOperationFactory;
import org.fcrepo.kernel.api.operations.RdfSourceOperation;
import org.fcrepo.kernel.api.operations.RdfSourceOperationFactory;
import org.fcrepo.kernel.api.operations.ResourceOperation;
import org.fcrepo.kernel.api.services.CreateResourceService;
import org.fcrepo.persistence.api.PersistentStorageSession;
import org.fcrepo.persistence.api.PersistentStorageSessionManager;
import org.fcrepo.persistence.api.exceptions.PersistentItemNotFoundException;
import org.fcrepo.persistence.api.exceptions.PersistentStorageException;
import org.fcrepo.persistence.common.MultiDigestInputStreamWrapper;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.core.Link;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static org.fcrepo.kernel.api.RdfLexicon.ARCHIVAL_GROUP;
import static org.fcrepo.kernel.api.RdfLexicon.FEDORA_NON_RDF_SOURCE_DESCRIPTION_URI;
import static org.fcrepo.kernel.api.RdfLexicon.FEDORA_PAIR_TREE;
import static org.fcrepo.kernel.api.RdfLexicon.NON_RDF_SOURCE;
import static org.fcrepo.kernel.api.rdf.DefaultRdfStream.fromModel;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.util.CollectionUtils.isEmpty;
/**
* Create a RdfSource resource.
* @author whikloj
* TODO: bbpennel has thoughts about moving this to HTTP layer.
*/
@Component
public class CreateResourceServiceImpl extends AbstractService implements CreateResourceService {
private static final Logger LOGGER = getLogger(CreateResourceServiceImpl.class);
@Inject
private PersistentStorageSessionManager psManager;
@Inject
private RdfSourceOperationFactory rdfSourceOperationFactory;
@Inject
private NonRdfSourceOperationFactory nonRdfSourceOperationFactory;
@Override
public void perform(final Transaction tx, final String userPrincipal, final FedoraId fedoraId,
final String contentType, final String filename,
final long contentSize, final List<String> linkHeaders, final Collection<URI> digest,
final InputStream requestBody, final ExternalContent externalContent) {
final PersistentStorageSession pSession = this.psManager.getSession(tx);
checkAclLinkHeader(linkHeaders);
// Locate a containment parent of fedoraId, if exists.
final FedoraId parentId = containmentIndex.getContainerIdByPath(tx, fedoraId, true);
checkParent(pSession, parentId);
final CreateNonRdfSourceOperationBuilder builder;
String mimeType = contentType;
long size = contentSize;
if (externalContent == null || externalContent.isCopy()) {
var contentInputStream = requestBody;
if (externalContent != null) {
LOGGER.debug("External content COPY '{}', '{}'", fedoraId, externalContent.getURL());
contentInputStream = externalContent.fetchExternalContent();
}
builder = nonRdfSourceOperationFactory.createInternalBinaryBuilder(tx, fedoraId, contentInputStream);
} else {
builder = nonRdfSourceOperationFactory.createExternalBinaryBuilder(tx, fedoraId,
externalContent.getHandling(), externalContent.getURI());
if (contentSize == -1L) {
size = externalContent.getContentSize();
}
if (!digest.isEmpty()) {
final var multiDigestWrapper = new MultiDigestInputStreamWrapper(
externalContent.fetchExternalContent(),
digest,
Collections.emptyList());
multiDigestWrapper.checkFixity();
}
}
if (externalContent != null && externalContent.getContentType() != null) {
mimeType = externalContent.getContentType();
}
final ResourceOperation createOp = builder
.parentId(parentId)
.userPrincipal(userPrincipal)
.contentDigests(digest)
.mimeType(mimeType)
.contentSize(size)
.filename(filename)
.build();
lockArchivalGroupResourceFromParent(tx, pSession, parentId);
tx.lockResource(fedoraId);
try {
pSession.persist(createOp);
} catch (final PersistentStorageException exc) {
throw new RepositoryRuntimeException(String.format("failed to create resource %s", fedoraId), exc);
}
// Populate the description for the new binary
createDescription(tx, pSession, userPrincipal, fedoraId);
addToContainmentIndex(tx, parentId, fedoraId);
membershipService.resourceCreated(tx, fedoraId);
addToSearchIndex(tx, fedoraId, pSession);
recordEvent(tx, fedoraId, createOp);
}
private void createDescription(final Transaction tx,
final PersistentStorageSession pSession,
final String userPrincipal,
final FedoraId binaryId) {
final var descId = binaryId.asDescription();
final var createOp = rdfSourceOperationFactory.createBuilder(
tx,
descId,
FEDORA_NON_RDF_SOURCE_DESCRIPTION_URI,
fedoraPropsConfig.getServerManagedPropsMode()
).userPrincipal(userPrincipal)
.parentId(binaryId)
.build();
tx.lockResource(descId);
try {
pSession.persist(createOp);
userTypesCache.cacheUserTypes(descId, Collections.emptyList(), pSession.getId());
} catch (final PersistentStorageException exc) {
throw new RepositoryRuntimeException(String.format("failed to create description %s", descId), exc);
}
}
@Override
public void perform(final Transaction tx, final String userPrincipal, final FedoraId fedoraId,
final List<String> linkHeaders, final Model model) {
final PersistentStorageSession pSession = this.psManager.getSession(tx);
checkAclLinkHeader(linkHeaders);
// Locate a containment parent of fedoraId, if exists.
final FedoraId parentId = containmentIndex.getContainerIdByPath(tx, fedoraId, true);
checkParent(pSession, parentId);
final List<String> rdfTypes = isEmpty(linkHeaders) ? emptyList() : getTypes(linkHeaders);
final String interactionModel = determineInteractionModel(rdfTypes, true,
model != null, false);
final RdfStream stream = fromModel(model.getResource(fedoraId.getFullId()).asNode(), model);
ensureValidDirectContainer(fedoraId, interactionModel, model);
final RdfSourceOperation createOp = rdfSourceOperationFactory
.createBuilder(tx, fedoraId, interactionModel, fedoraPropsConfig.getServerManagedPropsMode())
.parentId(parentId)
.triples(stream)
.relaxedProperties(model)
.archivalGroup(rdfTypes.contains(ARCHIVAL_GROUP.getURI()))
.userPrincipal(userPrincipal)
.build();
lockArchivalGroupResourceFromParent(tx, pSession, parentId);
tx.lockResource(fedoraId);
try {
pSession.persist(createOp);
} catch (final PersistentStorageException exc) {
throw new RepositoryRuntimeException(String.format("failed to create resource %s", fedoraId), exc);
}
userTypesCache.cacheUserTypes(fedoraId,
fromModel(model.getResource(fedoraId.getFullId()).asNode(), model), pSession.getId());
updateReferences(tx, fedoraId, userPrincipal, model);
addToContainmentIndex(tx, parentId, fedoraId);
membershipService.resourceCreated(tx, fedoraId);
addToSearchIndex(tx, fedoraId, pSession);
recordEvent(tx, fedoraId, createOp);
}
private void addToSearchIndex(final Transaction tx, final FedoraId fedoraId,
final PersistentStorageSession persistentStorageSession) {
final var resourceHeaders = persistentStorageSession.getHeaders(fedoraId, null);
this.searchIndex.addUpdateIndex(tx, resourceHeaders);
}
/**
* Check the parent to contain the new resource exists and can have a child.
*
* @param pSession a persistence session.
* @param fedoraId Id of parent.
*/
private void checkParent(final PersistentStorageSession pSession, final FedoraId fedoraId)
throws RepositoryRuntimeException {
if (fedoraId != null && !fedoraId.isRepositoryRoot()) {
final ResourceHeaders parent;
try {
// Make sure the parent exists.
// TODO: object existence can be from the index, but we don't have interaction model. Should we add it?
parent = pSession.getHeaders(fedoraId.asResourceId(), null);
} catch (final PersistentItemNotFoundException exc) {
throw new ItemNotFoundException(String.format("Item %s was not found", fedoraId), exc);
} catch (final PersistentStorageException exc) {
throw new RepositoryRuntimeException(String.format("Failed to find storage headers for %s", fedoraId),
exc);
}
if (parent.isDeleted()) {
throw new CannotCreateResourceException(
String.format("Cannot create resource as child of a tombstone. Tombstone found at %s",
fedoraId.getFullIdPath()));
}
final boolean isParentBinary = NON_RDF_SOURCE.toString().equals(parent.getInteractionModel());
if (isParentBinary) {
// Binary is not a container, can't have children.
throw new InteractionModelViolationException("NonRdfSource resources cannot contain other resources");
}
// TODO: Will this type still be needed?
final boolean isPairTree = FEDORA_PAIR_TREE.toString().equals(parent.getInteractionModel());
if (isPairTree) {
throw new CannotCreateResourceException("Objects cannot be created under pairtree nodes");
}
}
}
/**
* Get the rel="type" link headers from a list of them.
* @param headers a list of string LINK headers.
* @return a list of LINK headers with rel="type"
*/
private List<String> getTypes(final List<String> headers) {
final List<Link> hdrobjs = getLinkHeaders(headers);
try {
return hdrobjs == null ? emptyList() : hdrobjs.stream()
.filter(p -> p.getRel().equalsIgnoreCase("type")).map(Link::getUri)
.map(URI::toString).collect(Collectors.toList());
} catch (final Exception e ) {
throw new BadRequestException("Invalid Link header type found",e);
}
}
/**
* Converts a list of string LINK headers to actual LINK objects.
* @param headers the list of string link headers.
* @return the list of LINK headers.
*/
private List<Link> getLinkHeaders(final List<String> headers) {
return headers == null ? null : headers.stream().map(Link::valueOf).collect(Collectors.toList());
}
/**
* Add this pairing to the containment index.
* @param tx The transaction.
* @param parentId The parent ID.
* @param id The child ID.
*/
private void addToContainmentIndex(final Transaction tx, final FedoraId parentId, final FedoraId id) {
containmentIndex.addContainedBy(tx, parentId, id);
}
}
| 44.635417 | 119 | 0.674057 |
1bca5d514e8ae3300ad0185e0eddf634b2f13986 | 10,097 | //package cn.elwy.eplus.framework.security;
//
//import java.util.LinkedHashMap;
//import java.util.Map;
//
//import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
//import org.apache.shiro.cache.ehcache.EhCacheManager;
//import org.apache.shiro.codec.Base64;
//import org.apache.shiro.realm.AuthorizingRealm;
//import org.apache.shiro.spring.LifecycleBeanPostProcessor;
//import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
//import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
//import org.apache.shiro.web.mgt.CookieRememberMeManager;
//import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
//import org.apache.shiro.web.servlet.Cookie;
//import org.apache.shiro.web.servlet.ShiroHttpSession;
//import org.apache.shiro.web.servlet.SimpleCookie;
//import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
//import org.apache.shiro.web.session.mgt.ServletContainerSessionManager;
//import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import cn.elwy.eplus.framework.security.shiro.CustomCredentialsMatcher;
//import cn.elwy.eplus.framework.security.shiro.MySessionManager;
//import cn.elwy.eplus.framework.security.shiro.ShiroRealm;
//
///**
// * Shiro的配置类
// * @author huangsq
// * @version 1.0, 2018-02-19
// */
//@Configuration
//@ConfigurationProperties(prefix = "shiro")
//public class ShiroConfiguration {
//
// private String loginUrl;
// private String successUrl;
// private String unauthorizedUrl;
// private String cacheConfig;
// private String hashAlgorithm = "SHA-256";
// private int hashIterations = 1024;
// private boolean storedCredentialsHexEncoded = true;
//
// private Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
//
// @Bean(name = "securityManager")
// public DefaultWebSecurityManager getDefaultWebSecurityManager(AuthorizingRealm shiroRealm) {
// DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
// dwsm.setRealm(shiroRealm);
// // dwsm.setCacheManager(ehCacheManager);
// return dwsm;
// }
//
// /**
// * spring session管理器(多机环境)
// */
// @Bean
// @ConditionalOnProperty(prefix = "eplus", name = "spring-session-open", havingValue = "true")
// public ServletContainerSessionManager servletContainerSessionManager() {
// return new ServletContainerSessionManager();
// }
//
// /**
// * session管理器(单机环境)
// */
// @Bean(name = "sessionManager")
// @ConditionalOnProperty(prefix = "eplus", name = "spring-session-open", havingValue = "false")
// public DefaultWebSessionManager defaultWebSessionManager() {
// DefaultWebSessionManager sessionManager = new MySessionManager();
//
// // // 用户信息必须是序列化格式,要不创建用户信息创建不过去,此坑很大,
// // sessionManager.setSessionDAO(redisSessionDAO());// 如不想使用REDIS可注释此行
// // Collection<SessionListener> sessionListeners = new ArrayList<>();
// // sessionListeners.add(customSessionListener());
// // sessionManager.setSessionListeners(sessionListeners);
//
// // sessionManager.setCacheManager(cacheShiroManager);
// // 单位为毫秒(1秒=1000毫秒) 3600000毫秒为1个小时
// sessionManager.setSessionValidationInterval(3600000 * 12);
// // 3600000 milliseconds = 1 hour
// sessionManager.setGlobalSessionTimeout(3600000 * 12);
// // 是否删除无效的,默认也是开启
// sessionManager.setDeleteInvalidSessions(true);
// // 是否开启 检测,默认开启
// sessionManager.setSessionValidationSchedulerEnabled(true);
// // 创建会话Cookie
// Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
// cookie.setName("shiroCookie");
// // cookie.setName("WEBID");
// cookie.setHttpOnly(true);
//
// sessionManager.setSessionIdCookie(cookie);
// return sessionManager;
// }
//
// @Bean(name = "shiroRealm")
// public AuthorizingRealm getShiroRealm() {
// AuthorizingRealm shiroRealm = new ShiroRealm();
// shiroRealm.setCredentialsMatcher(getCredentialsMatcher());
// return shiroRealm;
// }
//
// @Bean(name = "shiroEhcacheManager")
// public EhCacheManager getEhCacheManager() {
// EhCacheManager em = new EhCacheManager();
// em.setCacheManagerConfigFile(cacheConfig);
// return em;
// }
//
// /**
// * Shiro的过滤器链
// */
// @Bean(name = "shiroFilter")
// public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
// ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// shiroFilterFactoryBean.setSecurityManager(securityManager);
// shiroFilterFactoryBean.setLoginUrl(loginUrl);
// shiroFilterFactoryBean.setSuccessUrl(successUrl);
// shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
// return shiroFilterFactoryBean;
// }
//
// /*-*
// * 在方法中 注入 securityManager,进行代理控制
//
// @Bean
// public MethodInvokingFactoryBean methodInvokingFactoryBean(DefaultWebSecurityManager securityManager) {
// MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean();
// bean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
// bean.setArguments(new Object[] { securityManager });
// return bean;
// }
// */
// /**
// * Shiro生命周期处理器: 用于在实现了Initializable接口的Shiro
// * bean初始化时调用Initializable接口会调(例如:UserRealm) 在实现了Destroyable接口的Shiro bean销毁时调用
// * Destroyable接口回调(例如:DefaultSecurityManager)
// */
// /**
// * LifecycleBeanPostProcessor,这是个DestructionAwareBeanPostProcessor的子类,
// * 负责org.apache.shiro.util.Initializable类型bean的生命周期的,初始化和销毁。
// * 主要是AuthorizingRealm类的子类,以及EhCacheManager类。
// */
// @Bean(name = "lifecycleBeanPostProcessor")
// public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
// return new LifecycleBeanPostProcessor();
// }
//
// /**
// * DefaultAdvisorAutoProxyCreator,Spring的一个bean,由Advisor决定对哪些类的方法进行AOP代理。
// */
// @Bean
// public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
// DefaultAdvisorAutoProxyCreator daapc = new DefaultAdvisorAutoProxyCreator();
// daapc.setProxyTargetClass(true);
// return daapc;
// }
//
// /**
// * 启用shrio授权注解拦截方式,AOP式方法级权限检查
// * AuthorizationAttributeSourceAdvisor,shiro里实现的Advisor类,
// * 内部使用AopAllianceAnnotationsAuthorizingMethodInterceptor来拦截用以下注解的方法。
// */
// @Bean
// public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
// DefaultWebSecurityManager securityManager) {
// AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
// authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
// return authorizationAttributeSourceAdvisor;
// }
//
// /**
// * HashedCredentialsMatcher,这个类是为了对密码进行编码的, 防止密码在数据库里明码保存,当然在登陆认证的时候,
// * 这个类也负责对form里输入的密码进行编码。
// */
// @Bean(name = "credentialsMatcher")
// public HashedCredentialsMatcher getCredentialsMatcher() {
// HashedCredentialsMatcher credentialsMatcher = new CustomCredentialsMatcher();
// credentialsMatcher.setHashAlgorithmName(hashAlgorithm);
// credentialsMatcher.setHashIterations(hashIterations);
// credentialsMatcher.setStoredCredentialsHexEncoded(storedCredentialsHexEncoded);
// return credentialsMatcher;
// }
//
// /**
// * rememberMe管理器, cipherKey生成见{@code Base64Test.java}
// */
// @Bean
// public CookieRememberMeManager rememberMeManager(SimpleCookie rememberMeCookie) {
// CookieRememberMeManager manager = new CookieRememberMeManager();
// manager.setCipherKey(Base64.decode("Z3VucwAAAAAAAAAAAAAAAA=="));
// manager.setCookie(rememberMeCookie);
// return manager;
// }
//
// /**
// * 记住密码Cookie
// */
// @Bean
// public SimpleCookie rememberMeCookie() {
// SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
// simpleCookie.setHttpOnly(true);
// simpleCookie.setMaxAge(7 * 24 * 60 * 60);// 7天
// return simpleCookie;
// }
//
// // /**
// // * EhCacheManager,缓存管理,用户登陆成功后,把用户信息和权限信息缓存起来,
// // * 然后每次用户请求时,放入用户的session中,如果不设置这个bean,每个请求都会查询一次数据库。
// // */
// // @Bean(name = "ehCacheManager")
// // @DependsOn("lifecycleBeanPostProcessor")
// // public EhCacheManager ehCacheManager() {
// // return new EhCacheManager();
// // }
//
// public String getLoginUrl() {
// return loginUrl;
// }
//
// public void setLoginUrl(String loginUrl) {
// this.loginUrl = loginUrl;
// }
//
// public String getSuccessUrl() {
// return successUrl;
// }
//
// public void setSuccessUrl(String successUrl) {
// this.successUrl = successUrl;
// }
//
// public String getUnauthorizedUrl() {
// return unauthorizedUrl;
// }
//
// public void setUnauthorizedUrl(String unauthorizedUrl) {
// this.unauthorizedUrl = unauthorizedUrl;
// }
//
// public String getCacheConfig() {
// return cacheConfig;
// }
//
// public void setCacheConfig(String cacheConfig) {
// this.cacheConfig = cacheConfig;
// }
//
// public String getHashAlgorithm() {
// return hashAlgorithm;
// }
//
// public void setHashAlgorithm(String hashAlgorithm) {
// this.hashAlgorithm = hashAlgorithm;
// }
//
// public int getHashIterations() {
// return hashIterations;
// }
//
// public void setHashIterations(int hashIterations) {
// this.hashIterations = hashIterations;
// }
//
// public boolean isStoredCredentialsHexEncoded() {
// return storedCredentialsHexEncoded;
// }
//
// public void setStoredCredentialsHexEncoded(boolean storedCredentialsHexEncoded) {
// this.storedCredentialsHexEncoded = storedCredentialsHexEncoded;
// }
//
// public Map<String, String> getFilterChainDefinitionMap() {
// return filterChainDefinitionMap;
// }
//
// public void setFilterChainDefinitionMap(Map<String, String> filterChainDefinitionMap) {
// this.filterChainDefinitionMap = filterChainDefinitionMap;
// }
//
//}
| 35.42807 | 121 | 0.733683 |
e89f1aa89aacdd7e389cc06365dc26880ac84ffe | 2,042 | /*
* 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.exadel.aem.toolkit.core.maven;
import com.exadel.aem.toolkit.api.runtime.ExceptionHandler;
import com.exadel.aem.toolkit.core.exceptions.PluginException;
import com.exadel.aem.toolkit.core.util.PluginReflectionUtility;
import com.exadel.aem.toolkit.core.util.PluginXmlUtility;
/**
* The fallback implementation of {@link PluginRuntimeContext} for the AEM Authoring Toolkit plugin instance that
* has not been properly and completely initialized
*/
class EmptyRuntimeContext implements PluginRuntimeContext {
private static final String NOT_INITIALIZED_EXCEPTION_MESSAGE = "Plugin was not properly initialized";
/**
* Throws a {@code PluginException} upon call, since no {@code PluginReflectionUtility} instance has been initialized
*/
@Override
public PluginReflectionUtility getReflectionUtility() {
throw new PluginException(NOT_INITIALIZED_EXCEPTION_MESSAGE);
}
/**
* Throws a {@code PluginException} upon call, since no {@code PluginReflectionUtility} instance has been initialized
*/
@Override
public ExceptionHandler getExceptionHandler() {
throw new PluginException(NOT_INITIALIZED_EXCEPTION_MESSAGE);
}
/**
* Throws a {@code PluginException} upon call, since no {@code PluginReflectionUtility} instance has been initialized
*/
@Override
public PluginXmlUtility getXmlUtility() {
throw new PluginException(NOT_INITIALIZED_EXCEPTION_MESSAGE);
}
}
| 38.528302 | 121 | 0.753183 |
65a25948372438dc40a42a564cba38f73b4f3bcf | 581 | package com.seu.blog.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.seu.blog.entity.CategoryEntity;
import com.seu.blog.vo.CategoryVo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 文章类别表
*
* @author qinnnn
* @date 2018-09-04 15:00:55
*/
@Mapper
public interface CategoryDao extends BaseMapper<CategoryEntity> {
/**
* 文章分类详情
*
* @return
*/
List<CategoryVo> queryCategoryDetails();
/**
* 单条文章分类详情
*
* @return
*/
CategoryVo queryOneCategoryDetail(Integer categoryId);
}
| 17.606061 | 65 | 0.672978 |
35b25b0d65721fedb99d186078edb2a3a32f56ad | 3,068 | /*******************************************************************************
* Copyright (c) 1998, 2015 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 impl
******************************************************************************/
package org.eclipse.persistence.sessions.serializers;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.eclipse.persistence.sessions.Session;
/**
* Uses JAXB to convert an object to XML.
* @author James Sutherland
*/
public class XMLSerializer extends AbstractSerializer {
JAXBContext context;
public XMLSerializer() {
}
public XMLSerializer(String packageName) {
try {
this.context = JAXBContext.newInstance(packageName);
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
public XMLSerializer(JAXBContext context) {
this.context = context;
}
@Override
public void initialize(Class serializeClass, String serializePackage, Session session) {
if (this.context == null) {
if (serializePackage == null) {
serializePackage = serializeClass.getPackage().getName();
}
try {
this.context = JAXBContext.newInstance(serializePackage, serializeClass.getClassLoader());
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
}
public Object serialize(Object object, Session session) {
try {
Marshaller marshaller = this.context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(object, writer);
return writer.toString();
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
public Object deserialize(Object xml, Session session) {
try {
Unmarshaller unmarshaller = this.context.createUnmarshaller();
StringReader reader = new StringReader((String)xml);
return unmarshaller.unmarshal(reader);
} catch (JAXBException exception) {
throw new RuntimeException(exception);
}
}
@Override
public Class getType() {
return String.class;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| 32.989247 | 106 | 0.625489 |
14fbf6d0e037651bcd21c32eab08a25d25befe59 | 2,083 | package net.trustyuri;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Reads and checks content from local files or URLs.
*
* @author Tobias Kuhn
*/
public class CheckFile {
/**
* Reads and checks the content of one or several URLs (in the form of trusty URIs) or local
* files (in the form of trusty file names).
*
* @param args a list of URLs or file names
*/
public static void main(String[] args) throws IOException, TrustyUriException {
for (String arg : args) {
check(arg);
}
}
/**
* Check the content of a trusty URI (fetched from the web) or a trusty file (read from the
* file system).
*
* @param fileOrUrl the file name or URL
*/
public static void check(String fileOrUrl) throws IOException, TrustyUriException {
CheckFile c;
try {
URL url = new URL(fileOrUrl);
c = new CheckFile(url);
} catch (MalformedURLException ex) {
c = new CheckFile(new File(fileOrUrl));
}
boolean valid = c.check();
if (valid) {
System.out.println("Correct hash: " + c.r.getArtifactCode());
//System.out.println("ni URI: " + TrustyUriUtils.getNiUri(fileName));
} else {
System.out.println("*** INCORRECT HASH ***");
}
}
private TrustyUriResource r;
/**
* Creates a new object to check the content to be fetch from a URL.
*
* @param url the URL
*/
public CheckFile(URL url) throws IOException {
r = new TrustyUriResource(url);
}
/**
* Creates a new object to check the content to be read from a local file.
*
* @param file
*/
public CheckFile(File file) throws IOException {
r = new TrustyUriResource(file);
}
/**
* Checks whether the content matches the hash of the trusty URI.
*
* @return true if the content matches the hash
*/
public boolean check() throws IOException, TrustyUriException {
TrustyUriModule module = ModuleDirectory.getModule(r.getModuleId());
if (module == null) {
throw new TrustyUriException("ERROR: Not a trusty URI or unknown module");
}
return module.hasCorrectHash(r);
}
}
| 24.505882 | 93 | 0.682669 |
cfe43afb747343b63ed13e4068d4067e73c5a486 | 17,287 | package io.mongock.driver.core.lock;
import io.mongock.driver.api.lock.LockCheckException;
import io.mongock.driver.api.lock.LockManager;
import io.mongock.utils.TimeService;
import io.mongock.utils.annotation.NotThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;
/**
* <p>This class is responsible of managing the lock at high level. It provides 3 main methods which are
* for acquiring, ensuring(doesn't acquires the lock, just refresh the expiration time if required) and
* releasing the lock.</p>
*
* <p>Note that this class is not threadSafe and it's not intended to be used by multiple executors. Each of them
* should acquire a new lock(different key).</p>
*
* <p>life cycle:
* - acquire
* - ensure x N
* - release
* </p>
**/
@NotThreadSafe
public class LockManagerDefault extends Thread implements LockManager {
//static constants
private static final Logger logger = LoggerFactory.getLogger(LockManagerDefault.class);
private static final String GOING_TO_SLEEP_MSG = "Mongock is going to sleep to wait for the lock: {} ms({} minutes)";
private static final String EXPIRATION_ARG_ERROR_MSG = "Lock expiration period must be greater than %d ms";
private static final String MAX_TRIES_ERROR_TEMPLATE = "Quit trying lock after %s millis due to LockPersistenceException: \n\tcurrent lock: %s\n\tnew lock: %s\n\tacquireLockQuery: %s\n\tdb error detail: %s";
private static final String LOCK_HELD_BY_OTHER_PROCESS = "Lock held by other process. Cannot ensure lock.\n\tcurrent lock: %s\n\tnew lock: %s\n\tacquireLockQuery: %s\n\tdb error detail: %s";
private static final long MIN_LOCK_ACQUIRED_FOR_MILLIS = 3 * 1000L;// 3 seconds
private static final long DEFAULT_LOCK_ACQUIRED_FOR_MILLIS = 60 * 1000L;// 1 minute
private static final long DEFAULT_QUIT_TRY_AFTER_MILLIS = 3 * DEFAULT_LOCK_ACQUIRED_FOR_MILLIS;//3 times default min acquired
private static final double LOCK_REFRESH_MARGIN_PERCENTAGE = 0.33;// 30%
private static final long MIN_LOCK_REFRESH_MARGIN_MILLIS = 1000L;// 1 second
private static final long DEFAULT_LOCK_REFRESH_MARGIN_MILLIS = (long) (DEFAULT_LOCK_ACQUIRED_FOR_MILLIS * LOCK_REFRESH_MARGIN_PERCENTAGE);
private static final long MINIMUM_WAITING_TO_TRY_AGAIN = 500L;//Half a second
private static final long DEFAULT_TRY_FREQUENCY_MILLIS = 1000L;// ! second
private static final String DEFAULT_KEY = "DEFAULT_KEY";
private final boolean daemonActive;
/**
* Moment when will mandatory to acquire the lock again.
*/
private volatile Date lockExpiresAt = null;
/**
* The instant the acquisition has shouldStopTryingAt
*/
private volatile Instant shouldStopTryingAt;
/**
* flag to release the lock asap and stop ensuring the lock
*/
private volatile boolean releaseStarted = false;
/*
Used to synchronize the ensureLock in the daemon and the release process.
*/
private final Object releaseMutex = new Object();
//injections
private final LockRepository repository;
private final TimeService timeService;
/**
* Owner of the lock
*/
private final String owner;
/**
* <p>The period of time for which the lock will be owned.</p>
*/
private final long lockAcquiredForMillis;
/**
* <p>Milliseconds after which it will try to acquire the lock again<p/>
*/
private final long lockTryFrequencyMillis;
/**
* <p>The margin in which the lock should be refresh to avoid losing it</p>
*/
private final long lockRefreshMarginMillis;
/**
* <p>Maximum time it will wait for the lock in total.</p>
*/
private final long lockQuitTryingAfterMillis;
public static DefaultLockManagerBuilder builder() {
return new DefaultLockManagerBuilder();
}
/**
* @param repository lockRepository to persist the lock
* @param timeService time service
* @param lockAcquiredForMillis number of millis that the lock will be initially acquired for
* @param lockQuitTryingAfterMillis number of seconds it will try to acquire the lock with no success
* @param lockTryFrequencyMillis how often(in millis) it will try to acquire the lock
* @param lockRefreshMarginMillis margin(in millis) after which the lock need to be refreshed
* @param owner owner of the lock
*/
private LockManagerDefault(LockRepository repository,
TimeService timeService,
long lockAcquiredForMillis,
long lockQuitTryingAfterMillis,
long lockTryFrequencyMillis,
long lockRefreshMarginMillis,
String owner,
boolean daemonActive) {
this.repository = repository;
this.timeService = timeService;
this.lockAcquiredForMillis = lockAcquiredForMillis;
this.lockQuitTryingAfterMillis = lockQuitTryingAfterMillis;
this.lockTryFrequencyMillis = lockTryFrequencyMillis;
this.lockRefreshMarginMillis = lockRefreshMarginMillis;
this.owner = owner;
this.daemonActive = daemonActive;
setDaemon(true);
}
@Override
public String getDefaultKey() {
return DEFAULT_KEY;
}
@Override
public void acquireLockDefault() throws LockCheckException {
initialize();
boolean keepLooping = true;
do {
try {
logger.info("Mongock trying to acquire the lock");
Date newLockExpiresAt = timeService.currentDatePlusMillis(lockAcquiredForMillis);
repository.insertUpdate(new LockEntry(getDefaultKey(), LockStatus.LOCK_HELD.name(), owner, newLockExpiresAt));
logger.info("Mongock acquired the lock until: {}", newLockExpiresAt);
updateStatus(newLockExpiresAt);
keepLooping = false;
startThreadIfApplies();
} catch (LockPersistenceException ex) {
handleLockException(true, ex);
}
} while (keepLooping);
}
@Override
public void ensureLockDefault() throws LockCheckException {
logger.debug("Ensuring the lock");
if (releaseStarted) {
throw new LockCheckException("Lock cannot be ensured after being cancelled");
}
do {
if (needsRefreshLock()) {
logger.debug("Lock refreshing required");
try {
refreshLock();
break;
} catch (LockPersistenceException ex) {
handleLockException(false, ex);
}
} else {
logger.debug("Dont need to refresh the lock at[{}], acquired until: {}", timeService.currentTime(), lockExpiresAt);
break;
}
} while (true);
}
/*
It will to ensure the lock, until it's cancelled.
It's synchronized with the release process. Once the mutex is taken, it ensures the release process hasn't started,
and, if so, ensures the lock. Then it goes to sleep thhe time the lock is safely acquired, if the release process
hasn't started by then.
*/
@Override
public void run() {
logger.info("Starting mongock lock daemon...");
while (!releaseStarted) {
try {
logger.debug("Mongock(daemon) ensuring lock");
synchronized (releaseMutex) {
if (!releaseStarted) {
refreshLock();
}
}
} catch (LockCheckException e) {
logger.warn("Mongock(daemon)Error ensuring the lock from daemon: {}", e.getMessage());
} catch (Exception e) {
logger.warn("Mongock(daemon)Generic error from daemon: {}", e.getMessage());
}
if (!releaseStarted) {
reposeIfRequired();
}
}
logger.info("Cancelled mongock lock daemon");
}
@Override
public void releaseLockDefault() {
logger.info("Mongock releasing the lock");
//releaseStarted doesn't really need to be volatile as here is the only place is written and synchronized block ensures
//it's flushed to main memory.
releaseStarted = true;
synchronized (releaseMutex) {
try {
logger.info("Mongock releasing the lock");
repository.removeByKeyAndOwner(getDefaultKey(), this.getOwner());
lockExpiresAt = null;
shouldStopTryingAt = Instant.now();//this makes the ensureLock to fail
logger.info("Mongock released the lock");
} catch (Exception ex) {
logger.warn("Error removing the lock from database", ex);
}
}
}
@Override
public void close() {
releaseLockDefault();
}
@Override
public boolean isReleaseStarted() {
return releaseStarted;
}
@Override
public long getLockTryFrequency() {
return lockTryFrequencyMillis;
}
@Override
public String getOwner() {
return owner;
}
@Override
public boolean isLockHeld() {
return lockExpiresAt != null && timeService.currentTime().compareTo(lockExpiresAt) < 1;
}
private void refreshLock() {
logger.debug("Mongock trying to refresh the lock");
Date lockExpiresAtTemp = timeService.currentDatePlusMillis(lockAcquiredForMillis);
LockEntry lockEntry = new LockEntry(getDefaultKey(), LockStatus.LOCK_HELD.name(), owner, lockExpiresAtTemp);
repository.updateIfSameOwner(lockEntry);
updateStatus(lockExpiresAtTemp);
logger.debug("Mongock refreshed the lock until: {}", lockExpiresAtTemp);
}
private void reposeIfRequired() {
try {
long reposingTime = getDaemonTimeSleep();
logger.debug("Mongock lock daemon sleeping for {}ms", reposingTime);
sleep(reposingTime);
} catch (InterruptedException ex) {
logger.warn("Interrupted exception ignored");
}
}
private long getDaemonTimeSleep() {
logger.debug("Calculating millis for lock daemon to sleep");
long baseSleepMillis;
if (lockExpiresAt != null) {
Date nowDate = timeService.currentTime();
long millisToRefresh = lockExpiresAt.getTime() - nowDate.getTime();
logger.debug("Difference now[{}] and Lock's expiry-date[{}]: {}ms ", nowDate, lockExpiresAt.toString(), millisToRefresh);
baseSleepMillis = millisToRefresh < lockRefreshMarginMillis && millisToRefresh > 0 ? millisToRefresh : lockAcquiredForMillis;
} else {
logger.debug("Taking lockAcquireForMillis[{}ms] as base to calculate daemon's sleep time", lockAcquiredForMillis);
baseSleepMillis = lockAcquiredForMillis;
}
return new Double(baseSleepMillis * LOCK_REFRESH_MARGIN_PERCENTAGE).longValue();
}
private void handleLockException(boolean acquiringLock, LockPersistenceException ex) {
LockEntry currentLock = repository.findByKey(getDefaultKey());
if (isAcquisitionTimerOver()) {
updateStatus(null);
throw new LockCheckException(String.format(
MAX_TRIES_ERROR_TEMPLATE,
lockQuitTryingAfterMillis,
currentLock != null ? currentLock.toString() : "none",
ex.getNewLockEntity(),
ex.getAcquireLockQuery(),
ex.getDbErrorDetail()));
}
if (isLockOwnedByOtherProcess(currentLock)) {
Date currentLockExpiresAt = currentLock.getExpiresAt();
logger.warn("Lock is taken by other process until: {}", currentLockExpiresAt);
if (!acquiringLock) {
throw new LockCheckException(String.format(
LOCK_HELD_BY_OTHER_PROCESS,
currentLock,
ex.getNewLockEntity(),
ex.getAcquireLockQuery(),
ex.getDbErrorDetail()));
}
waitForLock(currentLockExpiresAt);
}
}
private boolean isLockOwnedByOtherProcess(LockEntry currentLock) {
return currentLock != null && !currentLock.isOwner(owner);
}
private void waitForLock(Date expiresAtMillis) {
Date current = timeService.currentTime();
long currentLockWillExpireInMillis = expiresAtMillis.getTime() - current.getTime();
long sleepingMillis = lockTryFrequencyMillis;
if (lockTryFrequencyMillis > currentLockWillExpireInMillis) {
logger.info("The configured time frequency[{} millis] is higher than the current lock's expiration", lockTryFrequencyMillis);
sleepingMillis = currentLockWillExpireInMillis > MINIMUM_WAITING_TO_TRY_AGAIN ? currentLockWillExpireInMillis : MINIMUM_WAITING_TO_TRY_AGAIN;
}
logger.info("Mongock will try to acquire the lock in {} mills", sleepingMillis);
try {
logger.info(GOING_TO_SLEEP_MSG, sleepingMillis, timeService.millisToMinutes(sleepingMillis));
Thread.sleep(sleepingMillis);
} catch (InterruptedException ex) {
logger.error("ERROR acquiring the lock", ex);
Thread.currentThread().interrupt();
}
}
private boolean needsRefreshLock() {
if (lockExpiresAt == null) {
return true;
}
Date currentTime = timeService.currentTime();
Date expirationWithMargin = new Date(this.lockExpiresAt.getTime() - lockRefreshMarginMillis);
return currentTime.compareTo(expirationWithMargin) >= 0;
}
private void updateStatus(Date lockExpiresAt) {
this.lockExpiresAt = lockExpiresAt;
finishAcquisitionTimer();
}
/**
* idempotent operation only called from builder that
* - Starts the acquisition timer
* - Initializes and run the lock daemon.
*/
private synchronized void initialize() {
if (releaseStarted) {
throw new LockCheckException("Lock cannot be acquired after being cancelled");
}
if (shouldStopTryingAt == null) {
shouldStopTryingAt = timeService.nowPlusMillis(lockQuitTryingAfterMillis);
}
}
private synchronized void startThreadIfApplies() {
if (daemonActive) {
super.start();
}
}
public synchronized void start() {
throw new UnsupportedOperationException("Start method not supported");
}
/**
* idempotent operation to start the acquisition timer
*/
private void finishAcquisitionTimer() {
shouldStopTryingAt = null;
}
private boolean isAcquisitionTimerOver() {
return shouldStopTryingAt == null || timeService.isPast(shouldStopTryingAt);
}
public static class DefaultLockManagerBuilder {
private LockRepository lockRepository;
private long lockAcquiredForMillis = DEFAULT_LOCK_ACQUIRED_FOR_MILLIS;
private long lockTryFrequencyMillis = DEFAULT_TRY_FREQUENCY_MILLIS;
private long lockRefreshMarginMillis = DEFAULT_LOCK_REFRESH_MARGIN_MILLIS;
private long lockQuitTryingAfterMillis = DEFAULT_QUIT_TRY_AFTER_MILLIS;
private String owner = UUID.randomUUID().toString();
private TimeService timeService;
private boolean background = true;
public DefaultLockManagerBuilder() {
}
/**
* <p>If the flag 'waitForLog' is set, indicates the maximum time it will wait for the lock in total.</p>
*
* @param millis max waiting time for lock. Must be greater than 0
* @return LockChecker object for fluent interface
*/
public DefaultLockManagerBuilder setLockQuitTryingAfterMillis(long millis) {
if (millis <= 0) {
throw new IllegalArgumentException("Lock-quit-trying-after must be grater than 0 ");
}
lockQuitTryingAfterMillis = millis;
return this;
}
/**
* <p>Updates the maximum number of tries to acquire the lock, if the flag 'waitForLog' is set </p>
* <p>Default 1</p>
*
* @param millis number of tries
* @return LockChecker object for fluent interface
*/
public DefaultLockManagerBuilder setLockTryFrequencyMillis(long millis) {
if (millis < MINIMUM_WAITING_TO_TRY_AGAIN) {
throw new IllegalArgumentException(String.format("Lock-try-frequency must be grater than %d", MINIMUM_WAITING_TO_TRY_AGAIN));
}
lockTryFrequencyMillis = millis;
return this;
}
/**
* <p>Indicates the number of milliseconds the lock will be acquired for</p>
* <p>Minimum 3 seconds</p>
*
* @param millis milliseconds the lock will be acquired for
* @return LockChecker object for fluent interface
*/
public DefaultLockManagerBuilder setLockAcquiredForMillis(long millis) {
if (millis < MIN_LOCK_ACQUIRED_FOR_MILLIS) {
throw new IllegalArgumentException(String.format(EXPIRATION_ARG_ERROR_MSG, MIN_LOCK_ACQUIRED_FOR_MILLIS));
}
lockAcquiredForMillis = millis;
long marginTemp = (long) (lockAcquiredForMillis * LOCK_REFRESH_MARGIN_PERCENTAGE);
lockRefreshMarginMillis = Math.max(marginTemp, MIN_LOCK_REFRESH_MARGIN_MILLIS);
return this;
}
public DefaultLockManagerBuilder setLockRepository(LockRepository lockRepository) {
this.lockRepository = lockRepository;
return this;
}
public DefaultLockManagerBuilder setTimeService(TimeService timeService) {
this.timeService = timeService;
return this;
}
public DefaultLockManagerBuilder setOwner(String owner) {
this.owner = owner;
return this;
}
public DefaultLockManagerBuilder disableBackGround() {
background = false;
return this;
}
public LockManagerDefault build() {
return new LockManagerDefault(
lockRepository,
timeService != null ? timeService : new TimeService(),
lockAcquiredForMillis,
lockQuitTryingAfterMillis,
lockTryFrequencyMillis,
lockRefreshMarginMillis,
owner,
background);
}
}
}
| 34.574 | 210 | 0.697692 |
23f73e865c04395d8bacbb2ed483756296d05363 | 6,950 | /*
* Copyright 2017-present Open Networking Foundation
* Copyright © 2020 camunda services GmbH (info@camunda.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.cluster.impl;
import static org.assertj.core.api.Assertions.assertThat;
import io.atomix.cluster.BootstrapService;
import io.atomix.cluster.ClusterMembershipEvent;
import io.atomix.cluster.Member;
import io.atomix.cluster.TestBootstrapService;
import io.atomix.cluster.TestGroupMembershipProtocol;
import io.atomix.cluster.discovery.BootstrapDiscoveryProvider;
import io.atomix.cluster.discovery.ManagedNodeDiscoveryService;
import io.atomix.cluster.messaging.impl.TestMessagingServiceFactory;
import io.atomix.cluster.messaging.impl.TestUnicastServiceFactory;
import io.atomix.cluster.protocol.GroupMembershipEvent;
import io.atomix.utils.Version;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
@Execution(ExecutionMode.CONCURRENT)
final class DefaultClusterMembershipServiceTest {
private final TestMessagingServiceFactory messagingServiceFactory =
new TestMessagingServiceFactory();
private final TestUnicastServiceFactory unicastServiceFactory = new TestUnicastServiceFactory();
private final Member localMember = Member.member("0", "localhost:5000");
private final Version version = Version.from("1.0.0");
private final BootstrapService bootstrapService =
new TestBootstrapService(
messagingServiceFactory.newMessagingService(localMember.address()),
unicastServiceFactory.newUnicastService(localMember.address()));
private final ManagedNodeDiscoveryService discoveryService =
new DefaultNodeDiscoveryService(
bootstrapService, localMember, BootstrapDiscoveryProvider.builder().build());
// keep the type as a test type so we can use its test utilities
private final TestGroupMembershipProtocol protocol = new TestGroupMembershipProtocol();
@Test
void shouldManageDiscoveryService() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when - then
membershipService.start().join();
assertThat(discoveryService.isRunning()).as("the discovery service is now running").isTrue();
// when - then
membershipService.stop().join();
assertThat(discoveryService.isRunning())
.as("the discovery service is not running anymore")
.isFalse();
}
@Test
void shouldGetLocalMember() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when
membershipService.start().join();
// then
final var expectedMember = new StatefulMember(localMember, version);
assertThat(membershipService.getLocalMember())
.as("the local member is member 0")
.isEqualTo(expectedMember);
}
@Test
void shouldGetMembers() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when
protocol.getMembers().add(Member.member("1", "localhost:5001"));
membershipService.start().join();
// then
assertThat(membershipService.getMembers())
.as("there should be at least one member")
.isNotEmpty()
.as("the reported members are exactly the same as the protocol's")
.containsExactlyInAnyOrderElementsOf(protocol.getMembers());
}
@Test
void shouldTrackLocalMemberReachability() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when - then
membershipService.start().join();
assertThat(membershipService.getLocalMember().isActive())
.as("local member is active after starting")
.isTrue();
// when - then
membershipService.stop().join();
assertThat(membershipService.getLocalMember().isActive())
.as("local member is not active after stopping")
.isFalse();
}
@Test
void shouldTrackReachabilityOfLocalMember() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when - then
membershipService.start().join();
assertThat(membershipService.getLocalMember().isReachable())
.as("local member is reachable after starting")
.isTrue();
// when - then
membershipService.stop().join();
assertThat(membershipService.getLocalMember().isReachable())
.as("local member is not reachable after stopping")
.isFalse();
}
@Test
void shouldManageGroupMembershipOfLocalMember() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
// when - then
membershipService.start().join();
assertThat(protocol.getMembers())
.as("local member has joined the group protocol")
.containsExactly(membershipService.getLocalMember());
// when - then
membershipService.stop().join();
assertThat(protocol.getMembers()).as("local member has left the group protocol").isEmpty();
}
@Test
void shouldForwardGroupEvents() {
// given
final var membershipService =
new DefaultClusterMembershipService(
localMember, version, discoveryService, bootstrapService, protocol);
membershipService.start().join();
// when
final var event =
new GroupMembershipEvent(
GroupMembershipEvent.Type.MEMBER_REMOVED, Member.member("1", "localhost:5001"));
final var receivedEvent = new AtomicReference<ClusterMembershipEvent>();
membershipService.addListener(receivedEvent::set);
protocol.sendEvent(event);
// then
final var expectedEvent =
new ClusterMembershipEvent(
ClusterMembershipEvent.Type.MEMBER_REMOVED, event.member(), event.time());
assertThat(receivedEvent)
.as("the received event is the same as the one sent")
.hasValue(expectedEvent);
}
}
| 36.010363 | 98 | 0.724604 |
673916ed85cb50c646df97799ab03fa438a9d190 | 850 | package com.the_pangaea_paradigm;
import com.the_pangaea_paradigm.tests.TestConsoleRunner;
import io.ipfs.multihash.Multihash;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import java.util.Arrays;
/**
* The entry point of the Spring Boot application.
*/
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static Multihash PROJECT_LIST_FILE_IPFS_HASH = Multihash.fromBase58("QmSYXV6yzhoNYuQngLdcECf85JCV6R5x642hP7SWxek4V8");
public static void main(String[] args) {
if (Arrays.asList(args).contains("test")) {
TestConsoleRunner.main(args);
}
SpringApplication.run(Application.class, args);
}
}
| 30.357143 | 129 | 0.783529 |
08e5947d35fd5b34a88f7bda504432ed42444c73 | 1,462 | package com.github.mpetersen.lrpg.value;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Value {
private static final Pattern REGEX_INPUT = Pattern.compile("^((-)?\\d+)(\\.(\\d+))?$");
private final ValueFormat format;
private BigDecimal value;
/**
* Creates a new value. The input String defines the actual value and format of this instance.
*
* The format can contain any number, a leading minus sign and a decimal separator ".".
*
* @param input The input String.
*/
public Value(final String input) {
final Matcher m = REGEX_INPUT.matcher(input);
if (m.matches()) {
final String digits = m.group(4);
final int digitCount = digits == null ? 0 : digits.length();
final boolean withSign = false;
format = new ValueFormat(digitCount, withSign);
try {
value = (BigDecimal) format.parse(input);
} catch (final ParseException e) {
throw new RuntimeException(e);
}
}
else {
throw new IllegalArgumentException("Illegal format: " + input);
}
}
@Override
public String toString() {
return format.format(value);
}
public void inc(final Value other) {
value = value.add(other.value);
}
public boolean isLessThanOrEquals(final Value other) {
final int result = value.compareTo(other.value);
return result == -1 || result == 0;
}
}
| 28.115385 | 96 | 0.660055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.