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 |
|---|---|---|---|---|---|
eb99c9473d1fe9dc4dc629ed2aa9a22d70596966 | 828 | package pt.upskills.projeto.gui;
import pt.upskills.projeto.game.FireBallThread;
import pt.upskills.projeto.rogue.utils.Position;
/**
* @author Jorge Rafael Santos
*
* FireTile is the interface required to use "images" as FireBallThread on
* ImageMatrixGUI.
*
*/
public interface FireTile extends ImageTile {
/**
* Validate impact of FireTile. This function is called by {{@link FireBallThread}} after
* each movement. If this function returns false, is job will finish after 500 ms and
* the image on {{@link ImageMatrixGUI}} is removed.
* @return true if any impact was detected, false otherwise.
*/
boolean validateImpact();
/**
* Define new position
* @param position
*/
void setPosition(Position position);
}
| 27.6 | 94 | 0.657005 |
60a92cc063a87e22fea0881c049fbd3ffa5828a7 | 2,034 | package com.jlkj.common.exception.file;
import java.util.Arrays;
import org.apache.commons.fileupload.FileUploadException;
/**
* 文件上传 误异常类
*
* @author jlkj
*/
public class InvalidExtensionException extends FileUploadException
{
private static final long serialVersionUID = 1L;
private String[] allowedExtension;
private String extension;
private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
{
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
public String[] getAllowedExtension()
{
return allowedExtension;
}
public String getExtension()
{
return extension;
}
public String getFilename()
{
return filename;
}
public static class InvalidImageExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidFlashExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
}
| 28.25 | 145 | 0.689282 |
0fd4d3d02e0ddfe49fe53d435bff38a2d19486e7 | 3,485 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.io;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.TimeoutUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* @author traff
*/
public abstract class BaseOutputReader {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.BaseOutputReader");
protected final Reader myReader;
protected volatile boolean isStopped = false;
private final char[] myBuffer = new char[8192];
private final StringBuilder myTextBuffer = new StringBuilder();
private boolean skipLF = false;
private Future<?> myFinishedFuture = null;
public BaseOutputReader(@NotNull Reader reader) {
myReader = reader;
}
protected void start() {
if (myFinishedFuture == null) {
myFinishedFuture = executeOnPooledThread(new Runnable() {
public void run() {
doRun();
}
});
}
}
protected abstract Future<?> executeOnPooledThread(Runnable runnable);
protected void doRun() {
try {
while (true) {
boolean read = readAvailable();
if (isStopped) {
break;
}
TimeoutUtil.sleep(read ? 1 : 5); // give other threads a chance
}
}
catch (IOException e) {
LOG.info(e);
}
catch (Exception e) {
LOG.error(e);
}
finally {
try {
myReader.close();
}
catch (IOException e) {
LOG.error("Can't close stream", e);
}
}
}
/**
* Reads as much data as possible without blocking.
* @return true if non-zero amount of data has been read
* @exception IOException If an I/O error occurs
*/
protected final boolean readAvailable() throws IOException {
char[] buffer = myBuffer;
StringBuilder token = myTextBuffer;
token.setLength(0);
boolean read = false;
while (myReader.ready()) {
int n = myReader.read(buffer);
if (n <= 0) break;
read = true;
for (int i = 0; i < n; i++) {
char c = buffer[i];
if (skipLF && c != '\n') {
token.append('\r');
}
if (c == '\r') {
skipLF = true;
}
else {
skipLF = false;
token.append(c);
}
if (c == '\n') {
onTextAvailable(token.toString());
token.setLength(0);
}
}
}
if (token.length() != 0) {
onTextAvailable(token.toString());
token.setLength(0);
}
return read;
}
protected abstract void onTextAvailable(@NotNull String text);
public void stop() {
isStopped = true;
}
public void waitFor() throws InterruptedException {
try {
myFinishedFuture.get();
}
catch (ExecutionException e) {
LOG.error(e);
}
}
}
| 24.034483 | 97 | 0.619225 |
67229beb5a46c7334226adbcbe496e61a35158a3 | 1,832 | package com.maxchn.nytimesnewsapp.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.maxchn.nytimesnewsapp.R;
import com.maxchn.nytimesnewsapp.adapter.TabAdapter;
import com.maxchn.nytimesnewsapp.fragment.FavoritesFragment;
import com.maxchn.nytimesnewsapp.fragment.MostPopularFragment;
import com.maxchn.nytimesnewsapp.model.MostPopularType;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = findViewById(R.id.viewPager);
TabLayout tabLayout = findViewById(R.id.tabLayout);
TabAdapter adapter = new TabAdapter(getSupportFragmentManager());
adapter.addFragment(MostPopularFragment.newInstance(MostPopularType.EMAILED), getString(R.string.most_emailed));
adapter.addFragment(MostPopularFragment.newInstance(MostPopularType.SHARED), getString(R.string.most_shared));
adapter.addFragment(MostPopularFragment.newInstance(MostPopularType.VIEWED), getString(R.string.most_viewed));
adapter.addFragment(FavoritesFragment.newInstance(), getString(R.string.favorites));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
} | 40.711111 | 120 | 0.779476 |
f8f1a2c5bbee5b06d9a7f7eef9e7d5bc10ff09d6 | 1,306 |
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class HenkilotTiedostosta {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
System.out.println("Minkä niminen tiedosto luetaan?");
String tiedosto = lukija.nextLine();
ArrayList<Henkilo> henkilot = lueHenkilot(tiedosto);
System.out.println("Henkilöitä: " + henkilot.size());
System.out.println("Henkilöt:");
for (Henkilo henkilo : henkilot) {
System.out.println(henkilo);
}
}
public static ArrayList<Henkilo> lueHenkilot(String tiedosto) {
ArrayList<Henkilo> henkilot = new ArrayList<>();
// toteuta henkilöiden lukeminen ja luominen tänne
try (Scanner tiedostonLukija = new Scanner(Paths.get(tiedosto))) {
while (tiedostonLukija.hasNextLine()) {
String rivi = tiedostonLukija.nextLine();
String[] palat = rivi.split(",");
henkilot.add(new Henkilo(palat[0],Integer.valueOf(palat[1])));
}
} catch (IOException ex) {
System.out.println("Tiedoston " + tiedosto + " lukeminen epäonnistui.");
}
return henkilot;
}
}
| 29.681818 | 84 | 0.614089 |
c1f4d7f94c2a020fa95029fe5c82ca0a7666e799 | 2,866 | package hu.gamf.szakdolgozatbackend.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(unique = true, length = 15)
private String username;
@NotNull
@Column(length = 60)
private String password;
@Column(length = 16)
private String activation;
@Column(length = 16)
private String resetPasswordCode;
private boolean isEnabled;
@NotNull
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
@JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<Role>();
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Patient patient;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Practitioner practitioner;
public User() {
}
public User(String username, String password, Patient patient) {
this.username = username;
this.password = password;
this.patient = patient;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getActivation() {
return activation;
}
public void setActivation(String activation) {
this.activation = activation;
}
public String getResetPasswordCode() { return resetPasswordCode; }
public void setResetPasswordCode(String resetCode) { this.resetPasswordCode = resetCode; }
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Practitioner getPractitioner() {
return practitioner;
}
public void setPractitioner(Practitioner practitioner) {
this.practitioner = practitioner;
}
}
| 22.046154 | 105 | 0.744592 |
0f2604a5349314e84a0f9aa3170f063b5099e09e | 1,461 | package net.runelite.client.plugins.raids;
public class timerSpecial {
private long startTime = 0;
private long difference = 0;
private long pause = 0;
private long unpaused = 0;
private long tempTime = 0;
private boolean paused = false;
public boolean started = false;
public void start()
{
startTime = System.currentTimeMillis();
tempTime = startTime;
}
public void start(long offset){
startTime = System.currentTimeMillis() - offset*1000;
tempTime = startTime;
started = true;
}
public void pause(){
pause = System.currentTimeMillis();
tempTime = (System.currentTimeMillis() - startTime)/1000;
paused = true;
}
public void unpause(){
paused = false;
unpaused = System.currentTimeMillis();
difference = unpaused - pause;
startTime = startTime + difference;
}
public void reset(){
startTime = 0;
difference = 0;
pause = 0;
unpaused = 0;
tempTime = 0;
paused = false;
startTime = System.currentTimeMillis();
tempTime = startTime;
started = false;
}
public long getElapsedTime()
{
if(paused){
return (tempTime);
}
return (System.currentTimeMillis() - startTime)/1000;
// return (System.currentTimeMillis() - startTime + difference) / 1000; //returns in seconds
}
}
| 28.096154 | 99 | 0.590691 |
8bf30ba6381f97e502885b2ab05fd59b59fb743d | 2,498 | package io.quarkus.security.runtime.interceptor.check;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import io.quarkus.security.ForbiddenException;
import io.quarkus.security.UnauthorizedException;
import io.quarkus.security.identity.SecurityIdentity;
public class RolesAllowedCheck implements SecurityCheck {
/*
* The reason we want to cache RolesAllowedCheck is that it is very common
* to have a lot of methods using the same roles in the security check
* In such cases there is no need to have multiple instances of the class hanging around
* for the entire lifecycle of the application
*/
private static final Map<Collection<String>, RolesAllowedCheck> CACHE = new ConcurrentHashMap<>();
private final String[] allowedRoles;
private RolesAllowedCheck(String[] allowedRoles) {
this.allowedRoles = allowedRoles;
}
public static RolesAllowedCheck of(String[] allowedRoles) {
return CACHE.computeIfAbsent(getCollectionForKey(allowedRoles), new Function<Collection<String>, RolesAllowedCheck>() {
@Override
public RolesAllowedCheck apply(Collection<String> allowedRolesList) {
return new RolesAllowedCheck(allowedRolesList.toArray(new String[0]));
}
});
}
private static Collection<String> getCollectionForKey(String[] allowedRoles) {
if (allowedRoles.length == 0) { // shouldn't happen, but lets be on the safe side
return Collections.emptyList();
} else if (allowedRoles.length == 1) {
return Collections.singletonList(allowedRoles[0]);
}
// use a set in order to avoid caring about the order of elements
return new HashSet<>(Arrays.asList(allowedRoles));
}
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
Set<String> roles = identity.getRoles();
if (roles != null) {
for (String role : allowedRoles) {
if (roles.contains(role)) {
return;
}
}
}
if (identity.isAnonymous()) {
throw new UnauthorizedException();
} else {
throw new ForbiddenException();
}
}
}
| 36.202899 | 127 | 0.672938 |
b68842425ffd99e3890899fcaad092b356275a40 | 5,342 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.persistence.transaction;
import java.lang.reflect.Method;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.persistence.core.configuration.PersistenceConfiguration;
import org.jboss.arquillian.persistence.core.metadata.MetadataExtractor;
import org.jboss.arquillian.test.spi.event.suite.TestEvent;
import org.jboss.arquillian.transaction.api.annotation.TransactionMode;
import org.jboss.arquillian.transaction.spi.provider.TransactionEnabler;
public class PersistenceExtensionConventionTransactionEnabler implements TransactionEnabler
{
@Inject
Instance<PersistenceConfiguration> persistenceConfiguration;
@Inject
Instance<MetadataExtractor> metadataExtractor;
@Override
public boolean isTransactionHandlingDefinedOnClassLevel(TestEvent testEvent)
{
return hasTransactionMetadataDefinedOnClassLevel();
}
@Override
public boolean isTransactionHandlingDefinedOnMethodLevel(TestEvent testEvent)
{
return shouldWrapTestMethodInTransaction(testEvent.getTestMethod());
}
@Override
public TransactionMode getTransactionModeFromClassLevel(TestEvent testEvent)
{
return persistenceConfiguration.get().getDefaultTransactionMode();
}
@Override
public TransactionMode getTransactionModeFromMethodLevel(TestEvent testEvent)
{
return persistenceConfiguration.get().getDefaultTransactionMode();
}
// ---------------------------------------------------------------------------------------------------
// Internal methods
// ---------------------------------------------------------------------------------------------------
private boolean shouldWrapTestMethodInTransaction(final Method method)
{
return (hasDataSetAnnotation(method) || hasApplyScriptAnnotation(method)
|| hasJpaCacheEvictionAnnotation(method)
|| hasCleanupAnnotation(method)
|| hasCleanupUsingScriptAnnotation(method));
}
private boolean hasTransactionMetadataDefinedOnClassLevel()
{
return (hasDataSetAnnotationOnClass() || hasApplyScriptAnnotationOnClass()
|| hasPersistenceTestAnnotationOnClass() || hasJpaCacheEvictionAnnotationOnClass()
|| hasCreateSchemaAnnotationOnClass() || hasCleanupAnnotationOnClass()
|| hasCleanupUsingScriptAnnotationOnClass());
}
private boolean hasDataSetAnnotationOnClass()
{
return metadataExtractor.get().usingDataSet().isDefinedOnClassLevel()
|| metadataExtractor.get().shouldMatchDataSet().isDefinedOnClassLevel();
}
private boolean hasDataSetAnnotation(final Method method)
{
return metadataExtractor.get().usingDataSet().isDefinedOn(method)
|| metadataExtractor.get().shouldMatchDataSet().isDefinedOn(method);
}
private boolean hasApplyScriptAnnotation(final Method method)
{
return metadataExtractor.get().applyScriptBefore().isDefinedOn(method)
|| metadataExtractor.get().applyScriptAfter().isDefinedOn(method);
}
private boolean hasApplyScriptAnnotationOnClass()
{
return metadataExtractor.get().applyScriptBefore().isDefinedOnClassLevel()
|| metadataExtractor.get().applyScriptAfter().isDefinedOnClassLevel();
}
private boolean hasPersistenceTestAnnotationOnClass()
{
return metadataExtractor.get().hasPersistenceTestAnnotation();
}
private boolean hasJpaCacheEvictionAnnotationOnClass()
{
return metadataExtractor.get().jpaCacheEviction().isDefinedOnClassLevel();
}
private boolean hasJpaCacheEvictionAnnotation(final Method method)
{
return metadataExtractor.get().jpaCacheEviction().isDefinedOn(method);
}
private boolean hasCreateSchemaAnnotationOnClass()
{
return metadataExtractor.get().createSchema().isDefinedOnClassLevel();
}
private boolean hasCleanupAnnotationOnClass()
{
return metadataExtractor.get().cleanup().isDefinedOnClassLevel();
}
private boolean hasCleanupAnnotation(final Method method)
{
return metadataExtractor.get().cleanup().isDefinedOn(method);
}
private boolean hasCleanupUsingScriptAnnotationOnClass()
{
return metadataExtractor.get().cleanupUsingScript().isDefinedOnClassLevel();
}
private boolean hasCleanupUsingScriptAnnotation(final Method method)
{
return metadataExtractor.get().cleanupUsingScript().isDefinedOn(method);
}
}
| 35.852349 | 105 | 0.729689 |
49a5c60b4b9cf86242115e49d4557d0d3ae085e0 | 729 | /*
* dexulong.java June 17, 2015, 21:40
*
* Copyright 2015, FreeInternals.org. All rights reserved.
* Use is subject to license terms.
*/
package org.freeinternals.format.dex;
import java.math.BigInteger;
/**
* 64-bit unsigned int, little-endian.
*
* @author Amos Shi
* @see
* <a href="https://source.android.com/devices/tech/dalvik/dex-format.html">
* Dalvik Executable (DEX) format</a>
*/
public class Dex_ulong {
/**
* Length of the type in bytes.
*/
public static final int LENGTH = 8;
/**
* Value of the DEX <code>ulong</code>.
*/
public final BigInteger value;
protected Dex_ulong(BigInteger bi) {
this.value = bi;
}
} | 21.441176 | 77 | 0.60631 |
ae51749138f8b595ff552dcebbe1987e648e07e3 | 1,903 | /*
*
* * Copyright (c) [2019-2021] [NorthLan](lan6995@gmail.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.lan.iti.common.core.util.idgen.snowflake;
import org.lan.iti.common.core.util.idgen.exception.IdGeneratorException;
/**
* 雪花漂移算法
*
* @author NorthLan
* @date 2021-04-27
* @url https://noahlan.com
*/
public class ShiftedSnowflake extends Snowflake {
public ShiftedSnowflake() {
super();
}
public ShiftedSnowflake(SnowflakeOptions options) {
super(options);
}
@Override
public long nextLong() {
synchronized (syncLock) {
long currentTimeTick = getCurrentTimeTick();
if (lastTimeTick == currentTimeTick) {
if (currentSeqNumber++ > maxSeqNumber) {
this.currentSeqNumber = minSeqNumber;
currentTimeTick = getNextTimeTick();
}
} else {
this.currentSeqNumber = minSeqNumber;
}
if (currentTimeTick < lastTimeTick) {
throw new IdGeneratorException("Time error for {} milliseconds", lastTimeTick - currentTimeTick);
}
lastTimeTick = currentTimeTick;
return ((currentTimeTick << timestampShift) + (workerId << seqBitLength) + (int) currentSeqNumber);
}
}
}
| 29.734375 | 113 | 0.625328 |
69f6684dd131e5d9c5150d2baa32e7b696190427 | 11,708 | import Bril.*;
import PREStruct.*;
import Utils.ExpSet;
import Utils.Util;
import org.json.JSONObject;
import picocli.CommandLine;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import static PREStruct.CFGBlock.linkBlocks;
@CommandLine.Command(name = "BrilPRE", version = "BrilPRE 0.1.0", mixinStandardHelpOptions = true,
description = "A partial redundancy elimination pass for Bril")
public class BrilPRE implements Callable<Integer> {
@CommandLine.Parameters(index = "0", description = "The source code file in JSON.")
File inputFile;
@CommandLine.Parameters(index = "1", description = "The output code file in JSON.")
File outputFile;
public static void main(String[] args) {
int exitCode = new CommandLine(new BrilPRE()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
JSONObject ans = Util.programToJSON(PREPass(Util.parseJson(inputFile)));
Program program = Util.parseJson(inputFile);
//save bytecode into disk
FileWriter out = new FileWriter(outputFile);
out.write(ans.toString(4));
out.close();
return 0;
}
Program PREPass(Program program) {
CFG cfg = generateCFG(program);
System.err.println("finished cfg generation");
//cfg.display();
preprocess(cfg); // precalc usedInBlock, kill;
System.err.println("finished preprocess");
//pass1_anticipated(cfg);
WorkListAnticipated.work(cfg);
System.err.println("finished pass1");
//cfg.displayPRE();
//pass2_earliest(cfg);
WorkListEarliest.work(cfg);
System.err.println("finished pass2");
//cfg.displayPRE();
//pass3_postponable(cfg);
WorkListPostponable.work(cfg);
System.err.println("finished pass3");
//pass4_used(cfg);
WorkListUsed.work(cfg);
System.err.println("finished pass4");
//cfg.displayPRE();
VarNameGenerator vng = new VarNameGenerator(cfg.varSet);
transform(cfg, vng);
//cfg.display();
return cfgToProgram(cfg, vng);
}
Program cfgToProgram(CFG cfg, VarNameGenerator vng) {
Program program = new Program();
ArrayList<Instruction> instrs = new ArrayList<>();
ArrayList<CFGBlock> sortedBlocks = new ArrayList<>();
for (CFGBlock block : cfg.blocks) {
if (block == cfg.exit || block == cfg.entry) continue;
if (block.originalNo < 0) continue;
sortedBlocks.add(block);
for (int i = 0; i < block.succs.size(); ++i) {
CFGBlock succ = block.succs.get(i);
if (succ.originalNo < 0 && succ != cfg.exit) {
Instruction lastInstr = block.instrs.getLast();
if (lastInstr instanceof EffectOperation && ((EffectOperation) lastInstr).op.matches("jmp|br")) {
EffectOperation eo = (EffectOperation) lastInstr;
if (eo.op.equals("jmp")) {
block.instrs.removeLast();
for (Instruction instr : succ.instrs) {
block.instrs.add(instr);
}
block.instrs.add(eo);
linkBlocks(block, succ, succ.succs.get(0));
} else { //br
Label labelInstr = (Label) succ.succs.get(0).instrs.getLast();
String labelName = labelInstr.labelName;
String newLabelName = vng.genLabelName();
Label newLabel = new Label(newLabelName);
succ.instrs.addFirst(newLabel);
for (int bri = 1; bri <= 2; ++bri) {
if (labelName.equals(eo.args.get(bri))) {
eo.args.set(bri, newLabelName);
ArrayList<String> jmpArgs = new ArrayList<>();
jmpArgs.add(labelName);
Instruction newJmp = new EffectOperation("jmp", jmpArgs);
succ.instrs.addLast(newJmp);
break;
}
}
sortedBlocks.add(succ);
}
} else { // no jump
for (Instruction instr : succ.instrs) {
block.instrs.add(instr);
}
linkBlocks(block, succ, succ.succs.get(0));
}
}
}
}
// System.err.println("final block seq: ");
for (CFGBlock block : sortedBlocks) {
//block.display();
instrs.addAll(block.instrs);
}
Function funcMain = new Function("main", instrs);
program.functions.add(funcMain);
return program;
}
void transform(CFG cfg, VarNameGenerator vng) {
for (CFGBlock block : cfg.blocks) {
ExpSet tempExps = ExpSet.intersect(block.preInfo.latest, block.preInfo.toBeUsed.out);
if (block.instrs.size() > 0) {
Instruction instr = block.instrs.getFirst();
if (instr instanceof ValueOperation) {
ValueOperation vo = (ValueOperation) instr;
if (!vo.opName.equals("id")) {
Expression exp = vo.getExp();
if (!block.preInfo.latest.contains(exp) || block.preInfo.toBeUsed.out.contains(exp)) {
ArrayList<String> newArgs = new ArrayList<>();
newArgs.add(vng.genVarName(exp));
Instruction newInstr = new ValueOperation("id", vo.destName, vo.type, newArgs);
block.instrs.removeFirst();
block.instrs.addFirst(newInstr);
}
}
}
}
for (Expression exp : tempExps.expList) {
String destName = vng.genVarName(exp);
Instruction newInstr = new ValueOperation(exp.opName, destName, exp.type, exp.args);
block.instrs.addFirst(newInstr);
}
}
// remove empty blocks
for (CFGBlock block : cfg.blocks) {
if (block.instrs.size() < 1 && block != cfg.entry && block != cfg.exit) {
// must len(preds) == 1 and len(succs) == 1
CFGBlock pred = block.preds.get(0), succ = block.succs.get(0);
linkBlocks(pred, block, succ);
}
}
}
void preprocess(CFG cfg) {
// precalc usedInBlock, kill
// each block at most contain 1 instr
for (CFGBlock cur : cfg.blocks) {
if (cur.instrs.size() < 1) continue;
Instruction instr = cur.instrs.getFirst();
if (instr instanceof ConstOperation) {
// doesn't affect used, do kill
if (instr instanceof ConstBoolOperation) {
String destName = ((ConstBoolOperation) instr).dest;
cur.preInfo.kill.add(destName);
cfg.varSet.add(destName);
}
else if (instr instanceof ConstIntOperation) { // constintoperation
String destName = ((ConstIntOperation) instr).dest;
cur.preInfo.kill.add(((ConstIntOperation) instr).dest);
cfg.varSet.add(destName);
}
} else if (instr instanceof ValueOperation) {
ValueOperation vo = (ValueOperation) instr;
// uniform exp
// vo.setExp(vo.getExp());
cur.preInfo.kill.add(vo.destName);
if (!vo.opName.equals("id"))
cur.preInfo.usedInBlock.add(vo.getExp());
cfg.varSet.add(vo.destName);
for (String s : vo.args) {
cfg.varSet.add(s);
}
} else {
if (instr instanceof Label) {
cfg.varSet.add(((Label) instr).labelName);
}
// EffectOp doesn't affect anything
}
}
}
CFG generateCFG(Program program) {
// assume only one function main
Function funcMain = program.functions.get(0);
CFG cfg = new CFG();
HashMap<Integer, CFGBlock> indexToBlock = new HashMap<>(); // will not lookup entry
HashMap<String, CFGBlock> labelToBlock = new HashMap<>();
indexToBlock.put(funcMain.instrs.size(), cfg.exit);
// create one block for each instruction (label included)
for (int i = 0; i < funcMain.instrs.size(); ++i) {
CFGBlock newBlock = new CFGBlock();
newBlock.originalNo = i;
indexToBlock.put(i, newBlock);
Instruction ins = funcMain.instrs.get(i);
// System.err.println(i);
newBlock.instrs.add(ins);
if (ins instanceof Label) {
labelToBlock.put(((Label) ins).labelName, newBlock);
}
cfg.blocks.add(newBlock);
}
cfg.calcAllExp();
//cfg.display();
// link nodes
linkBlocks(cfg.entry, indexToBlock.get(0));
for (int i = 0; i < funcMain.instrs.size(); ++i) {
Instruction ins = funcMain.instrs.get(i);
CFGBlock thisBlock = indexToBlock.get(i);
if (ins instanceof EffectOperation &&
((EffectOperation) ins).op.matches("jmp|br|ret")) {
EffectOperation eo = (EffectOperation) ins;
if (eo.op.equals("br")) {
String l = eo.args.get(1), r = eo.args.get(2);
// System.err.println("br " + l + " " + r);
linkBlocks(thisBlock, labelToBlock.get(l));
linkBlocks(thisBlock, labelToBlock.get(r));
} else if (eo.op.equals("jmp")){ // jmp
String l = eo.args.get(0);
linkBlocks(thisBlock, labelToBlock.get(l));
} else { //ret
linkBlocks(thisBlock, indexToBlock.get(funcMain.instrs.size()));
}
} else {
linkBlocks(thisBlock, indexToBlock.get(i + 1));
}
}
// add empty blocks for edges (a->b) where b has multiple preds
ArrayList<CFGBlock> newBlocks = new ArrayList<>();
for (CFGBlock thisBlock : cfg.blocks) {
if (thisBlock.preds.size() > 1) {
for (int i = 0; i < thisBlock.preds.size(); ++i) {
CFGBlock pred = thisBlock.preds.get(i);
CFGBlock newBlock = new CFGBlock();
for (int j = 0; j < pred.succs.size(); ++j) {
if (pred.succs.get(j) == thisBlock) {
pred.succs.set(j, newBlock);
newBlock.preds.add(pred);
newBlock.succs.add(thisBlock);
thisBlock.preds.set(i, newBlock);
break;
}
}
newBlocks.add(newBlock);
}
}
}
cfg.blocks.addAll(newBlocks);
return cfg;
}
}
| 40.09589 | 117 | 0.504954 |
3e5fed4fd2e146b5da738a1352780ccb460da14a | 34,458 | package pl.tecna.gwt.connectors.client.elements;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import pl.tecna.gwt.connectors.client.CornerPoint;
import pl.tecna.gwt.connectors.client.Diagram;
import pl.tecna.gwt.connectors.client.Point;
import pl.tecna.gwt.connectors.client.drag.AxisXYDragController;
import pl.tecna.gwt.connectors.client.elements.SectionDecoration.DecorationDirection;
import pl.tecna.gwt.connectors.client.listeners.event.ConnectorClickEvent;
import pl.tecna.gwt.connectors.client.listeners.event.ConnectorDoubleClickEvent;
import pl.tecna.gwt.connectors.client.listeners.event.ElementDragEvent;
import pl.tecna.gwt.connectors.client.util.ConnectorStyle;
import pl.tecna.gwt.connectors.client.util.Position;
import pl.tecna.gwt.connectors.client.util.WidgetUtils;
import com.allen_sauer.gwt.dnd.client.DragEndEvent;
import com.allen_sauer.gwt.dnd.client.DragHandlerAdapter;
import com.allen_sauer.gwt.dnd.client.DragStartEvent;
import com.allen_sauer.gwt.dnd.client.drop.DropController;
import com.allen_sauer.gwt.dnd.client.util.DOMUtil;
import com.allen_sauer.gwt.dnd.client.util.WidgetLocation;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HTML;
public class Section extends HTML {
private final Logger LOG = Logger.getLogger("Section");
private static final int SIZE = 2;
private static final int TRANSPARENT_MARGIN_SIZE = 2;
public Point startPoint;
public Point endPoint;
public Connector connector;
public SectionDecoration startPointDecoration;
public SectionDecoration endPointDecoration;
private int height;
private int width;
public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;
private ConnectorStyle style;
/**
* Defines saved orientation, it doesn't contain current orientation
*/
public int savedOrientation;
private AxisXYDragController sectionDragController;
/**
* Section represents vertical or horizontal part of {@link Connector}.
*
* @param startPoint a {@link CornerPoint} or {@link EndPoint} where the Section starts
* @param endPoint a {@link CornerPoint} or {@link EndPoint} where the Section ends
* @param connector the connector
*/
public Section(Point startPoint, Point endPoint, Connector connector) throws IllegalArgumentException {
super();
// this.sinkEvents(Event.ONMOUSEDOWN);
// this.unsinkEvents(Event.ONDBLCLICK);
// this.unsinkEvents(Event.ONCLICK);
this.connector = connector;
this.startPoint = startPoint;
this.endPoint = endPoint;
if ((isHorizontal() == false) && (isVertical() == false)) {
throw new IllegalArgumentException("Sections must be horizontal or vertical! " + "Start :" + startPoint.getLeft()
+ " " + startPoint.getTop() + " end:" + endPoint.getLeft() + " " + endPoint.getTop());
}
// Count Section width and height
this.height = Math.abs(endPoint.getTop() - startPoint.getTop());
this.width = Math.abs(endPoint.getLeft() - startPoint.getLeft());
addDoubleClickHandler(new DoubleClickHandler() {
public void onDoubleClick(DoubleClickEvent event) {
Section.this.connector.onConnectorDoubleClick(new ConnectorDoubleClickEvent(Section.this.connector,
Section.this));
}
});
addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (!Section.this.connector.diagram.ctrlPressed) {
Section.this.connector.diagram.deselectAllSections();
Section.this.connector.diagram.shapeDragController.clearSelection();
}
if (Section.this.connector.isSelected) {
Section.this.connector.deselect();
} else {
Section.this.connector.select();
}
Section.this.connector.onConnectorClick(new ConnectorClickEvent(Section.this.connector, Section.this));
}
});
}
/**
* Shows Section on a given panel. The Section is represented by horizontal or vertical line. The
* panel argument must be of type of AbsolutePanel.
* <p>
* This method also add a focus panel to the Section. Focus panel is necessary to provide drag and
* drop functionality to the Section. It also makes possible selecting a Section.
* <p>
* If the Section is already on the Diagram this method do nothing.
*
* @param diagram an absolute panel on witch the line will be drawn
*/
public void showOnDiagram(Diagram diagram) {
showOnDiagram(diagram, false, ConnectorStyle.SOLID);
}
/**
* Shows Section on a given panel. The Section is represented by horizontal or vertical line. The
* panel argument must be of type of AbsolutePanel.
* <p>
* This method also add a focus panel to the Section. Focus panel is necessary to provide drag and
* drop functionality to the Section. It also makes possible selecting a Section.
* <p>
* If the Section is already on the Diagram this method do nothing.
*
* @param diagram an absolute panel on witch the line will be drawn
* @param isSelected defines whether connector is selected
* @param style the connector style
*/
public void showOnDiagram(Diagram diagram, boolean isSelected, ConnectorStyle style) {
// Create DIV to draw a line
// Using CSS
/*
* .gwt-connectors-line { font-size: 1px; line-height:1px; background-color: black }
* .gwt-connectors-line-vertical { width:1px } .gwt-connectors-line-horizontal { height:1px }
*/
this.style = style;
AbsolutePanel panel = diagram.boundaryPanel;
boolean allowHorizontalDragging = false;
boolean allowVerticalDragging = false;
// Set line look and behavior
if (isVertical()) {
if (isSelected) {
setHTML(selectedVerticalLine(this.height, style));
} else {
setHTML(verticalLine(this.height, style));
}
addStyleName("gwt-connectors-vertical-section");
allowHorizontalDragging = true;
} else if (isHorizontal()) {
if (isSelected) {
this.setHTML(selectedHorizontalLine(this.width, style));
} else {
this.setHTML(horizontalLine(this.width, style));
}
addStyleName("gwt-connectors-horizontal-section");
allowVerticalDragging = true;
}
// Add drag and drop functionality
this.sectionDragController = new AxisXYDragController(panel, true, allowHorizontalDragging, allowVerticalDragging) {
@Override
public void dragStart() {
// If dragged section startPoint or dragged section endPoint
// is glued to connectionPoint then split section into three
// to draw new lines to connectionPoint
connector.keepShape = true;
try {
if (Section.this.startPointIsGluedToConnectionPoint() || Section.this.endPointIsGluedToConnectionPoint()) {
// Calculate new CornerPoints
ArrayList<CornerPoint> newCornerPoints = new ArrayList<CornerPoint>();
Point sp = Section.this.startPoint;
Point ep = Section.this.endPoint;
CornerPoint cp1 =
new CornerPoint(sp.getLeft() + (ep.getLeft() - sp.getLeft()) / 2,
sp.getTop() + (ep.getTop() - sp.getTop()) / 2);
CornerPoint cp2 =
new CornerPoint(sp.getLeft() + (ep.getLeft() - sp.getLeft()) / 2,
sp.getTop() + (ep.getTop() - sp.getTop()) / 2);
newCornerPoints.add(cp1);
newCornerPoints.add(cp2);
// Split Section
Section.this.splitSection(newCornerPoints);
}
} catch (Exception e) {
LOG.severe("Section drag start error " + e.getMessage());
e.printStackTrace();
}
try {
super.dragStart();
} catch (Exception e) {
LOG.severe("Section (super) drag start error " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void dragMove() {
try {
if (isAllowHorizontalDragging()) {
if (Section.this.startPoint.getLeft() < Section.this.endPoint.getLeft()) {
Section.this.startPoint.setLeftPosition(context.draggable.getAbsoluteLeft()
- context.boundaryPanel.getAbsoluteLeft() + SIZE);
Section.this.endPoint.setLeftPosition(context.draggable.getAbsoluteLeft()
- context.boundaryPanel.getAbsoluteLeft() + width + SIZE);
} else {
Section.this.startPoint.setLeftPosition(context.draggable.getAbsoluteLeft()
- context.boundaryPanel.getAbsoluteLeft() + width + SIZE);
Section.this.endPoint.setLeftPosition(context.draggable.getAbsoluteLeft()
- context.boundaryPanel.getAbsoluteLeft() + SIZE);
}
}
if (isAllowVerticalDragging()) {
if (Section.this.startPoint.getTop() < Section.this.endPoint.getTop()) {
Section.this.startPoint.setTopPosition(context.draggable.getAbsoluteTop()
- context.boundaryPanel.getAbsoluteTop() + SIZE);
Section.this.endPoint.setTopPosition(context.draggable.getAbsoluteTop() -
context.boundaryPanel.getAbsoluteTop() + height + SIZE);
} else {
Section.this.startPoint.setTopPosition(context.draggable.getAbsoluteTop()
- context.boundaryPanel.getAbsoluteTop() + height + SIZE);
Section.this.endPoint.setTopPosition(context.draggable.getAbsoluteTop() - context.boundaryPanel.getAbsoluteTop() + SIZE);
}
}
if (Section.this.connector.getNextSection(Section.this) != null) {
Section.this.connector.getNextSection(Section.this).update();
};
if (Section.this.connector.getPrevSection(Section.this) != null) {
Section.this.connector.getPrevSection(Section.this).update();
};
Section.this.connector.endEndPoint.update();
Section.this.connector.startEndPoint.update();
if (startPointDecoration != null) {
startPointDecoration.update(calculateStartPointDecorationDirection(), startPoint.getLeft(), startPoint
.getTop());
}
if (endPointDecoration != null) {
endPointDecoration.update(calculateEndPointDecorationDirection(), endPoint.getLeft(), endPoint.getTop());
}
} catch (Exception e) {
LOG.severe("Section drag move error " + e.getMessage());
e.printStackTrace();
}
try {
// super.dragMove();
// To provide XY drag feature (BEGIN)
if (isAllowHorizontalDragging() == false) {
context.desiredDraggableX = initialDraggableLocation.getLeft() + boundaryOffsetX;
}
if (isAllowVerticalDragging() == false) {
context.desiredDraggableY = initialDraggableLocation.getTop() + boundaryOffsetY;
}
// To provide XY drag feature (END)
int desiredLeft = context.desiredDraggableX - boundaryOffsetX;
int desiredTop = context.desiredDraggableY - boundaryOffsetY;
if (getBehaviorConstrainedToBoundaryPanel()) {
desiredLeft =
Math.max(0, Math.min(desiredLeft, dropTargetClientWidth - context.draggable.getOffsetWidth()));
desiredTop =
Math.max(0, Math.min(desiredTop, dropTargetClientHeight - context.draggable.getOffsetHeight()));
}
if (isAllowHorizontalDragging()) {
if (startPoint.getTop().intValue() > endPoint.getTop().intValue()) {
desiredTop = endPoint.getTop();
} else {
desiredTop = startPoint.getTop();
}
desiredLeft += SIZE;
}
if (isAllowVerticalDragging()) {
if (startPoint.getLeft().intValue() > endPoint.getLeft().intValue()) {
desiredLeft = endPoint.getLeft();
} else {
desiredLeft = startPoint.getLeft();
}
desiredTop += SIZE;
}
DOMUtil.fastSetElementPosition(movablePanel.getElement(), desiredLeft, desiredTop);
DropController newDropController = getIntersectDropController(context.mouseX, context.mouseY);
if (context.dropController != newDropController) {
if (context.dropController != null) {
context.dropController.onLeave(context);
}
context.dropController = newDropController;
if (context.dropController != null) {
context.dropController.onEnter(context);
}
}
if (context.dropController != null) {
context.dropController.onMove(context);
}
} catch (Exception e) {
LOG.severe("Section (super) drag move error " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void dragEnd() {
// If after dragging two or more neighbor Sections are aligned to the line
// (they form one single line), those neighbor Sections are merged to one.
if (Section.this.connector.sections.size() > 2) {
if ((Section.this.connector.getPrevSection(Section.this) != null)
&& (Section.this.connector.getPrevSection(Section.this).hasNoDimensions())) {
System.out.println("merge with preceding Section");
// Loop 2 times to remove two preceding Sections
try {
for (int i = 0; i < 2; i++) {
Section.this.startPoint = Section.this.connector.getPrevSection(Section.this).startPoint;
Section.this.startPointDecoration =
Section.this.connector.getPrevSection(Section.this).startPointDecoration;
Section.this.connector.getPrevSection(Section.this).removeFromDiagram(false);
Section.this.connector.sections.remove(Section.this.connector.getPrevSection(Section.this));
}
} catch (Exception e) {
// LOG.e("error merging sections", e);
}
}
if ((Section.this.connector.getNextSection(Section.this) != null)
&& (Section.this.connector.getNextSection(Section.this).hasNoDimensions())) {
System.out.println("merge with succeeding Section");
// Loop 2 times to remove two succeeding Sections
for (int i = 0; i < 2; i++) {
try {
Section.this.endPoint = Section.this.connector.getNextSection(Section.this).endPoint;
Section.this.endPointDecoration =
Section.this.connector.getNextSection(Section.this).endPointDecoration;
Section.this.connector.getNextSection(Section.this).removeFromDiagram(false);
Section.this.connector.sections.remove(Section.this.connector.getNextSection(Section.this));
} catch (Exception e) {
// LOG.e("Error while connecting sections...");
}
}
}
}
super.dragEnd();
connector.updateCornerPoints();
}
};
int positionLeft = Math.min(this.startPoint.getLeft(), this.endPoint.getLeft());
int positionTop = Math.min(this.startPoint.getTop(),this.endPoint.getTop());
if (isVertical()) {
positionLeft -= TRANSPARENT_MARGIN_SIZE;
} else {
positionTop -= TRANSPARENT_MARGIN_SIZE;
}
// Add line to given panel
WidgetUtils.addWidget(panel, this, positionLeft, positionTop);
this.sectionDragController.makeDraggable(this);
this.sectionDragController.setBehaviorDragStartSensitivity(5);
this.sectionDragController.addDragHandler(new DragHandlerAdapter() {
@Override
public void onPreviewDragStart(DragStartEvent event) {
if (event.getContext().draggable != null) {
event.getContext().draggable.getElement().scrollIntoView();
if (sectionDragController.getBoundaryPanel().getParent() == null
|| (sectionDragController.getBoundaryPanel().getParent().getOffsetHeight() < event.getContext().draggable
.getOffsetHeight() || sectionDragController.getBoundaryPanel().getParent().getOffsetWidth() < event
.getContext().draggable.getOffsetWidth())) {
sectionDragController.setBehaviorScrollIntoView(false);
} else {
sectionDragController.setBehaviorScrollIntoView(true);
}
}
}
@Override
public void onDragStart(DragStartEvent event) {
int startX =
connector.diagram.boundaryPanel.getWidgetLeft(event.getContext().draggable)
- connector.diagram.boundaryPanel.getAbsoluteLeft();
int startY =
connector.diagram.boundaryPanel.getWidgetTop(event.getContext().draggable)
- connector.diagram.boundaryPanel.getAbsoluteTop();
connector.diagram.onElementDrag(new pl.tecna.gwt.connectors.client.listeners.event.ElementDragEvent(event
.getContext(), startX, startY,
pl.tecna.gwt.connectors.client.listeners.event.ElementDragEvent.DragEventType.DRAG_START));
Section.this.connector.select();
}
@Override
public void onDragEnd(DragEndEvent event) {
if (Section.this.isAttached()) {
Section.this.update();
}
// update end points
Section.this.connector.endEndPoint.update();
Section.this.connector.startEndPoint.update();
List<CornerPoint> corners = connector.getCorners();
if (connector.fixOverlapSections(corners)) {
connector.drawSections(corners);
}
// Merge last sections if length is lesser than defined
if (connector.startEndPoint.isGluedToConnectionPoint()) {
connector.mergeTwoFirstSections(connector.sections.get(0), corners);
}
if (connector.endEndPoint.isGluedToConnectionPoint()) {
connector.mergeTwoLastSections(connector.sections.get(connector.sections.size() - 1), corners);
}
connector.fixLineSections(corners);
connector.drawSections(corners, true);
// int endX =
// connector.diagram.boundaryPanel.getWidgetLeft(event.getContext().draggable)
// - connector.diagram.boundaryPanel.getAbsoluteLeft();
// int endY =
// connector.diagram.boundaryPanel.getWidgetTop(event.getContext().draggable)
// - connector.diagram.boundaryPanel.getAbsoluteTop();
connector.diagram.onElementDrag(new ElementDragEvent(event.getContext(),
event.getContext().desiredDraggableX, event.getContext().desiredDraggableY,
ElementDragEvent.DragEventType.DRAG_END));
}
});
// Calculate decoration's direction and add SectionDecorations to diagram
if (startPointDecoration != null) {
this.startPointDecoration.showOnDiagram(panel, calculateStartPointDecorationDirection(), startPoint.getLeft(),
startPoint.getTop());
}
if (endPointDecoration != null) {
this.endPointDecoration.showOnDiagram(panel, calculateEndPointDecorationDirection(), endPoint.getLeft(), endPoint
.getTop());
}
}
public DecorationDirection calculateEndPointDecorationDirection() {
if (isHorizontal()) {
if (this.endPoint.getLeft() < this.startPoint.getLeft()) {
return DecorationDirection.HORIZONTAL_LEFT;
} else {
return DecorationDirection.HORIZONTAL_RIGHT;
}
} else if (isVertical()) {
if (this.endPoint.getTop() < this.startPoint.getTop()) {
return DecorationDirection.VERTICAL_UP;
} else {
return DecorationDirection.VERTICAL_DOWN;
}
}
return DecorationDirection.HORIZONTAL_LEFT;
}
public DecorationDirection calculateStartPointDecorationDirection() {
if (isHorizontal()) {
if (this.startPoint.getLeft() < this.endPoint.getLeft()) {
return DecorationDirection.HORIZONTAL_LEFT;
} else {
return DecorationDirection.HORIZONTAL_RIGHT;
}
} else if (isVertical()) {
if (this.startPoint.getTop() < this.endPoint.getTop()) {
return DecorationDirection.VERTICAL_UP;
} else {
return DecorationDirection.VERTICAL_DOWN;
}
}
return DecorationDirection.HORIZONTAL_LEFT;
}
/**
* Returns true if Section has no dimensions. It means that Section's width and height equals
* zero.
*
* @return true if Section has no dimensions false if Section has dimensions
*/
protected boolean hasNoDimensions() {
if ((this.startPoint.getLeft().intValue() == this.endPoint.getLeft().intValue())
&& (this.startPoint.getTop().intValue() == this.endPoint.getTop().intValue())) {
return true;
} else {
return false;
}
}
protected boolean startPointIsGluedToConnectionPoint() {
if (Section.this.startPoint instanceof EndPoint) {
if (((EndPoint) Section.this.startPoint).isGluedToConnectionPoint()) {
return true;
}
}
return false;
}
protected boolean endPointIsGluedToConnectionPoint() {
if (Section.this.endPoint instanceof EndPoint) {
if (((EndPoint) Section.this.endPoint).isGluedToConnectionPoint()) {
return true;
}
}
return false;
}
/**
* Splits the Section using CornerPoints given as parameter.
*
* @param newCornerPoints an array of CornerPoints that determines a new shape of Section split up
* into few new Sections.
*/
protected void splitSection(ArrayList<CornerPoint> newCornerPoints) {
if (this.startPointIsGluedToConnectionPoint()) {
// Add a new horizontal Section as the first Section in Connector and move decorations into
// this section
Section s1 = new Section(this.startPoint, newCornerPoints.get(0), this.connector);
s1.setStartPointDecoration(this.startPointDecoration);
this.startPointDecoration = null;
s1.showOnDiagram(this.connector.diagram);
this.connector.sections.add(0, s1);
// Add a new vertical section as the second in Connector
Section s2 = new Section(newCornerPoints.get(0), newCornerPoints.get(1), this.connector);
s2.showOnDiagram(this.connector.diagram);
this.connector.sections.add(1, s2);
// Reconnect dragged Section to the second CornerPoint
this.startPoint = newCornerPoints.get(1);
this.update();
}
if (this.endPointIsGluedToConnectionPoint()) {
// Add a new vertical Section as the last but one Section in Connector
Section s1 = new Section(newCornerPoints.get(0), newCornerPoints.get(1), this.connector);
s1.showOnDiagram(this.connector.diagram);
this.connector.sections.add(s1);
// Add a new horizontal section as the last in Connector and move decorations into this
// section
Section s2 = new Section(newCornerPoints.get(1), this.endPoint, this.connector);
s2.setEndPointDecoration(this.endPointDecoration);
this.endPointDecoration = null;
s2.showOnDiagram(this.connector.diagram);
this.connector.sections.add(s2);
// Reconnect dragged Section to the first CornerPoint
this.endPoint = newCornerPoints.get(0);
this.update();
}
}
public boolean removeFromDiagram(boolean removeEndPoints) {
if (endPointDecoration != null && endPointDecoration.isAttached()) {
endPointDecoration.removeFromParent();
}
if (startPointDecoration != null && startPointDecoration.isAttached()) {
startPointDecoration.removeFromParent();
}
if (removeEndPoints) {
if (startPoint != null && startPoint.isAttached()) {
startPoint.removeFromParent();
}
if (endPoint != null && endPoint.isAttached()) {
endPoint.removeFromParent();
}
}
return connector.diagram.boundaryPanel.remove(this);
}
private String verticalLine(int height, ConnectorStyle style) {
return "<div style=\"border-left:" + SIZE + "px " + style.name().toLowerCase() +
" #B2B2B2; height:" + (height + SIZE) + "px\">";
}
private String horizontalLine(int width, ConnectorStyle style) {
return "<div style=\"border-top:" + SIZE + "px " + style.name().toLowerCase() +
" #B2B2B2; width:" + width + "px\">";
}
private String selectedVerticalLine(int height, ConnectorStyle style) {
return "<div style=\"border-left:" + SIZE + "px " + style.name().toLowerCase() +
" #00BFFF; height:" + (height + SIZE) + "px\">";
}
private String selectedHorizontalLine(int width, ConnectorStyle style) {
return "<div style=\"border-top:" + SIZE + "px " + style.name().toLowerCase() +
" #00BFFF; width:" + width + "px\">";
}
/**
* Updates section displayed on a diagram. Recalculates new position and size of the Section. Also
* sets the functionality of the horizontal or vertical dragging.
*/
public void update() {
if (startPoint.getLeft().compareTo(endPoint.getLeft()) != 0 &&
startPoint.getTop().compareTo(endPoint.getTop()) != 0) {
LOG.severe("!!! Error during section update !!!");
connector.logCornerPointsData();
connector.calculateStandardPointsPositions();
connector.drawSections();
return;
}
try {
this.height = Math.abs(endPoint.getTop() - startPoint.getTop());
this.width = Math.abs(endPoint.getLeft() - startPoint.getLeft());
if (isVertical()) {
if (this.connector.isSelected) {
this.setHTML(selectedVerticalLine(this.height, style));
} else {
this.setHTML(verticalLine(this.height, style));
}
sectionDragController.setAllowHorizontalDragging(true);
sectionDragController.setAllowVerticalDragging(false);
updateWidgetPosition(false);
} else if (isHorizontal()) {
if (this.connector.isSelected) {
this.setHTML(selectedHorizontalLine(this.width, style));
} else {
this.setHTML(horizontalLine(this.width, style));
}
sectionDragController.setAllowHorizontalDragging(false);
sectionDragController.setAllowVerticalDragging(true);
updateWidgetPosition(true);
}
// Calculate decoration's direction and update decorations
if (startPointDecoration != null) {
this.startPointDecoration.update(calculateStartPointDecorationDirection(), startPoint.getLeft(), startPoint
.getTop());
}
if (endPointDecoration != null) {
this.endPointDecoration.update(calculateEndPointDecorationDirection(), endPoint.getLeft(), endPoint.getTop());
}
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error updating section", e);
connector.calculateStandardPointsPositions();
connector.drawSections();
}
}
public void select() {
if (getElement().getChildCount() != 0 && getElement().getChild(0) instanceof com.google.gwt.user.client.Element) {
((com.google.gwt.user.client.Element) getElement().getChild(0)).getStyle().setBorderColor("#00BFFF");
}
// Select Section Decorations
if (startPointDecoration != null) {
this.startPointDecoration.select();
}
if (endPointDecoration != null) {
this.endPointDecoration.select();
}
}
public void deselect() {
if (getElement().getChildCount() != 0 && getElement().getChild(0) instanceof com.google.gwt.user.client.Element) {
((com.google.gwt.user.client.Element) getElement().getChild(0)).getStyle().setBorderColor("#B2B2B2");
}
// Deselect Section Decorations
if (startPointDecoration != null) {
this.startPointDecoration.deselect();
}
if (endPointDecoration != null) {
this.endPointDecoration.deselect();
}
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point startPoint) {
this.startPoint = startPoint;
}
public Point getEndPoint() {
return endPoint;
}
public void setEndPoint(Point endPoint) {
this.endPoint = endPoint;
}
public boolean isVertical() {
return isVertical(new ArrayList<Section>());
}
public boolean isVertical(List<Section> checkedSections) {
checkedSections.add(this);
if (!(this.hasNoDimensions())) {
if (this.startPoint.getLeft().intValue() == this.endPoint.getLeft().intValue()) {
return true;
}
} else {
if (!checkedSections.contains(this.connector.getNextSection(this))
&& (this.connector.getNextSection(this) != null)
&& (this.connector.getNextSection(this).isHorizontal(checkedSections))) {
return true;
}
if (!checkedSections.contains(this.connector.getPrevSection(this))
&& (this.connector.getPrevSection(this) != null)
&& (this.connector.getPrevSection(this).isHorizontal(checkedSections))) {
return true;
}
if (this.connector.getPrevSection(this) == null) {
return true;
}
}
return false;
}
public boolean isHorizontal() {
return isHorizontal(new ArrayList<Section>());
}
public boolean isHorizontal(List<Section> checkedSections) {
checkedSections.add(this);
if (!(this.hasNoDimensions())) {
if (this.startPoint.getTop().intValue() == this.endPoint.getTop().intValue()) {
return true;
}
} else {
if (!checkedSections.contains(this.connector.getNextSection(this))
&& (this.connector.getNextSection(this) != null)
&& (this.connector.getNextSection(this).isVertical(checkedSections))) {
return true;
}
if (!checkedSections.contains(this.connector.getPrevSection(this))
&& (this.connector.getPrevSection(this) != null)
&& (this.connector.getPrevSection(this).isVertical(checkedSections))) {
return true;
}
if (this.connector.getPrevSection(this) == null) {
return true;
}
}
return false;
}
public SectionDecoration getStartPointDecoration() {
return startPointDecoration;
}
public void setStartPointDecoration(SectionDecoration startPointDecoration) {
this.startPointDecoration = startPointDecoration;
}
public SectionDecoration getEndPointDecoration() {
return endPointDecoration;
}
public void setEndPointDecoration(SectionDecoration endPointDecoration) {
this.endPointDecoration = endPointDecoration;
}
public int getLength() {
if (isVertical()) {
return Math.abs(startPoint.getTop() - endPoint.getTop());
} else {
return Math.abs(startPoint.getLeft() - endPoint.getLeft());
}
}
public void makeNotDragable() {
this.sectionDragController.makeNotDraggable(this);
}
public int getCurrentTop() {
WidgetLocation location = new WidgetLocation(this, this.getParent());
if (isHorizontal()) {
return location.getTop() + TRANSPARENT_MARGIN_SIZE;
} else {
return location.getTop();
}
}
public int getCurrentLeft() {
WidgetLocation location = new WidgetLocation(this, this.getParent());
if (isVertical()) {
return location.getLeft() + TRANSPARENT_MARGIN_SIZE;
} else {
return location.getLeft();
}
}
public void setPosition(int left, int top) {
updateEndPointsPositions(left, top);
updateWidgetPosition();
if (startPointDecoration != null) {
startPointDecoration.update(calculateStartPointDecorationDirection(),
startPoint.getLeft(), startPoint.getTop());
}
if (endPointDecoration != null) {
endPointDecoration.update(calculateEndPointDecorationDirection(),
endPoint.getLeft(), endPoint.getTop());
}
}
/**
* Updates start and end point position after {@link Shape} move
* @param sectionLeft the left position
* @param sectionTop the top position
*/
public void updateEndPointsPositions(int sectionLeft, int sectionTop) {
Position startPosition = new Position();
Position endPosition = new Position();
int length = getLength();
if (isHorizontal()) {
if (startPoint.getLeft() < endPoint.getLeft()) {
startPosition.setLeft(sectionLeft);
endPosition.setLeft(sectionLeft + length);
} else {
startPosition.setLeft(sectionLeft + length);
endPosition.setLeft(sectionLeft);
}
startPosition.setTop(sectionTop);
endPosition.setTop(sectionTop);
} else {
if (startPoint.getTop() < endPoint.getTop()) {
startPosition.setTop(sectionTop);
endPosition.setTop(sectionTop + length);
} else {
startPosition.setTop(sectionTop + length);
endPosition.setTop(sectionTop);
}
startPosition.setLeft(sectionLeft);
endPosition.setLeft(sectionLeft);
}
}
public void updateWidgetPosition() {
updateWidgetPosition(isHorizontal());
}
/**
* Updates {@link Shape} position on boundary panel based on start and end points.
* @param horizontal true if section is horizontal
*/
public void updateWidgetPosition(boolean horizontal) {
if (horizontal) {
WidgetUtils.setWidgetPosition(((AbsolutePanel) this.getParent()), this,
Math.min(this.startPoint.getLeft(), this.endPoint.getLeft()),
this.startPoint.getTop() - TRANSPARENT_MARGIN_SIZE);
} else {
WidgetUtils.setWidgetPosition(((AbsolutePanel) this.getParent()), this,
this.startPoint.getLeft() - TRANSPARENT_MARGIN_SIZE,
Math.min(this.startPoint.getTop(), this.endPoint.getTop()));
}
}
public String toDebugString() {
StringBuilder builder = new StringBuilder();
builder.append("Start : ");
builder.append("top-");
builder.append(startPoint.getTop());
builder.append(" left-");
builder.append(startPoint.getLeft());
builder.append(" End : ");
builder.append("top-");
builder.append(endPoint.getTop());
builder.append(" left-");
builder.append(endPoint.getLeft());
builder.append(" isHorizontal-");
builder.append(isHorizontal());
return builder.toString();
}
}
| 37.535948 | 135 | 0.658135 |
63ca2fea6535bb4d65c7476fa83ba533ed1264b6 | 13,165 | /*
* Copyright 2012-2016 JetBrains s.r.o
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.jetpad.projectional.svg;
import jetbrains.jetpad.values.Color;
public abstract class SvgColor {
public static final SvgColor ALICE_BLUE = new SvgColorKeyword("aliceblue");
public static final SvgColor ANTIQUE_WHITE = new SvgColorKeyword("antiquewhite");
public static final SvgColor AQUA = new SvgColorKeyword("aqua");
public static final SvgColor AQUAMARINE = new SvgColorKeyword("aquamarine");
public static final SvgColor AZURE = new SvgColorKeyword("azure");
public static final SvgColor BEIGE = new SvgColorKeyword("beige");
public static final SvgColor BISQUE = new SvgColorKeyword("bisque");
public static final SvgColor BLACK = new SvgColorKeyword("black");
public static final SvgColor BLANCHED_ALMOND = new SvgColorKeyword("blanchedalmond");
public static final SvgColor BLUE = new SvgColorKeyword("blue");
public static final SvgColor BLUE_VIOLET = new SvgColorKeyword("blueviolet");
public static final SvgColor BROWN = new SvgColorKeyword("brown");
public static final SvgColor BURLY_WOOD = new SvgColorKeyword("burlywood");
public static final SvgColor CADET_BLUE = new SvgColorKeyword("cadetblue");
public static final SvgColor CHARTREUSE = new SvgColorKeyword("chartreuse");
public static final SvgColor CHOCOLATE = new SvgColorKeyword("chocolate");
public static final SvgColor CORAL = new SvgColorKeyword("coral");
public static final SvgColor CORNFLOWER_BLUE = new SvgColorKeyword("cornflowerblue");
public static final SvgColor CORNSILK = new SvgColorKeyword("cornsilk");
public static final SvgColor CRIMSON = new SvgColorKeyword("crimson");
public static final SvgColor CYAN = new SvgColorKeyword("cyan");
public static final SvgColor DARK_BLUE = new SvgColorKeyword("darkblue");
public static final SvgColor DARK_CYAN = new SvgColorKeyword("darkcyan");
public static final SvgColor DARK_GOLDEN_ROD = new SvgColorKeyword("darkgoldenrod");
public static final SvgColor DARK_GRAY = new SvgColorKeyword("darkgray");
public static final SvgColor DARK_GREEN = new SvgColorKeyword("darkgreen");
public static final SvgColor DARK_GREY = new SvgColorKeyword("darkgrey");
public static final SvgColor DARK_KHAKI = new SvgColorKeyword("darkkhaki");
public static final SvgColor DARK_MAGENTA = new SvgColorKeyword("darkmagenta");
public static final SvgColor DARK_OLIVE_GREEN = new SvgColorKeyword("darkolivegreen");
public static final SvgColor DARK_ORANGE = new SvgColorKeyword("darkorange");
public static final SvgColor DARK_ORCHID = new SvgColorKeyword("darkorchid");
public static final SvgColor DARK_RED = new SvgColorKeyword("darkred");
public static final SvgColor DARK_SALMON = new SvgColorKeyword("darksalmon");
public static final SvgColor DARK_SEA_GREEN = new SvgColorKeyword("darkseagreen");
public static final SvgColor DARK_SLATE_BLUE = new SvgColorKeyword("darkslateblue");
public static final SvgColor DARK_SLATE_GRAY = new SvgColorKeyword("darkslategray");
public static final SvgColor DARK_SLATE_GREY = new SvgColorKeyword("darkslategrey");
public static final SvgColor DARK_TURQUOISE = new SvgColorKeyword("darkturquoise");
public static final SvgColor DARK_VIOLET = new SvgColorKeyword("darkviolet");
public static final SvgColor DEEP_PINK = new SvgColorKeyword("deeppink");
public static final SvgColor DEEP_SKY_BLUE = new SvgColorKeyword("deepskyblue");
public static final SvgColor DIM_GRAY = new SvgColorKeyword("dimgray");
public static final SvgColor DIM_GREY = new SvgColorKeyword("dimgrey");
public static final SvgColor DODGER_BLUE = new SvgColorKeyword("dodgerblue");
public static final SvgColor FIRE_BRICK = new SvgColorKeyword("firebrick");
public static final SvgColor FLORAL_WHITE = new SvgColorKeyword("floralwhite");
public static final SvgColor FOREST_GREEN = new SvgColorKeyword("forestgreen");
public static final SvgColor FUCHSIA = new SvgColorKeyword("fuchsia");
public static final SvgColor GAINSBORO = new SvgColorKeyword("gainsboro");
public static final SvgColor GHOST_WHITE = new SvgColorKeyword("ghostwhite");
public static final SvgColor GOLD = new SvgColorKeyword("gold");
public static final SvgColor GOLDEN_ROD = new SvgColorKeyword("goldenrod");
public static final SvgColor GRAY = new SvgColorKeyword("gray");
public static final SvgColor GREY = new SvgColorKeyword("grey");
public static final SvgColor GREEN = new SvgColorKeyword("green");
public static final SvgColor GREEN_YELLOW = new SvgColorKeyword("greenyellow");
public static final SvgColor HONEY_DEW = new SvgColorKeyword("honeydew");
public static final SvgColor HOT_PINK = new SvgColorKeyword("hotpink");
public static final SvgColor INDIAN_RED = new SvgColorKeyword("indianred");
public static final SvgColor INDIGO = new SvgColorKeyword("indigo");
public static final SvgColor IVORY = new SvgColorKeyword("ivory");
public static final SvgColor KHAKI = new SvgColorKeyword("khaki");
public static final SvgColor LAVENDER = new SvgColorKeyword("lavender");
public static final SvgColor LAVENDER_BLUSH = new SvgColorKeyword("lavenderblush");
public static final SvgColor LAWN_GREEN = new SvgColorKeyword("lawngreen");
public static final SvgColor LEMON_CHIFFON = new SvgColorKeyword("lemonchiffon");
public static final SvgColor LIGHT_BLUE = new SvgColorKeyword("lightblue");
public static final SvgColor LIGHT_CORAL = new SvgColorKeyword("lightcoral");
public static final SvgColor LIGHT_CYAN = new SvgColorKeyword("lightcyan");
public static final SvgColor LIGHT_GOLDEN_ROD_YELLOW = new SvgColorKeyword("lightgoldenrodyellow");
public static final SvgColor LIGHT_GRAY = new SvgColorKeyword("lightgray");
public static final SvgColor LIGHT_GREEN = new SvgColorKeyword("lightgreen");
public static final SvgColor LIGHT_GREY = new SvgColorKeyword("lightgrey");
public static final SvgColor LIGHT_PINK = new SvgColorKeyword("lightpink");
public static final SvgColor LIGHT_SALMON = new SvgColorKeyword("lightsalmon");
public static final SvgColor LIGHT_SEA_GREEN = new SvgColorKeyword("lightseagreen");
public static final SvgColor LIGHT_SKY_BLUE = new SvgColorKeyword("lightskyblue");
public static final SvgColor LIGHT_SLATE_GRAY = new SvgColorKeyword("lightslategray");
public static final SvgColor LIGHT_SLATE_GREY = new SvgColorKeyword("lightslategrey");
public static final SvgColor LIGHT_STEEL_BLUE = new SvgColorKeyword("lightsteelblue");
public static final SvgColor LIGHT_YELLOW = new SvgColorKeyword("lightyellow");
public static final SvgColor LIME = new SvgColorKeyword("lime");
public static final SvgColor LIME_GREEN = new SvgColorKeyword("limegreen");
public static final SvgColor LINEN = new SvgColorKeyword("linen");
public static final SvgColor MAGENTA = new SvgColorKeyword("magenta");
public static final SvgColor MAROON = new SvgColorKeyword("maroon");
public static final SvgColor MEDIUM_AQUA_MARINE = new SvgColorKeyword("mediumaquamarine");
public static final SvgColor MEDIUM_BLUE = new SvgColorKeyword("mediumblue");
public static final SvgColor MEDIUM_ORCHID = new SvgColorKeyword("mediumorchid");
public static final SvgColor MEDIUM_PURPLE = new SvgColorKeyword("mediumpurple");
public static final SvgColor MEDIUM_SEAGREEN = new SvgColorKeyword("mediumseagreen");
public static final SvgColor MEDIUM_SLATE_BLUE = new SvgColorKeyword("mediumslateblue");
public static final SvgColor MEDIUM_SPRING_GREEN = new SvgColorKeyword("mediumspringgreen");
public static final SvgColor MEDIUM_TURQUOISE = new SvgColorKeyword("mediumturquoise");
public static final SvgColor MEDIUM_VIOLET_RED = new SvgColorKeyword("mediumvioletred");
public static final SvgColor MIDNIGHT_BLUE = new SvgColorKeyword("midnightblue");
public static final SvgColor MINT_CREAM = new SvgColorKeyword("mintcream");
public static final SvgColor MISTY_ROSE = new SvgColorKeyword("mistyrose");
public static final SvgColor MOCCASIN = new SvgColorKeyword("moccasin");
public static final SvgColor NAVAJO_WHITE = new SvgColorKeyword("navajowhite");
public static final SvgColor NAVY = new SvgColorKeyword("navy");
public static final SvgColor OLD_LACE = new SvgColorKeyword("oldlace");
public static final SvgColor OLIVE = new SvgColorKeyword("olive");
public static final SvgColor OLIVE_DRAB = new SvgColorKeyword("olivedrab");
public static final SvgColor ORANGE = new SvgColorKeyword("orange");
public static final SvgColor ORANGE_RED = new SvgColorKeyword("orangered");
public static final SvgColor ORCHID = new SvgColorKeyword("orchid");
public static final SvgColor PALE_GOLDEN_ROD = new SvgColorKeyword("palegoldenrod");
public static final SvgColor PALE_GREEN = new SvgColorKeyword("palegreen");
public static final SvgColor PALE_TURQUOISE = new SvgColorKeyword("paleturquoise");
public static final SvgColor PALE_VIOLET_RED = new SvgColorKeyword("palevioletred");
public static final SvgColor PAPAYA_WHIP = new SvgColorKeyword("papayawhip");
public static final SvgColor PEACH_PUFF = new SvgColorKeyword("peachpuff");
public static final SvgColor PERU = new SvgColorKeyword("peru");
public static final SvgColor PINK = new SvgColorKeyword("pink");
public static final SvgColor PLUM = new SvgColorKeyword("plum");
public static final SvgColor POWDER_BLUE = new SvgColorKeyword("powderblue");
public static final SvgColor PURPLE = new SvgColorKeyword("purple");
public static final SvgColor RED = new SvgColorKeyword("red");
public static final SvgColor ROSY_BROWN = new SvgColorKeyword("rosybrown");
public static final SvgColor ROYAL_BLUE = new SvgColorKeyword("royalblue");
public static final SvgColor SADDLE_BROWN = new SvgColorKeyword("saddlebrown");
public static final SvgColor SALMON = new SvgColorKeyword("salmon");
public static final SvgColor SANDY_BROWN = new SvgColorKeyword("sandybrown");
public static final SvgColor SEA_GREEN = new SvgColorKeyword("seagreen");
public static final SvgColor SEASHELL = new SvgColorKeyword("seashell");
public static final SvgColor SIENNA = new SvgColorKeyword("sienna");
public static final SvgColor SILVER = new SvgColorKeyword("silver");
public static final SvgColor SKY_BLUE = new SvgColorKeyword("skyblue");
public static final SvgColor SLATE_BLUE = new SvgColorKeyword("slateblue");
public static final SvgColor SLATE_GRAY = new SvgColorKeyword("slategray");
public static final SvgColor SLATE_GREY = new SvgColorKeyword("slategrey");
public static final SvgColor SNOW = new SvgColorKeyword("snow");
public static final SvgColor SPRING_GREEN = new SvgColorKeyword("springgreen");
public static final SvgColor STEEL_BLUE = new SvgColorKeyword("steelblue");
public static final SvgColor TAN = new SvgColorKeyword("tan");
public static final SvgColor TEAL = new SvgColorKeyword("teal");
public static final SvgColor THISTLE = new SvgColorKeyword("thistle");
public static final SvgColor TOMATO = new SvgColorKeyword("tomato");
public static final SvgColor TURQUOISE = new SvgColorKeyword("turquoise");
public static final SvgColor VIOLET = new SvgColorKeyword("violet");
public static final SvgColor WHEAT = new SvgColorKeyword("wheat");
public static final SvgColor WHITE = new SvgColorKeyword("white");
public static final SvgColor WHITE_SMOKE = new SvgColorKeyword("whitesmoke");
public static final SvgColor YELLOW = new SvgColorKeyword("yellow");
public static final SvgColor YELLOW_GREEN = new SvgColorKeyword("yellowgreen");
public static final SvgColor NONE = new SvgColorKeyword("none");
public static final SvgColor CURRENT_COLOR = new SvgColorKeyword("currentColor");
public static SvgColor create(int r, int g, int b) {
return new SvgColorRgb(r, g, b);
}
public static SvgColor create(Color color) {
if (color == null) {
return NONE;
}
return new SvgColorRgb(color.getRed(), color.getGreen(), color.getBlue());
}
private SvgColor() {
}
private static class SvgColorRgb extends SvgColor {
private final int myR;
private final int myG;
private final int myB;
SvgColorRgb(int r, int g, int b) {
myR = r;
myG = g;
myB = b;
}
@Override
public String toString() {
return "rgb(" + myR + "," + myG + "," + myB + ")";
}
}
private static class SvgColorKeyword extends SvgColor {
private String myLiteral;
SvgColorKeyword(String literal) {
myLiteral = literal;
}
@Override
public String toString() {
return myLiteral;
}
}
} | 60.949074 | 101 | 0.777744 |
9bfc31f80d4b347f23408b503a406764668eeccd | 12,854 | package com.brandon3055.draconicevolution.client.gui.componentguis;
import com.brandon3055.brandonscore.client.gui.guicomponents.*;
import com.brandon3055.brandonscore.client.utills.GuiHelper;
import com.brandon3055.brandonscore.common.utills.Utills;
import com.brandon3055.draconicevolution.client.handler.ResourceHandler;
import com.brandon3055.draconicevolution.common.container.ContainerReactor;
import com.brandon3055.draconicevolution.common.tileentities.multiblocktiles.reactor.TileReactorCore;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
/**
* Created by brandon3055 on 30/7/2015.
*/
public class GUIReactor extends GUIBase {
private TileReactorCore reactor;
private ContainerReactor container;
private static boolean showStats = false;
public GUIReactor(EntityPlayer player, TileReactorCore reactor, ContainerReactor container) {
super(container, 248, 222);
this.reactor = reactor;
this.container = container;
}
@Override
protected ComponentCollection assembleComponents() {
collection = new ComponentCollection(0, 0, 248, 222, this);
collection.addComponent(new ComponentTexturedRect(0, 0, xSize, ySize, ResourceHandler.getResource("textures/gui/Reactor.png")));
collection.addComponent(new ComponentTextureButton(14, 190, 18, 162, 18, 18, 0, this, "", StatCollector.translateToLocal("button.de.reactorCharge.txt"), ResourceHandler.getResource("textures/gui/Widgets.png"))).setName("CHARGE");
collection.addComponent(new ComponentTextureButton(14, 190, 18, 54, 18, 18, 1, this, "", StatCollector.translateToLocal("button.de.reactorStart.txt"), ResourceHandler.getResource("textures/gui/Widgets.png"))).setName("ACTIVATE");
collection.addComponent(new ComponentTextureButton(216, 190, 18, 108, 18, 18, 2, this, "", StatCollector.translateToLocal("button.de.reactorStop.txt"), ResourceHandler.getResource("textures/gui/Widgets.png"))).setName("DEACTIVATE");
collection.addComponent(new ComponentButton(9, 120, 43, 15, 3, this, StatCollector.translateToLocal("button.de.stats.txt"), StatCollector.translateToLocal("button.de.statsShow.txt"))).setName("STATS");
return collection;
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) {
super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY);
//Draw I/O Slots
if (reactor.reactorState == TileReactorCore.STATE_OFFLINE) {
RenderHelper.enableGUIStandardItemLighting();
drawTexturedModalRect(guiLeft + 14, guiTop + 139, 14, ySize, 18, 18);
drawTexturedModalRect(guiLeft + 216, guiTop + 139, 32, ySize, 18, 18);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.insert.txt"), guiLeft + 8, guiTop + 159, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.fuel.txt"), guiLeft + 13, guiTop + 168, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.extract.txt"), guiLeft + 206, guiTop + 159, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.fuel.txt"), guiLeft + 215, guiTop + 168, 0);
}
drawCenteredString(fontRendererObj, "Draconic Reactor", guiLeft + xSize / 2, guiTop + 4, 0x00FFFF);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
ResourceHandler.bindResource("textures/gui/Reactor.png");
GL11.glColor4f(1f, 1f, 1f, 1f);
//Draw Indicators
double value = Math.min(reactor.reactionTemperature, reactor.maxReactTemperature) / reactor.maxReactTemperature;
int pixOffset = (int) (value * 108);
drawTexturedModalRect(11, 112 - pixOffset, 0, 222, 14, 5);
value = reactor.fieldCharge / reactor.maxFieldCharge;
pixOffset = (int) (value * 108);
drawTexturedModalRect(35, 112 - pixOffset, 0, 222, 14, 5);
value = (double) reactor.energySaturation / (double) reactor.maxEnergySaturation;
pixOffset = (int) (value * 108);
drawTexturedModalRect(199, 112 - pixOffset, 0, 222, 14, 5);
value = ((double) reactor.convertedFuel) / ((double) reactor.reactorFuel + (double) reactor.convertedFuel);
pixOffset = (int) (value * 108);
drawTexturedModalRect(223, 112 - pixOffset, 0, 222, 14, 5);
GL11.glColor4f(1F, 1F, 1F, 1F);
if (!showStats) {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glTranslated(124, 71, 100);
double scale = 100 / (reactor.getCoreDiameter());
GL11.glScaled(scale, scale, scale);
GL11.glColor4f(1F, 1F, 1F, 1F);
GL11.glDisable(GL11.GL_CULL_FACE);
TileEntityRendererDispatcher.instance.renderTileEntityAt(reactor, -0.5D, -0.5D, -0.5D, 0.0F);
GL11.glPopAttrib();
GL11.glPopMatrix();
} else {
ResourceHandler.bindResource("textures/gui/Reactor.png");
for (int i = 1; i <= 10; i++) drawTexturedModalRect(63, i * 12, 0, 240, 122, 16);
drawStats();
}
String status = StatCollector.translateToLocal("gui.de.status.txt") + ": " + (reactor.reactorState == 0 ? EnumChatFormatting.DARK_GRAY : reactor.reactorState == 1 ? EnumChatFormatting.RED : reactor.reactorState == 2 ? EnumChatFormatting.DARK_GREEN : EnumChatFormatting.RED) + StatCollector.translateToLocal("gui.de.status" + reactor.reactorState + ".txt");
if (reactor.reactorState == 1 && reactor.canStart())
status = StatCollector.translateToLocal("gui.de.status.txt") + ": " + EnumChatFormatting.DARK_GREEN + StatCollector.translateToLocal("gui.de.status1_5.txt");
if (!showStats) fontRendererObj.drawString(status, xSize - 5 - fontRendererObj.getStringWidth(status), 125, 0);
}
@Override
public void drawScreen(int mouseX, int mouseY, float par3) {
super.drawScreen(mouseX, mouseY, par3);
List<String> text = new ArrayList<String>();
if (GuiHelper.isInRect(9, 4, 18, 114, mouseX - guiLeft, mouseY - guiTop)) {
text.add(StatCollector.translateToLocal("gui.de.reactionTemp.txt"));
text.add((int) reactor.reactionTemperature + "C");
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(33, 4, 18, 114, mouseX - guiLeft, mouseY - guiTop)) {
text.add(StatCollector.translateToLocal("gui.de.fieldStrength.txt"));
if (reactor.maxFieldCharge > 0)
text.add(Utills.round(reactor.fieldCharge / reactor.maxFieldCharge * 100D, 100D) + "%");
text.add(Utills.addCommas((int) reactor.fieldCharge) + " / " + Utills.addCommas((int) reactor.maxFieldCharge)); //todo refine or remove
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(197, 4, 18, 114, mouseX - guiLeft, mouseY - guiTop)) {
text.add(StatCollector.translateToLocal("gui.de.energySaturation.txt"));
if (reactor.maxEnergySaturation > 0)
text.add(Utills.round((double) reactor.energySaturation / (double) reactor.maxEnergySaturation * 100D, 100D) + "%");
text.add(Utills.addCommas(reactor.energySaturation) + " / " + Utills.addCommas(reactor.maxEnergySaturation)); //todo refine or remove
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(221, 4, 18, 114, mouseX - guiLeft, mouseY - guiTop)) {
text.add(StatCollector.translateToLocal("gui.de.fuelConversion.txt"));
if (reactor.reactorFuel + reactor.convertedFuel > 0)
text.add(Utills.round(((double) reactor.convertedFuel + reactor.conversionUnit) / ((double) reactor.convertedFuel + (double) reactor.reactorFuel) * 100D, 100D) + "%");
text.add(reactor.convertedFuel + " / " + (reactor.convertedFuel + reactor.reactorFuel)); //todo refine or remove
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
}
if (showStats) {
if (GuiHelper.isInRect(53, 15, 140, 18, mouseX - guiLeft, mouseY - guiTop)) {
text.addAll(fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal("gui.de.reacTempLoadFactor.txt"), 200));
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(53, 40, 140, 18, mouseX - guiLeft, mouseY - guiTop)) {
text.addAll(fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal("gui.de.reacCoreMass.txt"), 200));
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(53, 65, 140, 18, mouseX - guiLeft, mouseY - guiTop)) {
text.addAll(fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal("gui.de.reacGenRate.txt"), 200));
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(53, 88, 140, 18, mouseX - guiLeft, mouseY - guiTop)) {
text.addAll(fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal("gui.de.reacInputRate.txt"), 200));
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
} else if (GuiHelper.isInRect(53, 113, 140, 18, mouseX - guiLeft, mouseY - guiTop)) {
text.addAll(fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal("gui.de.reacConversionRate.txt"), 200));
drawHoveringText(text, mouseX, mouseY, fontRendererObj);
}
}
}
private void drawStats() {
double inputRate = reactor.fieldDrain / (1D - (reactor.fieldCharge / reactor.maxFieldCharge));
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.tempLoad.name"), 55, 16, 0x0000FF);
fontRendererObj.drawString(Utills.round(reactor.tempDrainFactor * 100D, 1D) + "%", 60, 2 + 24, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.mass.name"), 55, 16 + 24, 0x0000FF);
fontRendererObj.drawString(Utills.round((reactor.reactorFuel + reactor.convertedFuel) / 1296D, 100) + "m^3", 60, 2 + 2 * 24, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.genRate.name"), 55, 16 + 2 * 24, 0x0000FF);
fontRendererObj.drawString(Utills.addCommas((int) reactor.generationRate) + "RF/t", 60, 2 + 3 * 24, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.fieldInputRate.name"), 55, 16 + 3 * 24, 0x0000FF);
fontRendererObj.drawString(Utills.addCommas((int) Math.min(inputRate, Integer.MAX_VALUE)) + "RF/t", 60, 2 + 4 * 24, 0);
fontRendererObj.drawString(StatCollector.translateToLocal("gui.de.fuelConversion.name"), 55, 16 + 4 * 24, 0x0000FF);
fontRendererObj.drawString(Utills.addCommas((int) Math.round(reactor.fuelUseRate * 1000000D)) + "nb/t", 60, 2 + 5 * 24, 0);
}
@Override
public void updateScreen() {
if (reactor.reactorState == TileReactorCore.STATE_INVALID || reactor.reactorState == TileReactorCore.STATE_OFFLINE || reactor.reactorState == TileReactorCore.STATE_STOP)
collection.getComponent("DEACTIVATE").setEnabled(false);
else collection.getComponent("DEACTIVATE").setEnabled(true);
if ((reactor.reactorState == TileReactorCore.STATE_OFFLINE || (reactor.reactorState == TileReactorCore.STATE_STOP && !reactor.canStart())) && reactor.canCharge())
collection.getComponent("CHARGE").setEnabled(true);
else collection.getComponent("CHARGE").setEnabled(false);
if ((reactor.reactorState == TileReactorCore.STATE_START || reactor.reactorState == TileReactorCore.STATE_STOP) && reactor.canStart())
collection.getComponent("ACTIVATE").setEnabled(true);
else collection.getComponent("ACTIVATE").setEnabled(false);
super.updateScreen();
}
@Override
public void buttonClicked(int id, int button) {
super.buttonClicked(id, button);
if (id < 3) container.sendObjectToServer(null, 20, id);
else if (id == 3) {
showStats = !showStats;
((ComponentButton) collection.getComponent("STATS")).hoverText = showStats ? StatCollector.translateToLocal("button.de.statsHide.txt") : StatCollector.translateToLocal("button.de.statsShow.txt");
}
}
}
| 63.950249 | 364 | 0.687179 |
117c9a276b41377cf2b6611a314f141892cffd63 | 1,833 | package org.mapfish.print.map.geotools.function;
import org.geotools.filter.FunctionExpressionImpl;
import org.geotools.filter.capability.FunctionNameImpl;
import org.opengis.filter.capability.FunctionName;
import static org.geotools.filter.capability.FunctionNameImpl.parameter;
/**
* A Function that multiplies the two values.
*/
public final class MultiplicationFunction extends FunctionExpressionImpl {
/**
* The name of this function.
*/
public static final FunctionName NAME = new FunctionNameImpl("multiplication",
parameter("result", Double.class),
parameter("value1", Double.class),
parameter("value2", Double.class));
/**
* Default constructor.
*/
public MultiplicationFunction() {
super(NAME);
}
@Override
public Object evaluate(final Object feature) {
double value1;
double value2;
try { // attempt to get value and perform conversion
value1 = (getExpression(0).evaluate(feature, Double.class));
} catch (Exception e) {
// probably a type error
throw new IllegalArgumentException(
"Filter Function problem for function abs argument #0 - expected type double");
}
try { // attempt to get value and perform conversion
value2 = (getExpression(1).evaluate(feature, Double.class));
} catch (Exception e) {
// probably a type error
throw new IllegalArgumentException(
"Filter Function problem for function abs argument #1 - expected type double");
}
return value1 * value2;
}
}
| 35.25 | 100 | 0.588652 |
5ac37714ba5151e2795be20d9b33a75e27950ca6 | 1,533 | package ru.sftqa.pft.addressbook.model;
public class ContactData {
private final String firstName;
private final String middleName;
private final String lastName;
private final String nickName;
private final String title;
private final String company;
private final String address;
private final String homePhone;
private final String mobilePhone;
private final String email;
private final String group;
public ContactData(String firstName, String middleName, String lastName, String nickName, String title, String company, String address, String homePhone, String mobilePhone, String email, String group) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.nickName = nickName;
this.title = title;
this.company = company;
this.address = address;
this.homePhone = homePhone;
this.mobilePhone = mobilePhone;
this.email = email;
this.group = group;
}
public String getfirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getNickName() {
return nickName;
}
public String getTitle(){return title;}
public String getCompany(){return company;}
public String getAddress() {return address;}
public String getHomePhone() {return homePhone;}
public String getMobilePhone(){return mobilePhone;}
public String getEmail() {return email;}
public String getGroup() {
return group;
}
}
| 28.924528 | 205 | 0.727332 |
6ce8bfe711f78807b6ca35cfe2833d65221e4510 | 2,824 | /*
* Copyright 2018 Braden Hitchcock
*
* 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.github.bradenhc.querybaker.sql;
import static io.github.bradenhc.querybaker.cond.Condition.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.github.bradenhc.querybaker.sql.Column;
import io.github.bradenhc.querybaker.sql.DataType;
import io.github.bradenhc.querybaker.sql.Select;
import io.github.bradenhc.querybaker.sql.Table;
class TableTest {
private String mTableName;
private String mTableAlias;
private Column mCol1;
private Column mCol2;
private Column mCol3;
private Table mTable;
@BeforeEach
void setup() {
mTableName = "test_table";
mTableAlias = "tt";
mCol1 = new Column("column_1", DataType.INTEGER, 1, true, true);
mCol2 = new Column("column_2", DataType.VARCHAR, 255, true);
mCol3 = new Column("column_3", DataType.DATE, 1);
mTable = Table.create(mTableName).alias(mTableAlias).columns(mCol1, mCol2, mCol3);
}
@Test
void test() {
String expected = String.format("CREATE TABLE %s (%s, %s, %s);", mTableName, mCol1, mCol2, mCol3);
String actual = mTable.build();
System.out.println(actual);
assertEquals(expected, actual);
}
@Test
void testTableSelect() {
Select s = mTable.select().columns(mCol1, mCol2);
String expected = String.format("SELECT %s, %s FROM %s %s", mCol1.alias(), mCol2.alias(), mTableName,
mTableAlias);
String actual = s.build();
System.out.println(actual);
assertEquals(expected, actual);
// Remove the alias
mTable.alias(null);
s = mTable.select().columns(mCol1, mCol2);
expected = String.format("SELECT %s, %s FROM %s", mCol1.name(), mCol2.name(), mTableName);
actual = s.build();
System.out.println(actual);
assertEquals(expected, actual);
}
@Test
void testTablesSelectWithAliasedWhere() {
String date = "2018-1-1";
Select s = mTable.select().all().where(and(equal(mCol1, 24), not(lessThan(mCol3, date))));
String expected = String.format("SELECT %s* FROM %s %s WHERE (%s = 24 AND NOT (%s < \"%s\"))",
mTableAlias + ".", mTableName, mTableAlias, mCol1.alias(), mCol3.alias(), date);
String actual = s.build();
System.out.println(actual);
assertEquals(expected, actual);
}
}
| 27.153846 | 103 | 0.709278 |
64461ea7fd5084967fbd3b33bb11c608bcbb0e8a | 16,309 | package voldemort.store.routed;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static voldemort.VoldemortTestConstants.getEightNodeClusterWithZones;
import static voldemort.VoldemortTestConstants.getFourNodeClusterWithZones;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import org.junit.Before;
import org.junit.Test;
import voldemort.TestUtils;
import voldemort.client.RoutingTier;
import voldemort.client.TimeoutConfig;
import voldemort.consistency.cluster.Cluster;
import voldemort.consistency.cluster.Node;
import voldemort.cluster.failuredetector.NoopFailureDetector;
import voldemort.routing.RoutingStrategyType;
import voldemort.serialization.SerializerDefinition;
import voldemort.store.Store;
import voldemort.store.StoreDefinition;
import voldemort.store.StoreDefinitionBuilder;
import voldemort.store.memory.InMemoryStorageConfiguration;
import voldemort.store.memory.InMemoryStorageEngine;
import voldemort.consistency.utils.ByteArray;
import voldemort.consistency.versioning.Versioned;
import com.google.common.collect.Maps;
public class GetallNodeReachTest {
private Cluster cluster;
private StoreDefinition storeDef;
private RoutedStore store;
Map<Integer, Store<ByteArray, byte[], byte[]>> subStores;
@Before
public void setUp() throws Exception {}
private void makeStore() {
subStores = Maps.newHashMap();
for(Node n: cluster.getNodes()) {
Store<ByteArray, byte[], byte[]> subStore = new InMemoryStorageEngine<ByteArray, byte[], byte[]>("test");
subStores.put(n.getId(), subStore);
}
RoutedStoreFactory routedStoreFactory = new RoutedStoreFactory(Executors.newFixedThreadPool(2));
store = routedStoreFactory.create(cluster,
storeDef,
subStores,
new NoopFailureDetector(),
new RoutedStoreConfig().setTimeoutConfig(new TimeoutConfig(1000L)));
}
@Test
public void testGetallTouchOneZone() throws Exception {
cluster = getFourNodeClusterWithZones();
HashMap<Integer, Integer> zoneReplicationFactor = new HashMap<Integer, Integer>();
zoneReplicationFactor.put(0, 2);
zoneReplicationFactor.put(1, 1);
zoneReplicationFactor.put(2, 1);
storeDef = new StoreDefinitionBuilder().setName("test")
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setRoutingPolicy(RoutingTier.CLIENT)
.setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY)
.setReplicationFactor(4)
.setZoneReplicationFactor(zoneReplicationFactor)
.setKeySerializer(new SerializerDefinition("string"))
.setValueSerializer(new SerializerDefinition("string"))
.setPreferredReads(2)
.setRequiredReads(1)
.setPreferredWrites(1)
.setRequiredWrites(1)
.setZoneCountReads(0)
.setZoneCountWrites(0)
.build();
makeStore();
Versioned<byte[]> v = Versioned.value("v".getBytes());
subStores.get(0).put(TestUtils.toByteArray("k011_zone0_only"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k011_zone0_only"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k100_zone1_only"), v, null);
/* test single key getall */
List<ByteArray> keys011 = new ArrayList<ByteArray>();
keys011.add(TestUtils.toByteArray("k011_zone0_only"));
List<ByteArray> keys100 = new ArrayList<ByteArray>();
keys100.add(TestUtils.toByteArray("k100_zone1_only"));
assertEquals(2, store.getAll(keys011, null)
.get(TestUtils.toByteArray("k011_zone0_only"))
.size());
assertFalse(store.getAll(keys100, null)
.containsKey(TestUtils.toByteArray("k100_zone1_only")));
/* test multiple keys getall */
List<ByteArray> keys = new ArrayList<ByteArray>();
keys.add(TestUtils.toByteArray("k011_zone0_only"));
keys.add(TestUtils.toByteArray("k100_zone1_only"));
Map<ByteArray, List<Versioned<byte[]>>> result = store.getAll(keys, null);
assertEquals(2, result.get(TestUtils.toByteArray("k011_zone0_only")).size());
assertFalse(result.containsKey(TestUtils.toByteArray("k100_zone1_only")));
}
@Test
public void testGetall_211() throws Exception {
cluster = getFourNodeClusterWithZones();
HashMap<Integer, Integer> zoneReplicationFactor = new HashMap<Integer, Integer>();
zoneReplicationFactor.put(0, 2);
zoneReplicationFactor.put(1, 1);
zoneReplicationFactor.put(2, 1);
storeDef = new StoreDefinitionBuilder().setName("test")
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setRoutingPolicy(RoutingTier.CLIENT)
.setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY)
.setReplicationFactor(4)
.setZoneReplicationFactor(zoneReplicationFactor)
.setKeySerializer(new SerializerDefinition("string"))
.setValueSerializer(new SerializerDefinition("string"))
.setPreferredReads(1)
.setRequiredReads(1)
.setPreferredWrites(1)
.setRequiredWrites(1)
.setZoneCountReads(0)
.setZoneCountWrites(0)
.build();
makeStore();
Versioned<byte[]> v = Versioned.value("v".getBytes());
// k### indicates existence of itself in different nodes
// k**1 means this key exists at least on node 0
// k*1* means this key exists at least on node 1
// k0** means this key does not exist on node 2
subStores.get(0).put(TestUtils.toByteArray("k001"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k011"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k101"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k111"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k010"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k011"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k110"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k111"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k100"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k101"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k110"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k111"), v, null);
/* test multiple keys getall */
List<ByteArray> keys = new ArrayList<ByteArray>();
keys.add(TestUtils.toByteArray("k000"));
keys.add(TestUtils.toByteArray("k001"));
keys.add(TestUtils.toByteArray("k010"));
keys.add(TestUtils.toByteArray("k011"));
keys.add(TestUtils.toByteArray("k100"));
keys.add(TestUtils.toByteArray("k101"));
keys.add(TestUtils.toByteArray("k110"));
keys.add(TestUtils.toByteArray("k111"));
Map<ByteArray, List<Versioned<byte[]>>> result = store.getAll(keys, null);
assertFalse(result.containsKey(TestUtils.toByteArray("not_included")));
assertFalse(result.containsKey(TestUtils.toByteArray("k000")));
assertEquals(1, result.get(TestUtils.toByteArray("k011")).size());
assertFalse(result.containsKey(TestUtils.toByteArray("k100")));
assertEquals(1, result.get(TestUtils.toByteArray("k111")).size());
}
@Test
public void testGetall_211_zoneCountRead_1() throws Exception {
cluster = getFourNodeClusterWithZones();
HashMap<Integer, Integer> zoneReplicationFactor = new HashMap<Integer, Integer>();
zoneReplicationFactor.put(0, 2);
zoneReplicationFactor.put(1, 1);
zoneReplicationFactor.put(2, 1);
/*
* First n nodes on the preference list will be one node from each
* remote n zones, where n=zoneCountReads, therefore preferred read
* should be set > n if want to include local zone node results in
* parallel request
*/
storeDef = new StoreDefinitionBuilder().setName("test")
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setRoutingPolicy(RoutingTier.CLIENT)
.setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY)
.setReplicationFactor(4)
.setZoneReplicationFactor(zoneReplicationFactor)
.setKeySerializer(new SerializerDefinition("string"))
.setValueSerializer(new SerializerDefinition("string"))
.setPreferredReads(2)
.setRequiredReads(1)
.setPreferredWrites(1)
.setRequiredWrites(1)
.setZoneCountReads(1)
.setZoneCountWrites(0)
.build();
makeStore();
Versioned<byte[]> v = Versioned.value("v".getBytes());
subStores.get(0).put(TestUtils.toByteArray("k001"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k011"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k101"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k111"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k010"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k011"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k110"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k111"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k100"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k101"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k110"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k111"), v, null);
/* test multiple keys getall */
List<ByteArray> keys = new ArrayList<ByteArray>();
keys.add(TestUtils.toByteArray("k000"));
keys.add(TestUtils.toByteArray("k001"));
keys.add(TestUtils.toByteArray("k010"));
keys.add(TestUtils.toByteArray("k011"));
keys.add(TestUtils.toByteArray("k100"));
keys.add(TestUtils.toByteArray("k101"));
keys.add(TestUtils.toByteArray("k110"));
keys.add(TestUtils.toByteArray("k111"));
Map<ByteArray, List<Versioned<byte[]>>> result = store.getAll(keys, null);
assertFalse(result.containsKey(TestUtils.toByteArray("not_included")));
/* client will first try all the nodes in local zone */
assertFalse(result.containsKey(TestUtils.toByteArray("k000")));
assertEquals(1, result.get(TestUtils.toByteArray("k011")).size());
assertFalse(result.containsKey(TestUtils.toByteArray("not_included")));
assertFalse(result.containsKey(TestUtils.toByteArray("k000")));
assertEquals(1, result.get(TestUtils.toByteArray("k011")).size());
assertEquals(1, result.get(TestUtils.toByteArray("k100")).size());
assertEquals(2, result.get(TestUtils.toByteArray("k111")).size());
}
@Test
public void testGetall_322() throws Exception {
cluster = getEightNodeClusterWithZones();
HashMap<Integer, Integer> zoneReplicationFactor = new HashMap<Integer, Integer>();
zoneReplicationFactor.put(0, 3);
zoneReplicationFactor.put(1, 3);
storeDef = new StoreDefinitionBuilder().setName("test")
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setRoutingPolicy(RoutingTier.CLIENT)
.setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY)
.setReplicationFactor(6)
.setZoneReplicationFactor(zoneReplicationFactor)
.setKeySerializer(new SerializerDefinition("string"))
.setValueSerializer(new SerializerDefinition("string"))
.setPreferredReads(2)
.setRequiredReads(2)
.setPreferredWrites(2)
.setRequiredWrites(2)
.setZoneCountReads(0)
.setZoneCountWrites(0)
.build();
makeStore();
Versioned<byte[]> v = Versioned.value("v".getBytes());
subStores.get(0).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(0).put(TestUtils.toByteArray("k0000_1111"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(1).put(TestUtils.toByteArray("k0000_1111"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(2).put(TestUtils.toByteArray("k0000_1111"), v, null);
subStores.get(3).put(TestUtils.toByteArray("k0000_1111"), v, null);
subStores.get(3).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(4).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(4).put(TestUtils.toByteArray("k1111_0000"), v, null);
subStores.get(5).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(5).put(TestUtils.toByteArray("k1111_0000"), v, null);
subStores.get(6).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(6).put(TestUtils.toByteArray("k1111_0000"), v, null);
subStores.get(7).put(TestUtils.toByteArray("k1111_1111"), v, null);
subStores.get(7).put(TestUtils.toByteArray("k1111_0000"), v, null);
/* test multiple keys getall */
List<ByteArray> keys = new ArrayList<ByteArray>();
keys.add(TestUtils.toByteArray("k0000_0000"));
keys.add(TestUtils.toByteArray("k0000_1111"));
keys.add(TestUtils.toByteArray("k1111_0000"));
keys.add(TestUtils.toByteArray("k1111_1111"));
Map<ByteArray, List<Versioned<byte[]>>> result = store.getAll(keys, null);
assertFalse(result.containsKey(TestUtils.toByteArray("not_included")));
assertFalse(result.containsKey(TestUtils.toByteArray("k0000_0000")));
assertEquals(2, result.get(TestUtils.toByteArray("k0000_1111")).size());
assertFalse(result.containsKey(TestUtils.toByteArray("k1111_0000")));
assertEquals(2, result.get(TestUtils.toByteArray("k1111_1111")).size());
}
}
| 56.628472 | 117 | 0.582071 |
3ac67001b967bdac70e8d706f46eea5de19c28c0 | 1,916 | package pe.edu.upc.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
@Entity
@Table(name = "tareas")
public class Tarea implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idTarea;
@NotEmpty(message = "Ingresa la descripcion de la tarea")
@Column(name = "descripcionTarea", nullable = false, length = 45)
private String descripcionTarea;
@ManyToOne
@JoinColumn(name = "idProceso")
private Proceso proceso;
public Tarea() {
super();
// TODO Auto-generated constructor stub
}
public Tarea(int idTarea, String descripcionTarea, Proceso proceso) {
super();
this.idTarea = idTarea;
this.descripcionTarea = descripcionTarea;
this.proceso = proceso;
}
public int getIdTarea() {
return idTarea;
}
public void setIdTarea(int idTarea) {
this.idTarea = idTarea;
}
public String getDescripcionTarea() {
return descripcionTarea;
}
public void setDescripcionTarea(String descripcionTarea) {
this.descripcionTarea = descripcionTarea;
}
public Proceso getProceso() {
return proceso;
}
public void setProceso(Proceso proceso) {
this.proceso = proceso;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idTarea;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tarea other = (Tarea) obj;
if (idTarea != other.idTarea)
return false;
return true;
}
}
| 20.826087 | 70 | 0.733299 |
47122e509300b342dea8328bb14c289b569691b1 | 5,980 | /*
Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Shanghai YUEWEN Information Technology Co., Ltd. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD. AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。
这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然:
* 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。
* 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。
* 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。
免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任,包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等),不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。
*/
package org.albianj.cached.lcached;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public interface ILocalCached {
public Object put(Object key, Object value);
public Object put(Object key, Object value, long timespan);
public Object get(Object key);
public Object remove(Object key);
public void clear();
public int size();
public boolean isEmpty();
@SuppressWarnings("rawtypes")
public Collection values();
public boolean containsKey(Object key);
@SuppressWarnings("rawtypes")
public void putAll(Map map);
public boolean containsValue(Object value);
@SuppressWarnings("rawtypes")
public Set entrySet();
@SuppressWarnings("rawtypes")
public Set keySet();
/**
* Returns the name of this cache. The name is completely arbitrary and used
* only for display to administrators.
*
* @return the name of this cache.
*/
public String getName();
/**
* Returns the number of cache hits. A cache hit occurs every time the get
* method is called and the cache contains the requested object.
* <p>
* <p>
* Keeping track of cache hits and misses lets one measure how efficient the
* cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
public long getCacheHits();
/**
* Returns the number of cache misses. A cache miss occurs every time the
* get method is called and the cache does not contain the requested object.
* <p>
* <p>
* Keeping track of cache hits and misses lets one measure how efficient the
* cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
public long getCacheMisses();
/**
* Returns the size of the cache contents in bytes. This value is only a
* rough approximation, so cache users should expect that actual VM memory
* used by the cache could be significantly higher than the value reported
* by this method.
*
* @return the size of the cache contents in bytes.
*/
public int getCacheSize();
/**
* Returns the maximum size of the cache (in bytes). If the cache grows
* larger than the max size, the least frequently used items will be
* removed. If the max cache size is set to -1, there is no size limit.
*
* @return the maximum size of the cache (-1 indicates unlimited max size).
*/
public int getMaxCacheSize();
/**
* Sets the maximum size of the cache. If the cache grows larger than the
* max size, the least frequently used items will be removed. If the max
* cache size is set to -1, there is no size limit.
*
* @param maxCacheSize the maximum size of this cache (-1 indicates unlimited max
* size).
*/
public void setMaxCacheSize(int maxCacheSize);
/**
* Returns the maximum number of milleseconds that any object can live in
* cache. Once the specified number of milleseconds passes, the object will
* be automatically expried from cache. If the max lifetime is set to -1,
* then objects never expire.
*
* @return the maximum number of milleseconds before objects are expired.
*/
public long getDefaultLifetime();
/**
* Sets the maximum number of milleseconds that any object can live in
* cache. Once the specified number of milleseconds passes, the object will
* be automatically expried from cache. If the max lifetime is set to -1,
* then objects never expire.
*
* @param maxLifetime the maximum number of milleseconds before objects are expired.
*/
public void setDefaultLifetime(long defaultLifetime);
} | 42.112676 | 774 | 0.72709 |
a762e8caf8450b1ca8599a1e9c4f7a31db213dbf | 5,378 | /*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package test.aes;
import com.intel.dcsg.cpg.crypto.Aes128;
import com.intel.dcsg.cpg.crypto.CryptographyException;
import com.intel.dcsg.cpg.crypto.RsaUtil;
import com.intel.dcsg.cpg.performance.Task;
import com.intel.dcsg.cpg.performance.report.PerformanceInfo;
import static com.intel.dcsg.cpg.performance.report.PerformanceUtil.measureSingleTask;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;
import javax.crypto.SecretKey;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author jbuhacoff
*/
public class TestAesPerformance {
private static final Logger log = LoggerFactory.getLogger(TestAesPerformance.class);
private static final int max = 100000;
private static final int RSA_SIZE = 1024;
private static final int AES_SIZE = 128;
@BeforeClass
public static void startGrizzlyHttpServer() throws IOException {
}
@AfterClass
public static void stopGrizzlyHttpServer() {
}
@Test
public void testGenerateRsaPairs() throws Exception {
PerformanceInfo info = measureSingleTask(new GenerateRsaPair(RSA_SIZE), max);
printPerformanceInfo(info);
long[] data = info.getData();
for(int i=0; i<data.length; i++) {
System.out.println(String.format("%d\t%d", i, data[i]));
}
}
@Test
public void testGenerateAesKeys() throws Exception {
PerformanceInfo info = measureSingleTask(new GenerateAesKey(AES_SIZE), max);
printPerformanceInfo(info);
long[] data = info.getData();
for(int i=0; i<data.length; i++) {
System.out.println(String.format("%d\t%d", i, data[i]));
}
}
@Test
public void testAesEncryptPerformance() throws Exception {
SecretKey key = Aes128.generateKey();
PerformanceInfo info = measureSingleTask(new AesEncrypt(key), max);
printPerformanceInfo(info);
long[] data = info.getData();
for(int i=0; i<data.length; i++) {
// System.out.println(String.format("%d\t%d", i, data[i]));
}
}
private static void printPerformanceInfo(PerformanceInfo info) {
log.debug("Number of executions: {}", info.getData().length);
log.debug("Average time: {}", info.getAverage());
log.debug("Min time: {}", info.getMin());
log.debug("Max time: {}", info.getMax());
}
private static class GenerateRsaPair extends Task {
private final int keysize;
private KeyPair keypair;
public GenerateRsaPair(int keysize) {
super(String.format("RSA %d", keysize)); // or can use the hashcode of the messsage as the id: String.valueOf(message.hashCode())
this.keysize = keysize;
}
@Override
public void execute() throws Exception {
keypair = RsaUtil.generateRsaKeyPair(keysize);
// log.debug(format("GenerateRsaPair[%s]", getId()));
}
public KeyPair getKeyPair() { return keypair; }
}
private static class RsaEncrypt extends Task {
private final PrivateKey key;
private byte[] input;
private byte[] output;
public RsaEncrypt(PrivateKey key) {
super(String.format("RSA Encrypt")); // or can use the hashcode of the messsage as the id: String.valueOf(message.hashCode())
this.input = new byte[128]; // TODO: random bytes...
this.key = key;
}
@Override
public void execute() throws Exception {
// output = RsaUtil.(message);
// log.debug(format("GenerateRsaPair[%s]", getId()));
}
public byte[] getOutput() { return output; }
}
/**
* Java performance without AES-NI... on HP EliteBook 8560w running Intel Core i5-2560M CPU @ 2.6GHz
* 10k encryptions in about 3 seconds,
* 100k encryptions in about 30 seconds
*/
private static class GenerateAesKey extends Task {
private final int keysize;
private SecretKey key;
public GenerateAesKey(int keysize) {
super(String.format("AES %d", keysize)); // or can use the hashcode of the messsage as the id: String.valueOf(message.hashCode())
this.keysize = keysize;
}
@Override
public void execute() throws Exception {
key = Aes128.generateKey();
// log.debug(format("GenerateRsaPair[%s]", getId()));
}
public SecretKey getKey() { return key; }
}
private static class AesEncrypt extends Task {
private final Aes128 cipher;
private byte[] input;
private byte[] output;
public AesEncrypt(SecretKey key) throws CryptographyException {
super(String.format("AES Encrypt")); // or can use the hashcode of the messsage as the id: String.valueOf(message.hashCode())
this.cipher = new Aes128(key);
this.input = new byte[128]; // TODO: random bytes...
}
@Override
public void execute() throws Exception {
output = cipher.encrypt(input);
}
public byte[] getOutput() { return output; }
}
}
| 35.615894 | 141 | 0.631462 |
f81e3a9169d6b022b81519c98fa036abb66ca245 | 17,283 | /*
* This file was automatically generated by EvoSuite
* Sun Nov 29 05:51:07 GMT 2020
*/
package com.lts.io;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.lts.io.ArchiveScanner;
import com.lts.io.ImprovedFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Vector;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.mock.java.io.MockFile;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class ArchiveScanner_ESTest extends ArchiveScanner_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=1.0027182645175161
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
MockFile mockFile0 = new MockFile("3MEu");
ImprovedFile improvedFile0 = ImprovedFile.createTempDirectory("3MEu", "3MEu", (File) mockFile0);
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
// Undeclared exception!
try {
archiveScanner0.scandir(mockFile0, "3MEu", true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "OPk,p_");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[1];
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
Vector<InputStream> vector0 = new Vector<InputStream>();
archiveScanner0.dirsIncluded = vector0;
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "\"s75&bV2<[,Yn;");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 3
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[5];
stringArray0[0] = "OPk,p_";
stringArray0[1] = "OPk,p_";
stringArray0[2] = "OPk,p_";
stringArray0[3] = "OPk,p_";
stringArray0[4] = "OPk,p_";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "OPk,p_");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[1];
Vector<Integer> vector0 = new Vector<Integer>();
archiveScanner0.dirsExcluded = vector0;
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 5
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
Vector<ByteArrayInputStream> vector0 = new Vector<ByteArrayInputStream>();
archiveScanner0.filesExcluded = vector0;
String[] stringArray0 = new String[1];
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, "\"s75&bV2<[,Yn;");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
Vector<Object> vector0 = new Vector<Object>();
archiveScanner0.filesNotIncluded = vector0;
String[] stringArray0 = new String[1];
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
archiveScanner0.processFile("xI1@lI,");
assertEquals(1, ArchiveScanner.DIRECTORY);
}
/**
//Test case number: 7
/*Coverage entropy=0.8675632284814612
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[1];
Vector<Integer> vector0 = new Vector<Integer>();
archiveScanner0.dirsExcluded = vector0;
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
archiveScanner0.setExcludes(stringArray0);
File file0 = ImprovedFile.createTempFileName("v>{", "v>{", (File) null);
archiveScanner0.setBasedir(file0);
// Undeclared exception!
try {
archiveScanner0.processDirectory((File) null, "v>{", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[1];
Vector<Integer> vector0 = new Vector<Integer>();
archiveScanner0.dirsExcluded = vector0;
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
archiveScanner0.setExcludes(stringArray0);
archiveScanner0.processDirectory((File) null, "v>{", true);
assertEquals(1, ArchiveScanner.DIRECTORY);
}
/**
//Test case number: 9
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[1];
Vector<Integer> vector0 = new Vector<Integer>();
archiveScanner0.dirsExcluded = vector0;
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
String[] stringArray1 = new String[0];
archiveScanner0.setExcludes(stringArray1);
// Undeclared exception!
try {
archiveScanner0.processDirectory((File) null, "v>{", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 10
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
String[] stringArray0 = new String[3];
Vector<String> vector0 = new Vector<String>();
archiveScanner0.filesExcluded = vector0;
stringArray0[0] = "xI1@lI,";
stringArray0[1] = "v>{";
stringArray0[2] = "WC#%&((a'v KK\"3?jxi";
archiveScanner0.setIncludes(stringArray0);
archiveScanner0.setExcludes(stringArray0);
archiveScanner0.processFile("WC#%&((a'v KK\"3?jxi");
assertEquals(0, ArchiveScanner.FILE);
}
/**
//Test case number: 11
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
Vector<ByteArrayInputStream> vector0 = new Vector<ByteArrayInputStream>();
archiveScanner0.filesExcluded = vector0;
String[] stringArray0 = new String[1];
stringArray0[0] = "v>{";
archiveScanner0.setIncludes(stringArray0);
archiveScanner0.setExcludes(stringArray0);
archiveScanner0.processArchive((File) null, "v>{");
assertEquals(2, ArchiveScanner.ARCHIVE);
}
/**
//Test case number: 12
/*Coverage entropy=1.0114042647073516
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("5}8bD0TFW8J>l.jar");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
int int0 = archiveScanner0.toFileType(improvedFile0);
assertEquals(2, int0);
}
/**
//Test case number: 13
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.scandir((File) null, "$o*i6\"w> o#jwAPs", false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 14
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.scanArchive((File) null, (String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.archive.AbstractNestedArchive", e);
}
}
/**
//Test case number: 15
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile(", is neither a directory nor ");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
// Undeclared exception!
try {
archiveScanner0.processFile((String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 16
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.processFile("");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 17
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.processDirectory((File) null, (String) null, true);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 18
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.processArchive((File) null, (String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.DirectoryScanner", e);
}
}
/**
//Test case number: 19
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.isArchive((File) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 20
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("w.Lc", "Error trying to list archive contents ");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
try {
archiveScanner0.scandir(improvedFile0, (String) null, true);
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// IO error scanning directory /home/ubuntu/termite/projects/78_caloriecount/w.Lc/Error trying to list archive contents
//
verifyException("com.lts.io.ArchiveScanner", e);
}
}
/**
//Test case number: 21
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
try {
archiveScanner0.scanArchive(improvedFile0, "");
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Error trying to list archive,
//
verifyException("com.lts.io.archive.AbstractNestedArchive", e);
}
}
/**
//Test case number: 22
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
ArchiveScanner archiveScanner0 = new ArchiveScanner((ImprovedFile) null);
// Undeclared exception!
try {
archiveScanner0.scanArchive((File) null, "OPk,r_");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.lts.io.archive.AbstractNestedArchive", e);
}
}
/**
//Test case number: 23
/*Coverage entropy=0.5623351446188083
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("OPk,r_");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
boolean boolean0 = archiveScanner0.isArchive(improvedFile0);
assertFalse(boolean0);
}
/**
//Test case number: 24
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
ImprovedFile improvedFile0 = new ImprovedFile("");
ArchiveScanner archiveScanner0 = new ArchiveScanner(improvedFile0);
archiveScanner0.scandir(improvedFile0, "", false);
assertNull(improvedFile0.getParent());
}
}
| 32.609434 | 176 | 0.646994 |
9796cfcf64352908319d0687763999eafb6522fa | 2,403 | package org.pm4j.core.pb;
import org.pm4j.core.pb.PbFactory.ValueUpdateEvent;
/**
* Base iterface/implementation for presentation binding default settings.
*
* @author olaf boede
*
* @param <T_WIDGET_FACTORY_SET> The view platform specific widget set class.
*/
public abstract class PbDefaultsBase <T_WIDGET_FACTORY_SET extends PbWidgetFactorySet> {
/**
* Defines the UI event that triggers transfer of entered values to the PM.
* <p>
* This may be done on each modification (each click) or on the focus lost
* event.
*/
private ValueUpdateEvent valueUpdateEvent = ValueUpdateEvent.MODIFY;
/**
* Defines the set of default UI widgets factories used within the application.
*/
private T_WIDGET_FACTORY_SET widgetFactorySet;
/**
* Configures the PM to view matching strategies.<br>
* It defines the default view representation of PMs.
* <p>
* This {@link PbMatcher} defines the default set of {@link PbMatcher}s used
* for the application.
*/
private PbMatcher matcher;
/**
* Generates the default PM to factory matcher.
* <p>
* Each application may define here its own PM to view matching strategy
* for generic views.
*/
private PbMatcherFactory matcherFactory;
public PbDefaultsBase() {
super();
}
public ValueUpdateEvent getValueUpdateEvent() {
return valueUpdateEvent;
}
public void setValueUpdateEvent(ValueUpdateEvent valueUpdateEvent) {
this.valueUpdateEvent = valueUpdateEvent;
}
public PbMatcher getMatcher() {
if (matcher == null) {
matcher = getMatcherFactory().makeMatcher();
}
return matcher;
}
public void setMatcher(PbMatcher pbMatcher) {
this.matcher = pbMatcher;
}
public PbMatcherFactory getMatcherFactory() {
if (matcherFactory == null) {
matcherFactory = new PbMatcherFactory(getWidgetFactorySet());
}
return matcherFactory;
}
public void setMatcherFactory(PbMatcherFactory pbMatcherFactory) {
this.matcherFactory = pbMatcherFactory;
}
public T_WIDGET_FACTORY_SET getWidgetFactorySet() {
if (widgetFactorySet == null) {
widgetFactorySet = makeWidgetFactorySet();
}
return widgetFactorySet;
}
protected abstract T_WIDGET_FACTORY_SET makeWidgetFactorySet();
public void setWidgetFactorySet(T_WIDGET_FACTORY_SET widgetFactorySet) {
this.widgetFactorySet = widgetFactorySet;
}
} | 26.406593 | 88 | 0.72243 |
09dc279f271a71abc2952358f985f8eb1c7cfb68 | 1,469 | package com.hitszplaza.background.controller;
import com.google.gson.JsonObject;
import com.hitszplaza.background.service.impl.FeedbackServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("feedback")
public class FeedbackController {
@Autowired
private FeedbackServiceImpl feedbackService;
@GetMapping
public JsonObject find(@RequestParam String id) {
return feedbackService.find(id);
}
@GetMapping("/all")
public JsonObject findAllFeedback(@RequestParam Integer pageNo,
@RequestParam(defaultValue = "20") Integer pageSize) {
return feedbackService.findAll(pageNo - 1, pageSize);
}
@PostMapping("/condition")
public JsonObject findByCondition(@RequestParam Integer pageNo,
@RequestParam(defaultValue = "20") Integer pageSize,
@RequestBody String match) {
return feedbackService.findByCondition(pageNo - 1, pageSize, match);
}
@PatchMapping("status")
public JsonObject updateStatus(@RequestParam String id,
@RequestParam Integer status) {
return feedbackService.update(id, status);
}
@DeleteMapping
public JsonObject deleteUserPoster(@RequestParam String id) {
return feedbackService.delete(id);
}
}
| 33.386364 | 92 | 0.669843 |
6626069330e35df562fcc95e081e288e0a628af1 | 527 | package org.gbif.occurrence.download.file.dwca;
/**
* Tables suffixes used to name tables and files.
*/
public final class TableSuffixes {
//Suffixes for table names
public static final String INTERPRETED_SUFFIX = "_interpreted";
public static final String VERBATIM_SUFFIX = "_verbatim";
public static final String MULTIMEDIA_SUFFIX = "_multimedia";
public static final String CITATION_SUFFIX = "_citation";
/**
* Hidden/private constructor.
*/
private TableSuffixes() {
//empty constructor
}
}
| 23.954545 | 65 | 0.732448 |
632ab828cfd09336c48ea6754ecce5bad3a4f38a | 4,171 | /*
* Copyright 2016 h-j-k. 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.ikueb.wallclock;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
/**
* An immutable, ticking {@link WallClock} implementation that also extends from
* {@link Clock}.<br>
*
* @implNote This is essentially a wrapper for an underlying {@link Clock}
* instance, and there are more immediate ways of obtaining date and times from one, e.g.
* {@link LocalDate#now(Clock)}. This is meant to be a convenience class providing a
* non-fixed implementation of {@link WallClock}. {@link #atUTC()} is likely to be more
* useful providing a singleton instance of UTC system clock.
*/
public final class TickingClock extends Clock implements WallClock, Serializable {
private static final long serialVersionUID = 1L;
private final transient Clock clock;
/**
* Bases a new clock with the time-zone {@link ZoneOffset#UTC}.
*/
public TickingClock() {
this(ZoneOffset.UTC);
}
/**
* Bases a new clock with the given time-zone.
*
* @param zoneId the time-zone to use, not null
*/
public TickingClock(ZoneId zoneId) {
this(Clock.system(zoneId));
}
/**
* Bases a new clock with the given one.
*
* @param clock the clock to use, not null
*/
private TickingClock(Clock clock) {
this.clock = Objects.requireNonNull(clock);
}
@Override
public ZonedDateTime zonedDateTime() {
return ZonedDateTime.now(clock);
}
@Override
public LocalDate date() {
return LocalDate.now(clock);
}
@Override
public LocalTime time() {
return LocalTime.now(clock);
}
@Override
public LocalDateTime dateTime() {
return LocalDateTime.now(clock);
}
@Override
public Instant instant() {
return clock.instant();
}
@Override
public ZoneId getZone() {
return clock.getZone();
}
@Override
public Clock withZone(ZoneId zoneId) {
return new TickingClock(zoneId);
}
/**
* Returns either a new {@link WallClock} with a non-zero {@code duration} offset,
* else this.
*
* @param duration the duration to offset, not null
* @return either a new {@link WallClock} with a non-zero {@code duration} offset,
* else this
*/
@Override
public TickingClock offset(Duration duration) {
return duration.isZero() ? this : new TickingClock(Clock.offset(clock, duration));
}
@Override
public boolean equals(Object o) {
return o == this
|| (o instanceof TickingClock && ((TickingClock) o).clock.equals(clock));
}
@Override
public int hashCode() {
return clock.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "@" + zonedDateTime();
}
/**
* An enum-driven singleton instance for a UTC-based {@link TickingClock}.
*/
private enum UTCTickingClock {
INSTANCE;
private final TickingClock clock = new TickingClock();
}
/**
* Provides an {@code enum}-based UTC singleton {@link TickingClock}. <br>
* Useful for ensuring that there is only one {@link Clock#systemUTC()} returned per
* classloader.
*
* @return a singleton UTC clock
*/
public static TickingClock atUTC() {
return UTCTickingClock.INSTANCE.clock;
}
}
| 28.568493 | 91 | 0.623591 |
2133f81d3b39af2dfd5ec3c67974679001c98941 | 1,783 | /**
* Copyright (c) 2013-2022 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.datastore.hbase.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.RpcCallback;
public class GeoWaveBlockingRpcCallback<R> implements RpcCallback<R> {
private R result;
private boolean resultSet = false;
/**
* Called on completion of the RPC call with the response object, or {@code null} in the case of
* an error.
*
* @param parameter the response object or {@code null} if an error occurred
*/
@Override
public void run(final R parameter) {
synchronized (this) {
result = parameter;
resultSet = true;
notifyAll();
}
}
/**
* Returns the parameter passed to {@link #run(Object)} or {@code null} if a null value was
* passed. When used asynchronously, this method will block until the {@link #run(Object)} method
* has been called.
*
* @return the response object or {@code null} if no response was passed
*/
public synchronized R get() throws IOException {
while (!resultSet) {
try {
this.wait();
} catch (final InterruptedException ie) {
final InterruptedIOException exception = new InterruptedIOException(ie.getMessage());
exception.initCause(ie);
throw exception;
}
}
return result;
}
}
| 33.018519 | 100 | 0.701626 |
60b314ae7fca52b596bb0a5223db50e1aac095cb | 2,542 | package net.saisimon.agtms.web.service.upload;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import net.saisimon.agtms.core.dto.Result;
import net.saisimon.agtms.core.enums.ImageFormats;
import net.saisimon.agtms.core.factory.ObjectStorageServiceFactory;
import net.saisimon.agtms.core.property.OssProperties;
import net.saisimon.agtms.core.service.ObjectStorageService;
import net.saisimon.agtms.core.util.ResultUtils;
import net.saisimon.agtms.web.constant.ErrorMessage;
import net.saisimon.agtms.web.util.FileUtils;
/**
* 图片信息服务
*
* @author saisimon
*
*/
@Service
@Slf4j
public class ImageInfoService {
@Autowired
private OssProperties ossProperties;
@Autowired
protected HttpServletResponse response;
public Result upload(MultipartFile image) {
try {
ImageFormats imageFormat = FileUtils.imageFormat(image.getInputStream());
if (imageFormat == ImageFormats.UNKNOWN) {
return ErrorMessage.Common.UNSUPPORTED_FORMAT;
}
String filename = UUID.randomUUID().toString() + imageFormat.getSuffix();
ObjectStorageService oss = ObjectStorageServiceFactory.get(ossProperties.getType());
String path = oss.upload(image.getInputStream(), "image", filename);
if (path == null) {
return ErrorMessage.Common.UPLOAD_FAILED;
}
return ResultUtils.simpleSuccess(path);
} catch (IOException e) {
log.error("upload failed", e);
return ErrorMessage.Common.UPLOAD_FAILED;
}
}
public void fetch(String filename) throws IOException {
ImageFormats imageFormat = FileUtils.imageFormat(filename);
if (imageFormat == ImageFormats.UNKNOWN) {
response.sendError(HttpStatus.NOT_FOUND.value());
return;
}
setContentType(imageFormat);
ObjectStorageService oss = ObjectStorageServiceFactory.get(ossProperties.getType());
oss.fetch(response, "image", filename);
}
private void setContentType(ImageFormats imageFormat) {
switch (imageFormat) {
case JPG:
response.setContentType("image/jpeg");
break;
case PNG:
response.setContentType("image/png");
break;
case GIF:
response.setContentType("image/gif");
break;
case BMP:
response.setContentType("image/bmp");
break;
default:
response.setContentType("application/octet-stream");
break;
}
}
}
| 28.561798 | 87 | 0.764752 |
4d6218797cacb85d887a139b99769caa952b0b9d | 21,076 | package org.keycloak.testsuite.broker;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.graphene.Graphene;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.common.Profile;
import org.keycloak.models.ClientModel;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.ClientPolicyRepresentation;
import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.services.resources.admin.permissions.AdminPermissionManagement;
import org.keycloak.services.resources.admin.permissions.AdminPermissions;
import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.ProfileAssume;
import org.keycloak.testsuite.auth.page.login.UpdateAccount;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.social.AbstractSocialLoginPage;
import org.keycloak.testsuite.pages.social.BitbucketLoginPage;
import org.keycloak.testsuite.pages.social.FacebookLoginPage;
import org.keycloak.testsuite.pages.social.GitHubLoginPage;
import org.keycloak.testsuite.pages.social.GitLabLoginPage;
import org.keycloak.testsuite.pages.social.GoogleLoginPage;
import org.keycloak.testsuite.pages.social.LinkedInLoginPage;
import org.keycloak.testsuite.pages.social.MicrosoftLoginPage;
import org.keycloak.testsuite.pages.social.OpenShiftLoginPage;
import org.keycloak.testsuite.pages.social.PayPalLoginPage;
import org.keycloak.testsuite.pages.social.StackOverflowLoginPage;
import org.keycloak.testsuite.pages.social.TwitterLoginPage;
import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import org.keycloak.testsuite.util.IdentityProviderBuilder;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.RealmBuilder;
import org.keycloak.testsuite.util.URLUtils;
import org.keycloak.testsuite.util.WaitUtils;
import org.keycloak.util.BasicAuthHelper;
import org.openqa.selenium.By;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.FileInputStream;
import java.util.List;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.BITBUCKET;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.FACEBOOK;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.GITHUB;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.GITHUB_PRIVATE_EMAIL;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.GITLAB;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.GOOGLE;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.LINKEDIN;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.MICROSOFT;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.OPENSHIFT;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.PAYPAL;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.STACKOVERFLOW;
import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.TWITTER;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
* @author Vaclav Muzikar <vmuzikar@redhat.com>
*/
public class SocialLoginTest extends AbstractKeycloakTest {
public static final String SOCIAL_CONFIG = "social.config";
public static final String REALM = "social";
public static final String EXCHANGE_CLIENT = "exchange-client";
private static Properties config = new Properties();
@Page
private LoginPage loginPage;
@Page
private UpdateAccount updateAccountPage;
public enum Provider {
GOOGLE("google", GoogleLoginPage.class),
FACEBOOK("facebook", FacebookLoginPage.class),
GITHUB("github", GitHubLoginPage.class),
GITHUB_PRIVATE_EMAIL("github", "github-private-email", GitHubLoginPage.class),
TWITTER("twitter", TwitterLoginPage.class),
LINKEDIN("linkedin", LinkedInLoginPage.class),
MICROSOFT("microsoft", MicrosoftLoginPage.class),
PAYPAL("paypal", PayPalLoginPage.class),
STACKOVERFLOW("stackoverflow", StackOverflowLoginPage.class),
OPENSHIFT("openshift-v3", OpenShiftLoginPage.class),
GITLAB("gitlab", GitLabLoginPage.class),
BITBUCKET("bitbucket", BitbucketLoginPage.class);
private String id;
private Class<? extends AbstractSocialLoginPage> pageObjectClazz;
private String configId = null;
Provider(String id, Class<? extends AbstractSocialLoginPage> pageObjectClazz) {
this.id = id;
this.pageObjectClazz = pageObjectClazz;
}
Provider(String id, String configId, Class<? extends AbstractSocialLoginPage> pageObjectClazz) {
this.id = id;
this.pageObjectClazz = pageObjectClazz;
this.configId = configId;
}
public String id() {
return id;
}
public Class<? extends AbstractSocialLoginPage> pageObjectClazz() {
return pageObjectClazz;
}
public String configId() {
return configId != null ? configId : id;
}
}
@Deployment
public static WebArchive deploy() {
return RunOnServerDeployment.create();
}
private Provider currentTestProvider = null;
private AbstractSocialLoginPage currentSocialLoginPage = null;
@BeforeClass
public static void loadConfig() throws Exception {
assumeTrue(System.getProperties().containsKey(SOCIAL_CONFIG));
config.load(new FileInputStream(System.getProperty(SOCIAL_CONFIG)));
}
@Before
public void beforeSocialLoginTest() {
accountPage.setAuthRealm(REALM);
}
@After
public void afterSocialLoginTest() {
currentTestProvider = null;
}
private void removeUser() {
List<UserRepresentation> users = adminClient.realm(REALM).users().search(null, null, null);
for (UserRepresentation user : users) {
if (user.getServiceAccountClientId() == null) {
log.infof("removing test user '%s'", user.getUsername());
adminClient.realm(REALM).users().get(user.getId()).remove();
}
}
}
private void setTestProvider(Provider provider) {
adminClient.realm(REALM).identityProviders().create(buildIdp(provider));
log.infof("added '%s' identity provider", provider.id());
currentTestProvider = provider;
currentSocialLoginPage = Graphene.createPageFragment(currentTestProvider.pageObjectClazz(), driver.findElement(By.tagName("html")));
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation rep = RealmBuilder.create().name(REALM).build();
testRealms.add(rep);
}
@Override
protected boolean isImportAfterEachMethod() {
return true;
}
public static void setupClientExchangePermissions(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(REALM);
ClientModel client = session.realms().getClientByClientId(EXCHANGE_CLIENT, realm);
// lazy init
if (client != null) return;
client = realm.addClient(EXCHANGE_CLIENT);
client.setSecret("secret");
client.setPublicClient(false);
client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
client.setEnabled(true);
client.setDirectAccessGrantsEnabled(true);
ClientPolicyRepresentation clientPolicyRep = new ClientPolicyRepresentation();
clientPolicyRep.setName("client-policy");
clientPolicyRep.addClient(client.getId());
AdminPermissionManagement management = AdminPermissions.management(session, realm);
management.users().setPermissionsEnabled(true);
ResourceServer server = management.realmResourceServer();
Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientPolicyRep, server);
management.users().adminImpersonatingPermission().addAssociatedPolicy(clientPolicy);
management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
for (IdentityProviderModel idp : realm.getIdentityProviders()) {
management.idps().setPermissionsEnabled(idp, true);
management.idps().exchangeToPermission(idp).addAssociatedPolicy(clientPolicy);
}
}
@Test
public void openshiftLogin() {
setTestProvider(OPENSHIFT);
performLogin();
assertUpdateProfile(false, false, true);
assertAccount();
}
@Test
public void googleLogin() throws InterruptedException {
setTestProvider(GOOGLE);
performLogin();
assertAccount();
testTokenExchange();
}
@Test
public void bitbucketLogin() throws InterruptedException {
setTestProvider(BITBUCKET);
performLogin();
assertAccount();
testTokenExchange();
}
@Test
public void gitlabLogin() throws InterruptedException {
setTestProvider(GITLAB);
performLogin();
assertAccount();
testTokenExchange();
}
@Test
public void facebookLogin() throws InterruptedException {
setTestProvider(FACEBOOK);
performLogin();
assertAccount();
testTokenExchange();
}
@Test
public void githubLogin() throws InterruptedException {
setTestProvider(GITHUB);
performLogin();
assertAccount();
testTokenExchange();
}
@Test
public void githubPrivateEmailLogin() throws InterruptedException {
setTestProvider(GITHUB_PRIVATE_EMAIL);
performLogin();
assertAccount();
}
@Test
public void twitterLogin() {
setTestProvider(TWITTER);
performLogin();
assertUpdateProfile(false, false, true);
assertAccount();
}
@Test
public void linkedinLogin() {
setTestProvider(LINKEDIN);
performLogin();
assertAccount();
}
@Test
public void microsoftLogin() {
setTestProvider(MICROSOFT);
performLogin();
assertAccount();
}
@Test
public void paypalLogin() {
setTestProvider(PAYPAL);
performLogin();
assertAccount();
}
@Test
public void stackoverflowLogin() throws InterruptedException {
setTestProvider(STACKOVERFLOW);
performLogin();
assertUpdateProfile(false, false, true);
assertAccount();
}
private IdentityProviderRepresentation buildIdp(Provider provider) {
IdentityProviderRepresentation idp = IdentityProviderBuilder.create().alias(provider.id()).providerId(provider.id()).build();
idp.setEnabled(true);
idp.setStoreToken(true);
idp.getConfig().put("clientId", getConfig(provider, "clientId"));
idp.getConfig().put("clientSecret", getConfig(provider, "clientSecret"));
if (provider == STACKOVERFLOW) {
idp.getConfig().put("key", getConfig(provider, "clientKey"));
}
if (provider == OPENSHIFT) {
idp.getConfig().put("baseUrl", getConfig(provider, "baseUrl"));
}
if (provider == PAYPAL) {
idp.getConfig().put("sandbox", getConfig(provider, "sandbox"));
}
return idp;
}
private String getConfig(Provider provider, String key) {
String providerKey = provider.configId() + "." + key;
return System.getProperty("social." + providerKey, config.getProperty(providerKey, config.getProperty("common." + key)));
}
private String getConfig(String key) {
return getConfig(currentTestProvider, key);
}
private void performLogin() {
currentSocialLoginPage.logout(); // try to logout first to be sure we're not logged in
accountPage.navigateTo();
loginPage.clickSocial(currentTestProvider.id());
// Just to be sure there's no redirect in progress
WaitUtils.pause(3000);
WaitUtils.waitForPageToLoad();
// Only when there's not active session for the social provider, i.e. login is required
if (URLUtils.currentUrlDoesntStartWith(getAuthServerRoot().toASCIIString())) {
log.infof("current URL: %s", driver.getCurrentUrl());
log.infof("performing log in to '%s' ...", currentTestProvider.id());
currentSocialLoginPage.login(getConfig("username"), getConfig("password"));
}
else {
log.infof("already logged in to '%s'; skipping the login process", currentTestProvider.id());
}
}
private void assertAccount() {
assertTrue(URLUtils.currentUrlStartWith(accountPage.toString())); // Sometimes after login the URL ends with /# or similar
assertEquals(getConfig("profile.firstName"), accountPage.getFirstName());
assertEquals(getConfig("profile.lastName"), accountPage.getLastName());
assertEquals(getConfig("profile.email"), accountPage.getEmail());
}
private void assertUpdateProfile(boolean firstName, boolean lastName, boolean email) {
assertTrue(URLUtils.currentUrlDoesntStartWith(accountPage.toString()));
if (firstName) {
assertTrue(updateAccountPage.fields().getFirstName().isEmpty());
updateAccountPage.fields().setFirstName(getConfig("profile.firstName"));
}
else {
assertEquals(getConfig("profile.firstName"), updateAccountPage.fields().getFirstName());
}
if (lastName) {
assertTrue(updateAccountPage.fields().getLastName().isEmpty());
updateAccountPage.fields().setLastName(getConfig("profile.lastName"));
}
else {
assertEquals(getConfig("profile.lastName"), updateAccountPage.fields().getLastName());
}
if (email) {
assertTrue(updateAccountPage.fields().getEmail().isEmpty());
updateAccountPage.fields().setEmail(getConfig("profile.email"));
}
else {
assertEquals(getConfig("profile.email"), updateAccountPage.fields().getEmail());
}
updateAccountPage.submit();
}
protected void testTokenExchange() {
ProfileAssume.assumeFeatureEnabled(Profile.Feature.TOKEN_EXCHANGE);
testingClient.server().run(SocialLoginTest::setupClientExchangePermissions);
List<UserRepresentation> users = adminClient.realm(REALM).users().search(null, null, null);
Assert.assertEquals(1, users.size());
String username = users.get(0).getUsername();
Client httpClient = ClientBuilder.newClient();
WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
.path("/realms")
.path(REALM)
.path("protocol/openid-connect/token");
// obtain social token
Response response = exchangeUrl.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(EXCHANGE_CLIENT, "secret"))
.post(Entity.form(
new Form()
.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
.param(OAuth2Constants.REQUESTED_SUBJECT, username)
.param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
.param(OAuth2Constants.REQUESTED_ISSUER, currentTestProvider.id())
));
Assert.assertEquals(200, response.getStatus());
AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
response.close();
String socialToken = tokenResponse.getToken();
Assert.assertNotNull(socialToken);
// remove all users
removeUser();
users = adminClient.realm(REALM).users().search(null, null, null);
Assert.assertEquals(0, users.size());
// now try external exchange where we trust social provider and import the external token.
response = exchangeUrl.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(EXCHANGE_CLIENT, "secret"))
.post(Entity.form(
new Form()
.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
.param(OAuth2Constants.SUBJECT_TOKEN, socialToken)
.param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
.param(OAuth2Constants.SUBJECT_ISSUER, currentTestProvider.id())
));
Assert.assertEquals(200, response.getStatus());
tokenResponse = response.readEntity(AccessTokenResponse.class);
response.close();
users = adminClient.realm(REALM).users().search(null, null, null);
Assert.assertEquals(1, users.size());
Assert.assertEquals(username, users.get(0).getUsername());
// remove all users
removeUser();
users = adminClient.realm(REALM).users().search(null, null, null);
Assert.assertEquals(0, users.size());
///// Test that we can update social token from session with stored tokens turned off.
// turn off store token
IdentityProviderRepresentation idp = adminClient.realm(REALM).identityProviders().get(currentTestProvider.id).toRepresentation();
idp.setStoreToken(false);
adminClient.realm(REALM).identityProviders().get(idp.getAlias()).update(idp);
// first exchange social token to get a user session that should store the social token there
response = exchangeUrl.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(EXCHANGE_CLIENT, "secret"))
.post(Entity.form(
new Form()
.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
.param(OAuth2Constants.SUBJECT_TOKEN, socialToken)
.param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
.param(OAuth2Constants.SUBJECT_ISSUER, currentTestProvider.id())
));
Assert.assertEquals(200, response.getStatus());
tokenResponse = response.readEntity(AccessTokenResponse.class);
String keycloakToken = tokenResponse.getToken();
response.close();
// now take keycloak token and make sure it can get back the social token from the user session since stored tokens are off
response = exchangeUrl.request()
.header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(EXCHANGE_CLIENT, "secret"))
.post(Entity.form(
new Form()
.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
.param(OAuth2Constants.SUBJECT_TOKEN, keycloakToken)
.param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
.param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
.param(OAuth2Constants.REQUESTED_ISSUER, currentTestProvider.id())
));
Assert.assertEquals(200, response.getStatus());
tokenResponse = response.readEntity(AccessTokenResponse.class);
response.close();
Assert.assertEquals(socialToken, tokenResponse.getToken());
// turn on store token
idp = adminClient.realm(REALM).identityProviders().get(currentTestProvider.id).toRepresentation();
idp.setStoreToken(true);
adminClient.realm(REALM).identityProviders().get(idp.getAlias()).update(idp);
httpClient.close();
}
}
| 40.844961 | 140 | 0.686705 |
1b04487ef3cccdaae9a876c8534b1d8f7f0e44c1 | 529 | package org.mp.naumann.database.data;
public class GenericColumn<T> implements Column<T> {
private String name;
private Class<T> clazz;
public GenericColumn(String name, Class<T> clazz) {
this.name = name;
this.clazz = clazz;
}
public static GenericColumn<String> StringColumn(String name) {
return new GenericColumn<>(name, String.class);
}
public String getName() {
return name;
}
@Override
public Class<T> getType() {
return clazz;
}
}
| 20.346154 | 67 | 0.625709 |
3b7c54048c62f92b5ef60cdac57daad588744347 | 4,189 | package com.wenox.users.dto;
import com.wenox.users.domain.Role;
import com.wenox.users.domain.User;
import com.wenox.users.domain.UserStatus;
import com.wenox.users.service.FormatDate;
import java.util.Objects;
/** Password and relations are not returned. */
public class FullUserResponse {
public static FullUserResponse from(User user) {
var dto = new FullUserResponse();
dto.setId(user.getId());
dto.setEmail(user.getEmail());
dto.setRole(user.getRole());
dto.setFirstName(user.getFirstName());
dto.setLastName(user.getLastName());
dto.setPurpose(user.getPurpose());
dto.setStatus(user.getStatus());
dto.setVerified(user.isVerified());
dto.setMarkedForRemoval(user.isMarkedForRemoval());
dto.setForceRemoval(user.isForceRemoval());
dto.setRemovalRequestedDate(FormatDate.toString(user.getRemovalRequestedDate()));
dto.setRemovedDate(FormatDate.toString(user.getRemovedDate()));
dto.setBlockedDate(FormatDate.toString(user.getBlockedDate()));
dto.setRegisteredDate(FormatDate.toString(user.getRegisteredDate()));
dto.setLastLoginDate(FormatDate.toString(user.getLastLoginDate()));
return dto;
}
private String id;
private String email;
private Role role;
private String firstName;
private String lastName;
private String purpose;
private UserStatus status;
private boolean verified;
private boolean markedForRemoval;
private boolean forceRemoval;
private String removalRequestedDate;
private String removedDate;
private String blockedDate;
private String registeredDate;
private String lastLoginDate;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FullUserResponse user = (FullUserResponse) o;
return id.equals(user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
public boolean isMarkedForRemoval() {
return markedForRemoval;
}
public void setMarkedForRemoval(boolean markedForRemoval) {
this.markedForRemoval = markedForRemoval;
}
public boolean isForceRemoval() {
return forceRemoval;
}
public void setForceRemoval(boolean forceRemoval) {
this.forceRemoval = forceRemoval;
}
public String getRemovalRequestedDate() {
return removalRequestedDate;
}
public void setRemovalRequestedDate(String removalRequestedDate) {
this.removalRequestedDate = removalRequestedDate;
}
public String getRemovedDate() {
return removedDate;
}
public void setRemovedDate(String removedDate) {
this.removedDate = removedDate;
}
public String getBlockedDate() {
return blockedDate;
}
public void setBlockedDate(String blockedDate) {
this.blockedDate = blockedDate;
}
public String getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(String registeredDate) {
this.registeredDate = registeredDate;
}
public String getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(String lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
}
| 20.945 | 85 | 0.706135 |
f6ae855d426cd9798e6428cc59721aecd228e8cf | 631 | import com.chaos.hades.client.config.ConfigBasedHadesClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Created by zcfrank1st on 22/11/2016.
*/
public class ConfigBasedHadesClientTest {
private ConfigBasedHadesClient configBasedHadesClient;
@Before
public void init () throws Exception {
this.configBasedHadesClient = new ConfigBasedHadesClient();
}
@Test
public void getConfig() {
Assert.assertEquals(configBasedHadesClient.getOrElse("q", ""), "");
// Assert.assertEquals(configBasedHadesClient.getOrElse("key1", ""), "hello world");
}
}
| 27.434783 | 91 | 0.713154 |
40138f03673e74415b81d2856968bcce1ac9a8f5 | 2,359 | package datastructure.binarytree;
import java.util.ArrayList;
import java.util.List;
/**
* @author tsc
* @description: 第一天
* @date 2022/4/1 11:52
*/
public class FirstDay {
/**
* 144 二叉树的前序遍历
*
* @param root
* @return
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
return preorderTraversal(root, result);
}
public List<Integer> preorderTraversal(TreeNode root, List<Integer> list) {
if (root == null) {
return list;
}
list.add(root.val);
preorderTraversal(root.left, list);
preorderTraversal(root.right, list);
return list;
}
/**
* 543 二叉树的直径
*
* @param root
* @return
*/
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return getMaxValue(root);
}
int maxValue = getMaxValue(root);
int leftValue = diameterOfBinaryTree(root.left);
maxValue = Math.max(maxValue, leftValue);
int rightValue = diameterOfBinaryTree(root.right);
return Math.max(maxValue, rightValue);
}
public int getMaxValue(TreeNode root) {
if (root == null) {
return 0;
}
int max = 0;
int i = diameterOfBinaryTreeLeft(root, max);
max = Math.max(i, max);
int j = diameterOfBinaryTreeLeft(root, max);
max = Math.max(j, max);
return max;
}
public int diameterOfBinaryTreeRight(TreeNode root, int value) {
if (root.left == null) {
return value;
}
value++;
return diameterOfBinaryTreeRight(root.left, value);
}
public int diameterOfBinaryTreeLeft(TreeNode root, int value) {
if (root.left == null) {
return value;
}
value++;
return diameterOfBinaryTreeLeft(root.right, value);
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void main(String[] args) {
}
}
| 21.842593 | 79 | 0.550233 |
a03f6bb8e3c540803b2661a2f562c2d3afdee8e7 | 4,786 | /*
Copyright (C) 2008 Srinivas Hasti
This source code is release under the BSD License.
This file is part of JQuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://jquantlib.org/
JQuantLib is free software: you can redistribute it and/or modify it
under the terms of the JQuantLib license. You should have received a
copy of the license along with this program; if not, please email
<jquant-devel@lists.sourceforge.net>. The license is also available online at
<http://www.jquantlib.org/index.php/LICENSE.TXT>.
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 license for more details.
JQuantLib is based on QuantLib. http://quantlib.org/
When applicable, the original copyright notice follows this notice.
*/
/*
Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
Copyright (C) 2004, 2005, 2006 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
package org.jquantlib.instruments;
import java.util.List;
import org.jquantlib.QL;
import org.jquantlib.exercise.Exercise;
import org.jquantlib.lang.exceptions.LibraryException;
import org.jquantlib.math.functions.Bind2ndPredicate;
import org.jquantlib.math.functions.FindIf;
import org.jquantlib.math.functions.GreaterEqualPredicate;
import org.jquantlib.math.matrixutilities.Array;
/**
* Discretized option on a given asset
* <p>
* @warning it is advised that derived classes take care of creating and
* initializing themselves an instance of the underlying.
*
* @author Srinivas Hasti
*/
public class DiscretizedOption extends DiscretizedAsset {
protected Exercise.Type exerciseType;
protected Array exerciseTimes;
protected DiscretizedAsset underlying;
public DiscretizedOption(
final DiscretizedAsset underlying,
final Exercise.Type exerciseType,
final Array exerciseTimes) {
this.underlying = underlying;
this.exerciseType = exerciseType;
this.exerciseTimes = exerciseTimes;
}
@Override
public void reset(final int size) {
QL.require(method().equals(underlying.method()) , "option and underlying were initialized on different methods");
values_ = new Array(size);
adjustValues();
}
@Override
public List</* @Time */Double> mandatoryTimes() {
final List</* @Time */Double> times = underlying.mandatoryTimes();
// discard negative times...
final Array array = new FindIf(exerciseTimes, new Bind2ndPredicate(new GreaterEqualPredicate(), 0.0)).op();
// and add the positive ones
for (int i=0; i< array.size(); i++) {
times.add(array.get(i));
}
return times;
}
protected void applyExerciseCondition() {
for (int i = 0; i < values_.size(); i++) {
values_.set(i, Math.max(underlying.values().get(i), values_.get(i)));
}
}
@Override
public void postAdjustValuesImpl() {
/*
* In the real world, with time flowing forward, first any payment is
* settled and only after options can be exercised. Here, with time
* flowing backward, options must be exercised before performing the
* adjustment.
*/
underlying.partialRollback(time());
underlying.preAdjustValues();
int i;
switch (exerciseType) {
case American:
if (time >= exerciseTimes.get(0) && time <= exerciseTimes.get(1)) {
applyExerciseCondition();
}
break;
case Bermudan:
case European:
for (i = 0; i < exerciseTimes.size(); i++) {
final /* @Time */ double t = exerciseTimes.get(i);
if (t >= 0.0 && isOnTime(t)) {
applyExerciseCondition();
}
}
break;
default:
throw new LibraryException("invalid exercise type"); // TODO: message
}
underlying.postAdjustValues();
}
}
| 35.984962 | 121 | 0.677392 |
c05a0dea174c918d09e9a0dc2d81a8d59abf209d | 871 | package com.mmc.security.record.rest;
import com.mmc.security.common.msg.ObjectRestResponse;
import com.mmc.security.common.rest.BaseController;
import com.mmc.security.record.biz.OrderBiz;
import com.mmc.security.record.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: mmc
* @create: 2019-06-19 23:19
**/
@RestController
@RequestMapping("order")
public class OrderController extends BaseController<OrderBiz,Order> {
@Autowired
private OrderBiz orderBiz;
@PostMapping("monthReport")
public ObjectRestResponse monthReport () {
return orderBiz.monthReport();
}
}
| 30.034483 | 71 | 0.755454 |
74a3fdac3493235b58b03db9cc0c6e53d89e1bcb | 843 | /*
* XML Type: ActClassROI
* Namespace: urn:hl7-org:v3
* Java type: uk.nhs.connect.iucds.cda.ucr.ActClassROI
*
* Automatically generated - do not modify.
*/
package uk.nhs.connect.iucds.cda.ucr.impl;
/**
* An XML ActClassROI(@urn:hl7-org:v3).
*
* This is a union type. Instances are of one of the following types:
* uk.nhs.connect.iucds.cda.ucr.ActClassROIX
*/
public class ActClassROIImpl extends org.apache.xmlbeans.impl.values.XmlUnionImpl implements uk.nhs.connect.iucds.cda.ucr.ActClassROI, uk.nhs.connect.iucds.cda.ucr.ActClassROIX
{
private static final long serialVersionUID = 1L;
public ActClassROIImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType, false);
}
protected ActClassROIImpl(org.apache.xmlbeans.SchemaType sType, boolean b)
{
super(sType, b);
}
}
| 29.068966 | 176 | 0.705813 |
6986c2c82a6a14cb08c42063fee128a9a07b95a0 | 811 | package org.shoulder.web.template.dictionary;
import org.shoulder.web.template.crud.CrudCacheableController;
import org.shoulder.web.template.dictionary.model.DictionaryEntity;
import org.shoulder.web.template.dictionary.service.DictionaryService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
/**
* 枚举型字典接口-默认实现
*
* @author lym
*/
@RestController
@RequestMapping(value = "${shoulder.web.ext.dictionary.path:/api/v1/dictionary}")
public class DictionaryCrudController<ID extends Serializable> extends CrudCacheableController<
DictionaryService<ID>, DictionaryEntity<ID>, ID, DictionaryEntity<ID>, DictionaryEntity<ID>, DictionaryEntity<ID>
> implements DictionaryController {
}
| 35.26087 | 121 | 0.806412 |
7276ac9e9147b8f33727a884b9b4fc1469bee4ba | 6,489 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.rest;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.concurrent.NotThreadSafe;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MediaType;
/**
* Method options for creating a REST API test case.
*/
// TODO(jiri): consolidate input stream and body fields
@NotThreadSafe
public final class TestCaseOptions {
/* Supported content types */
public static final String JSON_CONTENT_TYPE = MediaType.APPLICATION_JSON;
public static final String OCTET_STREAM_CONTENT_TYPE = MediaType.APPLICATION_OCTET_STREAM;
public static final String XML_CONTENT_TYPE = MediaType.APPLICATION_XML;
public static final String TEXT_PLAIN_CONTENT_TYPE = MediaType.TEXT_PLAIN;
/* Headers */
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String CONTENT_TYPE_HEADER = "Content-Type";
public static final String CONTENT_MD5_HEADER = "Content-MD5";
private String mAuthorization;
private String mContentType;
private String mMD5;
// mHeaders contains the previously defined headers
// - Users may add additional headers
private final Map<String, String> mHeaders;
private Object mBody;
private Charset mCharset; // used when converting byte data into strings
private boolean mPrettyPrint; // used for ObjectMapper when printing strings
/**
* @return the default {@link TestCaseOptions}
*/
public static TestCaseOptions defaults() {
return new TestCaseOptions();
}
private TestCaseOptions() {
mAuthorization = null;
mBody = null;
mContentType = OCTET_STREAM_CONTENT_TYPE;
mCharset = StandardCharsets.UTF_8;
mHeaders = new HashMap<>();
mMD5 = null;
mPrettyPrint = false;
}
/**
* @return the object representing the data to be sent to the web server
*/
public Object getBody() {
return mBody;
}
/**
* @return the pretty print flag
*/
public boolean isPrettyPrint() {
return mPrettyPrint;
}
/**
* @return the content type
*/
public String getContentType() {
return mContentType;
}
/**
* @return the Base64 encoded MD5 digest of the request body
*/
public String getMD5() {
return mMD5;
}
/**
* @return the authorization header
*/
public String getAuthorization() {
return mAuthorization;
}
/**
* @return the charset map
*/
public Charset getCharset() {
return mCharset;
}
/**
* @return the headers map
*/
public Map<String, String> getHeaders() {
return mHeaders;
}
/**
* @param body the body to use
* @return the updated options object
*/
public TestCaseOptions setBody(Object body) {
mBody = body;
return this;
}
/**
* @param prettyPrint the pretty print flag value to use
* @return the updated options object
*/
public TestCaseOptions setPrettyPrint(boolean prettyPrint) {
mPrettyPrint = prettyPrint;
return this;
}
/**
* @param contentType the content type to set
* @return the updated options object
*/
public TestCaseOptions setContentType(String contentType) {
mContentType = contentType;
mHeaders.put(CONTENT_TYPE_HEADER, contentType);
return this;
}
/**
* @param md5 the Base64 encoded MD5 digest of the request body
* @return the updated options object
*/
public TestCaseOptions setMD5(String md5) {
mMD5 = md5;
mHeaders.put(CONTENT_MD5_HEADER, md5);
return this;
}
/**
* @param authorization the authorization header
* @return the updated options object
*/
public TestCaseOptions setAuthorization(String authorization) {
mAuthorization = authorization;
mHeaders.put(AUTHORIZATION_HEADER, authorization);
return this;
}
/**
* @param charset the charset to use
* @return the updated options object
*/
public TestCaseOptions setCharset(@NotNull Charset charset) {
mCharset = charset;
return this;
}
/**
* Adds the provided headers to the existing headers map. Overwrites duplicate keys.
* Note that this does not update the class header fields if you overwrite them.
* @param headers headers map
* @return the updated options object
*/
public TestCaseOptions addHeaders(@NotNull Map<String, String> headers) {
mHeaders.putAll(headers);
return this;
}
/**
* Adds the provided header to the existing headers map. Overwrites duplicate keys.
* Note that this does not update the class header fields if you overwrite them.
* @param key header key
* @param value header value
* @return the updated options object
*/
public TestCaseOptions addHeader(String key, String value) {
mHeaders.put(key, value);
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TestCaseOptions)) {
return false;
}
TestCaseOptions that = (TestCaseOptions) o;
return Objects.equal(mAuthorization, that.mAuthorization)
&& Objects.equal(mBody, that.mBody)
&& Objects.equal(mCharset, that.mCharset)
&& Objects.equal(mContentType, that.mContentType)
&& Objects.equal(mHeaders, that.mHeaders)
&& Objects.equal(mMD5, that.mMD5)
&& mPrettyPrint == that.mPrettyPrint;
}
@Override
public int hashCode() {
return Objects.hashCode(mAuthorization, mBody, mCharset, mContentType, mHeaders, mMD5,
mPrettyPrint);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("authorization", mAuthorization)
.add("body", mBody)
.add("charset", mCharset)
.add("content type", mContentType)
.add("headers", mHeaders)
.add("MD5", mMD5)
.add("pretty print", mPrettyPrint)
.toString();
}
}
| 27.495763 | 98 | 0.696872 |
81e2b03a9ea5adc96917a6b850755b54e631d159 | 5,262 | package top.feb13th.athena.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.feb13th.athena.core.message.JsonMessageConvert;
import top.feb13th.athena.core.message.MessageConvert;
import top.feb13th.athena.server.protocol.DefaultServerChannelInitializer;
import top.feb13th.athena.core.util.ExceptionUtil;
import top.feb13th.athena.core.util.ObjectUtil;
/**
* 默认实现的服务器启动类
*
* @author zhoutaotao
* @date 2019/8/30 11:10
*/
public class DefaultServerApplication implements ServerApplication {
// 日志
private static final Logger logger = LoggerFactory.getLogger(DefaultServerApplication.class);
private static final int DEFAULT_PORT = 9111;
private static final int DEFAULT_IDLE_TIME = 10;
private static final int DEFAULT_SESSION_AUTH_EXPIRE_TIME = 3;
// 端口
@Getter
@Setter
private int port = DEFAULT_PORT;
// 心跳检测时间, 单位:秒
@Getter
@Setter
private int idleTimeSecond = DEFAULT_IDLE_TIME;
// 会话授权过期时间
@Getter
@Setter
private int sessionAuthExpireSecond = DEFAULT_SESSION_AUTH_EXPIRE_TIME;
// 消息转换器
@Getter
@Setter
private MessageConvert messageConvert = new JsonMessageConvert();
// channel 初始化器
@Setter
private ChannelInitializer<SocketChannel> channelInitializer;
// 事件驱动线程池
@Getter
@Setter
private EventLoopGroup bossGroup = new NioEventLoopGroup();
@Getter
@Setter
private EventLoopGroup workerGroup = new NioEventLoopGroup();
@Getter
@Setter
private Class<? extends ServerChannel> channelClass = NioServerSocketChannel.class;
// boss管道参数
private final Map<ChannelOption, Object> bossOptions = new HashMap<>();
// worker管道参数
private final Map<ChannelOption, Object> workerOptions = new HashMap<>();
@Getter
private ChannelFuture channelFuture;
public DefaultServerApplication() {
// bean 创建完成后进行基础的初始化
addBossOption(ChannelOption.SO_BACKLOG, 128);
addWorkerOption(ChannelOption.SO_KEEPALIVE, true);
}
@Override
@SuppressWarnings("unchecked")
public ChannelFuture run() {
try {
// 服务器启动脚本
ServerBootstrap serverBootstrap = new ServerBootstrap();
// 线程池
serverBootstrap.group(getBossGroup(), getWorkerGroup());
// 线程模型
serverBootstrap.channel(getChannelClass());
serverBootstrap.childHandler(getChannelInitializer());
// channel 参数
for (Entry<ChannelOption, Object> entry : bossOptions.entrySet()) {
serverBootstrap.option(entry.getKey(), entry.getValue());
}
// 子channel参数
for (Entry<ChannelOption, Object> entry : workerOptions.entrySet()) {
serverBootstrap.childOption(entry.getKey(), entry.getValue());
}
// 启用服务器
channelFuture = serverBootstrap.bind(port).sync();
} catch (InterruptedException e) {
logger.error("服务器启动失败", e);
throw ExceptionUtil.unchecked(e);
} finally {
closeEventLoopGroup();
}
return channelFuture;
}
@Override
public void close() {
try {
if (ObjectUtil.nonNull(channelFuture)) {
channelFuture.channel().closeFuture().sync();
}
} catch (InterruptedException e) {
throw ExceptionUtil.unchecked(e);
} finally {
closeEventLoopGroup();
}
}
/**
* 关闭事件线程池
*/
private void closeEventLoopGroup() {
if (ObjectUtil.nonNull(bossGroup)) {
bossGroup.shutdownGracefully();
}
if (ObjectUtil.nonNull(workerGroup)) {
workerGroup.shutdownGracefully();
}
}
/**
* 获取channel初始化器
*/
public ChannelInitializer<SocketChannel> getChannelInitializer() {
if (ObjectUtil.isNull(channelInitializer)) {
channelInitializer = new DefaultServerChannelInitializer(getIdleTimeSecond(),
getSessionAuthExpireSecond(), getMessageConvert());
}
return channelInitializer;
}
/**
* 添加boss管道参数 - 值为null时则移除当前参数项
*
* @param option 参数项
* @param value 参数值
* @param <T> 值类型
*/
public <T> void addBossOption(ChannelOption<T> option, T value) {
if (option == null) {
throw new NullPointerException("option");
}
if (value == null) {
synchronized (bossOptions) {
bossOptions.remove(option);
}
} else {
synchronized (bossOptions) {
bossOptions.put(option, value);
}
}
}
/**
* 添加worker管道参数 - 值为null时则移除当前参数项
*
* @param option 参数项
* @param value 参数值
* @param <T> 值类型
*/
public <T> void addWorkerOption(ChannelOption<T> option, T value) {
if (option == null) {
throw new NullPointerException("option");
}
if (value == null) {
synchronized (workerOptions) {
workerOptions.remove(option);
}
} else {
synchronized (workerOptions) {
workerOptions.put(option, value);
}
}
}
}
| 27.123711 | 95 | 0.696883 |
0f2e9573b286d07c83af7b2c2ddfe2420752716f | 4,564 | package org.flowvisor.config;
import java.io.FileNotFoundException;
import org.flowvisor.VeRTIGO;
import org.flowvisor.api.APIServer;
import org.flowvisor.api.JettyServer;
import org.flowvisor.exceptions.DuplicateControllerException;
import org.flowvisor.flows.FlowEntry;
import org.flowvisor.flows.FlowMap;
import org.flowvisor.flows.LinearFlowMap;
import org.flowvisor.flows.SliceAction;
import org.flowvisor.log.LogLevel;
import org.openflow.protocol.OFMatch;
/**
* List of things to populate FVConfig with on startup Everything here can be
* overridden from the config file
*
* @author capveg
*
*/
public class DefaultConfig {
static public void init(String rootPasswd) {
FVConfig.clear(); // remove any pre-existing config
// setup a bunch of default things in the config
FlowMap flowMap = new LinearFlowMap();
SliceAction aliceAction = new SliceAction("alice", SliceAction.WRITE);
SliceAction bobAction = new SliceAction("bob", SliceAction.WRITE);
OFMatch match = new OFMatch();
short alicePorts[] = { 0, 2, 3 };
String aliceMacs[] = { "00:00:00:00:00:02", "00:01:00:00:00:02" };
// short alicePorts[] = { 0 };
// String aliceMacs[] = {"00:00:00:00:00:02"};
int i, j;
match.setWildcards(OFMatch.OFPFW_ALL
& ~(OFMatch.OFPFW_DL_SRC | OFMatch.OFPFW_IN_PORT));
// add all of alice's rules
for (i = 0; i < alicePorts.length; i++) {
match.setInputPort(alicePorts[i]);
for (j = 0; j < aliceMacs.length; j++) {
match.setDataLayerSource(aliceMacs[j]);
flowMap.addRule(new FlowEntry(match.clone(), aliceAction));
}
}
short bobPorts[] = { 1, 3 };
String bobMacs[] = { "00:00:00:00:00:01", "00:01:00:00:00:01" };
// short bobPorts[] = { 3};
// String bobMacs[] = { "00:01:00:00:00:01"};
// add all of bob's rules
for (i = 0; i < bobPorts.length; i++) {
match.setInputPort(bobPorts[i]);
for (j = 0; j < bobMacs.length; j++) {
match.setDataLayerSource(bobMacs[j]);
flowMap.addRule(new FlowEntry(match.clone(), bobAction));
}
}
// now populate the config
try {
FVConfig.setInt(FVConfig.LISTEN_PORT, FVConfig.OFP_TCP_PORT);
FVConfig.setInt(FVConfig.API_WEBSERVER_PORT, APIServer
.getDefaultPort());
FVConfig.setInt(FVConfig.API_JETTY_WEBSERVER_PORT, JettyServer.default_jetty_port);
FVConfig.setString(FVConfig.VERSION_STR,
VeRTIGO.FLOWVISOR_VERSION);
FVConfig.setInt(FVConfig.CONFIG_VERSION_STR,
FVConfig.CONFIG_VERSION);
// checkpointing on by default
FVConfig.setBoolean(FVConfig.CHECKPOINTING, true);
// stats_desc hack on by default
FVConfig.setBoolean(FVConfig.STATS_DESC_HACK, true);
// topology server on by default
FVConfig.setBoolean(FVConfig.TOPOLOGY_SERVER, true);
// track flows off by default -- experimental feature
FVConfig.setBoolean(FVConfig.FLOW_TRACKING, false);
// set logging to NOTE by default
FVConfig.setString(FVConfig.LOG_THRESH, LogLevel.NOTE.toString());
/**
* @authors roberto.doriguzzi matteo.gerola
*/
FVConfig.setString(FVConfig.DB_TYPE,"ram");
FVConfig.setString(FVConfig.DB_IP,"127.0.0.1");
FVConfig.setInt(FVConfig.DB_PORT, 0);
FVConfig.setString(FVConfig.DB_USER,"flowvisor");
FVConfig.setString(FVConfig.DB_PASSWD,"flowvisor");
// create slices
FVConfig.createSlice(FVConfig.SUPER_USER, "none", 0, rootPasswd,
"sillysalt", "fvadmin@localhost", FVConfig.SUPER_USER);
FVConfig.createSlice("alice", "localhost", 54321, "alicePass",
"sillysalt", "alice@foo.com", FVConfig.SUPER_USER);
FVConfig.createSlice("bob", "localhost", 54322, "bobPass",
"sillysalt", "bob@foo.com", FVConfig.SUPER_USER);
// create switches
FVConfig.create(FVConfig.SWITCHES, ConfigType.DIR);
FVConfig.setFlowMap(FVConfig.FLOWSPACE, flowMap);
// set .switches.default.flood_perm to the super user
FVConfig.updateVersion_1_to_2();
} catch (ConfigError e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InvalidSliceName e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (DuplicateControllerException e) {
e.printStackTrace();
}
}
/**
* Print default config to stdout
*
* @param args
* @throws FileNotFoundException
*/
public static void main(String args[]) throws FileNotFoundException {
if (args.length == 0) {
System.err.println("Generating default config");
DefaultConfig.init("CHANGEME");
} else {
System.err.println("Reading config from: " + args[0]);
FVConfig.readFromFile(args[0]);
}
FVConfig.walk(new ConfigDumper(System.out));
}
}
| 33.313869 | 86 | 0.707932 |
0e6ea7dc179545700c11c98dbe9cb1a5a7b4607b | 2,339 | package com.Server.security;
import com.Server.service.impl.UserDetailsimpl;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* Class security use to Generate Token JWT.
* @author Krystian Cwioro Kamil Bieniasz Damian Mierzynski.
* @version 1.0
* @since 2020-12-29.
*/
@Component
public class JwtUtils {
/**Logger use to logger on server.*/
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${jwtSecret}")
/**SecretKey*/
private String jwtSecret;
/**Time experience token JWT.*/
@Value("${jwtExpirationMs}")
private int jwtExpirationMs;
/**Method used to generate token JWT.*/
public String generateJwtToken(Authentication authentication) {
UserDetailsimpl userDetails = (UserDetailsimpl) authentication.getPrincipal();
return Jwts.builder().setSubject(userDetails.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
/** Method to get username*/
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
/**Method validate /token JWT.*/
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (ExpiredJwtException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("Invalid token: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Token is expired: {}", e.getMessage());
} catch (SignatureException e) {
logger.error("Token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT string is empty : {}", e.getMessage());
}
return false;
}
}
| 35.439394 | 99 | 0.663104 |
df7249cf3865efccd2b815641c07fbc6bdb0637b | 672 | package io.github.talelin.latticy.model;
import io.github.talelin.latticy.model.BaseModel;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @author generator@TaleLin
* @since 2021-03-04
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("pms_attr_group")
public class PmsAttrGroupDO extends BaseModel {
/**
* 组名
*/
private String attrGroupName;
/**
* 排序
*/
private Integer sort;
/**
* 描述
*/
private String description;
/**
* 组图标
*/
private String icon;
}
| 16 | 53 | 0.66369 |
ce9354dc5c6fcae6b260f68b16b44a714d248d15 | 1,420 | class stick{
boolean taken = false;
public synchronized void take(){
while(taken){
try{ wait();}
catch(Exception e){}
}
taken=true;
}
public synchronized void drop(){
taken=false;
notifyAll();
}
}
class phil implements Runnable{
int num;
stick left;
stick right;
phil(int a, stick left , stick right){
num = a;
this.left = left;
this.right = right;
}
public void run(){
while(!Thread.interrupted()){
if(left.taken==false&&right.taken==false)
left.take();
System.out.println("---Left Stick taken by +"+num+" Philosopher ---");
right.take();
System.out.println("---Right Stick taken by +"+num+" Philosopher ---");
System.out.println("###Both sticks taken by Philosopher #"+num+" ###");
try{wait(150);}
catch(Exception e){}
left.drop();
right.drop();
System.out.println(num+" Philosopher has dropped both the sticks and is back in the queue");
}
}
}
public class din {
public static void main(String[] args){
stick[] sticks = new stick[5];
phil[] phils = new phil[5];
for(int i=0;i<5;i++) sticks[i] = new stick();
for(int i=0;i<5;i++) phils[i] = new phil(i+1,sticks[i],sticks[(i+1)%5]);
Thread[] t = new Thread[5];
for(int i=0;i<5;i++){
t[i] = new Thread(phils[i]);
t[i].start();
}
}
}
| 26.296296 | 99 | 0.553521 |
a4617e4a1ef9de9c7596ec4098aa9312e7ae40f0 | 2,645 | /*
* @author Ramesh Lingappa
*/
package com.jmandrillapi.http;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import com.jmandrillapi.enums.MediaType;
import com.jmandrillapi.utils.ObjectUtils;
/**
* The Class MandrillApiRequest.
*
* @param <T> the generic type
*/
public class MandrillApiRequest<T> {
/** The url. */
private String url;
/** The params. */
private Map<String, Object> params;
/** The resp content type. */
private MediaType respContentType = MediaType.JSON;
/** The response type. */
private Class<T> responseType;
/**
* Instantiates a new mandrill api request.
*
* @param url the url
*/
public MandrillApiRequest(String url) {
this.url(url);
}
/**
* Instantiates a new mandrill api request.
*
* @param url the url
* @param responseType the response type
*/
public MandrillApiRequest(String url, Class<T> responseType) {
this.url(url);
this.type(responseType);
}
/* Builder Methods */
/**
* Url.
*
* @param url the url
* @return the mandrill api request
*/
public MandrillApiRequest<T> url(String url) {
if (ObjectUtils.isBlank(url))
throw new IllegalArgumentException("invalid url value");
this.url = url;
return this;
}
/**
* Params.
*
* @param params the params
* @return the mandrill api request
*/
public MandrillApiRequest<T> params(Map<String, Object> params) {
this.params = params;
return this;
}
/**
* Type.
*
* @param responseType the response type
* @return the mandrill api request
*/
public MandrillApiRequest<T> type(Class<T> responseType) {
this.responseType = responseType;
if (responseType == null)
throw new IllegalArgumentException("invalid response type");
return this;
}
/**
* Resp content type.
*
* @param type the type
* @return the mandrill api request
*/
public MandrillApiRequest<T> respContentType(MediaType type) {
if (type != null)
this.respContentType = type;
return this;
}
/**
* Gets the params.
*
* @return the params
*/
public Map<String, Object> getParams() {
return this.params;
}
/**
* Gets the resp type.
*
* @return the resp type
*/
public Class<T> getRespType() {
return this.responseType;
}
/**
* Gets the resp content type.
*
* @return the resp content type
*/
public MediaType getRespContentType() {
return this.respContentType;
}
/**
* Builds the url.
*
* @return the url
* @throws MalformedURLException the malformed url exception
*/
public URL buildUrl() throws MalformedURLException {
return new URL(url + "." + respContentType.toString());
}
}
| 18.892857 | 66 | 0.670321 |
9564f14434c22fe5d3bc38d0e2fbd6e1f9048345 | 241 | package com.capco.noc.algo.strategy;
import com.capco.noc.algo.schema.Portfolio;
public interface StrategyCreator {
void defineInitialPortfolioAllocation(Portfolio portfolio);
void defineAccountStrategy(Portfolio portfolio);
}
| 21.909091 | 64 | 0.80083 |
352d78ec74a069ac108d5f4b50cbb42f78960590 | 6,663 | package com.qianmi.boat.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.VideoView;
import com.qianmi.boat.R;
import com.qianmi.boat.utils.ControllerManager;
import com.qianmi.boat.utils.L;
import com.qianmi.boat.widget.Controller;
import com.qianmi.boat.widget.Throttle2;
import com.qianmi.boat.widget.ThrottleBar;
import butterknife.Bind;
import butterknife.ButterKnife;
public class ControllerActivity extends Activity implements Controller.Trigger, Throttle2.ThrottleTrigger, ThrottleBar.ThrottleTrigger,MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
private static final String TEST_URL = "rtsp://192.168.1.101:8554/";
public static final String EXTRA_IP = "extra_ip";
public static final String EXTRA_PORT = "extra_port";
@Bind(R.id.controller_left)
Controller mControllerLeft;
@Bind(R.id.video)
VideoView mVideoView;
@Bind(R.id.throttle_right)
Throttle2 mThrottle;
@Bind(R.id.throttle_normal)
ThrottleBar throttleBar;
@Bind(R.id.throttle_servo)
ThrottleBar servoBar;
@Bind(R.id.tv_msg)
TextView mMsg;
@Bind(R.id.tv_msg_control)
TextView mMsgControl;
private Context mContext;
private int mVHeight;
private int mVWidth;
private Handler mInHandler;
private Handler mOutHandler;
private String ip;
private int port;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controller);
ButterKnife.bind(this);
initHandler();
mContext = this;
mControllerLeft.setTrigger(this);
mThrottle.setThrottleTrigger(this);
throttleBar.setThrottleTrigger(this);
servoBar.setThrottleTrigger(new ThrottleBar.ThrottleTrigger() {
@Override
public void onThrottleTrigger(int direction) {
ControllerManager.getInstance(mContext).sendMsg("s1," + (direction * 10));
}
});
servoBar.setMax(10);
servoBar.setPosition(5);
mVideoView.setOnPreparedListener(this);
mVideoView.setOnErrorListener(this);
mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
showMsg("缓冲数据...");
new Handler(mContext.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
showMsg("");
}
}, 3000);
return true;
}
});
Intent intent = getIntent();
if (intent != null) {
ip = intent.getStringExtra(EXTRA_IP);
port = Integer.parseInt(intent.getStringExtra(EXTRA_PORT));
}
showMsg("初始化...");
}
private void initHandler() {
mInHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
try {
if (msg.obj != null) {
String s = msg.obj.toString();
if (s.trim().length() > 0) {
mMsgControl.setText(s);
} else {
L.d("没有数据返回不更新");
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
};
mOutHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
try {
if (msg.obj != null) {
String s = msg.obj.toString();
if (msg.what == 1) {
mMsgControl.setText(s + " 发送成功");
} else {
mMsgControl.setText(s + " 发送失败");
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
};
}
@Override
protected void onResume() {
super.onResume();
connect(ip, port);
}
private void connect(String i, int p) {
ControllerManager.getInstance(mContext).connectServer(i, p, mContext, mInHandler, mOutHandler);
}
@Override
protected void onDestroy() {
super.onDestroy();
mVideoView.pause();
ControllerManager.getInstance(mContext).stopConnect();
}
@Override
public void onTrigger(int direction) {
switch (direction) {
case Controller.DIRECTION_LEFT:
L.d("trigger left");
L.d("connect the server ....");
ControllerManager.getInstance(mContext).sendMsg("s1,80");
break;
case Controller.DIRECTION_RIGHT:
L.d("trigger right");
L.d("sending msg...");
// ControllerManager.getInstance(mContext).sendMsg("helloworld");
ControllerManager.getInstance(mContext).sendMsg("s1,20");
break;
case Controller.DIRECTION_UP:
L.d("trigger up");
L.d("play rtsp");
String url = "rtsp://" + ip + ":8554/";
//playRtspStream(url);
break;
case Controller.DIRECTION_DOWN:
L.d("trigger down");
break;
}
}
private void playRtspStream(String rtspUrl){
L.d("display url : " + rtspUrl);
mVideoView.setVideoURI(Uri.parse(rtspUrl));
mVideoView.requestFocus();
mVideoView.start();
}
private void showMsg(String msg) {
if (mMsg != null) {
mMsg.setText(msg);
}
}
@Override
public void onPrepared(MediaPlayer mp) {
showMsg("连接成功");
mVHeight = mp.getVideoHeight();
mVWidth = mp.getVideoWidth();
L.d("video width and height : " + mVWidth + "," + mVHeight);
}
@Override
public void onThrottleTrigger(int direction) {
L.v("dir = "+direction);
ControllerManager.getInstance(mContext).sendMsg("m1,"+ (direction * 10));
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
showMsg("连接错误");
return true;
}
}
| 29.878924 | 196 | 0.556656 |
50c5eed41e8454c7566b77fa4ec5aa4ad61c90cd | 6,152 | //
// Decompiled by Procyon v0.5.36
//
package jdk.nashorn.internal.objects;
import jdk.nashorn.internal.codegen.CompilerConstants;
import java.lang.invoke.MethodHandles;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.arrays.ContinuousArrayData;
import java.lang.invoke.MethodHandle;
import java.nio.FloatBuffer;
import jdk.nashorn.internal.runtime.Property;
import java.util.Collection;
import java.util.Collections;
import jdk.nashorn.internal.runtime.arrays.TypedArrayData;
import java.nio.ByteBuffer;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.PropertyMap;
public final class NativeFloat32Array extends ArrayBufferView
{
public static final int BYTES_PER_ELEMENT = 4;
private static PropertyMap $nasgenmap$;
private static final Factory FACTORY;
public static NativeFloat32Array constructor(final boolean newObj, final Object self, final Object... args) {
return (NativeFloat32Array)ArrayBufferView.constructorImpl(newObj, args, NativeFloat32Array.FACTORY);
}
NativeFloat32Array(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
super(buffer, byteOffset, length);
}
@Override
protected Factory factory() {
return NativeFloat32Array.FACTORY;
}
@Override
protected boolean isFloatArray() {
return true;
}
protected static Object set(final Object self, final Object array, final Object offset) {
return ArrayBufferView.setImpl(self, array, offset);
}
protected static NativeFloat32Array subarray(final Object self, final Object begin, final Object end) {
return (NativeFloat32Array)ArrayBufferView.subarrayImpl(self, begin, end);
}
@Override
protected ScriptObject getPrototype(final Global global) {
return global.getFloat32ArrayPrototype();
}
static {
FACTORY = new Factory(4) {
@Override
public ArrayBufferView construct(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
return new NativeFloat32Array(buffer, byteOffset, length);
}
@Override
public Float32ArrayData createArrayData(final ByteBuffer nb, final int start, final int end) {
return new Float32ArrayData(nb.asFloatBuffer(), start, end);
}
@Override
public String getClassName() {
return "Float32Array";
}
};
$clinit$();
}
public static void $clinit$() {
NativeFloat32Array.$nasgenmap$ = PropertyMap.newMap(Collections.EMPTY_LIST);
}
private static final class Float32ArrayData extends TypedArrayData<FloatBuffer>
{
private static final MethodHandle GET_ELEM;
private static final MethodHandle SET_ELEM;
private Float32ArrayData(final FloatBuffer nb, final int start, final int end) {
super(((FloatBuffer)nb.position(start).limit(end)).slice(), end - start);
}
@Override
public Class<?> getElementType() {
return Double.TYPE;
}
@Override
public Class<?> getBoxedElementType() {
return Double.class;
}
@Override
protected MethodHandle getGetElem() {
return Float32ArrayData.GET_ELEM;
}
@Override
protected MethodHandle getSetElem() {
return Float32ArrayData.SET_ELEM;
}
private double getElem(final int index) {
try {
return ((FloatBuffer)this.nb).get(index);
}
catch (IndexOutOfBoundsException e) {
throw new ClassCastException();
}
}
private void setElem(final int index, final double elem) {
try {
if (index < ((FloatBuffer)this.nb).limit()) {
((FloatBuffer)this.nb).put(index, (float)elem);
}
}
catch (IndexOutOfBoundsException e) {
throw new ClassCastException();
}
}
@Override
public MethodHandle getElementGetter(final Class<?> returnType, final int programPoint) {
if (returnType == Integer.TYPE) {
return null;
}
return this.getContinuousElementGetter(this.getClass(), Float32ArrayData.GET_ELEM, returnType, programPoint);
}
@Override
public int getInt(final int index) {
return (int)this.getDouble(index);
}
@Override
public double getDouble(final int index) {
return this.getElem(index);
}
@Override
public double getDoubleOptimistic(final int index, final int programPoint) {
return this.getElem(index);
}
@Override
public Object getObject(final int index) {
return this.getDouble(index);
}
@Override
public ArrayData set(final int index, final Object value, final boolean strict) {
return this.set(index, JSType.toNumber(value), strict);
}
@Override
public ArrayData set(final int index, final int value, final boolean strict) {
return this.set(index, (double)value, strict);
}
@Override
public ArrayData set(final int index, final double value, final boolean strict) {
this.setElem(index, value);
return this;
}
static {
GET_ELEM = CompilerConstants.specialCall(MethodHandles.lookup(), Float32ArrayData.class, "getElem", Double.TYPE, Integer.TYPE).methodHandle();
SET_ELEM = CompilerConstants.specialCall(MethodHandles.lookup(), Float32ArrayData.class, "setElem", Void.TYPE, Integer.TYPE, Double.TYPE).methodHandle();
}
}
}
| 33.802198 | 165 | 0.617848 |
484d0977cc184e8688be26cbab4a47e420adcd15 | 1,535 | package com.codethales.classesabstratas.domainmodel;
/* A palavra abstract impede a classe de ser instanciada. Ela se torna algo como um template.
* Essa ação é muito útil em casos onde desejamos que a classe seja utilizada apenas com o intuito de ser herdada
* para que seus atributos e métodos sejam utilizados por suas classes filhas.
* Neste exemplo, um Funcionário nunca deverá ser instanciado, considerando que Funcionário é uma abastração muito alta,
* uma generalização de tipos de funcionários, assim como a classe Pessoa, que é uma abstração ainda mais alta.
* O que queremos na verdade, são objetos que herdam caracteristias de um Funcionário, como gerente, desenvolvedor, etc.
*/
public abstract class Funcionario extends Pessoa {
protected String name;
protected double salary;
public Funcionario(String name, double salary) {
this.name = name;
this.salary = salary;
calculaBonus();
}
/* NO caso dos métodos abstratos, eles obrigam que as classes filhas implementem alguma versão desse método.
* Neste exemplo, eu quero que todos os 'tipos' de funcionários (gerente, desenvolvedor, etc.) tenham um cálculo
* específico de bônus, sem correr o risco de alguma subclasse não o implementar, recebendo o cálculo de bonus
* default que viria da super classe Funcionário. Por isso também, métodos astract não possuem corpo.
*/
public abstract void calculaBonus();
@Override
public void imprimir() {
System.out.println("Imprimindo...");
}
}
| 47.96875 | 119 | 0.744625 |
c223ac7f469a306dd8a6440044c57321bdcb5144 | 2,532 | package com.fans.fansrobot.listener;
import catcode.CatCodeUtil;
import com.fans.fansrobot.util.FileReaderUtils;
import love.forte.simbot.annotation.Filter;
import love.forte.simbot.annotation.OnGroup;
import love.forte.simbot.api.message.events.GroupMsg;
import love.forte.simbot.api.sender.MsgSender;
import love.forte.simbot.filter.MatchType;
import org.springframework.stereotype.Component;
/**
* 群聊消息监听器
*
* @author fans
* @date 2022/1/1
*/
@Component
public class GroupMsgListener {
@OnGroup
@Filter(value = "狗鑫", matchType = MatchType.CONTAINS)
public void hjx(GroupMsg msg, MsgSender msgSender) {
CatCodeUtil util = CatCodeUtil.getInstance();
String hjxImage = util.getStringCodeBuilder("image", true).key("file").value(FileReaderUtils.CLASS_PATH + "static/images/hjx.jpg").build();
msgSender.SENDER.sendGroupMsg(msg, "[CAT:at,code=" + msg.getAccountInfo().getAccountCode() + "] " + hjxImage);
}
@OnGroup
@Filter(value = "15", matchType = MatchType.CONTAINS)
public void cjw(GroupMsg msg, MsgSender msgSender) {
CatCodeUtil util = CatCodeUtil.getInstance();
String cjwImage = util.getStringCodeBuilder("image", true).key("file").value(FileReaderUtils.CLASS_PATH + "static/images/154gou.jpg").build();
msgSender.SENDER.sendGroupMsg(msg, "[CAT:at,code=" + msg.getAccountInfo().getAccountCode() + "] " + cjwImage);
}
@OnGroup
@Filter("粘贴板")
public void paste(GroupMsg msg, MsgSender msgSender) {
msgSender.SENDER.sendGroupMsg(msg, "[CAT:at,code=" + msg.getAccountInfo().getAccountCode() + "]粘贴板:\nhttps://paste.ubuntu.com/");
}
@OnGroup
@Filter(value = "合肥市人才政策", matchType = MatchType.CONTAINS)
public void talentsPolicy(GroupMsg msg, MsgSender msgSender) {
msgSender.SENDER.sendGroupMsg(msg, "[CAT:at,code=" + msg.getAccountInfo().getAccountCode() + "]合肥市人才政策:\nhttps://docs.qq.com/doc/DZEJEQXdCRkZiQlV1");
}
@OnGroup
@Filter(value = "牛马下班", matchType = MatchType.CONTAINS)
@Filter(value = "下班了", matchType = MatchType.CONTAINS)
@Filter(value = "下班啦", matchType = MatchType.CONTAINS)
public void xb(GroupMsg msg, MsgSender msgSender) {
CatCodeUtil util = CatCodeUtil.getInstance();
String xklImage = util.getStringCodeBuilder("image", true).key("file").value(FileReaderUtils.CLASS_PATH + "static/images/xkl.jpg").build();
msgSender.SENDER.sendGroupMsg(msg, "[CAT:at,code=" + msg.getAccountInfo().getAccountCode() + "] " + xklImage);
}
}
| 42.915254 | 157 | 0.702607 |
85de6db219168f633dddb88792ab9bf48792a3e8 | 8,767 | /*
* Disq
*
* MIT License
*
* Copyright (c) 2018-2019 Disq 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.disq_bio.disq.serializer;
import static com.google.common.base.Preconditions.checkNotNull;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import de.javakaffee.kryoserializers.CollectionsEmptyListSerializer;
import de.javakaffee.kryoserializers.CollectionsSingletonListSerializer;
import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer;
import org.apache.spark.serializer.KryoRegistrator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Kryo registrator for Disq.
*
* <p>To use this class, specify the following Spark configuration parameters
*
* <pre>
* spark.serializer=org.apache.spark.serializer.KryoSerializer
* spark.kryo.registrator=org.disq_bio.disq.serializer.DisqKryoRegistrator
* spark.kryo.registrationRequired=true
* </pre>
*
* To include the classes registered here in your own registrator, either extend DisqKryoRegistrator
*
* <pre>
* class MyKryoRegistrator extends DisqKryoRegistrator {
* public void registerClasses(final Kryo kryo) {
* super.registerClasses(kryo);
* kryo.register(MyClass.class);
* }
* }
* </pre>
*
* or extend by delegation
*
* <pre>
* class MyKryoRegistrator implements KryoRegistrator {
* public void registerClasses(final Kryo kryo) {
* DisqKryoRegistrator.registerDisqClasses(kryo);
* kryo.register(MyClass.class);
* }
* }
* </pre>
*/
public class DisqKryoRegistrator implements KryoRegistrator {
private final Logger logger = LoggerFactory.getLogger(DisqKryoRegistrator.class);
@Override
public void registerClasses(final Kryo kryo) {
// Register Avro classes using fully qualified class names
// Sort alphabetically and add blank lines between packages
// htsjdk.samtools
kryo.register(htsjdk.samtools.AlignmentBlock.class);
kryo.register(htsjdk.samtools.BAMRecord.class);
kryo.register(htsjdk.samtools.Chunk.class);
kryo.register(htsjdk.samtools.Cigar.class);
kryo.register(htsjdk.samtools.CigarElement.class);
kryo.register(htsjdk.samtools.CigarOperator.class);
kryo.register(htsjdk.samtools.SAMBinaryTagAndValue.class);
kryo.register(htsjdk.samtools.SAMFileHeader.class);
kryo.register(htsjdk.samtools.SAMFileHeader.GroupOrder.class);
kryo.register(htsjdk.samtools.SAMFileHeader.SortOrder.class);
kryo.register(htsjdk.samtools.SAMProgramRecord.class);
kryo.register(htsjdk.samtools.SAMReadGroupRecord.class);
kryo.register(htsjdk.samtools.SAMRecord.class);
kryo.register(htsjdk.samtools.SAMSequenceDictionary.class);
kryo.register(htsjdk.samtools.SAMSequenceRecord.class);
kryo.register(htsjdk.samtools.SBIIndex.class);
kryo.register(htsjdk.samtools.SBIIndex.Header.class);
kryo.register(htsjdk.samtools.ValidationStringency.class);
// htsjdk.samtools.cram.ref
kryo.register(htsjdk.samtools.cram.ref.ReferenceSource.class);
// htsjdk.samtools.reference
kryo.register(htsjdk.samtools.reference.FastaSequenceIndex.class);
kryo.register(htsjdk.samtools.reference.FastaSequenceIndexEntry.class);
kryo.register(htsjdk.samtools.reference.IndexedFastaSequenceFile.class);
// htsjdk.samtools.util
kryo.register(htsjdk.samtools.util.Interval.class);
// htsjdk.variant.variantcontext
kryo.register(htsjdk.variant.variantcontext.Allele.class);
kryo.register(htsjdk.variant.variantcontext.CommonInfo.class);
kryo.register(htsjdk.variant.variantcontext.FastGenotype.class);
kryo.register(htsjdk.variant.variantcontext.GenotypeType.class);
// Use JavaSerializer for LazyGenotypesContext to handle transient fields correctly
kryo.register(htsjdk.variant.variantcontext.LazyGenotypesContext.class, new JavaSerializer());
kryo.register(htsjdk.variant.variantcontext.VariantContext.class);
kryo.register(htsjdk.variant.variantcontext.VariantContext.Type.class);
// htsjdk.variant.vcf
kryo.register(htsjdk.variant.vcf.VCFCompoundHeaderLine.SupportedHeaderLineType.class);
kryo.register(htsjdk.variant.vcf.VCFContigHeaderLine.class);
kryo.register(htsjdk.variant.vcf.VCFFilterHeaderLine.class);
kryo.register(htsjdk.variant.vcf.VCFFormatHeaderLine.class);
kryo.register(htsjdk.variant.vcf.VCFHeader.class);
kryo.register(htsjdk.variant.vcf.VCFHeaderLine.class);
kryo.register(htsjdk.variant.vcf.VCFHeaderLineCount.class);
kryo.register(htsjdk.variant.vcf.VCFHeaderLineType.class);
kryo.register(htsjdk.variant.vcf.VCFInfoHeaderLine.class);
// java.io
kryo.register(java.io.FileDescriptor.class);
// java.lang
kryo.register(java.lang.Object.class);
kryo.register(java.lang.Object[].class);
// java.util
kryo.register(java.util.ArrayList.class);
kryo.register(
java.util.Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer());
kryo.register(
java.util.Collections.singletonList("").getClass(),
new CollectionsSingletonListSerializer());
kryo.register(java.util.HashMap.class);
kryo.register(java.util.HashSet.class);
kryo.register(java.util.LinkedHashMap.class);
registerByName(kryo, "java.util.LinkedHashMap$Entry");
registerByName(kryo, "java.util.LinkedHashMap$LinkedValueIterator");
kryo.register(java.util.LinkedHashSet.class);
kryo.register(java.util.TreeSet.class);
UnmodifiableCollectionsSerializer.registerSerializers(kryo);
// org.apache.spark.internal.io
kryo.register(org.apache.spark.internal.io.FileCommitProtocol.TaskCommitMessage.class);
// org.disq_bio.disq
kryo.register(org.disq_bio.disq.HtsjdkReadsTraversalParameters.class);
// org.disq_bio.disq.impl.formats.bam
kryo.register(
org.disq_bio.disq.impl.formats.bam.BamRecordGuesserChecker.RecordStartResult.class);
// org.disq_bio.disq.impl.formats.bgzf
kryo.register(org.disq_bio.disq.impl.formats.bgzf.BgzfBlockGuesser.BgzfBlock.class);
// scala.collection.immutable
registerByName(kryo, "scala.collection.immutable.Set$EmptySet$");
// scala.collection.mutable
kryo.register(scala.collection.mutable.WrappedArray.ofRef.class);
// sun.nio.ch
registerByName(kryo, "sun.nio.ch.FileChannelImpl");
registerByName(kryo, "sun.nio.ch.FileDispatcherImpl");
registerByName(kryo, "sun.nio.ch.NativeThreadSet");
// sun.nio.fs
registerByName(kryo, "sun.nio.fs.BsdFileSystem");
registerByName(kryo, "sun.nio.fs.BsdFileSystemProvider");
registerByName(kryo, "sun.nio.fs.LinuxFileSystem");
registerByName(kryo, "sun.nio.fs.LinuxFileSystemProvider");
registerByName(kryo, "sun.nio.fs.MacOSXFileSystem");
registerByName(kryo, "sun.nio.fs.MacOSXFileSystemProvider");
registerByName(kryo, "sun.nio.fs.SolarisFileSystem");
registerByName(kryo, "sun.nio.fs.SolarisFileSystemProvider");
registerByName(kryo, "sun.nio.fs.UnixFileSystem");
registerByName(kryo, "sun.nio.fs.UnixFileSystemProvider");
registerByName(kryo, "sun.nio.fs.UnixPath");
}
void registerByName(final Kryo kryo, final String className) {
try {
kryo.register(Class.forName(className));
} catch (ClassNotFoundException e) {
logger.debug("Unable to register class {} by name", e, className);
}
}
/**
* Register all classes serialized in Disq with the specified Kryo instance.
*
* @param kryo Kryo instance to register all classes serialized in Disq with, must not be null
*/
public static final void registerDisqClasses(final Kryo kryo) {
checkNotNull(kryo);
new DisqKryoRegistrator().registerClasses(kryo);
}
}
| 41.159624 | 100 | 0.760123 |
1b4f2026e13906b45484bbef67324266d91af28c | 2,408 | /*
*
*
* 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 eu.amidst.core.variables;
import java.io.Serializable;
/**
* This class defines the state space type.
*/
public abstract class StateSpaceType implements Serializable {
/** Represents the serial version ID for serializing the object. */
private static final long serialVersionUID = 4158293895929418259L;
/** Represents an enum of type {@link StateSpaceTypeEnum}. */
private StateSpaceTypeEnum stateSpaceTypeEnum;
/** Represents a String equal to "NA". */
private String unit="NA";
/**
* An empty constructor.
*/
public StateSpaceType(){}
/**
* Creates a new StateSpaceType for a given type.
* @param type the state space type.
*/
public StateSpaceType(StateSpaceTypeEnum type){
this.stateSpaceTypeEnum = type;
}
/**
* Returns the state space type.
* @return the state space type.
*/
public StateSpaceTypeEnum getStateSpaceTypeEnum(){
return this.stateSpaceTypeEnum;
}
/**
* Returns the unit of this StateSpaceType.
* @return the unit of this StateSpaceType.
*/
public String getUnit() {
return unit;
}
/**
* Sets the unit of this StateSpaceType.
* @param unit the unit.
*/
public void setUnit(String unit) {
this.unit = unit;
}
/**
* Returns an string representation of the associated value.
* @param value, a valid value of the state space.
* @return a string object representing the value.
*/
public abstract String stringValue(double value);
}
| 29.728395 | 111 | 0.675249 |
4b1fef77815f4bb447e65f8466c55139e09e5e2e | 1,000 | package jasmine.orm.query.impl;
import jasmine.orm.code.DbConfig;
import jasmine.orm.code.DbContext;
import jasmine.orm.table.TableMapping;
public class OracleDialectQueryImpl<T> extends AbstractSupportQueryImpl<T>{
public OracleDialectQueryImpl(TableMapping<T> tableMapping, DbConfig config) {
super(tableMapping, config);
// TODO Auto-generated constructor stub
}
public OracleDialectQueryImpl(TableMapping<T> tableMapping, DbContext context) {
super(tableMapping, context);
}
@Override
public String buildPagingSQL(int pageNo, int pageSize) {
int start = (pageNo - 1) * pageSize;
int end = pageNo * pageSize;
StringBuilder sql = new StringBuilder();
sql.append("SELECT * ");
sql.append("FROM (SELECT ROW_.*, ROWNUM ROWNUM_ ");
sql.append("FROM (");
sql.append(buildSelectSQL());
sql.append(") ROW_");
sql.append("WHERE ROWNUM <= "+end+") ");
sql.append("WHERE ROWNUM_ >= "+start+" ");
return sql.toString();
}
}
| 27.027027 | 82 | 0.692 |
26f3ba75ced80ba43537ec98cd1cead99ea3b083 | 4,846 | /**
* *****************************************************************************
*
* <p>Copyright 2017 Walmart, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
* <p>*****************************************************************************
*/
package com.oneops.proxy.config;
import static com.oneops.proxy.security.KeywhizKeyStore.Name.Keywhiz;
import static com.oneops.proxy.security.KeywhizKeyStore.Name.LDAP;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oneops.proxy.keywhiz.KeywhizAutomationClient;
import com.oneops.proxy.keywhiz.KeywhizClient;
import com.oneops.proxy.ldap.LdapClient;
import com.oneops.proxy.security.KeywhizKeyStore;
import java.security.GeneralSecurityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* Keywhiz proxy application java config.
*
* @author Suresh
*/
@Configuration
public class ApplicationConfig {
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* A {@link BeanFactoryPostProcessor} to validate the properties.
*
* @return {@link PropertyVerifier}
*/
@Bean
public static PropertyVerifier propertyVerifierBean() {
return new PropertyVerifier();
}
/**
* Show application arguments.
*
* @param config {@link OneOpsConfig}
* @return {@link CommandLineRunner}
*/
@Bean
public CommandLineRunner init(OneOpsConfig config) {
return args -> {
log.info("Starting OneOps Secret Management Server...");
log.info("Application config, " + config);
String cliArgs = String.join(", ", args);
log.info("Application arguments are, " + ((cliArgs.isEmpty()) ? "N/A" : cliArgs));
};
}
/**
* Returns the keystrore for keywhiz server
*
* @param config Keywhiz config properties.
* @param loader resource loader.
* @return {@link KeywhizKeyStore}
*/
@Bean(name = "keywhizKeyStore")
public KeywhizKeyStore keywhizKeyStore(OneOpsConfig config, ResourceLoader loader) {
OneOpsConfig.Keywhiz keywhiz = config.getKeywhiz();
return new KeywhizKeyStore(Keywhiz, keywhiz.getTrustStore(), keywhiz.getKeyStore(), loader);
}
/**
* Returns the keystrore for LDAP server
*
* @param config LDAP config properties.
* @param loader resource loader.
* @return {@link KeywhizKeyStore}
*/
@Bean(name = "ldapKeyStore")
public KeywhizKeyStore ldapKeyStore(OneOpsConfig config, ResourceLoader loader) {
OneOpsConfig.LDAP ldap = config.getLdap();
return new KeywhizKeyStore(LDAP, ldap.getTrustStore(), ldap.getKeyStore(), loader);
}
/** Returns the keywhiz http client */
@Bean
public KeywhizClient keywhizClient(
OneOpsConfig config, @Qualifier("keywhizKeyStore") KeywhizKeyStore keywhizKeyStore)
throws GeneralSecurityException {
OneOpsConfig.Keywhiz keywhiz = config.getKeywhiz();
return new KeywhizClient(keywhizKeyStore, keywhiz);
}
/** Returns the keywhiz automation client */
@Bean
public KeywhizAutomationClient keywhizAutomationClient(
OneOpsConfig config, @Qualifier("keywhizKeyStore") KeywhizKeyStore keywhizKeyStore)
throws GeneralSecurityException {
OneOpsConfig.Keywhiz keywhiz = config.getKeywhiz();
return new KeywhizAutomationClient(keywhizKeyStore, keywhiz);
}
/** Returns the LDAP client. */
@Bean
@Lazy
public LdapClient ldapClient(
OneOpsConfig config, @Qualifier("ldapKeyStore") KeywhizKeyStore keywhizKeyStore)
throws GeneralSecurityException {
return new LdapClient(config.getLdap(), keywhizKeyStore);
}
/**
* Json (de)serializer config.
*
* @return Object mapper.
*/
@Bean
public ObjectMapper objectMapper() {
return new Jackson2ObjectMapperBuilder()
.serializationInclusion(JsonInclude.Include.NON_NULL)
.build();
}
}
| 34.126761 | 99 | 0.717293 |
5ea909fd718854ca768d8d803444832cbfe47020 | 7,911 | package com.fr.swift.generate;
import com.fr.swift.beans.annotation.SwiftBean;
import com.fr.swift.beans.annotation.SwiftScope;
import com.fr.swift.bitmap.BitMaps;
import com.fr.swift.bitmap.ImmutableBitMap;
import com.fr.swift.bitmap.MutableBitMap;
import com.fr.swift.cube.io.Types.StoreType;
import com.fr.swift.cube.io.location.IResourceLocation;
import com.fr.swift.exception.meta.SwiftMetaDataException;
import com.fr.swift.log.SwiftLoggers;
import com.fr.swift.segment.Segment;
import com.fr.swift.segment.SegmentUtils;
import com.fr.swift.segment.column.BitmapIndexedColumn;
import com.fr.swift.segment.column.Column;
import com.fr.swift.segment.column.ColumnKey;
import com.fr.swift.segment.column.DetailColumn;
import com.fr.swift.segment.column.DictionaryEncodedColumn;
import com.fr.swift.segment.operator.column.SwiftColumnIndexer;
import com.fr.swift.setting.PerformancePlugManager;
import com.fr.swift.source.ColumnTypeConstants.ClassType;
import com.fr.swift.source.ColumnTypeUtils;
import com.fr.swift.source.SwiftMetaData;
import com.fr.swift.source.SwiftMetaDataColumn;
import com.fr.swift.structure.array.IntList;
import com.fr.swift.structure.array.IntListFactory;
import com.fr.swift.structure.external.map.ExternalMap;
import com.fr.swift.structure.external.map.intlist.BaseIntListExternalMap;
import com.fr.swift.structure.external.map.intlist.IntListExternalMapFactory;
import com.fr.swift.task.TaskResult.Type;
import com.fr.swift.task.impl.BaseWorker;
import com.fr.swift.task.impl.TaskResultImpl;
import com.fr.swift.util.Assert;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import static com.fr.swift.segment.column.impl.base.FakeStringDetailColumn.EXTERNAL_STRING;
/**
* @author anchore
* @date 2018/2/26
*/
@SwiftBean(name = "columnIndexer")
@SwiftScope("prototype")
public class ColumnIndexer<T> extends BaseWorker implements SwiftColumnIndexer {
private SwiftMetaData meta;
private ColumnKey key;
private List<Segment> segments;
/**
* segments通过外部传入
*
* @param key column key
* @param segments segs
*/
public ColumnIndexer(ColumnKey key, List<Segment> segments) {
Assert.notNull(key);
Assert.notEmpty(segments);
this.meta = segments.get(0).getMetaData();
this.key = key;
this.segments = segments;
}
@Override
public void work() {
try {
buildIndex();
workOver(new TaskResultImpl(Type.SUCCEEDED));
} catch (Exception e) {
SwiftLoggers.getLogger().error(e);
workOver(new TaskResultImpl(Type.FAILED, e));
}
}
@Override
public void buildIndex() throws Exception {
for (Segment segment : segments) {
try {
Column<T> column = getColumn(segment);
buildColumnIndex(column, segment.getRowCount());
} finally {
SegmentUtils.releaseColumnsOf(segment);
SegmentUtils.release(segment);
}
}
}
protected Column<T> getColumn(Segment segment) {
return segment.getColumn(key);
}
private void buildColumnIndex(Column<T> column, int rowCount) throws Exception {
Map<T, IntList> map = null;
IResourceLocation location = column.getLocation();
SwiftMetaDataColumn columnMeta = meta.getColumn(key.getName());
try {
if (isDetailInExternal(ColumnTypeUtils.getClassType(columnMeta),
location.getStoreType())) {
ExternalMap<T, IntList> extMap = newIntListExternalMap(
column.getDictionaryEncodedColumn().getComparator(),
location.buildChildLocation(EXTERNAL_STRING).getAbsolutePath());
extMap.readExternal();
map = extMap;
} else {
map = mapDictValueToRows(column, rowCount);
}
iterateBuildIndex(toIterable(map), column, rowCount);
} finally {
if (map != null) {
// ext map用完release,不然线程爆炸
map.clear();
}
}
}
private static boolean isDetailInExternal(ClassType klass, StoreType storeType) {
// 非内存的String类型没写明细,数据写到外排map里了,所以这里可以直接开始索引了
// @see FakeStringDetailColumn#calExternalLocation
// return klass == STRING && storeType != StoreType.MEMORY;
// string明细不写外排了
return false;
}
private Map<T, IntList> mapDictValueToRows(Column<T> column, int rowCount) throws SwiftMetaDataException {
DetailColumn<T> detailColumn = column.getDetailColumn();
ImmutableBitMap nullIndex = column.getBitmapIndex().getNullIndex();
Map<T, IntList> map;
Comparator<T> c = column.getDictionaryEncodedColumn().getComparator();
// 字典值 -> 值对应的所有行号
if (PerformancePlugManager.getInstance().isDiskSort()) {
BaseIntListExternalMap<T> extMap = newIntListExternalMap(c, column.getLocation().buildChildLocation("external_index").getAbsolutePath());
for (int i = 0; i < rowCount; i++) {
if (nullIndex.contains(i)) {
continue;
}
T val = detailColumn.get(i);
extMap.put(val, i);
}
map = extMap;
} else {
map = new TreeMap<T, IntList>(c);
for (int i = 0; i < rowCount; i++) {
if (nullIndex.contains(i)) {
continue;
}
T val = detailColumn.get(i);
if (map.containsKey(val)) {
map.get(val).add(i);
} else {
IntList list = IntListFactory.createIntList();
list.add(i);
map.put(val, list);
}
}
}
return map;
}
private void iterateBuildIndex(Iterable<Entry<T, IntList>> iterable, Column<T> column, int rowCount) {
DictionaryEncodedColumn<T> dictColumn = column.getDictionaryEncodedColumn();
BitmapIndexedColumn indexColumn = column.getBitmapIndex();
ImmutableBitMap nullIndex = indexColumn.getNullIndex();
// row -> index, 0作为null值行号的对应序号
int[] rowToIndex = new int[rowCount];
// 有效值序号从1开始
int pos = 0;
dictColumn.putter().putValue(pos++, null);
for (Entry<T, IntList> entry : iterable) {
T val = entry.getKey();
IntList rows = entry.getValue();
// 考虑到外排map会写入NULL_VALUE,这里判断下
if (nullIndex.contains(rows.get(0))) {
continue;
}
dictColumn.putter().putValue(pos, val);
MutableBitMap bitmap = BitMaps.newRoaringMutable();
for (int i = 0, len = rows.size(), row; i < len; i++) {
row = rows.get(i);
rowToIndex[row] = pos;
bitmap.add(row);
}
indexColumn.putBitMapIndex(pos, bitmap);
pos++;
}
dictColumn.putter().putSize(pos);
for (int row = 0, len = rowToIndex.length; row < len; row++) {
dictColumn.putter().putIndex(row, rowToIndex[row]);
}
}
private BaseIntListExternalMap<T> newIntListExternalMap(Comparator<T> c, String path) throws SwiftMetaDataException {
SwiftMetaDataColumn columnMeta = meta.getColumn(key.getName());
return (BaseIntListExternalMap<T>) IntListExternalMapFactory.getIntListExternalMap(ColumnTypeUtils.getClassType(columnMeta), c, path, true);
}
private static <V> Iterable<Entry<V, IntList>> toIterable(Map<V, IntList> map) {
if (map instanceof ExternalMap) {
return (ExternalMap<V, IntList>) map;
}
return map.entrySet();
}
} | 35.79638 | 149 | 0.627734 |
c2ce6b3013c104ba54cca61ffa58e9d3fd56f39c | 2,038 | /**
* Copyright 2017 ZTE Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onap.aai.esr.entity.rest;
public class VimAuthInfo {
private String cloudDomain;
private String userName;
private String password;
private String authUrl;
private String defaultTenant;
private String sslCacert;
private Boolean sslInsecure;
public String getCloudDomain() {
return cloudDomain;
}
public void setCloudDomain(String cloudDomain) {
this.cloudDomain = cloudDomain;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAuthUrl() {
return authUrl;
}
public void setAuthUrl(String authUrl) {
this.authUrl = authUrl;
}
public String getSslCacert() {
return sslCacert;
}
public void setSslCacert(String sslCacert) {
this.sslCacert = sslCacert;
}
public Boolean getSslInsecure() {
return sslInsecure;
}
public void setSslInsecure(Boolean sslInsecure) {
this.sslInsecure = sslInsecure;
}
public String getDefaultTenant() {
return defaultTenant;
}
public void setDefaultTenant(String defaultTenant) {
this.defaultTenant = defaultTenant;
}
}
| 22.395604 | 75 | 0.670265 |
12ec7c5a3db823f5c19780191c8614e26a0bea1f | 1,053 | package org.spica.javaclient.params;
public abstract class AbstractInputParam<T> implements InputParam<T>{
private String key;
private String displayname;
private T value;
private Renderer<T> renderer;
private boolean visible = true;
@Override
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public T getValue() {
return value;
}
@Override
public void setValue(T value) {
this.value = value;
}
@Override
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public Renderer<T> getRenderer() {
return renderer;
}
public void setRenderer(Renderer<T> renderer) {
this.renderer = renderer;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
| 17.847458 | 69 | 0.612536 |
7544f2b03bf1c601925876712b4c17654e14f159 | 171 | package manifold.util.cache;
public class IllegalTypeNameException extends RuntimeException
{
public IllegalTypeNameException( String msg )
{
super( msg );
}
}
| 17.1 | 62 | 0.754386 |
c6277f0beaa1a40cb45f2f3d2e63d1266c6dbaab | 2,370 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openspaces.core.config;
import org.openspaces.core.map.MapFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* @author kimchy
*/
public class MapBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
public static final String SPACE = "space";
protected Class getBeanClass(Element element) {
return MapFactoryBean.class;
}
protected boolean isEligibleAttribute(String attributeName) {
return super.isEligibleAttribute(attributeName) && !SPACE.equals(attributeName);
}
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
super.doParse(element, parserContext, builder);
String space = element.getAttribute(SPACE);
if (StringUtils.hasLength(space)) {
builder.addPropertyReference("space", space);
}
String compression = element.getAttribute("compression");
if (StringUtils.hasLength(compression)) {
builder.addPropertyValue("compression", compression);
}
Element localCacheSettingEle = DomUtils.getChildElementByTagName(element, "local-cache-support");
if (localCacheSettingEle != null) {
Object template = parserContext.getDelegate().parsePropertySubElement(localCacheSettingEle, builder.getRawBeanDefinition());
builder.addPropertyValue("localCacheSupport", template);
}
}
}
| 37.619048 | 136 | 0.74135 |
1759aa15b67c7854e245ea9c62385c1a67eda9df | 4,641 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.docs.v1.model;
/**
* A mask that indicates which of the fields on the base EmbeddedObjectBorder have been changed in
* this suggestion. For any field set to true, there is a new suggested value.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Docs API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class EmbeddedObjectBorderSuggestionState extends com.google.api.client.json.GenericJson {
/**
* Indicates if there was a suggested change to color.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean colorSuggested;
/**
* Indicates if there was a suggested change to dash_style.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dashStyleSuggested;
/**
* Indicates if there was a suggested change to property_state.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean propertyStateSuggested;
/**
* Indicates if there was a suggested change to width.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean widthSuggested;
/**
* Indicates if there was a suggested change to color.
* @return value or {@code null} for none
*/
public java.lang.Boolean getColorSuggested() {
return colorSuggested;
}
/**
* Indicates if there was a suggested change to color.
* @param colorSuggested colorSuggested or {@code null} for none
*/
public EmbeddedObjectBorderSuggestionState setColorSuggested(java.lang.Boolean colorSuggested) {
this.colorSuggested = colorSuggested;
return this;
}
/**
* Indicates if there was a suggested change to dash_style.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDashStyleSuggested() {
return dashStyleSuggested;
}
/**
* Indicates if there was a suggested change to dash_style.
* @param dashStyleSuggested dashStyleSuggested or {@code null} for none
*/
public EmbeddedObjectBorderSuggestionState setDashStyleSuggested(java.lang.Boolean dashStyleSuggested) {
this.dashStyleSuggested = dashStyleSuggested;
return this;
}
/**
* Indicates if there was a suggested change to property_state.
* @return value or {@code null} for none
*/
public java.lang.Boolean getPropertyStateSuggested() {
return propertyStateSuggested;
}
/**
* Indicates if there was a suggested change to property_state.
* @param propertyStateSuggested propertyStateSuggested or {@code null} for none
*/
public EmbeddedObjectBorderSuggestionState setPropertyStateSuggested(java.lang.Boolean propertyStateSuggested) {
this.propertyStateSuggested = propertyStateSuggested;
return this;
}
/**
* Indicates if there was a suggested change to width.
* @return value or {@code null} for none
*/
public java.lang.Boolean getWidthSuggested() {
return widthSuggested;
}
/**
* Indicates if there was a suggested change to width.
* @param widthSuggested widthSuggested or {@code null} for none
*/
public EmbeddedObjectBorderSuggestionState setWidthSuggested(java.lang.Boolean widthSuggested) {
this.widthSuggested = widthSuggested;
return this;
}
@Override
public EmbeddedObjectBorderSuggestionState set(String fieldName, Object value) {
return (EmbeddedObjectBorderSuggestionState) super.set(fieldName, value);
}
@Override
public EmbeddedObjectBorderSuggestionState clone() {
return (EmbeddedObjectBorderSuggestionState) super.clone();
}
}
| 33.15 | 182 | 0.73217 |
c89c6781cf63318270e0e9d5f8e331e5c1924ed4 | 2,428 | package com.pinger.model;
import java.util.ArrayList;
import java.util.List;
public class Site implements SiteLinkRepository {
private String tag;
private final String name;
private final String description;
private final SiteProdLink prodLink;
private final SiteDevLink devLink;
private final SiteTestLink testLink;
public Site(String tag, String name, String description, SiteProdLink prodLink, SiteDevLink devLink, SiteTestLink testLink) {
this.tag = tag;
this.name = name;
this.description = description;
this.prodLink = prodLink;
this.devLink = devLink;
this.testLink = testLink;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public SiteProdLink getProdLink() {
return prodLink;
}
public SiteDevLink getDevLink() {
return devLink;
}
public SiteTestLink getTestLink() {
return testLink;
}
@Override
public List<SiteLink> getAllLinks() {
final List<SiteLink> siteLinks = new ArrayList<>();
if (prodLink != null) siteLinks.add(prodLink);
if (devLink != null) siteLinks.add(devLink);
if (testLink != null) siteLinks.add(testLink);
return siteLinks;
}
@Override
public boolean isAnyLinkDown() {
boolean anyIsDown = false;
for (final SiteLink link : getAllLinks()) {
if (SiteStatus.DOWN.equals(link.getStatus())) {
anyIsDown = true;
break;
}
}
return anyIsDown;
}
@Override
public List<SiteLink> getAllOnlineLinks() {
final List<SiteLink> onlineLinks = new ArrayList<>();
for (final SiteLink link : getAllLinks()) {
if (SiteStatus.ONLINE.equals(link.getStatus())) {
onlineLinks.add(link);
}
}
return onlineLinks;
}
@Override
public List<SiteLink> getAllDownLinks() {
final List<SiteLink> downLinks = new ArrayList<>();
for (final SiteLink link : getAllLinks()) {
if (SiteStatus.DOWN.equals(link.getStatus())) {
downLinks.add(link);
}
}
return downLinks;
}
}
| 25.030928 | 129 | 0.593904 |
5298283560c98b853d1e93453fc8a8b6f392c44d | 4,807 | package com.vladykin.replicamap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TestMap<K,V> implements ReplicaMap<K,V> {
private Object id;
public Map<K,V> m;
protected final AtomicReference<ReplicaMapListener<K,V>> listener = new AtomicReference<>();
public TestMap(Map<K,V> m) {
this(0, m);
}
public TestMap(Object id, Map<K,V> m) {
this.id = id;
this.m = m;
}
@Override
public Object id() {
return id;
}
@Override
public ReplicaMapManager getManager() {
throw new UnsupportedOperationException();
}
@Override
public Map<K,V> unwrap() {
return m;
}
@Override
public CompletableFuture<V> asyncPut(K key, V value) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().put(key, value));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncPutIfAbsent(K key, V value) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().putIfAbsent(key, value));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncReplace(K key, V value) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().replace(key, value));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<Boolean> asyncReplace(K key, V oldValue, V newValue) {
CompletableFuture<Boolean> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().replace(key, oldValue, newValue));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncRemove(K key) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().remove(key));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<Boolean> asyncRemove(K key, V value) {
CompletableFuture<Boolean> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().remove(key, value));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncCompute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().compute(key, remappingFunction));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncComputeIfPresent(K key,
BiFunction<? super K,? super V,? extends V> remappingFunction) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().computeIfPresent(key, remappingFunction));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public CompletableFuture<V> asyncComputeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) {
V newValue = mappingFunction.apply(key);
return asyncPutIfAbsent(key, newValue).thenApply(v -> v == null ? newValue : v);
}
@Override
public CompletableFuture<V> asyncMerge(K key, V value,
BiFunction<? super V,? super V,? extends V> remappingFunction) {
CompletableFuture<V> fut = new CompletableFuture<>();
try {
fut.complete(unwrap().merge(key, value, remappingFunction));
}
catch (RuntimeException e) {
fut.completeExceptionally(e);
}
return fut;
}
@Override
public void setListener(ReplicaMapListener<K,V> listener) {
this.listener.set(listener);
}
@Override
public ReplicaMapListener<K,V> getListener() {
return listener.get();
}
@Override
public boolean casListener(ReplicaMapListener<K,V> expected, ReplicaMapListener<K,V> newListener) {
return listener.compareAndSet(expected, newListener);
}
}
| 28.443787 | 116 | 0.602039 |
55d3be97c401b821e741468f986eee53f4a547dc | 11,748 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twitter.distributedlog;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.google.common.base.Preconditions;
import com.twitter.distributedlog.exceptions.InvalidEnvelopedEntryException;
import org.apache.bookkeeper.stats.Counter;
import org.apache.bookkeeper.stats.OpStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
import com.twitter.distributedlog.annotations.DistributedLogAnnotations.Compression;
import com.twitter.distributedlog.io.CompressionCodec;
import com.twitter.distributedlog.io.CompressionUtils;
import com.twitter.distributedlog.util.BitMaskUtils;
/**
* An enveloped entry written to BookKeeper.
*
* Data type in brackets. Interpretation should be on the basis of data types and not individual
* bytes to honor Endianness.
*
* Entry Structure:
* ---------------
* Bytes 0 : Version (Byte)
* Bytes 1 - (DATA = 1+Header.length-1) : Header (Integer)
* Bytes DATA - DATA+3 : Payload Length (Integer)
* BYTES DATA+4 - DATA+4+payload.length-1 : Payload (Byte[])
*
* V1 Header Structure: // Offsets relative to the start of the header.
* -------------------
* Bytes 0 - 3 : Flags (Integer)
* Bytes 4 - 7 : Original payload size before compression (Integer)
*
* Flags: // 32 Bits
* -----
* 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
* |_|
* |
* Compression Type
*
* Compression Type: // 2 Bits (Least significant)
* ----------------
* 00 : No Compression
* 01 : LZ4 Compression
* 10 : Unused
* 11 : Unused
*/
public class EnvelopedEntry {
public static final int VERSION_LENGTH = 1; // One byte long
public static final byte VERSION_ONE = 1;
public static final byte LOWEST_SUPPORTED_VERSION = VERSION_ONE;
public static final byte HIGHEST_SUPPORTED_VERSION = VERSION_ONE;
public static final byte CURRENT_VERSION = VERSION_ONE;
private final OpStatsLogger compressionStat;
private final OpStatsLogger decompressionStat;
private final Counter compressedEntryBytes;
private final Counter decompressedEntryBytes;
private final byte version;
private Header header = new Header();
private Payload payloadCompressed = new Payload();
private Payload payloadDecompressed = new Payload();
public EnvelopedEntry(byte version,
StatsLogger statsLogger) throws InvalidEnvelopedEntryException {
Preconditions.checkNotNull(statsLogger);
if (version < LOWEST_SUPPORTED_VERSION || version > HIGHEST_SUPPORTED_VERSION) {
throw new InvalidEnvelopedEntryException("Invalid enveloped entry version " + version + ", expected to be in [ "
+ LOWEST_SUPPORTED_VERSION + " ~ " + HIGHEST_SUPPORTED_VERSION + " ]");
}
this.version = version;
this.compressionStat = statsLogger.getOpStatsLogger("compression_time");
this.decompressionStat = statsLogger.getOpStatsLogger("decompression_time");
this.compressedEntryBytes = statsLogger.getCounter("compressed_bytes");
this.decompressedEntryBytes = statsLogger.getCounter("decompressed_bytes");
}
/**
* @param statsLogger
* Used for getting stats for (de)compression time
* @param compressionType
* The compression type to use
* @param decompressed
* The decompressed payload
* NOTE: The size of the byte array passed as the decompressed payload can be larger
* than the actual contents to be compressed.
*/
public EnvelopedEntry(byte version,
CompressionCodec.Type compressionType,
byte[] decompressed,
int length,
StatsLogger statsLogger)
throws InvalidEnvelopedEntryException {
this(version, statsLogger);
Preconditions.checkNotNull(compressionType);
Preconditions.checkNotNull(decompressed);
Preconditions.checkArgument(length >= 0, "Invalid bytes length " + length);
this.header = new Header(compressionType, length);
this.payloadDecompressed = new Payload(length, decompressed);
}
private boolean isReady() {
return (header.ready && payloadDecompressed.ready);
}
@Compression
public void writeFully(DataOutputStream out) throws IOException {
Preconditions.checkNotNull(out);
if (!isReady()) {
throw new IOException("Entry not writable");
}
// Version
out.writeByte(version);
// Header
header.write(out);
// Compress
CompressionCodec codec = CompressionUtils.getCompressionCodec(header.compressionType);
byte[] compressed = codec.compress(
payloadDecompressed.payload,
0,
payloadDecompressed.length,
compressionStat);
this.payloadCompressed = new Payload(compressed.length, compressed);
this.compressedEntryBytes.add(payloadCompressed.length);
this.decompressedEntryBytes.add(payloadDecompressed.length);
payloadCompressed.write(out);
}
@Compression
public void readFully(DataInputStream in) throws IOException {
Preconditions.checkNotNull(in);
// Make sure we're reading the right versioned entry.
byte version = in.readByte();
if (version != this.version) {
throw new IOException(String.format("Version mismatch while reading. Received: %d," +
" Required: %d", version, this.version));
}
header.read(in);
payloadCompressed.read(in);
// Decompress
CompressionCodec codec = CompressionUtils.getCompressionCodec(header.compressionType);
byte[] decompressed = codec.decompress(
payloadCompressed.payload,
0,
payloadCompressed.length,
header.decompressedSize,
decompressionStat);
this.payloadDecompressed = new Payload(decompressed.length, decompressed);
this.compressedEntryBytes.add(payloadCompressed.length);
this.decompressedEntryBytes.add(payloadDecompressed.length);
}
public byte[] getDecompressedPayload() throws IOException {
if (!isReady()) {
throw new IOException("Decompressed payload is not initialized");
}
return payloadDecompressed.payload;
}
public static class Header {
public static final int COMPRESSION_CODEC_MASK = 0x3;
public static final int COMPRESSION_CODEC_NONE = 0x0;
public static final int COMPRESSION_CODEC_LZ4 = 0x1;
private int flags = 0;
private int decompressedSize = 0;
private CompressionCodec.Type compressionType = CompressionCodec.Type.UNKNOWN;
// Whether this struct is ready for reading/writing.
private boolean ready = false;
// Used while reading.
public Header() {
}
public Header(CompressionCodec.Type compressionType,
int decompressedSize) {
this.compressionType = compressionType;
this.decompressedSize = decompressedSize;
this.flags = 0;
switch (compressionType) {
case NONE:
this.flags = (int) BitMaskUtils.set(flags, COMPRESSION_CODEC_MASK,
COMPRESSION_CODEC_NONE);
break;
case LZ4:
this.flags = (int) BitMaskUtils.set(flags, COMPRESSION_CODEC_MASK,
COMPRESSION_CODEC_LZ4);
break;
default:
throw new RuntimeException(String.format("Unknown Compression Type: %s",
compressionType));
}
// This can now be written.
this.ready = true;
}
private void write(DataOutputStream out) throws IOException {
out.writeInt(flags);
out.writeInt(decompressedSize);
}
private void read(DataInputStream in) throws IOException {
this.flags = in.readInt();
int compressionType = (int) BitMaskUtils.get(flags, COMPRESSION_CODEC_MASK);
if (compressionType == COMPRESSION_CODEC_NONE) {
this.compressionType = CompressionCodec.Type.NONE;
} else if (compressionType == COMPRESSION_CODEC_LZ4) {
this.compressionType = CompressionCodec.Type.LZ4;
} else {
throw new IOException(String.format("Unsupported Compression Type: %s",
compressionType));
}
this.decompressedSize = in.readInt();
// Values can now be read.
this.ready = true;
}
}
public static class Payload {
private int length = 0;
private byte[] payload = null;
// Whether this struct is ready for reading/writing.
private boolean ready = false;
// Used for reading
Payload() {
}
Payload(int length, byte[] payload) {
this.length = length;
this.payload = payload;
this.ready = true;
}
private void write(DataOutputStream out) throws IOException {
out.writeInt(length);
out.write(payload, 0, length);
}
private void read(DataInputStream in) throws IOException {
this.length = in.readInt();
this.payload = new byte[length];
in.readFully(payload);
this.ready = true;
}
}
/**
* Return an InputStream that reads from the provided InputStream, decompresses the data
* and returns a new InputStream wrapping the underlying payload.
*
* Note that src is modified by this call.
*
* @return
* New Input stream with the underlying payload.
* @throws Exception
*/
public static InputStream fromInputStream(InputStream src,
StatsLogger statsLogger) throws IOException {
src.mark(VERSION_LENGTH);
byte version = new DataInputStream(src).readByte();
src.reset();
EnvelopedEntry entry = new EnvelopedEntry(version, statsLogger);
entry.readFully(new DataInputStream(src));
return new ByteArrayInputStream(entry.getDecompressedPayload());
}
}
| 39.555556 | 124 | 0.618829 |
5aac898c27a6cb1fca3c4ce071c5c016ae53d56c | 1,983 | package cn.com.myproject.learn.leetcode;
import org.springframework.util.CollectionUtils;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* 三数之和
* */
public class LeetCode15 {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.parallelSort(nums);
int len = nums.length;
int l,r;
int sum = 0;
List<Integer> list;
for(int i=0;i<len-2;i++){
if(nums[i]>0){
break;
}
//去重
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
l = i+1;
r = len-1;
while(l<r){
sum = nums[i]+nums[l]+nums[r];
if(sum==0) {
result.add(Arrays.asList(nums[i],nums[l],nums[r]));
// 去重
while (l<r && nums[l] == nums[l+1]) {
l++;
}
// 去重
while (l<r && nums[r] == nums[r-1]){
r--;
}
l++;
r--;
}else if(sum>0){
while(l < r && nums[r] == nums[r-1]){
r--;
}
r--;
//while(l < r && nums[r] == nums[--r]);
}else{
while(l < r && nums[l] == nums[l+1]){
l++;
}
l++;
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{1,2,-2,-1};
List<List<Integer>> result = threeSum(nums);
for(List<Integer> list : result) {
System.out.println(Arrays.toString(list.toArray()));
}
}
}
| 26.797297 | 71 | 0.377206 |
9faf2bc533c2ae440515e7c32530d45b05affda8 | 607 | package beone.acnt.service;
import java.util.List;
import java.util.Map;
import beone.acnt.vo.AcntVO;
import beone.corp.vo.CorpVO;
import beone.transaction.vo.TransactionVO;
public interface AcntService {
/**
* 계좌번호로 계좌 정보 검색
* @param no
* @return
*/
public AcntVO selectOne(String no);
/**
* 계좌 잔액 변경
* @param map (계좌번호, 금액)
*/
void updateBalance(Map<String, Object> map);
/**
* 유저 소유의 모든 계좌 조회
* @param corp
* @return
*/
List<AcntVO> selectAll(CorpVO corp);
/**
* 가장 최근에 개설된 계좌 하나만 가져오기
* @param corp
* @return
*/
AcntVO selectOneByRegDate(CorpVO corp);
}
| 15.973684 | 45 | 0.652389 |
de247d085fe2f130bc559b39096daff356fb5da2 | 5,831 | package com.sankholin.web.ui;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.xml.parsers.DocumentBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import com.sankholin.core.model.Car;
import com.sankholin.core.service.ICarService;
@Controller
public class CarController {
@Autowired
private Validator validator;
@Autowired
private ICarService iCarService;
//space1
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model) {
model.addAttribute("message", "Spring MVC Hello World");
return "home";
}
@RequestMapping("/car")
public String car(Model model) {
List<Car> carList = iCarService.findAll();
model.addAttribute("carList", carList);
return "car/carHome";
}
@RequestMapping("/car/list")
public String carList(Model model) {
List<Car> carList = iCarService.findAll();
model.addAttribute("carList", carList);
return "car/list";
}
@RequestMapping(value = "/car/add")
public String carAdd() {
return "car/add";
}
@RequestMapping(value = "/car/add", method = RequestMethod.POST)
public String carAddSubmit(@ModelAttribute("car") @Valid Car car, BindingResult result) {
// Read http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-beanvalidation-spring
Set<ConstraintViolation<Car>> violations = validator.validate(car);
for (ConstraintViolation<Car> violation : violations) {
String propertyPath = violation.getPropertyPath().toString();
String message = violation.getMessage();
// Add JSR-303 errors to BindingResult
// This allows Spring to display them in view via a FieldError
result.addError(new FieldError("car", propertyPath, "Invalid " + propertyPath + "(" + message + ")"));
}
if (result.hasErrors()) {
return "car/add";
}
iCarService.add(car);
return "redirect:/space1/car/list";
}
@RequestMapping(value = "/carvelo", method = RequestMethod.GET)
public String carvelo(Model model) {
List<Car> list = iCarService.findAll();
model.addAttribute("cars", list);
return "carvelo";
}
@RequestMapping(value = "/carfm", method = RequestMethod.GET)
public String carfm(@ModelAttribute("model") ModelMap model) {
List<Car> carList = iCarService.findAll();
model.addAttribute("carList", carList);
return "carfm";
}
@RequestMapping(value = "/fmlayout", method = RequestMethod.GET)
public String fmlayout(ModelMap model) {
model.addAttribute("message", "Knock, knock, anyone there!");
return "fmlayout";
}
//space2
@RequestMapping("/xslview")
public String xslview(Model model) throws Exception {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement("wordList");
List<String> words = Arrays.asList("Hello", "Spring", "Framework");
for (String word : words) {
Element wordNode = document.createElement("word");
Text textNode = document.createTextNode(word);
wordNode.appendChild(textNode);
root.appendChild(wordNode);
}
model.addAttribute("wordList", root);
return "xslview";
}
@RequestMapping("/employee")
public ModelAndView employee() throws Exception {
Resource resource = new ClassPathResource("citizens.xml");
ModelAndView model = new ModelAndView("employee");
model.addObject("xmlSource", resource);
return model;
}
//space3
@RequestMapping("/cover")
public String cover(ModelMap model) {
model.addAttribute("title", "Cover Page - Bootstrap");
return "cover";
}
@RequestMapping("/theme")
public String theme(ModelMap model) {
model.addAttribute("title", "Theme Page - Bootstrap");
return "theme";
}
@RequestMapping(value = {"/admin", "/admin/dashboard"})
public String dashboard(ModelMap model) {
model.addAttribute("title", "Dashboard - Bootstrap");
return "admin/dashboard";
}
//space4
@RequestMapping("/thyme")
public String thyme(ModelMap model) {
model.addAttribute("title", "Online - Thymeleaf");
model.addAttribute("message", "Welcome to Thymeleaf");
return "thyme";
}
@RequestMapping("/blog")
public String blog(ModelMap model) {
model.addAttribute("title", "Blog Home");
return "blog";
}
@RequestMapping("/thycars")
public String thycars(ModelMap model) {
model.addAttribute("title", "ThyCars");
return "thycars";
}
//common model attribute
@ModelAttribute("carList")
private List<Car> getCarList() {
return iCarService.findAll();
}
}
| 31.518919 | 138 | 0.667638 |
3964758fdacb9d12a59a2cef10f86a622c5a2d3e | 837 | package org.andot.share.common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
/**
* 使用jackson进行封装的json array工具方法
* @author andot
*/
public class JSONArray extends LinkedList {
private static final ObjectMapper objectMapper = new ObjectMapper();
public JSONArray() {
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* 返回当前集合的json字符串
* @return 如果返回为null, 则表示抛出异常
*/
public String toJsonString() {
if(this.size() == 0){
return "";
}
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
return null;
}
}
}
| 23.25 | 80 | 0.65233 |
c265d72b47ac138145bc3c898b1d75a907fa25d8 | 2,270 | package bc.gov.agri.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.web.cors.CorsUtils;
@Configuration
@EnableWebSecurity
@Profile("!dev")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter =
new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest)
.permitAll()
.antMatchers(HttpMethod.GET, "/v1/admin/dashboard")
.hasRole("NMPAdmin")
.antMatchers(HttpMethod.GET, "/v1/admin/stations")
.hasRole("NMPAdmin")
.antMatchers(HttpMethod.GET, "/v1/admin/stations/**")
.hasRole("NMPAdmin")
.antMatchers(HttpMethod.PUT, "/v1/admin/stations/**")
.hasRole("NMPAdmin")
.antMatchers(HttpMethod.POST, "/v1/page")
.hasRole("NMPAdmin")
.anyRequest()
.permitAll()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(this.jwtAuthenticationConverter());
}
}
| 39.137931 | 105 | 0.755066 |
128dc03caa97dfc588a67a35961a7349e3092518 | 302 | package com.example.diploma.admin.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AuthController {
@RequestMapping("/login")
public String getLoginPage() {
return "login";
}
}
| 20.133333 | 62 | 0.751656 |
7e5359fb4c35d7f414a7760801421d5584d53242 | 1,382 | package com.indeed.mph.serializers;
import com.indeed.util.core.Pair;
import com.indeed.mph.LinearDiophantineEquation;
import com.indeed.mph.SmartSerializer;
import javax.annotation.Nonnull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* @author xinjianz
*/
public class SmartPairSerializer<U, V> extends AbstractSmartSerializer<Pair<U, V>> {
private static final long serialVersionUID = 1325745619L;
private final SmartSerializer<U> serializer1;
private final SmartSerializer<V> serializer2;
public SmartPairSerializer(final SmartSerializer<U> serializer1,
final SmartSerializer<V> serializer2) {
this.serializer1 = serializer1;
this.serializer2 = serializer2;
}
@Override
public void write(@Nonnull final Pair<U, V> pair, final DataOutput out) throws IOException {
serializer1.write(pair.getFirst(), out);
serializer2.write(pair.getSecond(), out);
}
@Override
public Pair<U, V> read(final DataInput in) throws IOException {
return new Pair<>(serializer1.read(in), serializer2.read(in));
}
@Override
public LinearDiophantineEquation size() {
if (serializer1.size() == null) {
return null;
} else {
return serializer1.size().add(serializer2.size());
}
}
}
| 28.791667 | 96 | 0.680897 |
4edccab2d24bac263bf1addefe96898de9bd72d8 | 659 | package leetcode_problems.medium;
import java.util.HashMap;
import java.util.Map;
public class FourSumII_454 {
public int fourSumCount(int[] a, int[] b, int[] c, int[] d) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
map.put(a[i] + b[j], map.getOrDefault(a[i] + b[j], 0) + 1);
}
}
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
res += map.getOrDefault(0 - (c[i] + d[j]), 0);
}
}
return res;
}
}
| 25.346154 | 75 | 0.4522 |
ad54da66be6001e9cbafb11bc1a740c647f5a499 | 512 | package com.platform.aix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* @description:
* @author: fuyl
* @create: 2020-08-24 14:25
**/
@SpringBootApplication(scanBasePackages = {"com.platform"})
public class PlatformAixApplication {
public static void main(String[] args) {
SpringApplication.run(PlatformAixApplication.class);
}
}
| 28.444444 | 79 | 0.775391 |
43b10d19ccdb0a24cc0c2a1eccb0527daf7c4fa8 | 1,974 | package com.juyss.mapper.impl;
import com.juyss.mapper.BookMapper;
import com.juyss.pojo.Book;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author ShmeBluk
* @version 1.0
* @ClassName: BookMapperImpl
* @Desc: BookMapper实现类
* @package com.juyss.mapper.impl
* @project SSM-Merge
* @date 2020/9/13 18:41
*/
@Repository("bookMapper")
public class BookMapperImpl implements BookMapper {
private SqlSession sqlSession;
//自动注入sqlSession
@Autowired
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public BookMapperImpl() {
System.out.println("调用了BookMapperImpl类无参构造器");
}
/**
* 获取Book表所有数据
*
* @return Book数据集合
*/
@Override
public List<Book> getBookList() {
return sqlSession.getMapper(BookMapper.class).getBookList();
}
/**
* 获取指定id的Book
*
* @param id 要获取的Book
* @return 查询到的Book数据
*/
@Override
public Book getBookById(@Param("bookId") Integer id) {
return sqlSession.getMapper(BookMapper.class).getBookById(id);
}
/**
* 插入一条数据
*
* @param book 要插入的Book对象实例
* @return 受影响的行数
*/
@Override
public int insertBook(Book book) {
return sqlSession.getMapper(BookMapper.class).insertBook(book);
}
/**
* 更新一条数据
*
* @param book 要更新的Book对象实例
* @return 受影响的行数
*/
@Override
public int updateBook(Book book) {
return sqlSession.getMapper(BookMapper.class).updateBook(book);
}
/**
* 删除一条数据
*
* @param id 要删除的数据的id
* @return 受影响的行数
*/
@Override
public int deleteBookById(@Param("bookId") Integer id) {
return sqlSession.getMapper(BookMapper.class).deleteBookById(id);
}
}
| 21.692308 | 73 | 0.647416 |
02db044e23d89a9bdccf7849cc0d658b6a31d021 | 835 | package io.micronaut.validation.validator.customwithdefaultconstraints;
import io.micronaut.core.annotation.AnnotationValue;
import io.micronaut.validation.validator.constraints.ConstraintValidator;
import io.micronaut.validation.validator.constraints.ConstraintValidatorContext;
import jakarta.inject.Singleton;
import java.util.Objects;
@Singleton
public class EmployeeExperienceConstraintValidator implements ConstraintValidator<EmployeeExperienceConstraint, Employee> {
@Override
public boolean isValid(Employee value, AnnotationValue<EmployeeExperienceConstraint> annotationMetadata, ConstraintValidatorContext context) {
if (Objects.nonNull(value) && value.getExperience() <= 20) {
context.messageTemplate("Experience Ineligible");
return false;
}
return true;
}
}
| 37.954545 | 146 | 0.790419 |
526380d69fe7dca218f3e10365b01779ac562237 | 1,822 | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rust;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
public class RustLibrary extends RustLinkable {
public RustLibrary(
BuildRuleParams params,
SourcePathResolver resolver,
ImmutableSet<SourcePath> srcs,
ImmutableSet<String> features,
ImmutableList<String> rustcFlags,
Tool compiler) {
super(
params,
resolver,
srcs,
ImmutableList.<String>builder()
.add("--crate-type", "rlib")
.add("--emit", "link")
.addAll(rustcFlags)
.build(),
features,
BuildTargets.getGenPath(
params.getBuildTarget(), "%s/lib" + params.getBuildTarget().getShortName() + ".rlib"),
compiler);
}
@Override
public BuildableProperties getProperties() {
return new BuildableProperties(BuildableProperties.Kind.LIBRARY);
}
}
| 32.535714 | 98 | 0.705269 |
769c069f28f93f43936fb3062df164d7a74badff | 1,190 | /*
*
* Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.config.trait;
import com.speedment.runtime.config.Document;
/**
* A trait for {@link Document documents} that implement the
* {@link #mainInterface()} method.
*
* @author Per Minborg
* @since 2.3.0
*/
public interface HasMainInterface extends Document {
/**
* Returns the {@code Class} of the interface of this node.
* <p>
* This should <b>not</b> be overridden by implementing classes!
*
* @return the main interface class
*/
Class<? extends Document> mainInterface();
} | 29.75 | 80 | 0.697479 |
cef1e0956a721f62b9b062c0d3894757df41e545 | 13,427 | package com.tony.ngeno.ridealong;
import com.tony.ngeno.ridealong.models.Carpool;
import com.tony.ngeno.ridealong.models.RideRequestPost;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
public class Mapper {
// Member variables:
private Document mDocument;
private String tripURL;
// Constructors:
public Mapper() {
}
public Mapper(Carpool carpool) {
try {
String driverSource = carpool.getDriverPost().source.replaceAll(" ", "+");
String destination = carpool.getDriverPost().destination.replaceAll(" ", "+");
System.out.println("MAPPING Carpool from source @ " + carpool.getDriverPost().source + "...");
ArrayList<String> riderSources = new ArrayList<>();
for (RideRequestPost riderPost : carpool.getRiderPosts()) {
System.out.println("...to pickup rider @ " + riderPost.source + "...");
riderSources.add(riderPost.source.replaceAll(" ", "+"));
}
System.out.println("...to destination @ " + carpool.getDriverPost().destination + ".");
String urlString = getCarpoolUrlString(driverSource, destination, riderSources);
tripURL = urlString;
System.out.println("URL = " + urlString);
URL url = new URL(urlString);
DocumentFetcher documentFetcher = new DocumentFetcher();
mDocument = documentFetcher.execute(url).get();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// Information methods:
// returns the trip time (in seconds) of all legs of the carpool:
public int getTotalTripTime() {
return getCarpoolTotalTripDurationValue(mDocument);
}
// returns the trip distance (in meters) of all legs of the carpool:
public int getTotalTripDistance() {
return getCarpoolTotalTripDistanceValue(mDocument);
}
// returns a list of trip times (in seconds) for each leg of the carpool:
public ArrayList<Integer> getTripWaypointTimes() {
return getLegDurations(mDocument);
}
// returns a list of end addresses for each leg of the carpool:
public ArrayList<String> getTripWaypointAddresses() {
return getTripWaypointAddresses(mDocument);
}
// Helper methods:
private String getCarpoolUrlString(String driverSource, String destination, List<String> riderSources) {
if (riderSources.isEmpty()) {
System.out.println("ERROR: Mapper:riderSources.isEmpty()");
}
String urlString = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + driverSource // driverSource.latitude + "," + driverSource.longitude
+ "&destination=" + destination // destination.latitude + "," + destination.longitude
+ "&waypoints=optimize:true|"; // Use waypoints for pickup points.
// NOTE: optimize:true means will reorder the waypoints to create the fastest route.
Iterator<String> iterator = riderSources.iterator();
while (iterator.hasNext()) {
String riderSource = iterator.next();
urlString += riderSource; // riderSource.latitude + "," + riderSource.longitude;
if (iterator.hasNext()) {
urlString += "|"; // Add "|" between multiple waypoint stops.
}
}
urlString += "&sensor=false&units=imperial&mode=driving"; // imperial: miles
return urlString;
}
private int getCarpoolTotalTripDurationValue (Document doc) {
int duration = 0;
try {
XPath xPath = XPathFactory.newInstance().newXPath();
/*
XML format:
<route>
...
<leg>
...
<duration>
<value>1455</value>
<text>24 mins</text>
</duration>
</leg>
<leg>
...
</leg>
</route>
*/
// Go to a list of "leg" tags, wit each leg tag having a "duration" tag with a "value" tag within it:
NodeList nodeList = (NodeList) xPath.evaluate("//leg/duration/value", doc, XPathConstants.NODESET);
System.out.println("nodeList.getLength() = " + nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println("Leg/Duration/Value: Node Name[" + i + "] = " + node.getNodeName());
// OUTPUT = Leg/Duration/Value: Node Name[0] = value
System.out.println("Leg/Duration/Value: Node Value[" + i + "] = " + node.getTextContent());
// OUTPUT = Leg/Duration/Value: Node Value[0] = 1455
int legDuration = Integer.parseInt(node.getTextContent());
duration += legDuration;
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return duration;
}
private int getCarpoolTotalTripDistanceValue (Document doc) {
int distance = 0;
try {
XPath xPath = XPathFactory.newInstance().newXPath();
/*
XML format:
<route>
...
<leg>
...
<distance>
<value>1223</value>
<text>0.8 mi</text>
</distance>
</leg>
<leg>
...
</leg>
</route>
*/
// Go to a list of "leg" tags, wit each leg tag having a "distance" tag with a "value" tag within it:
NodeList nodeList = (NodeList) xPath.evaluate("//leg/distance/value", doc, XPathConstants.NODESET);
// System.out.println("nodeList.getLength() = " + nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
// System.out.println("Leg/Duration/Value: Node Name[" + i + "] = " + node.getNodeName());
// OUTPUT = Leg/Duration/Value: Node Name[0] = value
// System.out.println("Leg/Duration/Value: Node Value[" + i + "] = " + node.getTextContent());
// OUTPUT = Leg/Duration/Value: Node Value[0] = 1455
int legDistance = Integer.parseInt(node.getTextContent());
distance += legDistance;
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return distance;
}
private ArrayList<Integer> getLegDurations(Document doc) {
ArrayList<Integer> legDurations = new ArrayList<Integer>();
try {
XPath xPath = XPathFactory.newInstance().newXPath();
/*
XML format:
<route>
...
<leg>
...
<duration>
<value>1455</value>
<text>24 mins</text>
</duration>
</leg>
<leg>
...
</leg>
</route>
*/
// Go to a list of "leg" tags, wit each leg tag having a "duration" tag with a "value" tag within it:
NodeList nodeList = (NodeList) xPath.evaluate("//leg/duration/value", doc, XPathConstants.NODESET);
System.out.println("nodeList.getLength() = " + nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println("Leg/Duration/Value: Node Name[" + i + "] = " + node.getNodeName());
// OUTPUT = Leg/Duration/Value: Node Name[0] = value
System.out.println("Leg/Duration/Value: Node Value[" + i + "] = " + node.getTextContent());
// OUTPUT = Leg/Duration/Value: Node Value[0] = 1455
int legDuration = Integer.parseInt(node.getTextContent());
legDurations.add(legDuration);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return legDurations;
}
private ArrayList<String> getTripWaypointAddresses(Document doc) {
ArrayList<String> legEndAddresses = new ArrayList<String>();
try {
XPath xPath = XPathFactory.newInstance().newXPath();
/*
XML format:
<route>
...
<leg>
...
<start_address>123 N 10th St, San Jose, CA 95112, USA</start_address>
<end_address>437 N 7th St, San Jose, CA 95112, USA</end_address>
</leg>
<leg>
...
</leg>
</route>
*/
// Go to a list of "leg" tags, wit each leg tag having a "duration" tag with a "value" tag within it:
NodeList nodeList = (NodeList) xPath.evaluate("//leg/end_address", doc, XPathConstants.NODESET);
System.out.println("nodeList.getLength() = " + nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println("Leg/end_address: Node Name[" + i + "] = " + node.getNodeName());
// OUTPUT = Leg/Duration/Value: Node Name[0] = value
System.out.println("Leg/end_address: Node Value[" + i + "] = " + node.getTextContent());
// OUTPUT = Leg/Duration/Value: Node Value[0] = 1455
String legEndAddress = node.getTextContent();
legEndAddresses.add(legEndAddress);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return legEndAddresses;
}
public String getTripURL() {
return tripURL;
}
// //This method returns the latitude and longitude of an address
// private LatLng getLocationFromAddress(Context context, String strAddress) throws IOException {
// Geocoder coder = new Geocoder(context);
//
// List<Address> addressesFound = coder.getFromLocationName(strAddress, 1);
//
// Address address = addressesFound.get(0);
//
// return new LatLng(address.getLatitude(), address.getLongitude());
// }
//This method returns the latitude and longitude of an address
// private LatLng getLocationFromAddress(String strAddress) throws IOException {
//// Geocoder coder = new Geocoder(context);
////
//// List<Address> addressesFound = coder.getFromLocationName(strAddress, 1);
////
//// Address address = addressesFound.get(0);
////
//// return new LatLng(address.getLatitude(), address.getLongitude());
// return null;
// }
// // TODO: DELETE - TESTING ONLY:
// public void test() {
// String driverSource = "21250 Stevens Creek Blvd, Cupertino, CA 95014, USA".replaceAll(" ", "+");
// // String driverSource = driverSource1.replaceAll(" ", "+");// "21250+Stevens+Creek+Blvd,+Cupertino,+CA+95014,+USA";// new LatLng(37.3195396, -122.0450548); //
// String destination = "1+Washington+Sq,+San+Jose,+CA+95192,+USA"; // new LatLng(37.3351874, -121.8810715); //
//
// ArrayList<String> riderSources = new ArrayList<>();
// riderSources.add("470+N+10th+St,+San+Jose,+CA+95112,+USA"); // new LatLng(37.3487380, -121.8866706)); //
//
// String urlString = getCarpoolUrlString(driverSource, destination, riderSources);
//
// System.out.println("TEST URL = " + urlString);
// // http://maps.googleapis.com/maps/api/directions/xml?origin=37.3195396,-122.0450548&destination=37.3351874,-121.8810715&waypoints=optimize:true|37.348738,-121.8866706&sensor=false&units=metric&mode=driving
//
// try {
// URL url = new URL(urlString);
// DocumentFetcher documentFetcher = new DocumentFetcher();
// Document document = documentFetcher.execute(url).get();
//
// System.out.println("Document = " + document.toString());
//
// System.out.println("Duration (int) = " + getCarpoolTotalTripDurationValue(document));
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
// }
}
| 35.521164 | 216 | 0.549788 |
021dba8b066a33f30daf7e251188d3079b8652f3 | 76,635 | /*
Copyright (c) 2000-2020, Board of Trustees of Leland Stanford Jr. University.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lockss.crawler;
import java.util.*;
import junit.framework.Test;
import org.lockss.util.*;
import org.lockss.util.lang.LockssRandom;
import org.lockss.util.os.PlatformUtil;
import org.lockss.util.time.*;
import org.lockss.util.time.Deadline;
import org.lockss.util.time.TimeBase;
import org.lockss.test.*;
import org.lockss.state.*;
import org.lockss.plugin.*;
import org.lockss.plugin.exploded.*;
import org.lockss.daemon.*;
import org.lockss.config.*;
import org.lockss.alert.*;
/**
* Test class for CrawlManagerImpl.
*/
public class TestCrawlManagerImpl extends LockssTestCase {
public static final String GENERIC_URL = "http://www.example.com/index.html";
protected TestableCrawlManagerImpl crawlManager = null;
protected MockArchivalUnit mau = null;
protected MockLockssDaemon theDaemon;
protected MockCrawler crawler;
protected CachedUrlSet cus;
protected CrawlRule rule;
protected CrawlManager.StatusSource statusSource;
protected MyPluginManager pluginMgr;
//protected MockAuState maus;
protected Plugin plugin;
protected Properties cprops = new Properties();
protected List semsToGive;
public void setUp() throws Exception {
super.setUp();
semsToGive = new ArrayList();
// default enable is now false for laaws.
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWLER_ENABLED, "true");
// some tests start the service, but most don't want the crawl starter
// to run.
cprops.put(CrawlManagerImpl.PARAM_START_CRAWLS_INTERVAL, "0");
plugin = new MockPlugin(getMockLockssDaemon());
rule = new MockCrawlRule();
theDaemon = getMockLockssDaemon();
pluginMgr = new MyPluginManager();
pluginMgr.initService(theDaemon);
theDaemon.setPluginManager(pluginMgr);
crawlManager = new TestableCrawlManagerImpl(pluginMgr);
theDaemon.setCrawlManager(crawlManager);
statusSource = (CrawlManager.StatusSource)crawlManager;
crawlManager.initService(theDaemon);
}
void setUpMockAu() {
mau = new MockArchivalUnit();
mau.setPlugin(plugin);
mau.setCrawlRule(rule);
mau.setStartUrls(ListUtil.list("blah"));
mau.setCrawlWindow(new MockCrawlWindow(true));
PluginTestUtil.registerArchivalUnit(plugin, mau);
cus = mau.makeCachedUrlSet(new SingleNodeCachedUrlSetSpec(GENERIC_URL));
crawler = new MockCrawler();
crawlManager.setTestCrawler(crawler);
AuTestUtil.setUpMockAus(mau);
}
public void tearDown() throws Exception {
TimeBase.setReal();
for (Iterator iter = semsToGive.iterator(); iter.hasNext(); ) {
SimpleBinarySemaphore sem = (SimpleBinarySemaphore)iter.next();
sem.give();
}
crawlManager.stopService();
theDaemon.stopDaemon();
super.tearDown();
}
MockArchivalUnit newMockArchivalUnit(String auid) {
MockArchivalUnit mau = new MockArchivalUnit(plugin, auid);
AuTestUtil.setUpMockAus(mau);
return mau;
}
SimpleBinarySemaphore semToGive(SimpleBinarySemaphore sem) {
semsToGive.add(sem);
return sem;
}
String didntMsg(String what, long time) {
return "Crawl didn't " + what + " in " +
TimeUtil.timeIntervalToString(time);
}
protected void waitForCrawlToFinish(SimpleBinarySemaphore sem) {
if (!sem.take(TIMEOUT_SHOULDNT)) {
PlatformUtil.getInstance().threadDump(true);
TimerUtil.guaranteedSleep(1000);
fail(didntMsg("finish", TIMEOUT_SHOULDNT));
}
}
MockArchivalUnit[] makeMockAus(int n) {
MockArchivalUnit[] res = new MockArchivalUnit[n];
for (int ix = 0; ix < n; ix++) {
res[ix] = newMockArchivalUnit("mau" + ix);
}
return res;
}
public static class TestsWithAutoStart extends TestCrawlManagerImpl {
public void setUp() throws Exception {
super.setUp();
setUpMockAu();
theDaemon.setAusStarted(true);
cprops.put(CrawlManagerImpl.PARAM_USE_ODC, "false");
ConfigurationUtil.addFromProps(cprops);
crawlManager.startService();
}
public void testNullAuForIsCrawlingAu() {
try {
TestCrawlCB cb = new TestCrawlCB(new SimpleBinarySemaphore());
crawlManager.startNewContentCrawl(null, cb, "blah");
fail("Didn't throw an IllegalArgumentException on a null AU");
} catch (IllegalArgumentException iae) {
}
}
// public void testNewCrawlDeadlineIsMax() {
// SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
// crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null, null);
// waitForCrawlToFinish(sem);
// assertEquals(Deadline.MAX, crawler.getDeadline());
// }
public void testStoppingCrawlAbortsNewContentCrawl() throws Exception {
SimpleBinarySemaphore finishedSem = new SimpleBinarySemaphore();
//start the crawler, but use a crawler that will hang
TestCrawlCB cb = new TestCrawlCB(finishedSem);
SimpleBinarySemaphore sem1 = new SimpleBinarySemaphore();
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
//gives sem1 when doCrawl is entered, then takes sem2
MockCrawler crawler =
new HangingCrawler("testStoppingCrawlAbortsNewContentCrawl",
sem1, sem2);
semToGive(sem2);
crawlManager.setTestCrawler(crawler);
assertFalse(sem1.take(0));
crawlManager.startNewContentCrawl(mau, cb, null);
assertTrue(didntMsg("start", TIMEOUT_SHOULDNT),
sem1.take(TIMEOUT_SHOULDNT));
//we know that doCrawl started
// stopping AU should run AuEventHandler, which should cancel crawl
pluginMgr.stopAu(mau, AuEvent.forAu(mau, AuEvent.Type.Delete));
assertTrue(crawler.wasAborted());
}
public void testStoppingCrawlDoesntAbortCompletedCrawl() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertTrue("doCrawl() not called", crawler.doCrawlCalled());
crawlManager.auEventDeleted(AuEvent.forAu(mau, AuEvent.Type.Delete), mau);
assertFalse(crawler.wasAborted());
}
public void testStoppingCrawlAbortsRepairCrawl() {
String url1 = "http://www.example.com/index1.html";
String url2 = "http://www.example.com/index2.html";
List urls = ListUtil.list(url1, url2);
SimpleBinarySemaphore finishedSem = new SimpleBinarySemaphore();
//start the crawler, but use a crawler that will hang
TestCrawlCB cb = new TestCrawlCB(finishedSem);
SimpleBinarySemaphore sem1 = new SimpleBinarySemaphore();
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
//gives sem1 when doCrawl is entered, then takes sem2
MockCrawler crawler =
new HangingCrawler("testStoppingCrawlAbortsRepairCrawl",
sem1, sem2);
semToGive(sem2);
crawlManager.setTestCrawler(crawler);
crawlManager.startRepair(mau, urls, cb, null);
assertTrue(didntMsg("start", TIMEOUT_SHOULDNT),
sem1.take(TIMEOUT_SHOULDNT));
//we know that doCrawl started
crawlManager.auEventDeleted(AuEvent.forAu(mau, AuEvent.Type.Delete), mau);
assertTrue(crawler.wasAborted());
}
class AbortRecordingCrawler extends MockCrawler {
List<ArchivalUnit> abortedCrawls = new ArrayList<ArchivalUnit>();
public AbortRecordingCrawler(List<ArchivalUnit> abortedCrawlsList) {
super();
this.abortedCrawls = abortedCrawlsList;
}
public AbortRecordingCrawler(List<ArchivalUnit> abortedCrawlsList,
ArchivalUnit au) {
super(au);
this.abortedCrawls = abortedCrawlsList;
}
public void abortCrawl() {
abortedCrawls.add(getAu());
super.abortCrawl();
crawlManager.removeFromRunningCrawls(this);
}
List<ArchivalUnit> getAbortedCrawls() {
return abortedCrawls;
}
}
public void testAbortCrawl() {
theDaemon.setAusStarted(true);
List<ArchivalUnit> abortLst = new ArrayList<ArchivalUnit>();
MockArchivalUnit[] aus = makeMockAus(5);
for (ArchivalUnit au : aus) {
MockCrawler mc = new AbortRecordingCrawler(abortLst, au);
crawlManager.addToRunningCrawls(au, mc);
}
assertEmpty(abortLst);
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP,
"(4|5),3");
assertEmpty(abortLst);
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP,
"(4|5),-25000");
assertSameElements(ListUtil.list(aus[4]), abortLst);
crawlManager.addToRunningCrawls(aus[4],
new AbortRecordingCrawler(abortLst,
aus[4]));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP,
"(3|4|5),-25000");
// CrawlManagerImpl processes running crawls in indeterminate order
assertSameElements(ListUtil.list(aus[4], aus[3], aus[4]), abortLst);
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP,
"(3|4|5),-25000;(xx|yy),-26000");
assertSameElements(ListUtil.list(aus[4], aus[3], aus[4]), abortLst);
}
private void setNewContentRateLimit(String rate, String startRate,
String pluginRate) {
cprops.put(CrawlManagerImpl.PARAM_MAX_NEW_CONTENT_RATE, rate);
cprops.put(CrawlManagerImpl.PARAM_NEW_CONTENT_START_RATE, startRate);
cprops.put(CrawlManagerImpl.PARAM_MAX_PLUGIN_REGISTRY_NEW_CONTENT_RATE,
pluginRate);
ConfigurationUtil.addFromProps(cprops);
}
private void setRepairRateLimit(int events, long interval) {
cprops.put(CrawlManagerImpl.PARAM_MAX_REPAIR_RATE, events+"/"+interval);
ConfigurationUtil.addFromProps(cprops);
}
private void assertDoesCrawlNew(MockCrawler crawler) {
crawler.setDoCrawlCalled(false);
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertTrue("doCrawl() not called at time " + TimeBase.nowMs(),
crawler.doCrawlCalled());
}
private void assertDoesCrawlNew() {
assertDoesCrawlNew(crawler);
}
private void assertDoesNotCrawlNew() {
crawler.setDoCrawlCalled(false);
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertFalse("doCrawl() called at time " + TimeBase.nowMs(),
crawler.doCrawlCalled());
}
private void assertDoesCrawlRepair() {
crawler.setDoCrawlCalled(false);
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL),
new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertTrue("doCrawl() not called at time " + TimeBase.nowMs(),
crawler.doCrawlCalled());
}
private void assertDoesNotCrawlRepair() {
crawler.setDoCrawlCalled(false);
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL),
new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertFalse("doCrawl() called at time " + TimeBase.nowMs(),
crawler.doCrawlCalled());
}
void assertEligible(ArchivalUnit au)
throws CrawlManagerImpl.NotEligibleException {
assertTrue(crawlManager.isEligibleForNewContentCrawl(au));
crawlManager.checkEligibleForNewContentCrawl(au);
}
void assertNotEligible(String expectedExceptionMessageRE,
ArchivalUnit au) {
assertNotEligible(CrawlManagerImpl.NotEligibleException.class,
expectedExceptionMessageRE,
au);
}
void assertNotEligible(Class expectedExceptionClass,
String expectedExceptionMessageRE,
ArchivalUnit au) {
assertFalse(crawlManager.isEligibleForNewContentCrawl(au));
try {
crawlManager.checkEligibleForNewContentCrawl(au);
} catch (Exception e) {
assertClass(expectedExceptionClass, e);
assertMatchesRE(expectedExceptionMessageRE, e.getMessage());
}
}
void assertQueueable(ArchivalUnit au)
throws CrawlManagerImpl.NotEligibleException {
crawlManager.checkEligibleToQueueNewContentCrawl(au);
}
void assertNotQueueable(String expectedExceptionMessageRE,
ArchivalUnit au) {
assertNotQueueable(CrawlManagerImpl.NotEligibleException.class,
expectedExceptionMessageRE,
au);
}
void assertNotQueueable(Class expectedExceptionClass,
String expectedExceptionMessageRE,
ArchivalUnit au) {
try {
crawlManager.checkEligibleToQueueNewContentCrawl(au);
} catch (Exception e) {
assertClass(expectedExceptionClass, e);
assertMatchesRE(expectedExceptionMessageRE, e.getMessage());
}
}
void makeRateLimiterReturn(RateLimiter limiter, boolean val) {
if (val) {
while (!limiter.isEventOk()) {
limiter.unevent();
}
} else {
while (limiter.isEventOk()) {
limiter.event();
}
}
}
public void testIsEligibleForNewContentCrawl() throws Exception {
assertQueueable(mau);
assertEligible(mau);
crawlManager.setRunningNCCrawl(mau, true);
assertNotQueueable("is crawling now", mau);
assertNotEligible("is crawling now", mau);
crawlManager.setRunningNCCrawl(mau, false);
assertQueueable(mau);
assertEligible(mau);
mau.setCrawlWindow(new CrawlWindows.Never());
assertQueueable(mau);
assertNotEligible("window.*closed", mau);
mau.setCrawlWindow(new CrawlWindows.Always());
assertQueueable(mau);
assertEligible(mau);
RateLimiter limit = crawlManager.getNewContentRateLimiter(mau);
makeRateLimiterReturn(limit, false);
assertNotQueueable(CrawlManagerImpl.NotEligibleException.RateLimiter.class,
"Exceeds crawl-start rate", mau);
assertNotEligible(CrawlManagerImpl.NotEligibleException.RateLimiter.class,
"Exceeds crawl-start rate", mau);
makeRateLimiterReturn(limit, true);
assertQueueable(mau);
assertEligible(mau);
}
public void testDoesNCCrawl() {
assertDoesCrawlNew();
}
public void testDoesntNCCrawlWhenOutsideWindow() {
mau.setCrawlWindow(new ClosedCrawlWindow());
assertDoesNotCrawlNew();
}
public void testNewContentRateLimiter() {
TimeBase.setSimulated(100);
setNewContentRateLimit("4/100", "unlimited", "1/100000");
for (int ix = 1; ix <= 4; ix++) {
assertDoesCrawlNew();
TimeBase.step(10);
}
assertDoesNotCrawlNew();
TimeBase.step(10);
assertDoesNotCrawlNew();
TimeBase.step(50);
assertDoesCrawlNew();
TimeBase.step(500);
// ensure RateLimiter changes when config does
setNewContentRateLimit("2/5", "unlimited", "1/100000");
assertDoesCrawlNew();
assertDoesCrawlNew();
assertDoesNotCrawlNew();
TimeBase.step(5);
assertDoesCrawlNew();
assertDoesCrawlNew();
}
public void testPluginRegistryNewContentRateLimiter() {
crawlManager.setInternalAu(true);
TimeBase.setSimulated(100);
setNewContentRateLimit("1/1000000", "unlimited", "3/100");
for (int ix = 1; ix <= 3; ix++) {
assertDoesCrawlNew();
TimeBase.step(10);
}
assertDoesNotCrawlNew();
TimeBase.step(10);
assertDoesNotCrawlNew();
TimeBase.step(60);
assertDoesCrawlNew();
TimeBase.step(500);
// ensure RateLimiter changes when config does
setNewContentRateLimit("1/1000000", "unlimited", "2/5");
assertDoesCrawlNew();
assertDoesCrawlNew();
assertDoesNotCrawlNew();
TimeBase.step(5);
assertDoesCrawlNew();
assertDoesCrawlNew();
}
public void testNewContentRateLimiterWindowClose() {
TimeBase.setSimulated(100);
mau.setStartUrls(ListUtil.list("two"));
mau.setCrawlRule(new MockCrawlRule());
setNewContentRateLimit("1/10", "unlimited", "1/100000");
assertDoesCrawlNew();
assertDoesNotCrawlNew();
TimeBase.step(10);
assertDoesCrawlNew();
assertDoesNotCrawlNew();
TimeBase.step(10);
MockCrawler c2 = new CloseWindowCrawler();
crawlManager.setTestCrawler(mau, c2);
assertDoesCrawlNew(c2);
}
public void testRepairRateLimiter() {
TimeBase.setSimulated(100);
setRepairRateLimit(6, 200);
for (int ix = 1; ix <= 6; ix++) {
assertDoesCrawlRepair();
TimeBase.step(10);
}
assertDoesNotCrawlRepair();
TimeBase.step(10);
assertDoesNotCrawlRepair();
TimeBase.step(130);
assertDoesCrawlRepair();
TimeBase.step(500);
// ensure RateLimiter changes when config does
setRepairRateLimit(2, 5);
assertDoesCrawlRepair();
assertDoesCrawlRepair();
assertDoesNotCrawlRepair();
TimeBase.step(5);
assertDoesCrawlRepair();
}
public void testBasicNewContentCrawl() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null);
waitForCrawlToFinish(sem);
assertTrue("doCrawl() not called", crawler.doCrawlCalled());
}
//If the AU throws, the crawler should trap it and call the callbacks
public void testCallbacksCalledWhenPassedThrowingAU() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
ThrowingAU au = new ThrowingAU();
try {
crawlManager.startNewContentCrawl(au, cb, null);
fail("Should have thrown ExpectedRuntimeException");
} catch (ExpectedRuntimeException ere) {
assertTrue(cb.wasTriggered());
}
}
public void testRepairCrawlFreesActivityLockWhenDone() {
String url1 = "http://www.example.com/index1.html";
String url2 = "http://www.example.com/index2.html";
List urls = ListUtil.list(url1, url2);
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
CachedUrlSet cus1 =
mau.makeCachedUrlSet(new SingleNodeCachedUrlSetSpec(url1));
CachedUrlSet cus2 =
mau.makeCachedUrlSet(new SingleNodeCachedUrlSetSpec(url2));
crawlManager.startRepair(mau, urls, cb, null);
waitForCrawlToFinish(sem);
}
List<AuEvent.ContentChangeInfo> changeEvents = new ArrayList();
SimpleBinarySemaphore eventSem = new SimpleBinarySemaphore();
class MyAuEventHandler extends AuEventHandler.Base {
@Override public void auContentChanged(AuEvent event, ArchivalUnit au,
AuEvent.ContentChangeInfo info) {
changeEvents.add(info);
eventSem.give();
}
}
public void testAuEventCrawl() {
AuEventCrawler auc = new AuEventCrawler(mau);
crawler = auc;
auc.setCrawlSuccessful(true);
auc.setMimes(ListUtil.list(ListUtil.list("text1", "text/plain"),
ListUtil.list("html1", "text/html"),
ListUtil.list("html2", "text/html;charset=foo"),
ListUtil.list("pdf1", "application/pdf")));
crawlManager.setTestCrawler(auc);
pluginMgr.registerAuEventHandler(new MyAuEventHandler());
crawlManager.startNewContentCrawl(mau, null, null);
waitForCrawlToFinish(eventSem);
assertEquals(1, changeEvents.size());
AuEvent.ContentChangeInfo ci = changeEvents.get(0);
assertEquals(AuEvent.ContentChangeInfo.Type.Crawl, ci.getType());
assertTrue(ci.isComplete());
Map expMime = MapUtil.map("text/plain", 1,
"text/html", 2,
"application/pdf", 1);
assertEquals(4, ci.getNumUrls());
assertEquals(expMime, ci.getMimeCounts());
assertFalse(ci.hasUrls());
assertNull(ci.getUrls());
}
public void testAuEventCrawlAborted() {
AuEventCrawler auc = new AuEventCrawler(mau);
crawler = auc;
auc.setCrawlSuccessful(false);
auc.setMimes(ListUtil.list(ListUtil.list("text1", "text/plain"),
ListUtil.list("html1", "text/html"),
ListUtil.list("html2", "text/html;charset=foo"),
ListUtil.list("pdf1", "application/pdf")));
crawlManager.setTestCrawler(auc);
pluginMgr.registerAuEventHandler(new MyAuEventHandler());
crawlManager.startNewContentCrawl(mau, null, null);
waitForCrawlToFinish(eventSem);
assertEquals(1, changeEvents.size());
AuEvent.ContentChangeInfo ci = changeEvents.get(0);
assertEquals(AuEvent.ContentChangeInfo.Type.Crawl, ci.getType());
assertFalse(ci.isComplete());
Map expMime = MapUtil.map("text/plain", 1,
"text/html", 2,
"application/pdf", 1);
assertEquals(4, ci.getNumUrls());
assertEquals(expMime, ci.getMimeCounts());
assertFalse(ci.hasUrls());
assertNull(ci.getUrls());
}
public void testAuEventRepairCrawl() {
AuEventCrawler auc = new AuEventCrawler(mau);
crawler = auc;
auc.setCrawlSuccessful(true);
auc.setIsWholeAU(false);
auc.setMimes(ListUtil.list(ListUtil.list("text1", "text/plain"),
ListUtil.list("html1", "text/html"),
ListUtil.list("html2", "text/html;charset=foo"),
ListUtil.list("pdf1", "application/pdf")));
crawlManager.setTestCrawler(auc);
pluginMgr.registerAuEventHandler(new MyAuEventHandler());
crawlManager.startRepair(mau, ListUtil.list("foo"), null, null);
waitForCrawlToFinish(eventSem);
assertEquals(1, changeEvents.size());
AuEvent.ContentChangeInfo ci = changeEvents.get(0);
assertEquals(AuEvent.ContentChangeInfo.Type.Repair, ci.getType());
assertTrue(ci.isComplete());
Map expMime = MapUtil.map("text/plain", 1,
"text/html", 2,
"application/pdf", 1);
assertEquals(4, ci.getNumUrls());
assertEquals(expMime, ci.getMimeCounts());
assertTrue(ci.hasUrls());
assertSameElements(ListUtil.list("text1", "html1", "html2", "pdf1"),
ci.getUrls());
}
public void testNewContentCallbackTriggered() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startNewContentCrawl(mau, cb, null);
waitForCrawlToFinish(sem);
assertTrue("Callback wasn't triggered", cb.wasTriggered());
}
public void testNewContentCrawlCallbackReturnsCookie() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
String cookie = "cookie string";
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startNewContentCrawl(mau, cb, cookie);
waitForCrawlToFinish(sem);
assertEquals(cookie, (String)cb.getCookie());
}
public void testNewContentCrawlCallbackReturnsNullCookie() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
String cookie = null;
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startNewContentCrawl(mau, cb, cookie);
waitForCrawlToFinish(sem);
assertEquals(cookie, (String)cb.getCookie());
}
public void testKicksOffNewThread() {
SimpleBinarySemaphore finishedSem = new SimpleBinarySemaphore();
//start the crawler, but use a crawler that will hang
//if we aren't running it in another thread we'll hang too
TestCrawlCB cb = new TestCrawlCB(finishedSem);
SimpleBinarySemaphore sem1 = new SimpleBinarySemaphore();
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
//gives sem1 when doCrawl is entered, then takes sem2
MockCrawler crawler = new HangingCrawler("testKicksOffNewThread",
sem1, sem2);
semToGive(sem2);
crawlManager.setTestCrawler(crawler);
crawlManager.startNewContentCrawl(mau, cb, null);
assertTrue(didntMsg("start", TIMEOUT_SHOULDNT),
sem1.take(TIMEOUT_SHOULDNT));
//we know that doCrawl started
//if the callback was triggered, the crawl completed
assertFalse("Callback was triggered", cb.wasTriggered());
sem2.give();
waitForCrawlToFinish(finishedSem);
}
public void testScheduleRepairNullAu() {
try{
crawlManager.startRepair(null, ListUtil.list("http://www.example.com"),
new TestCrawlCB(), "blah");
fail("Didn't throw IllegalArgumentException on null AU");
} catch (IllegalArgumentException iae) {
}
}
public void testScheduleRepairNullUrls() {
try{
crawlManager.startRepair(mau, (Collection)null,
new TestCrawlCB(), "blah");
fail("Didn't throw IllegalArgumentException on null URL list");
} catch (IllegalArgumentException iae) {
}
}
public void testBasicRepairCrawl() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL), cb, null);
waitForCrawlToFinish(sem);
assertTrue("doCrawl() not called", crawler.doCrawlCalled());
}
public void testRepairCallbackTriggered() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL), cb, null);
waitForCrawlToFinish(sem);
assertTrue("Callback wasn't triggered", cb.wasTriggered());
}
public void testRepairCallbackGetsCookie() {
String cookie = "test cookie str";
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
TestCrawlCB cb = new TestCrawlCB(sem);
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL), cb, cookie);
waitForCrawlToFinish(sem);
assertEquals(cookie, cb.getCookie());
}
//StatusSource tests
public void testGetCrawlStatusListReturnsEmptyListIfNoCrawls() {
List list = statusSource.getStatus().getCrawlerStatusList();
assertEquals(0, list.size());
}
public void testGetCrawlsOneRepairCrawl() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL),
new TestCrawlCB(sem), null);
List actual = statusSource.getStatus().getCrawlerStatusList();
List expected = ListUtil.list(crawler.getCrawlerStatus());
assertEquals(expected, actual);
waitForCrawlToFinish(sem);
}
public void testGetCrawlsOneNCCrawl() {
SimpleBinarySemaphore sem = new SimpleBinarySemaphore();
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem), null);
List actual = statusSource.getStatus().getCrawlerStatusList();
List expected = ListUtil.list(crawler.getCrawlerStatus());
assertEquals(expected, actual);
waitForCrawlToFinish(sem);
}
public void testGetCrawlsMulti() {
SimpleBinarySemaphore sem1 = new SimpleBinarySemaphore();
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
crawlManager.startRepair(mau, ListUtil.list(GENERIC_URL),
new TestCrawlCB(sem1), null);
MockCrawler crawler2 = new MockCrawler();
crawlManager.setTestCrawler(crawler2);
crawlManager.startNewContentCrawl(mau, new TestCrawlCB(sem2), null);
// The two status objects will have been added to the status map in
// the order created above, but if one of them gets referenced before
// this test it might be moved to the most-recently-used position of
// the LRUMap, so the order here is unpredictable
List actual = statusSource.getStatus().getCrawlerStatusList();
Set expected = SetUtil.set(crawler.getCrawlerStatus(), crawler2.getCrawlerStatus());
assertEquals(expected, SetUtil.theSet(actual));
waitForCrawlToFinish(sem1);
waitForCrawlToFinish(sem2);
}
public void testGloballyPermittedHosts() {
assertFalse(crawlManager.isGloballyPermittedHost("foo27.com"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_PERMITTED_HOSTS,
"foo[0-9]+\\.com");
assertTrue(crawlManager.isGloballyPermittedHost("foo27.com"));
assertFalse(crawlManager.isGloballyPermittedHost("bar42.edu"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_PERMITTED_HOSTS,
"^foo[0-9]+\\.com$;^bar..\\.edu$");
assertTrue(crawlManager.isGloballyPermittedHost("foo27.com"));
assertTrue(crawlManager.isGloballyPermittedHost("bar42.edu"));
assertFalse(crawlManager.isGloballyPermittedHost("foo27.com;bar42.edu"));
}
public void testAllowedPluginPermittedHosts() {
assertFalse(crawlManager.isAllowedPluginPermittedHost("foo27.com"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_PERMITTED_HOSTS,
"foo[0-9]+\\.com");
assertFalse(crawlManager.isAllowedPluginPermittedHost("foo27.com"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_ALLOWED_PLUGIN_PERMITTED_HOSTS,
"foo[0-9]+\\.com");
assertTrue(crawlManager.isAllowedPluginPermittedHost("foo27.com"));
ConfigurationUtil.removeKey(CrawlManagerImpl.PARAM_PERMITTED_HOSTS);
assertTrue(crawlManager.isAllowedPluginPermittedHost("foo27.com"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_ALLOWED_PLUGIN_PERMITTED_HOSTS,
"^foo[0-9]+\\.com$;^baz..\\.edu$");
assertTrue(crawlManager.isAllowedPluginPermittedHost("foo27.com"));
assertTrue(crawlManager.isAllowedPluginPermittedHost("baz42.edu"));
assertFalse(crawlManager.isAllowedPluginPermittedHost("foo27.com;baz42.edu"));
}
public void testDeleteRemovesFromHighPriorityQueue() {
crawlManager.disableCrawlStarter();
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_USE_ODC, "true");
MockArchivalUnit mau1 = newMockArchivalUnit("foo1");
PluginTestUtil.registerArchivalUnit(plugin, mau1);
CrawlReq req = new CrawlReq(mau1, new CrawlerStatus(mau1,
mau1.getStartUrls(), null));
req.setPriority(8);
req.setRefetchDepth(1232);
crawlManager.enqueueHighPriorityCrawl(req);
//startNewContentCrawl
List<ArchivalUnit> quas = crawlManager.getHighPriorityAus();
assertEquals(ListUtil.list(mau1), quas);
crawlManager.auEventDeleted(AuEvent.forAu(mau1, AuEvent.Type.Delete),
mau1);
assertEmpty(crawlManager.getHighPriorityAus());
crawlManager.auEventCreated(AuEvent.forAu(mau1, AuEvent.Type.Create),
mau1);
assertEmpty(crawlManager.getHighPriorityAus());
crawlManager.enqueueHighPriorityCrawl(req);
assertEquals(ListUtil.list(mau1), crawlManager.getHighPriorityAus());
crawlManager.auEventDeleted(AuEvent.forAu(mau1, AuEvent.Type.RestartDelete),
mau1);
assertEmpty(crawlManager.getHighPriorityAus());
crawlManager.auEventCreated(AuEvent.forAu(mau1, AuEvent.Type.Create),
mau1);
assertEquals(ListUtil.list(mau1), crawlManager.getHighPriorityAus());
}
}
public static class TestsWithoutAutoStart extends TestCrawlManagerImpl {
public void setUp() throws Exception {
super.setUp();
}
public void testNoQueuePoolSize(int max) {
setUpMockAu();
cprops.put(CrawlManagerImpl.PARAM_CRAWLER_QUEUE_ENABLED, "false");
cprops.put(CrawlManagerImpl.PARAM_USE_ODC, "false");
cprops.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX,
Integer.toString(max));
cprops.put(CrawlManagerImpl.PARAM_MAX_NEW_CONTENT_RATE, (max*2)+"/1h");
cprops.put(CrawlManagerImpl.PARAM_NEW_CONTENT_START_RATE, "unlimited");
ConfigurationUtil.addFromProps(cprops);
crawlManager.startService();
SimpleBinarySemaphore[] startSem = new SimpleBinarySemaphore[max];
SimpleBinarySemaphore[] endSem = new SimpleBinarySemaphore[max];
SimpleBinarySemaphore[] finishedSem = new SimpleBinarySemaphore[max];
HangingCrawler[] crawler = new HangingCrawler[max];
TestCrawlCB[] cb = new TestCrawlCB[max];
for (int ix = 0; ix < max; ix++) {
finishedSem[ix] = new SimpleBinarySemaphore();
//start a crawler that hangs until we post its semaphore
cb[ix] = new TestCrawlCB(finishedSem[ix]);
startSem[ix] = new SimpleBinarySemaphore();
endSem[ix] = new SimpleBinarySemaphore();
//gives sem1 when doCrawl is entered, then takes sem2
crawler[ix] = new HangingCrawler("testNoQueuePoolSize " + ix,
startSem[ix], endSem[ix]);
MockArchivalUnit au = newMockArchivalUnit("mau" + ix);
au.setCrawlRule(rule);
au.setStartUrls(ListUtil.list("blah"));
PluginTestUtil.registerArchivalUnit(plugin, au);
setupAuToCrawl(au, crawler[ix]);
semToGive(endSem[ix]);
crawlManager.startNewContentCrawl(au, cb[ix], null);
}
for (int ix = 0; ix < max; ix++) {
assertTrue(didntMsg("start("+ix+")", TIMEOUT_SHOULDNT),
startSem[ix].take(TIMEOUT_SHOULDNT));
//we know that doCrawl started
}
MockCrawler crawlerN =
new HangingCrawler("testNoQueuePoolSize ix+1",
new SimpleBinarySemaphore(),
semToGive(new SimpleBinarySemaphore()));
crawlManager.setTestCrawler(crawlerN);
TestCrawlCB onecb = new TestCrawlCB();
log.info("Pool is blocked exception expected");
crawlManager.startNewContentCrawl(mau, onecb, null);
assertTrue("Callback for non schedulable crawl wasn't triggered",
onecb.wasTriggered());
assertFalse("Non schedulable crawl succeeded",
onecb.wasSuccessful());
for (int ix = 0; ix < max; ix++) {
//if the callback was triggered, the crawl completed
assertFalse("Callback was triggered", cb[ix].wasTriggered());
endSem[ix].give();
waitForCrawlToFinish(finishedSem[ix]);
}
}
public void testNoQueueBoundedPool() {
testNoQueuePoolSize(5);
}
public void testQueuedPool(int qMax, int poolMax) {
setUpMockAu();
int tot = qMax + poolMax;
cprops.put(CrawlManagerImpl.PARAM_CRAWLER_QUEUE_ENABLED, "true");
cprops.put(CrawlManagerImpl.PARAM_USE_ODC, "false");
cprops.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX,
Integer.toString(poolMax));
cprops.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_QUEUE_SIZE,
Integer.toString(qMax));
cprops.put(CrawlManagerImpl.PARAM_MAX_NEW_CONTENT_RATE, (tot*2)+"/1h");
int startInterval = 10;
cprops.put(CrawlManagerImpl.PARAM_NEW_CONTENT_START_RATE,
"1/" + startInterval);
ConfigurationUtil.addFromProps(cprops);
crawlManager.startService();
HangingCrawler[] crawler = new HangingCrawler[tot];
SimpleBinarySemaphore[] startSem = new SimpleBinarySemaphore[tot];
SimpleBinarySemaphore[] endSem = new SimpleBinarySemaphore[tot];
SimpleBinarySemaphore[] finishedSem = new SimpleBinarySemaphore[tot];
TestCrawlCB[] cb = new TestCrawlCB[tot];
long startTime[] = new long[tot];
// queue enough crawlers to fill the queue and pool
for (int ix = 0; ix < tot; ix++) {
finishedSem[ix] = new SimpleBinarySemaphore();
//start a crawler that hangs until we post its semaphore
cb[ix] = new TestCrawlCB(finishedSem[ix]);
startSem[ix] = new SimpleBinarySemaphore();
endSem[ix] = new SimpleBinarySemaphore();
//gives sem1 when doCrawl is entered, then takes sem2
crawler[ix] = new HangingCrawler("testQueuedPool " + ix,
startSem[ix], endSem[ix]);
MockArchivalUnit au = newMockArchivalUnit("mau" + ix);
au.setCrawlRule(rule);
au.setStartUrls(ListUtil.list("blah"));
PluginTestUtil.registerArchivalUnit(plugin, au);
setupAuToCrawl(au, crawler[ix]);
semToGive(endSem[ix]);
// queue the crawl directly
crawlManager.startNewContentCrawl(au, cb[ix], null);
}
// wait for the first poolMax crawlers to start. Keep track of their
// start times
for (int ix = 0; ix < tot; ix++) {
if (ix < poolMax) {
assertTrue(didntMsg("start("+ix+")", TIMEOUT_SHOULDNT),
startSem[ix].take(TIMEOUT_SHOULDNT));
startSem[ix] = null;
startTime[ix] = crawler[ix].getStartTime();
} else {
assertFalse("Wasn't queued "+ix, cb[ix].wasTriggered());
assertFalse("Shouldn't have started " + ix,
startSem[ix].take(0));
}
}
// now check that no two start times are closer together than allowed
// by the start rate limiter. We don't know what order the crawl
// threads ran in, so must sort the times first. Thefirst qMax will
// be zero because only poolMax actually got started.
Arrays.sort(startTime);
long lastTime = 0;
for (int ix = qMax; ix < tot; ix++) {
long thisTime = startTime[ix];
assertTrue( "Crawler " + ix + " started early in " +
(thisTime - lastTime),
thisTime >= lastTime + startInterval);
lastTime = thisTime;
}
MockCrawler failcrawler =
new HangingCrawler("testNoQueuePoolSize ix+1",
new SimpleBinarySemaphore(),
semToGive(new SimpleBinarySemaphore()));
crawlManager.setTestCrawler(failcrawler);
TestCrawlCB onecb = new TestCrawlCB();
log.info("Pool is blocked exception expected");
crawlManager.startNewContentCrawl(mau, onecb, null);
assertTrue("Callback for non schedulable crawl wasn't triggered",
onecb.wasTriggered());
assertFalse("Non schedulable crawl succeeded",
onecb.wasSuccessful());
for (int ix = poolMax; ix < tot; ix++) {
int poke = randomActive(startSem, endSem);
assertFalse("Shouldnt have finished "+poke, cb[poke].wasTriggered());
endSem[poke].give();
waitForCrawlToFinish(finishedSem[poke]);
endSem[poke] = null;
assertTrue(didntMsg("start("+ix+")", TIMEOUT_SHOULDNT),
startSem[ix].take(TIMEOUT_SHOULDNT));
startSem[ix] = null;
}
}
public void testCrawlStarter(int qMax, int poolMax) {
assertEmpty(pluginMgr.getAllAus());
int tot = qMax + poolMax;
Properties p = new Properties();
p.put(CrawlManagerImpl.PARAM_CRAWLER_QUEUE_ENABLED,
"true");
p.put(CrawlManagerImpl.PARAM_USE_ODC, "false");
p.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX,
Integer.toString(poolMax));
p.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_QUEUE_SIZE,
Integer.toString(qMax));
p.put(CrawlManagerImpl.PARAM_MAX_NEW_CONTENT_RATE, (tot*2)+"/1h");
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INITIAL_DELAY, "100");
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INTERVAL, "1s");
theDaemon.setAusStarted(true);
ConfigurationUtil.addFromProps(p);
crawlManager.ausStartedSem = new OneShotSemaphore();
crawlManager.startService();
HangingCrawler[] crawler = new HangingCrawler[tot];
SimpleBinarySemaphore endSem = new SimpleBinarySemaphore();
semToGive(endSem);
crawlManager.recordExecute(true);
assertEmpty(pluginMgr.getAllAus());
// Create AUs and build the pieces necessary for the crawl starter to
// get the list of AUs from the PluginManager. The crawl starter
// should then shortly start poolMax of them. We only check that it
// called startNewContentCrawl() on each.
for (int ix = 0; ix < tot-1; ix++) {
crawler[ix] = new HangingCrawler("testQueuedPool " + ix,
null, endSem);
MockArchivalUnit au = newMockArchivalUnit("mau" + ix);
au.setCrawlRule(rule);
au.setStartUrls(ListUtil.list("blah"));
setupAuToCrawl(au, crawler[ix]);
PluginTestUtil.registerArchivalUnit(plugin, au);
}
// Last one is a RegistryArchivalUnit crawl
RegistryArchivalUnit rau = makeRegistryAu();
crawler[tot-1] = new HangingCrawler("testQueuedPool(reg au) " + (tot-1),
null, endSem);
setupAuToCrawl(rau, crawler[tot-1]);
pluginMgr.addRegistryAu(rau);
// now let the crawl starter proceed
crawlManager.ausStartedSem.fill();
// Ensure they all got queued
List exe = Collections.EMPTY_LIST;
Interrupter intr = interruptMeIn(TIMEOUT_SHOULDNT, true);
while (true) {
exe = crawlManager.getExecuted();
if (exe.size() == tot) {
break;
}
crawlManager.waitExecuted();
assertFalse("Only " + exe.size() + " of " + tot +
" expected crawls were started by the crawl starter",
intr.did());
}
intr.cancel();
assertEquals(SetUtil.fromArray(crawler),
SetUtil.theSet(crawlersOf(exe)));
// The registry au crawl should always be first
assertEquals(crawler[tot-1], crawlersOf(exe).get(0));
}
void setupAuToCrawl(ArchivalUnit au, MockCrawler crawler) {
crawlManager.setTestCrawler(au, crawler);
}
List crawlersOf(List runners) {
List res = new ArrayList();
for (Iterator iter = runners.iterator(); iter.hasNext(); ) {
CrawlManagerImpl.CrawlRunner runner =
(CrawlManagerImpl.CrawlRunner)iter.next();
res.add(runner.getCrawler());
}
return res;
}
static LockssRandom random = new LockssRandom();
int randomActive(SimpleBinarySemaphore[] startSem,
SimpleBinarySemaphore[] endSem) {
while (true) {
int x = random.nextInt(startSem.length);
if (startSem[x] == null && endSem[x] != null) return x;
}
}
public void testQueuedPool() {
testQueuedPool(10, 3);
}
public void testCrawlStarter() {
testCrawlStarter(10, 3);
}
// ODC tests
CrawlReq[] makeReqs(int n) {
CrawlReq[] res = new CrawlReq[n];
for (int ix = 0; ix < n; ix++) {
MockArchivalUnit mau = newMockArchivalUnit(String.format("mau%2d", ix));
res[ix] =
new CrawlReq(mau, new CrawlerStatus(mau, mau.getStartUrls(), null));
}
return res;
}
void setReq(CrawlReq req,
int pri, int crawlResult,
long crawlAttempt, long crawlFinish) {
setReq(req, pri, crawlResult, crawlAttempt, crawlFinish, null);
}
void setReq(CrawlReq req,
int pri, int crawlResult,
long crawlAttempt, long crawlFinish,
String limiterKey) {
req.priority = pri;
setAu((MockArchivalUnit)req.getAu(),
crawlResult, crawlAttempt, crawlFinish, limiterKey);
}
void setAu(MockArchivalUnit mau,
int crawlResult, long crawlAttempt, long crawlFinish) {
setAu(mau, crawlResult, crawlAttempt, crawlFinish, null);
}
void setAu(MockArchivalUnit mau,
int crawlResult, long crawlAttempt, long crawlFinish,
String limiterKey) {
MockAuState aus = (MockAuState)AuUtil.getAuState(mau);
aus.setLastCrawlTime(crawlFinish);
aus.setLastCrawlAttempt(crawlAttempt);
aus.setLastCrawlResult(crawlResult, "foo");
mau.setFetchRateLimiterKey(limiterKey);
}
CrawlManagerImpl.CrawlPriorityComparator cmprtr() {
return crawlManager.cmprtr();
}
void assertCompareLess(CrawlReq r1, CrawlReq r2) {
assertTrue("Expected " + r1 + " less than " + r2 + " but wasn't",
cmprtr().compare(r1, r2) < 0);
}
public void testCrawlPriorityComparator(CrawlReq[] reqs) {
for (int ix = 0; ix <= reqs.length - 2; ix++) {
assertCompareLess(reqs[ix], reqs[ix+1]);
}
List lst = ListUtil.fromArray(reqs);
for (int ix = 0; ix <= 5; ix++) {
TreeSet sorted = new TreeSet(cmprtr());
sorted.addAll(CollectionUtil.randomPermutation(lst));
sorted.add(reqs[0]);
assertIsomorphic(reqs, sorted);
}
}
public void testCrawlPriorityComparator1() {
ConfigurationUtil.setFromArgs(CrawlManagerImpl.PARAM_RESTART_AFTER_CRASH,
"true");
CrawlReq[] reqs = makeReqs(11);
setReq(reqs[0], 1, Crawler.STATUS_WINDOW_CLOSED, 9999, 9999);
setReq(reqs[1], 1, 0, 5000, 5000);
setReq(reqs[2], 0, Crawler.STATUS_WINDOW_CLOSED, -1, 2000);
setReq(reqs[3], 0, Crawler.STATUS_WINDOW_CLOSED, 1000, 1000);
setReq(reqs[4], 0, Crawler.STATUS_RUNNING_AT_CRASH, 1000, 1000);
setReq(reqs[5], 0, 0, -1, 500);
setReq(reqs[6], 0, 0, 123, -1);
setReq(reqs[7], 0, 0, 123, 456);
setReq(reqs[8], 0, Crawler.STATUS_WINDOW_CLOSED, -1, 2000);
setReq(reqs[9], 0, 0, -1, 500);
setReq(reqs[10], 1, 0, 5000, 5000);
for (int ix=8; ix<=10; ix++) {
reqs[ix].auDeleted();
}
assertFalse(reqs[8].isActive());
assertTrue(reqs[7].isActive());
testCrawlPriorityComparator(reqs);
}
public void testCrawlPriorityComparator2() {
ConfigurationUtil.setFromArgs(CrawlManagerImpl.PARAM_RESTART_AFTER_CRASH,
"false");
CrawlReq[] reqs = makeReqs(8);
setReq(reqs[0], 1, Crawler.STATUS_WINDOW_CLOSED, 9999, 9999);
setReq(reqs[1], 1, 0, 5000, 5000);
setReq(reqs[2], 0, Crawler.STATUS_WINDOW_CLOSED, -1, 2000);
setReq(reqs[3], 0, Crawler.STATUS_WINDOW_CLOSED, 1000, 1000);
setReq(reqs[4], 0, 0, -1, 500);
setReq(reqs[5], 0, 0, 123, -1);
setReq(reqs[6], 0, 0, 123, 456);
setReq(reqs[7], 0, Crawler.STATUS_RUNNING_AT_CRASH, 1000, 1000);
testCrawlPriorityComparator(reqs);
}
void setAuCreationTime(CrawlReq req, long time) {
MockAuState aus = (MockAuState)AuUtil.getAuState(req.getAu());
aus.setAuCreationTime(time);
}
public void testCrawlPriorityComparatorCreationOrder() {
ConfigurationUtil.setFromArgs(CrawlManagerImpl.PARAM_RESTART_AFTER_CRASH,
"false",
CrawlManagerImpl.PARAM_CRAWL_ORDER,
"CreationDate");
CrawlReq[] reqs = makeReqs(8);
setReq(reqs[0], 0, Crawler.STATUS_WINDOW_CLOSED, 1001, 1001);
setReq(reqs[1], 0, Crawler.STATUS_RUNNING_AT_CRASH, 1000, 1000);
setReq(reqs[2], 0, 0, 123, 456);
setReq(reqs[3], 0, 0, 123, -1);
setReq(reqs[4], 0, 0, -1, 500);
setReq(reqs[5], 0, 0, -1, 2000);
setReq(reqs[6], 0, 0, 5000, 5000);
setReq(reqs[7], 0, 0, 9999, 9999);
for (int ix = 0; ix < reqs.length; ix++) {
setAuCreationTime(reqs[ix], 9990 + ix);
}
testCrawlPriorityComparator(reqs);
}
void registerAus(MockArchivalUnit[] aus) {
List lst = ListUtil.fromArray(aus);
List<MockArchivalUnit> rand = CollectionUtil.randomPermutation(lst);
for (MockArchivalUnit mau : rand) {
PluginTestUtil.registerArchivalUnit(plugin, mau);
}
}
CrawlRateLimiter getCrl(Crawler c) {
return crawlManager.getCrawlRateLimiter(c);
}
public void testOdcQueue() throws Exception {
Properties p = new Properties();
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INTERVAL, "-1");
p.put(CrawlManagerImpl.PARAM_SHARED_QUEUE_MAX, "4");
p.put(CrawlManagerImpl.PARAM_UNSHARED_QUEUE_MAX, "3");
p.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX, "3");
p.put(CrawlManagerImpl.PARAM_FAVOR_UNSHARED_RATE_THREADS, "1");
p.put(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP, "auNever,-10000");
theDaemon.setAusStarted(true);
ConfigurationUtil.addFromProps(p);
crawlManager.startService();
MockArchivalUnit[] aus = makeMockAus(15);
registerAus(aus);
MockArchivalUnit auPri = newMockArchivalUnit("auPri");
setAu(auPri, 0, 9999, 9999);
MockArchivalUnit auNever = newMockArchivalUnit("auNever");
setAu(auNever, 0, 1, 2);
registerAus(new MockArchivalUnit[] { auNever });
setAu(aus[0], Crawler.STATUS_WINDOW_CLOSED, -1, 2000);
setAu(aus[1], Crawler.STATUS_WINDOW_CLOSED, 1000, 1000);
setAu(aus[2], 0, -1, 1000);
setAu(aus[3], 0, 123, -1);
setAu(aus[4], 0, 123, 456);
setAu(aus[5], Crawler.STATUS_WINDOW_CLOSED, -1, 2001, "foo");
setAu(aus[6], Crawler.STATUS_WINDOW_CLOSED, 1001, 1001, "foo");
setAu(aus[7], 0, -1, 1001, "foo");
setAu(aus[8], 0, 124, -1, "foo"); // repair
setAu(aus[9], 0, 124, 457, "foo"); // repair
setAu(aus[10], Crawler.STATUS_WINDOW_CLOSED, -1, 2002, "bar");
setAu(aus[11], Crawler.STATUS_WINDOW_CLOSED, 1002, 1002, "bar");
setAu(aus[12], 0, -1, 1002, "bar");
setAu(aus[13], 0, 125, -1, "bar");
setAu(aus[14], 0, 125, 458, "bar"); // repair
assertEquals(0, crawlManager.rebuildCount);
assertEquals(aus[5], crawlManager.nextReq().getAu());
assertEquals(1, crawlManager.rebuildCount);
MockCrawler cr5 = crawlManager.addToRunningRateKeys(aus[5]);
// Should fail to assign a crl to another nc crawl in pool foo
try {
crawlManager.addToRunningRateKeys(aus[8]);
fail("Attempt to add new content crawler in full pool should throw");
} catch (IllegalStateException e) {
}
// Repair crawl in pool foo should get same crl as nc crawl
MockCrawler cr8 = crawlManager.addToRunningRateKeys(aus[8], false);
CrawlRateLimiter crl = getCrl(cr8);
assertNotNull(crl);
assertSame(crl, getCrl(cr5));
crawlManager.delFromRunningRateKeys(aus[8]);
// Add a repair in pool bar
MockCrawler cr14 = crawlManager.addToRunningRateKeys(aus[14], false);
assertEquals(aus[10], crawlManager.nextReq().getAu());
MockCrawler cr10 = crawlManager.addToRunningRateKeys(aus[10]);
assertNotNull(getCrl(cr10));
assertSame(getCrl(cr10), getCrl(cr14));
assertEquals(aus[0], crawlManager.nextReq().getAu());
assertEquals(aus[1], crawlManager.nextReq().getAu());
crawlManager.delFromRunningRateKeys(aus[10]);
assertEquals(aus[11], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[11]);
aus[5].setShouldCrawlForNewContent(false);
aus[10].setShouldCrawlForNewContent(false);
aus[0].setShouldCrawlForNewContent(false);
aus[1].setShouldCrawlForNewContent(false);
aus[11].setShouldCrawlForNewContent(false);
assertEquals(aus[2], crawlManager.nextReq().getAu());
crawlManager.delFromRunningRateKeys(aus[5]);
assertEquals(aus[6], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[6]);
aus[2].setShouldCrawlForNewContent(false);
aus[6].setShouldCrawlForNewContent(false);
assertEquals(1, crawlManager.rebuildCount);
assertEquals(aus[3], crawlManager.nextReq().getAu());
assertEquals(2, crawlManager.rebuildCount);
assertEquals(aus[4], crawlManager.nextReq().getAu());
aus[3].setShouldCrawlForNewContent(false);
aus[4].setShouldCrawlForNewContent(false);
assertEquals(null, crawlManager.nextReq());
crawlManager.delFromRunningRateKeys(aus[11]);
assertEquals(aus[12], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[12]);
assertEquals(null, crawlManager.nextReq());
crawlManager.delFromRunningRateKeys(aus[12]);
crawlManager.delFromRunningRateKeys(aus[6]);
PluginTestUtil.registerArchivalUnit(plugin, auPri);
assertEquals(aus[7], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[7]);
aus[12].setShouldCrawlForNewContent(false);
aus[7].setShouldCrawlForNewContent(false);
auPri.setShouldCrawlForNewContent(false);
crawlManager.startNewContentCrawl(auPri, 1, null, null);
assertEquals(auPri, crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(auPri);
auPri.setShouldCrawlForNewContent(false);
assertEquals(aus[13], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[13]);
assertEquals(null, crawlManager.nextReq());
}
public void testOdcQueueWithConcurrentPool() throws Exception {
Properties p = new Properties();
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INTERVAL, "-1");
p.put(CrawlManagerImpl.PARAM_SHARED_QUEUE_MAX, "4");
p.put(CrawlManagerImpl.PARAM_UNSHARED_QUEUE_MAX, "3");
p.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX, "3");
p.put(CrawlManagerImpl.PARAM_FAVOR_UNSHARED_RATE_THREADS, "1");
p.put(CrawlManagerImpl.PARAM_CONCURRENT_CRAWL_LIMIT_MAP, "foo,2;bar,3");
theDaemon.setAusStarted(true);
ConfigurationUtil.addFromProps(p);
crawlManager.startService();
MockArchivalUnit[] aus = makeMockAus(15);
registerAus(aus);
setAu(aus[0], 0, 0, 2000);
setAu(aus[1], 0, 0, 4000);
setAu(aus[2], 0, 0, 6000);
setAu(aus[3], 0, 0, 8000);
setAu(aus[4], 0, 0, 10000);
setAu(aus[5], 0, 0, 2002, "foo");
setAu(aus[6], 0, 0, 2004, "foo");
setAu(aus[7], 0, 0, 2006, "foo");
setAu(aus[8], 0, 0, 4002, "foo"); // repair
setAu(aus[9], 0, 0, 4004, "foo"); // repair
setAu(aus[10], 0, 0, 2001, "bar");
setAu(aus[11], 0, 0, 2003, "bar");
setAu(aus[12], 0, 0, 2005, "bar");
setAu(aus[13], 0, 0, 4001, "bar");
setAu(aus[14], 0, 0, 4003, "bar"); // repair
assertFalse(crawlManager.isWorthRebuildingQueue());
assertEquals(aus[10], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[10]);
aus[10].setShouldCrawlForNewContent(false);
assertTrue(crawlManager.isWorthRebuildingQueue());
assertEquals(aus[5], crawlManager.nextReq().getAu());
MockCrawler cr5 = crawlManager.addToRunningRateKeys(aus[5]);
assertEquals(aus[0], crawlManager.nextReq().getAu());
aus[0].setShouldCrawlForNewContent(false);
assertEquals(aus[11], crawlManager.nextReq().getAu());
MockCrawler cr11 = crawlManager.addToRunningRateKeys(aus[11]);
aus[11].setShouldCrawlForNewContent(false);
assertNotSame(getCrl(cr5), getCrl(cr11));
// Repair crawl in foo should get different crl
MockCrawler cr8 = crawlManager.addToRunningRateKeys(aus[8], false);
assertNotSame(getCrl(cr5), getCrl(cr8));
// Next nc in foo should get same crl as repair
assertEquals(aus[6], crawlManager.nextReq().getAu());
MockCrawler cr6 = crawlManager.addToRunningRateKeys(aus[6]);
aus[6].setShouldCrawlForNewContent(false);
assertSame(getCrl(cr8), getCrl(cr6));
assertEquals(aus[12], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[12]);
aus[12].setShouldCrawlForNewContent(false);
assertEquals(aus[1], crawlManager.nextReq().getAu());
aus[1].setShouldCrawlForNewContent(false);
crawlManager.delFromRunningRateKeys(aus[5]);
assertEquals(aus[7], crawlManager.nextReq().getAu());
crawlManager.addToRunningRateKeys(aus[7]);
aus[7].setShouldCrawlForNewContent(false);
assertEquals(aus[2], crawlManager.nextReq().getAu());
aus[2].setShouldCrawlForNewContent(false);
assertEquals(aus[3], crawlManager.nextReq().getAu());
aus[3].setShouldCrawlForNewContent(false);
crawlManager.delFromRunningRateKeys(aus[10]);
assertEquals(aus[13], crawlManager.nextReq().getAu());
assertEquals(aus[14], crawlManager.nextReq().getAu());
assertEquals(aus[4], crawlManager.nextReq().getAu());
assertNull(crawlManager.nextReq());
assertFalse(crawlManager.isWorthRebuildingQueue());
}
public void testCrawlPriorityAuidPatterns() {
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AUID_MAP,
"foo(4|5),3;bar,5;baz,-1");
MockArchivalUnit mau1 = new MockArchivalUnit(new MockPlugin(theDaemon));
mau1.setAuId("other");
CrawlReq req = new CrawlReq(mau1, new CrawlerStatus(mau1,
mau1.getStartUrls(), null));
crawlManager.setReqPriority(req);
assertEquals(0, req.getPriority());
mau1.setAuId("foo4");
crawlManager.setReqPriority(req);
assertEquals(3, req.getPriority());
mau1.setAuId("foo5");
crawlManager.setReqPriority(req);
assertEquals(3, req.getPriority());
mau1.setAuId("x~ybar~z");
crawlManager.setReqPriority(req);
assertEquals(5, req.getPriority());
mau1.setAuId("bazab");
crawlManager.setReqPriority(req);
assertEquals(-1, req.getPriority());
// Remove param, ensure priority map gets removed
ConfigurationUtil.resetConfig();
mau1.setAuId("foo4");
req.setPriority(-3);
crawlManager.setReqPriority(req);
assertEquals(-3, req.getPriority());
}
public void testCrawlPriorityAuPatterns() throws Exception {
MockArchivalUnit mau1 = new MockArchivalUnit(new MockPlugin(theDaemon));
mau1.setAuId("auid1");
MockArchivalUnit mau2 = new MockArchivalUnit(new MockPlugin(theDaemon));
mau2.setAuId("auid2");
MockArchivalUnit mau3 = new MockArchivalUnit(new MockPlugin(theDaemon));
mau3.setAuId("auid3");
Tdb tdb = new Tdb();
Properties tprops = new Properties();
tprops.put("journalTitle", "jtitle");
tprops.put("plugin", "Plug1");
tprops.put("param.1.key", "volume");
tprops.put("title", "title 1");
tprops.put("param.1.value", "vol_1");
tprops.put("attributes.year", "2001");
mau1.setTdbAu(tdb.addTdbAuFromProperties(tprops));
tprops.put("title", "title 2");
tprops.put("param.1.value", "vol_2");
tprops.put("attributes.year", "2002");
mau2.setTdbAu(tdb.addTdbAuFromProperties(tprops));
tprops.put("title", "title 3");
tprops.put("param.1.value", "vol_3");
tprops.put("attributes.year", "2003");
mau3.setTdbAu(tdb.addTdbAuFromProperties(tprops));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AU_MAP,
"[RE:isMatchRe(tdbAu/params/volume,'vol_1')],6;" +
"[RE:isMatchRe(tdbAu/params/volume,'vol_(1|2)')],3;");
CrawlReq req1 = new CrawlReq(mau1,
new CrawlerStatus(mau1, mau1.getStartUrls(), null));
CrawlReq req2 = new CrawlReq(mau2,
new CrawlerStatus(mau2, mau2.getStartUrls(), null));
CrawlReq req3 = new CrawlReq(mau3,
new CrawlerStatus(mau3, mau3.getStartUrls(), null));
crawlManager.setReqPriority(req1);
crawlManager.setReqPriority(req2);
crawlManager.setReqPriority(req3);
assertEquals(6, req1.getPriority());
assertEquals(3, req2.getPriority());
assertEquals(0, req3.getPriority());
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CRAWL_PRIORITY_AU_MAP,
"[tdbAu/year <= '2002'],10;" +
"[tdbAu/year >= '2002'],-20000;");
crawlManager.setReqPriority(req1);
crawlManager.setReqPriority(req2);
crawlManager.setReqPriority(req3);
assertEquals(10, req1.getPriority());
assertEquals(10, req2.getPriority());
assertEquals(-20000, req3.getPriority());
// Remove param, ensure priority map gets removed
ConfigurationUtil.resetConfig();
req1.setPriority(0);
crawlManager.setReqPriority(req1);
assertEquals(0, req1.getPriority());
}
public void testCrawlPoolSizeMap() {
// map not configured
assertEquals(1, crawlManager.getCrawlPoolSize("nopool"));
assertEquals(1, crawlManager.getCrawlPoolSize("foopool"));
ConfigurationUtil.addFromArgs(CrawlManagerImpl.PARAM_CONCURRENT_CRAWL_LIMIT_MAP,
"foopool,2;barpool,4");
assertEquals(1, crawlManager.getCrawlPoolSize("nopool"));
assertEquals(2, crawlManager.getCrawlPoolSize("foopool"));
assertEquals(4, crawlManager.getCrawlPoolSize("barpool"));
// Remove param, ensure map reverts to empty
ConfigurationUtil.resetConfig();
assertEquals(1, crawlManager.getCrawlPoolSize("nopool"));
assertEquals(1, crawlManager.getCrawlPoolSize("foopool"));
}
public void testOdcCrawlStarter() {
int num = 15;
int tot = num+1;
int rauix = tot-1;
int nthreads = 3;
Properties p = new Properties();
p.put(CrawlManagerImpl.PARAM_USE_ODC, "true");
p.put(CrawlManagerImpl.PARAM_CRAWLER_THREAD_POOL_MAX, ""+nthreads);
p.put(CrawlManagerImpl.PARAM_MAX_NEW_CONTENT_RATE, "1/1w");
p.put(CrawlManagerImpl.PARAM_NEW_CONTENT_START_RATE, (tot*2)+"/1h");
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INITIAL_DELAY, "10");
p.put(CrawlManagerImpl.PARAM_START_CRAWLS_INTERVAL, "10");
p.put(CrawlManagerImpl.PARAM_QUEUE_RECALC_AFTER_NEW_AU, "200");
p.put(CrawlManagerImpl.PARAM_QUEUE_EMPTY_SLEEP, "500");
p.put(CrawlManagerImpl.PARAM_SHARED_QUEUE_MAX, "10");
p.put(CrawlManagerImpl.PARAM_UNSHARED_QUEUE_MAX, "10");
p.put(CrawlManagerImpl.PARAM_FAVOR_UNSHARED_RATE_THREADS, "1");
ConfigurationUtil.addFromProps(p);
crawlManager.ausStartedSem = new OneShotSemaphore();
crawlManager.startService();
// Uncomment to stress startup logic
// TimerUtil.guaranteedSleep(1000);
MockArchivalUnit[] aus = makeMockAus(num);
RegistryArchivalUnit rau = makeRegistryAu();
setAu(aus[0], Crawler.STATUS_WINDOW_CLOSED, -1, 2000);
setAu(aus[1], Crawler.STATUS_WINDOW_CLOSED, 1000, 1000);
setAu(aus[2], 0, -1, -2);
setAu(aus[3], 0, 123, -1);
setAu(aus[4], 0, 123, 456);
setAu(aus[5], Crawler.STATUS_WINDOW_CLOSED, -1, 2001, "foo");
setAu(aus[6], Crawler.STATUS_WINDOW_CLOSED, 1001, 1001, "foo");
setAu(aus[7], 0, -1, 1001, "foo");
setAu(aus[8], 0, 124, -1, "foo");
setAu(aus[9], 0, 124, 457, "foo");
setAu(aus[10], Crawler.STATUS_WINDOW_CLOSED, -1, 2002, "bar");
setAu(aus[11], Crawler.STATUS_WINDOW_CLOSED, 1002, 1002, "bar");
setAu(aus[12], 0, -1, 1002, "bar");
setAu(aus[13], 0, 125, -1, "bar");
setAu(aus[14], 0, 125, 458, "bar");
assertEmpty(pluginMgr.getAllAus());
registerAus(aus);
pluginMgr.addRegistryAu(rau);
HangingCrawler[] crawler = new HangingCrawler[tot];
TestCrawlCB[] cb = new TestCrawlCB[tot];
SimpleBinarySemaphore[] startSem = new SimpleBinarySemaphore[tot];
SimpleBinarySemaphore[] endSem = new SimpleBinarySemaphore[tot];
SimpleBinarySemaphore[] finishedSem = new SimpleBinarySemaphore[tot];
long startTime[] = new long[tot];
crawlManager.recordExecute(true);
// Create AUs and build the pieces necessary for the crawl starter to
// get the list of AUs from the PluginManager. The crawl starter
// should then shortly start poolMax of them. We only check that it
// called startNewContentCrawl() on each.
for (int ix = 0; ix < tot; ix++) {
startSem[ix] = new SimpleBinarySemaphore();
endSem[ix] = new SimpleBinarySemaphore();
finishedSem[ix] = new SimpleBinarySemaphore();
if (ix == rauix) {
// Last one is a RegistryArchivalUnit crawl
crawler[ix] = new HangingCrawler("testOdcCrawlStarter(reg au) " + ix,
startSem[ix], endSem[ix]);
setupAuToCrawl(rau, crawler[ix]);
} else {
crawler[ix] = new HangingCrawler("testOdcCrawlStarter " + ix,
startSem[ix], endSem[ix]);
aus[ix].setCrawlRule(rule);
aus[ix].setStartUrls(ListUtil.list("blah"));
setupAuToCrawl(aus[ix], crawler[ix]);
}
semToGive(endSem[ix]);
}
theDaemon.setAusStarted(true);
// now let the crawl starter proceed
crawlManager.ausStartedSem.fill();
// PluginTestUtil.registerArchivalUnit() doesn't cause Create AuEvent
// to be signalled so must ensure CrawlManagerImpl rebuilds queue
// promptly
crawlManager.rebuildQueueSoon();
// Ensure they all got queued
List exe = Collections.EMPTY_LIST;
Interrupter intr = interruptMeIn(TIMEOUT_SHOULDNT * 2, true);
int pokeOrder[] =
{ -1, -1, -1, 0, 10, 1, 5, 6, 7, 8, 9, 3, 4, 11, 12, 13, 14};
int expStartOrder[] =
{ 5, 10, 0, 1, 11, 2, 6, 7, 8, 9, 3, 4, -1, 12, 13, 14, -1};
// wait for first nthreads to start
// check correct three (unordered)
// repeat until done
// let one finish
// correct next one starts
List expExec = new ArrayList();
List expRun = new ArrayList();
List expEnd = new ArrayList();
for (int ix = 0; ix < tot; ix++) {
int poke = pokeOrder[ix];
if (poke >= 0) {
endSem[poke].give();
}
int wait = expStartOrder[ix];
if (wait >= 0) {
assertTrue(didntMsg("start("+ix+") = " + wait, TIMEOUT_SHOULDNT),
startSem[wait].take(TIMEOUT_SHOULDNT));
expExec.add(crawler[wait]);
}
if (ix >= nthreads - 1) {
while (exe.size() < expExec.size()) {
crawlManager.waitExecuted();
assertFalse("Expected " + expExec +
", but timed out and was " + exe,
intr.did());
exe = crawlManager.getExecuted();
}
assertEquals(expExec, crawlersOf(exe));
}
}
}
}
RegistryPlugin regplugin;
RegistryArchivalUnit makeRegistryAu() {
if (regplugin == null) {
regplugin = new RegistryPlugin();
regplugin.initPlugin(theDaemon);
}
RegistryArchivalUnit res = new MyRegistryArchivalUnit(regplugin);
AuTestUtil.setUpMockAus(mau);
return res;
}
class MyRegistryArchivalUnit extends RegistryArchivalUnit {
MyRegistryArchivalUnit(RegistryPlugin plugin) {
super(plugin);
try {
setConfiguration(ConfigurationUtil.fromArgs(ConfigParamDescr.BASE_URL.getKey(), "http://foo.bar/"));
} catch (ArchivalUnit.ConfigurationException e) {
throw new RuntimeException("setConfiguration()", e);
}
}
}
class MyPluginManager extends PluginManager {
private List registryAus;
public Collection getAllRegistryAus() {
if (registryAus == null) {
return super.getAllRegistryAus();
} else {
return registryAus;
}
}
public void addRegistryAu(ArchivalUnit au) {
if (registryAus == null) {
registryAus = new ArrayList();
}
registryAus.add(au);
}
@Override
protected void raiseAlert(Alert alert, String msg) {
}
}
private static class TestCrawlCB implements CrawlManager.Callback {
SimpleBinarySemaphore sem;
boolean called = false;
Object cookie;
boolean success;
public TestCrawlCB() {
this(null);
}
public TestCrawlCB(SimpleBinarySemaphore sem) {
this.sem = sem;
}
public void signalCrawlAttemptCompleted(boolean success,
Object cookie,
CrawlerStatus status) {
this.success = success;
called = true;
this.cookie = cookie;
if (sem != null) {
sem.give();
}
}
public boolean wasSuccessful() {
return success;
}
public void signalCrawlSuspended(Object cookie) {
this.cookie = cookie;
}
public Object getCookie() {
return cookie;
}
public boolean wasTriggered() {
return called;
}
}
private static class TestableCrawlManagerImpl extends CrawlManagerImpl {
private MockCrawler mockCrawler;
private HashMap auCrawlers = new HashMap();
private boolean recordExecute = false;
private List executed = new ArrayList();
private SimpleBinarySemaphore executedSem = new SimpleBinarySemaphore();
private OneShotSemaphore ausStartedSem;
private boolean isInternalAu = false;
private Map<ArchivalUnit,Crawler> auCrawlerMap =
new HashMap<ArchivalUnit,Crawler>();
TestableCrawlManagerImpl(PluginManager pmgr) {
pluginMgr = pmgr;
}
protected Crawler makeFollowLinkCrawler(ArchivalUnit au,
CrawlerStatus crawlerStatus) {
MockCrawler crawler = getCrawler(au);
crawler.setAu(au);
crawler.setUrls(au.getStartUrls());
crawler.setFollowLinks(true);
crawler.setType(Crawler.Type.NEW_CONTENT);
crawler.setIsWholeAU(true);
crawlerStatus.setStartUrls(au.getStartUrls());
crawlerStatus.setType(Crawler.Type.NEW_CONTENT.name());
crawler.setCrawlerStatus(crawlerStatus);
return crawler;
}
protected Crawler makeRepairCrawler(ArchivalUnit au,
Collection repairUrls) {
MockCrawler crawler = getCrawler(au);
crawler.setAu(au);
crawler.setUrls(repairUrls);
crawler.setFollowLinks(false);
crawler.setType(Crawler.Type.REPAIR);
crawler.setIsWholeAU(false);
return crawler;
}
protected void execute(Runnable run) throws InterruptedException {
if (recordExecute) {
executed.add(run);
executedSem.give();
}
super.execute(run);
}
@Override
void waitUntilAusStarted() throws InterruptedException {
if (ausStartedSem != null) {
ausStartedSem.waitFull(Deadline.MAX);
} else {
super.waitUntilAusStarted();
}
}
@Override
boolean areAusStarted() {
if (ausStartedSem != null) {
return ausStartedSem.isFull();
} else {
return super.areAusStarted();
}
}
MockCrawler addToRunningRateKeys(ArchivalUnit au) {
return addToRunningRateKeys(au, true);
}
MockCrawler addToRunningRateKeys(ArchivalUnit au, boolean isWholeAU) {
MockCrawler mc = new MockCrawler();
mc.setAu(au);
mc.setIsWholeAU(isWholeAU);
return addToRunningRateKeys(au, mc);
}
MockCrawler addToRunningRateKeys(ArchivalUnit au, MockCrawler mc) {
mc.setAu(au);
addToRunningCrawls(au, mc);
auCrawlerMap.put(au, mc);
highPriorityCrawlRequests.remove(au.getAuId());
return mc;
}
void delFromRunningRateKeys(ArchivalUnit au) {
Crawler crawler = auCrawlerMap.get(au);
if (crawler != null) {
removeFromRunningCrawls(crawler);
auCrawlerMap.remove(au);
}
}
int rebuildCount = 0;
void rebuildCrawlQueue() {
rebuildCount++;
super.rebuildCrawlQueue();
}
public void recordExecute(boolean val) {
recordExecute = val;
}
public void waitExecuted() {
executedSem.take();
}
public List getExecuted() {
return executed;
}
private void setTestCrawler(MockCrawler crawler) {
this.mockCrawler = crawler;
}
private MockCrawler getCrawler(ArchivalUnit au) {
MockCrawler crawler = (MockCrawler)auCrawlers.get(au);
if (crawler != null) {
return crawler;
}
return mockCrawler;
}
private void setTestCrawler(ArchivalUnit au, MockCrawler crawler) {
auCrawlers.put(au, crawler);
}
protected void instrumentBeforeStartRateLimiterEvent(Crawler crawler) {
if (crawler instanceof MockCrawler) {
((MockCrawler)crawler).setStartTime(TimeBase.nowMs());
}
}
CrawlPriorityComparator cmprtr() {
return new CrawlPriorityComparator();
}
void setInternalAu(boolean val) {
isInternalAu = val;
}
@Override
protected boolean isInternalAu(ArchivalUnit au) {
return isInternalAu || super.isInternalAu(au);
}
}
private static class ThrowingCrawler extends MockCrawler {
RuntimeException e = null;
public ThrowingCrawler(RuntimeException e) {
this.e = e;
}
public boolean doCrawl() {
if (false) return super.doCrawl();
throw e;
}
}
private static class HangingCrawler extends MockCrawler {
String name;
SimpleBinarySemaphore sem1;
SimpleBinarySemaphore sem2;
public HangingCrawler(String name,
SimpleBinarySemaphore sem1,
SimpleBinarySemaphore sem2) {
this.name = name;
this.sem1 = sem1;
this.sem2 = sem2;
}
public boolean doCrawl() {
if (false) return super.doCrawl();
if (sem1 != null) sem1.give();
if (sem2 != null) sem2.take();
return false;
}
public String toString() {
return "HangingCrawler " + name;
}
}
private static class SignalDoCrawlCrawler extends MockCrawler {
SimpleBinarySemaphore sem;
public SignalDoCrawlCrawler(SimpleBinarySemaphore sem) {
this.sem = sem;
}
public boolean doCrawl() {
if (false) return super.doCrawl();
sem.give();
return true;
}
}
private static class CloseWindowCrawler extends MockCrawler {
public CloseWindowCrawler() {
}
public boolean doCrawl() {
super.doCrawl();
MockArchivalUnit au = (MockArchivalUnit)getAu();
au.setCrawlWindow(new ClosedCrawlWindow());
return false;
}
}
private static class ClosedCrawlWindow implements CrawlWindow {
public boolean canCrawl() {
return false;
}
public boolean canCrawl(Date x) {
return false;
}
}
private static class AuEventCrawler extends MockCrawler {
List<List<String>> urls = Collections.EMPTY_LIST;
public AuEventCrawler(ArchivalUnit au) {
setStatus(new CrawlerStatus(au, ListUtil.list("foo"), "New content"));
}
void setMimes(List<List<String>> urls) {
this.urls = urls;
}
public boolean doCrawl() {
for (List<String> pair : urls) {
getCrawlerStatus().signalUrlFetched(pair.get(0));
String mime = HeaderUtil.getMimeTypeFromContentType(pair.get(1));
getCrawlerStatus().signalMimeTypeOfUrl(mime, pair.get(0));
}
if (super.doCrawl()) {
getCrawlerStatus().setCrawlStatus(Crawler.STATUS_SUCCESSFUL);
return true;
} else {
getCrawlerStatus().setCrawlStatus(Crawler.STATUS_ERROR);
return false;
}
}
}
private static class ThrowingAU extends NullPlugin.ArchivalUnit {
public CachedUrlSet makeCachedUrlSet(CachedUrlSetSpec spec) {
throw new ExpectedRuntimeException("I throw");
}
public CachedUrl makeCachedUrl(CachedUrlSet owner, String url) {
throw new ExpectedRuntimeException("I throw");
}
public UrlCacher makeUrlCacher(CachedUrlSet owner, String url) {
throw new ExpectedRuntimeException("I throw");
}
public CachedUrlSet getAuCachedUrlSet() {
throw new ExpectedRuntimeException("I throw");
}
public boolean shouldBeCached(String url) {
throw new ExpectedRuntimeException("I throw");
}
public Collection getUrlStems() {
throw new ExpectedRuntimeException("I throw");
}
public Plugin getPlugin() {
throw new ExpectedRuntimeException("I throw");
}
}
public static Test suite() {
return variantSuites(new Class[] {TestsWithAutoStart.class,
TestsWithoutAutoStart.class});
}
public static void main(String[] argv) {
String[] testCaseList = { TestCrawlManagerImpl.class.getName()};
junit.textui.TestRunner.main(testCaseList);
}
}
| 36.475488 | 108 | 0.669968 |
1f97fd7bf57f02914b65e8c9a5f2f82702996385 | 583 | package com.scottlogic.deg.generator.outputs.datasetwriters;
import com.scottlogic.deg.generator.ProfileFields;
import com.scottlogic.deg.generator.outputs.GeneratedObject;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
public interface DataSetWriter<TWriter extends Closeable> {
TWriter openWriter(
Path directory,
String fileName,
ProfileFields profileFields) throws IOException;
void writeRow(TWriter writer, GeneratedObject row) throws IOException;
String getFileName(String fileNameWithoutExtension);
}
| 29.15 | 74 | 0.789022 |
a8076f8878d080e387bb5941612781bc38bbba44 | 338 | package org.filho.sergio.projections.pojo;
import lombok.Data;
import org.filho.sergio.projections.Projection;
import org.filho.sergio.projections.Property;
@Data
public class WrongConstructorAuthorDTO implements Projection {
@Property
private String name;
public WrongConstructorAuthorDTO(String name) {
this.name = name;
}
}
| 18.777778 | 62 | 0.798817 |
6db127f41daff1de1aca33b45c440d473bb18d14 | 1,555 | /*
* Copyright 2016-2018 Litsec AB
*
* 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 se.litsec.opensaml.utils.spring;
import org.junit.Assert;
import org.junit.Test;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.saml.saml2.metadata.EntitiesDescriptor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import se.litsec.opensaml.OpenSAMLTestBase;
/**
* Test cases for {@link XMLObjectFactoryBean}.
*
* @author Martin Lindström (martin.lindstrom@litsec.se)
*/
public class XMLObjectFactoryBeanTest extends OpenSAMLTestBase {
public static final Resource METADATA_RESOURCE = new ClassPathResource("/metadata/sveleg-fedtest.xml");
@Test
public void testEntitiesDescriptor() throws Exception {
XMLObjectFactoryBean factory = new XMLObjectFactoryBean(METADATA_RESOURCE);
factory.afterPropertiesSet();
XMLObject object = factory.getObject();
Assert.assertNotNull(object);
Assert.assertTrue(object instanceof EntitiesDescriptor);
}
}
| 33.804348 | 105 | 0.767846 |
a4b7a13c134ec7df91e22f3dd8c3d19a3a4350fc | 2,647 | /*
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]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 com.helger.graph.impl;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.annotation.ReturnsMutableObject;
import com.helger.commons.collection.attr.AttributeContainerAny;
import com.helger.commons.hashcode.HashCodeGenerator;
import com.helger.commons.string.StringHelper;
import com.helger.commons.string.ToStringGenerator;
import com.helger.graph.IMutableBaseGraphObject;
/**
* Base class for graph nodes and graph relations.
*
* @author Philip Helger
*/
@NotThreadSafe
public abstract class AbstractBaseGraphObject implements IMutableBaseGraphObject
{
private final String m_sID;
private final AttributeContainerAny <String> m_aAttrs = new AttributeContainerAny <> ();
/**
* Constructor
*
* @param sID
* If <code>null</code> a new ID is generated by the
* {@link GraphObjectIDFactory}.
*/
public AbstractBaseGraphObject (@Nullable final String sID)
{
if (StringHelper.hasNoText (sID))
m_sID = GraphObjectIDFactory.createNewGraphObjectID ();
else
m_sID = sID;
}
@Nonnull
@Nonempty
public final String getID ()
{
return m_sID;
}
@Nonnull
@ReturnsMutableObject
public final AttributeContainerAny <String> attrs ()
{
return m_aAttrs;
}
@Override
public boolean equals (final Object o)
{
if (o == this)
return true;
if (o == null || !getClass ().equals (o.getClass ()))
return false;
final AbstractBaseGraphObject rhs = (AbstractBaseGraphObject) o;
return m_sID.equals (rhs.m_sID) && m_aAttrs.equals (rhs.m_aAttrs);
}
@Override
public int hashCode ()
{
return new HashCodeGenerator (this).append (m_sID).append (m_aAttrs).getHashCode ();
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("ID", m_sID).append ("Attrs", m_aAttrs).getToString ();
}
}
| 28.159574 | 103 | 0.720816 |
4634514b7693fc252ce6dfbbbb4d00781a282e95 | 239 | package org.leibnizcenter.rechtspraak.tagging.crf.features.textpatterns.title;
import org.junit.Test;
/**
* Created by maarten on 1-4-16.
*/
public class TitlePatternsTest {
@Test
public void testPatterns() {
//todo
}
} | 18.384615 | 78 | 0.698745 |
2535622831a4061e0d1e53efdf48e90cda55293c | 3,996 | package uk.gov.hmcts.reform.ccd.documentam.client.datastore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import uk.gov.hmcts.reform.ccd.documentam.apihelper.Constants;
import uk.gov.hmcts.reform.ccd.documentam.exception.BadRequestException;
import uk.gov.hmcts.reform.ccd.documentam.exception.ForbiddenException;
import uk.gov.hmcts.reform.ccd.documentam.exception.ServiceException;
import uk.gov.hmcts.reform.ccd.documentam.model.CaseDocumentMetadata;
import uk.gov.hmcts.reform.ccd.documentam.model.CaseDocumentResource;
import uk.gov.hmcts.reform.ccd.documentam.model.DocumentPermissions;
import uk.gov.hmcts.reform.ccd.documentam.security.SecurityUtils;
import java.util.Optional;
import java.util.UUID;
@Slf4j
@Service
public class CaseDataStoreClientImpl implements CaseDataStoreClient {
private static final String CASE_ERROR_MESSAGE = "Couldn't find document for case : ";
private final RestTemplate restTemplate;
private final String caseDataStoreUrl;
private final SecurityUtils securityUtils;
@Autowired
public CaseDataStoreClientImpl(@Qualifier("dataStoreRestTemplate") final RestTemplate restTemplate,
@Value("${caseDataStoreUrl}") final String caseDataStoreUrl,
final SecurityUtils securityUtils) {
this.restTemplate = restTemplate;
this.caseDataStoreUrl = caseDataStoreUrl;
this.securityUtils = securityUtils;
}
@Override
@SuppressWarnings("unchecked")
public Optional<DocumentPermissions> getCaseDocumentMetadata(String caseId, UUID documentId) {
try {
final HttpHeaders headers = prepareRequestForUpload();
final ResponseEntity<CaseDocumentResource> responseEntity = restTemplate.exchange(
String.format("%s/cases/%s/documents/%s", caseDataStoreUrl, caseId, documentId),
HttpMethod.GET,
new HttpEntity<>(headers),
CaseDocumentResource.class
);
return Optional.ofNullable(responseEntity.getBody())
.map(CaseDocumentResource::getDocumentMetadata)
.map(CaseDocumentMetadata::getDocumentPermissions);
} catch (HttpClientErrorException exception) {
log.error("Exception occurred while getting document permissions from CCD Data store: {}",
exception.getMessage());
if (HttpStatus.NOT_FOUND.equals(exception.getStatusCode())) {
return Optional.empty();
} else if (HttpStatus.FORBIDDEN.equals(exception.getStatusCode())) {
throw new ForbiddenException(CASE_ERROR_MESSAGE + caseId);
} else if (HttpStatus.BAD_REQUEST.equals(exception.getStatusCode())) {
throw new BadRequestException(Constants.INPUT_INVALID);
} else {
throw new ServiceException(String.format(
"Problem fetching the document for document id: %s because of %s",
documentId,
exception.getMessage()
));
}
}
}
private HttpHeaders prepareRequestForUpload() {
HttpHeaders headers = new HttpHeaders();
headers.addAll(securityUtils.authorizationHeaders());
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
}
| 44.4 | 103 | 0.71021 |
7fbee40678e50aa359d483b79884b87b4e712d58 | 3,197 | package com.scj.beilu.app.ui.merchant.adapter;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.scj.beilu.app.GlideApp;
import com.scj.beilu.app.GlideRequest;
import com.scj.beilu.app.R;
import com.scj.beilu.app.base.BaseViewHolder;
import com.scj.beilu.app.listener.OnItemClickListener;
import com.scj.beilu.app.mvp.merchant.bean.MerchantInfoCoachPicInfoBean;
import com.scj.beilu.app.ui.merchant.MerchantCoachAlbumListFrag;
import java.util.List;
/**
* @author Mingxun
* @time on 2019/4/16 17:27
*/
public class MerchantCoachAlbumListAdapter extends RecyclerView.Adapter<MerchantCoachAlbumListAdapter.CoachAlbumViewHolder> {
private List<MerchantInfoCoachPicInfoBean> mPicInfoBeans;
private GlideRequest<Drawable> mOriginal, mThumbnail;
private OnItemClickListener<MerchantInfoCoachPicInfoBean> mOnItemClickListener;
public MerchantCoachAlbumListAdapter(MerchantCoachAlbumListFrag frag) {
mOriginal = GlideApp.with(frag).asDrawable().optionalCenterCrop();
mThumbnail = GlideApp.with(frag).asDrawable().optionalCenterCrop();
}
public void setPicInfoBeans(List<MerchantInfoCoachPicInfoBean> picInfoBeans) {
mPicInfoBeans = picInfoBeans;
notifyDataSetChanged();
}
public void setOnItemClickListener(OnItemClickListener<MerchantInfoCoachPicInfoBean> onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
@NonNull
@Override
public CoachAlbumViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_merchant_coach_album, parent, false);
return new CoachAlbumViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CoachAlbumViewHolder holder, int position) {
try {
MerchantInfoCoachPicInfoBean picInfoBean = mPicInfoBeans.get(position);
mOriginal.load(picInfoBean.getCoachPicAddr())
.thumbnail(mThumbnail.load(picInfoBean.getCoachPicAddrZip()))
.into(holder.iv_merchant_coach_img);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return mPicInfoBeans == null ? 0 : mPicInfoBeans.size();
}
public class CoachAlbumViewHolder extends BaseViewHolder {
private ImageView iv_merchant_coach_img;
public CoachAlbumViewHolder(View itemView) {
super(itemView);
iv_merchant_coach_img = findViewById(R.id.iv_merchant_coach_img);
iv_merchant_coach_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(getAdapterPosition(), mPicInfoBeans.get(getAdapterPosition()), v);
}
}
});
}
}
}
| 36.329545 | 125 | 0.713481 |
725e4f5017fc3a820596eb4cfbb5fa534abecbf1 | 1,180 | /*
* Copyright 2021 Adobe. 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.adobe.aem.dot.dispatcher.core.parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConfigurationIndexTest {
@Test
public void basics() {
ConfigurationIndex index = new ConfigurationIndex(2, 3);
assertEquals("char is 2", 2, index.getCharIndex());
assertEquals("line is 3", 3, index.getLineIndex());
index.setCharIndex(4);
assertEquals("char is 4", 4, index.getCharIndex());
index.setLineIndex(5);
assertEquals("line is 5", 5, index.getLineIndex());
}
}
| 31.052632 | 78 | 0.704237 |
82ddbdc965231047fabe55dc58c7ac4e71b22cd1 | 155 | package Exceptions;
public class StackException extends Exception{
public StackException(){super();}
public StackException(String s){super(s);}
}
| 22.142857 | 46 | 0.748387 |
f12ef4c7d4c965ae23287dd7150d21de331ad44f | 22,356 | package ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.candidatePatternsGeneration.CandidateGenerator;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.database.SequenceDatabase;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.patterns.Pattern;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.savers.Saver;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.savers.SaverIntoFile;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.savers.SaverIntoMemory;
import ca.pfv.spmf.tools.MemoryLogger;
/**
* This is an implementation of the SPADE. SPADE was proposed by ZAKI in 2001.
*
* NOTE: This implementation saves the pattern to a file as soon as they are
* found or can keep the pattern into memory, depending on what the user choose.
*
* Copyright Antonio Gomariz Peñalver 2013
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF 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.
*
* SPMF 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
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*
* @author agomariz
*/
public class AlgoSPADE {
public long joinCount; // PFV 2013
/**
* the minimum support threshold
*/
protected double minSup;
/**
* The minimum support relative threshold, i.e. the minimum number of
* sequences where the patterns have to be
*/
protected double minSupRelative;
/**
* Flag indicating if we want a depth-first search when true. Otherwise we
* say that we want a breadth-first search
*/
protected boolean dfs;
/**
* Saver variable to decide where the user want to save the results, if it
* the case
*/
Saver saver = null;
/**
* Start and end points in order to calculate the overall time taken by the
* algorithm
*/
public long start, end;
/**
* Equivalence class whose class identifier is a frequent item
*/
protected List<EquivalenceClass> frequentItems;
/**
* Abstraction creator
*/
private AbstractionCreator abstractionCreator;
/**
* Number of frequent patterns found by the algorithm
*/
private int numberOfFrequentPatterns;
/**
* Constructor of the class that calls SPADE algorithm.
*
* @param support Minimum support (from 0 up to 1)
* @param dfs Flag for indicating if we want a depth first search. If false,
* we indicate that we want a breath-first search.
* @param abstractionCreator An abstraction creator.
*/
public AlgoSPADE(double support, boolean dfs, AbstractionCreator abstractionCreator) {
this.minSup = support;
this.abstractionCreator = abstractionCreator;
this.dfs = dfs;
}
/**
* Actual call to SPADE algorithm. The output can be either kept or ignore.
* Whenever we choose to keep the patterns found, we can keep them in a file
* or in the main memory
*
* @param database Original database in where we want to search for the
* frequent patterns.
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param keepPatterns Flag indicating if we want to keep the output or not
* @param verbose Flag for debugging purposes
* @param outputFilePath Path of the file in which we want to store the
* frequent patterns. If this value is null, we keep the patterns in the
* main memory. This argument is taken into account just when keepPatterns
* is activated.
* @param outputSequenceIdentifiers if true, sequence identifiers will be output for each pattern
* @throws IOException
*/
public void runAlgorithm(SequenceDatabase database, CandidateGenerator candidateGenerator, boolean keepPatterns, boolean verbose, String outputFilePath, boolean outputSequenceIdentifiers) throws IOException {
//If we do no have any file path
if (outputFilePath == null) {
//The user wants to save the results in memory
saver = new SaverIntoMemory(outputSequenceIdentifiers);
} else {
//Otherwise, the user wants to save them in the given file
saver = new SaverIntoFile(outputFilePath, outputSequenceIdentifiers);
}
//this.minSupRelative = minSup; // PFV 2013
this.minSupRelative = (int) Math.ceil(database.size() * minSup);
if (this.minSupRelative == 0) { // protection
this.minSupRelative = 1;
}
// reset the stats about memory usage
MemoryLogger.getInstance().reset();
//keeping the starting time
start = System.currentTimeMillis();
//We run SPADE algorithm
runSPADE(database, candidateGenerator, (long) minSupRelative, dfs, keepPatterns, verbose);
//keeping the ending time
end = System.currentTimeMillis();
//Search for frequent patterns: Finished
saver.finish();
}
/**
* Actual call to SPADE algorithm. The output can be either kept or ignore.
* Whenever we choose to keep the patterns found, we can keep them in a file
* or in the main memory. The algorithm SPADE is executed in a parallel way.
*
* @param database Original database in where we want to search for the
* frequent patterns.
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param keepPatterns Flag indicating if we want to keep the output or not
* @param verbose Flag for debugging purposes
* @param outputFilePath Path of the file in which we want to store the
* frequent patterns. If this value is null, we keep the patterns in the
* main memory. This argument is taken into account just when keepPatterns
* is activated.
* @param outputSequenceIdentifiers if true, sequence identifiers will be output for each pattern
* @throws IOException
*/
public void runAlgorithmParallelized(SequenceDatabase database, CandidateGenerator candidateGenerator, boolean keepPatterns, boolean verbose, String outputFilePath, boolean outputSequenceIdentifiers) throws IOException {
//If we do no have any file path
if (outputFilePath == null) {
//The user wants to save the results in memory
saver = new SaverIntoMemory(outputSequenceIdentifiers);
} else {
//Otherwise, the user wants to save them in the given file
saver = new SaverIntoFile(outputFilePath,outputSequenceIdentifiers);
}
this.minSupRelative = (int) Math.ceil(minSup * database.size());
//this.minSupRelative = (int) (database.size() * minSup);
if (this.minSupRelative == 0) { // protection
this.minSupRelative = 1;
}
// reset the stats about memory usage
MemoryLogger.getInstance().reset();
//keeping the starting time
start = System.currentTimeMillis();
//We run SPADE algorithm
runSPADEFromSize2PatternsParallelized2(database, candidateGenerator, (long) minSupRelative, dfs, keepPatterns, verbose);
//keeping the ending time
end = System.currentTimeMillis();
//Search for frequent patterns: Finished
saver.finish();
}
/**
*
* The actual method for extracting frequent sequences.
*
* @param database The original database
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param minSupportCount The minimum relative support
* @param dfs Flag for indicating if we want a depth first search. If false,
* we indicate that we want a breath-first search.
* @param keepPatterns flag indicating if we are interested in keeping the
* output of the algorithm
* @param verbose Flag for debugging purposes
*/
protected void runSPADE(SequenceDatabase database, CandidateGenerator candidateGenerator, long minSupportCount, boolean dfs, boolean keepPatterns, boolean verbose) {
//We get the equivalence classes formed by the frequent 1-patterns
frequentItems = database.frequentItems();
//We extract their patterns
Collection<Pattern> size1sequences = getPatterns(frequentItems);
//If we want to keep the output
if (keepPatterns) {
for (Pattern atom : size1sequences) {
//We keep all the frequent 1-patterns
saver.savePattern(atom);
}
}
// CREATE COOCURENCE MAP
database = null;
//We define the root class
EquivalenceClass rootClass = new EquivalenceClass(null);
/*And we insert the equivalence classes corresponding to the frequent
1-patterns as its members*/
for (EquivalenceClass atom : frequentItems) {
rootClass.addClassMember(atom);
}
//Inizialitation of the class that is in charge of find the frequent patterns
FrequentPatternEnumeration frequentPatternEnumeration = new FrequentPatternEnumeration(candidateGenerator, minSupRelative, saver);
//We set the number of frequent items to the number of frequent items
frequentPatternEnumeration.setFrequentPatterns(frequentItems.size());
//We execute the search
frequentPatternEnumeration.execute(rootClass, dfs, keepPatterns, verbose, null,null);
/* Once we had finished, we keep the number of frequent patterns that we
* finally found
*/
numberOfFrequentPatterns = frequentPatternEnumeration.getFrequentPatterns();
// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
joinCount = frequentPatternEnumeration.INTERSECTION_COUNTER;
}
/**
*
* The actual method for extracting frequent sequences. This method it starts
* with both the frequent 1-patterns and 2-patterns already found.
*
* @param database The original database
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param minSupportCount The minimum relative support
* @param dfs Flag for indicating if we want a depth first search. If false,
* we indicate that we want a breath-first search.
* @param keepPatterns flag indicating if we are interested in keeping the
* output of the algorithm
* @param verbose Flag for debugging purposes
*/
protected void runSPADEFromSize2Sequences(SequenceDatabase database, CandidateGenerator candidateGenerator, long minSupportCount, boolean dfs, boolean keepPatterns, boolean verbose) {
frequentItems = database.frequentItems();
Collection<Pattern> size1Patterns = getPatterns(frequentItems);
saver.savePatterns(size1Patterns);
List<EquivalenceClass> size2Patterns = database.getSize2FrecuentSequences(minSupRelative);
Collection<Pattern> size2sequences = getPatterns(size2Patterns);
saver.savePatterns(size2sequences);
size2Patterns.clear();
database.clear();
size2Patterns = null;
database = null;
FrequentPatternEnumeration frequentPatternEnumeration = new FrequentPatternEnumeration(candidateGenerator, minSupRelative, saver);
frequentPatternEnumeration.setFrequentPatterns(size1Patterns.size() + size2sequences.size());
size1Patterns = null;
size2sequences = null;
while (frequentItems.size() > 0) {
EquivalenceClass frequentAtomClass = frequentItems.get(frequentItems.size() - 1);
if (verbose) {
System.out.println("Exploring... " + frequentAtomClass);
}
frequentPatternEnumeration.execute(frequentAtomClass, dfs, keepPatterns, verbose, null,null);
frequentItems.remove(frequentItems.size() - 1);
if (verbose) {
System.out.println("\tWe found " + frequentPatternEnumeration.getFrequentPatterns() + " frequent patterns so far.");
}
// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
}
numberOfFrequentPatterns = frequentPatternEnumeration.getFrequentPatterns();
}
/**
* It gets the patterns that are the identifiers of the given equivalence classes
* @param equivalenceClasses The set of equivalence classes from where we want
* to obtain their class identifiers
* @return
*/
private Collection<Pattern> getPatterns(List<EquivalenceClass> equivalenceClasses) {
ArrayList<Pattern> patterns = new ArrayList<Pattern>();
for (EquivalenceClass equivalenceClass : equivalenceClasses) {
Pattern frequentPattern = equivalenceClass.getClassIdentifier();
patterns.add(frequentPattern);
}
return patterns;
}
public String printStatistics() {
StringBuilder sb = new StringBuilder(200);
sb.append("============= Algorithm - STATISTICS =============\n Total time ~ ");
sb.append(getRunningTime());
sb.append(" ms\n");
sb.append(" Frequent sequences count : ");
sb.append(numberOfFrequentPatterns);
sb.append('\n');
sb.append(" Join count : ");
sb.append(joinCount);
sb.append('\n');
sb.append(" Max memory (mb):");
sb.append(MemoryLogger.getInstance().getMaxMemory());
sb.append('\n');
sb.append(saver.print());
sb.append("\n===================================================\n");
return sb.toString();
}
public int getNumberOfFrequentPatterns() {
return numberOfFrequentPatterns;
}
/**
* It gets the time spent by the algoritm in its execution.
* @return
*/
public long getRunningTime() {
return (end - start);
}
/**
* It gets the minimum relative support, i.e. the minimum number of database
* sequences where a pattern has to appear
* @return
*/
public double getMinSupRelative() {
return minSupRelative;
}
/**
* It clears all the attributes of AlgoPrefixSpan class
*/
public void clear() {
frequentItems.clear();
abstractionCreator = null;
if (saver != null) {
saver.clear();
saver = null;
}
}
/**
*
* The actual method for extracting frequent sequences. This method it starts
* with both the frequent 1-patterns and 2-patterns already found. Besides, it
* resolves each equivalence class formed by the 1-patterns independently.
*
* @param database The original database
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param minSupportCount The minimum relative support
* @param dfs Flag for indicating if we want a depth first search. If false,
* we indicate that we want a breath-first search.
* @param keepPatterns flag indicating if we are interested in keeping the
* output of the algorithm
* @param verbose Flag for debugging purposes
*/
protected void runSPADEFromSize2PatternsParallelized(SequenceDatabase database, CandidateGenerator candidateGenerator, long minSupportCount, boolean dfs, boolean keepPatterns, boolean verbose) {
frequentItems = database.frequentItems();
Collection<Pattern> size1Patterns = getPatterns(frequentItems);
saver.savePatterns(size1Patterns);
List<EquivalenceClass> size2EquivalenceClass = database.getSize2FrecuentSequences(minSupRelative);
Collection<Pattern> size2Sequences = getPatterns(size2EquivalenceClass);
saver.savePatterns(size2Sequences);
size2EquivalenceClass = null;
database = null;
FrequentPatternEnumeration frequentPatternEnumeration = new FrequentPatternEnumeration(candidateGenerator, minSupRelative, saver);
frequentPatternEnumeration.setFrequentPatterns(size1Patterns.size() + size2Sequences.size());
size1Patterns = null;
size2Sequences = null;
Runtime runtime = Runtime.getRuntime();
int numberOfAvailableProcessors = runtime.availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(numberOfAvailableProcessors);
ArrayList<Future<Void>> set = new ArrayList<Future<Void>>();
while (frequentItems.size() > 0) {
EquivalenceClass frequentItem = frequentItems.get(frequentItems.size() - 1);
if (verbose) {
System.out.println("Exploring " + frequentItem);
}
Callable<Void> callable = new FrequentPatternEnumerationFacade(frequentPatternEnumeration, frequentItem, dfs, keepPatterns, verbose, saver);
Future<Void> future = pool.submit(callable);
set.add(future);
frequentItems.remove(frequentItems.size() - 1);
// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
}
try {
int cont = 1;
System.err.println("There are " + set.size() + " equivalence classes and " + numberOfAvailableProcessors + " available processors");
while (!set.isEmpty()) {
for (int i = 0; i < set.size(); i++) {
Future<Void> future = set.get(i);
if (future.isDone()) {
System.err.println(cont++ + ":this thread is done.");
set.remove(i);
i--;
}
}
}
numberOfFrequentPatterns = frequentPatternEnumeration.getFrequentPatterns();// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
pool.shutdown();
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (Exception e) {
System.err.println("Problems with the concurrency!!");
e.printStackTrace();
}
}
/**
*
* The actual method for extracting frequent sequences. This method it starts
* with both the frequent 1-patterns and 2-patterns already found. Besides, it
* resolves each equivalence class formed by the 1-patterns independently.
*
* @param database The original database
* @param candidateGenerator The candidate generator used by the algorithm
* SPADE
* @param minSupportCount The minimum relative support
* @param dfs Flag for indicating if we want a depth first search. If false,
* we indicate that we want a breath-first search.
* @param keepPatterns flag indicating if we are interested in keeping the
* output of the algorithm
* @param verbose Flag for debugging purposes
*/
protected void runSPADEFromSize2PatternsParallelized2(SequenceDatabase database, CandidateGenerator candidateGenerator, long minSupportCount, boolean dfs, boolean keepPatterns, boolean verbose) {
frequentItems = database.frequentItems();
Collection<Pattern> size1Sequences = getPatterns(frequentItems);
saver.savePatterns(size1Sequences);
List<EquivalenceClass> size2EquivalenceClasses = database.getSize2FrecuentSequences(minSupRelative);
Collection<Pattern> size2Sequences = getPatterns(size2EquivalenceClasses);
saver.savePatterns(size2Sequences);
numberOfFrequentPatterns = size1Sequences.size() + size2Sequences.size();
size2EquivalenceClasses = null;
database = null;
Runtime runtime = Runtime.getRuntime();
ExecutorService pool = Executors.newFixedThreadPool(runtime.availableProcessors());
Set<Future<Void>> set = new LinkedHashSet<Future<Void>>();
ArrayList<FrequentPatternEnumeration> enumerates = new ArrayList<FrequentPatternEnumeration>();
while (frequentItems.size() > 0) {
EquivalenceClass frequentAtom = frequentItems.get(frequentItems.size() - 1);
if (verbose) {
System.out.println("Exploring " + frequentAtom);
}
FrequentPatternEnumeration frequentPatternEnumeration = new FrequentPatternEnumeration(candidateGenerator, minSupRelative, saver);
enumerates.add(frequentPatternEnumeration);
Callable<Void> callable = new FrequentPatternEnumerationFacade(frequentPatternEnumeration, frequentAtom, dfs, keepPatterns, verbose, saver);
Future<Void> future = pool.submit(callable);
set.add(future);
frequentItems.remove(frequentItems.size() - 1);
// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
}
try {
pool.shutdown();
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (Exception e) {
System.err.println("Problems with the concurrency!!");
}
FrequentPatternEnumeration fpe = new FrequentPatternEnumeration(candidateGenerator, minSup, saver);
numberOfFrequentPatterns += fpe.getFrequentPatterns();
// check the memory usage for statistics
MemoryLogger.getInstance().checkMemory();
}
}
| 42.827586 | 224 | 0.675166 |
e591aac2201351f3d94b76baa3619f7032812f63 | 9,793 | /***************************************************************************
* $Id: Point.java 1316 2011-07-01 18:18:32Z mathews $
*
* (C) Copyright MITRE Corporation 2006-2007
*
* The program is provided "as is" without any warranty express or implied,
* including the warranty of non-infringement and the implied warranties of
* merchantability and fitness for a particular purpose. The Copyright
* owner will not be liable for any damages suffered by you as a result of
* using the Program. In no event will the Copyright owner be liable for
* any special, indirect or consequential damages or lost profits even if
* the Copyright owner has been advised of the possibility of their
* occurrence.
*
***************************************************************************/
package org.opensextant.giscore.geometry;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.opensextant.geodesy.Angle;
import org.opensextant.geodesy.GeoPoint;
import org.opensextant.geodesy.Geodetic2DBounds;
import org.opensextant.geodesy.Geodetic2DPoint;
import org.opensextant.geodesy.Geodetic3DBounds;
import org.opensextant.geodesy.Geodetic3DPoint;
import org.opensextant.geodesy.Latitude;
import org.opensextant.geodesy.Longitude;
import org.opensextant.geodesy.UnmodifiableGeodetic2DBounds;
import org.opensextant.geodesy.UnmodifiableGeodetic3DBounds;
import org.opensextant.giscore.IStreamVisitor;
import org.opensextant.giscore.utils.SimpleObjectInputStream;
import org.opensextant.giscore.utils.SimpleObjectOutputStream;
/**
* The Point class represents a single Geodetic point (Geodetic2DPoint or
* Geodetic3DPoint) for input and output in GIS formats such as ESRI Shapefiles
* or Google Earth KML files. In ESRI Shapefiles, this object corresponds to a
* ShapeType of Point or PointZ. In Google KML files, this object corresponds to
* a Geometry object of type Point. <p/>
*
* Note Point extends GeometryBase including tessellate and drawOrder fields but those
* fields are not applicable to the Point geometry and ignored.
*
* @author Paul Silvey
*/
public class Point extends GeometryBase {
private static final long serialVersionUID = 1L;
@NonNull
private Geodetic2DPoint pt; // or extended Geodetic3DPoint
/**
* Empty ctor only for object IO. Constructor must be followed by call to {@code readData()}
* to initialize the object instance otherwise object is invalid.
* @see SimpleObjectInputStream
* @see SimpleObjectOutputStream
*/
public Point() {
pt = new Geodetic2DPoint();
}
/**
* Ctor, create a point given a lat and lon value in a WGS84 spatial
* reference system.
*
* @param lat
* the latitude in degrees
* @param lon
* the longitude in degrees
*/
public Point(double lat, double lon) {
this(lat, lon, false);
}
/**
* Create a point given a lat and lon value in a WGS84 spatial
* reference system.
*
* @param lat
* the latitude, never null
* @param lon
* the longitude, never null
* @throws NullPointerException if latitude or longitude are null
*/
public Point(Latitude lat, Longitude lon) {
this(new Geodetic2DPoint(lon, lat));
}
/**
* Ctor, create a point given a lat and lon value in a WGS84 spatial
* reference system.
*
* @param lat
* the latitude in degrees
* @param lon
* the longitude in degrees
* @param is3d
* a three d point if <code>true</code>
*
*/
public Point(double lat, double lon, boolean is3d) {
this(is3d ? new Geodetic3DPoint(new Longitude(lon, Angle.DEGREES),
new Latitude(lat, Angle.DEGREES), 0.0) : new Geodetic2DPoint(
new Longitude(lon, Angle.DEGREES), new Latitude(lat,
Angle.DEGREES)));
}
/**
* This constructor takes a Longitude, Latitude, and an elevation value in meters.
* The default elevation reference point (vertical datum) is the tangent surface plane
* touching the WGS84 Ellipsoid at the given longitude and latitude.
*
* @param lat
* the latitude in degrees
* @param lon
* the longitude in degrees
* @param elevation
* elevation in meters from the assumed reference point
*/
public Point(double lat, double lon, double elevation) {
this(new Geodetic3DPoint(new Longitude(lon, Angle.DEGREES),
new Latitude(lat, Angle.DEGREES), elevation));
}
/**
* This constructor takes a Longitude, Latitude, and an elevation value in meters.
*
* @param lat the latitude in degrees, never null
* @param lon the longitude in degrees, never null
* @param elevation elevation in meters from the assumed reference point
* if elevation is null then Geodetic2DPoint is created otherwise
* Geodetic3DPoint is created with the elvation.
* @throws NullPointerException if lat or lon are null
*/
public Point(Latitude lat, Longitude lon, Double elevation) {
this(elevation == null
? new Geodetic2DPoint(lon, lat)
: new Geodetic3DPoint(lon, lat, elevation));
}
/**
* The Constructor takes a GeoPoint that is either a {@code Geodetic2DPoint} or a
* {@code Geodetic3DPoint} and initializes a Geometry object for it.
* <P>
* Note {@code GeoPoint} object is copied by reference so caller must copy this
* point and/or construct a new {@code GeoPoint} object if need to modify its
* state after this constructor is invoked. Assumes GeoPoints are immutable
* if used in context of Point geometries.
*
* @param gp
* GeoPoint to initialize this Point with (must be Geodetic form)
* @throws IllegalArgumentException
* error if object is not valid.
*/
public Point(GeoPoint gp) throws IllegalArgumentException {
if (gp == null)
throw new IllegalArgumentException("Point must not be null");
if (gp instanceof Geodetic3DPoint) {
is3D = true;
} else if (gp instanceof Geodetic2DPoint) {
is3D = false;
} else
throw new IllegalArgumentException("Point must be in Geodetic form");
pt = (Geodetic2DPoint) gp;
}
/**
* This method returns a Geodetic2DPoint that is at the center of this
* Geometry object's Bounding Box.
*
* @return Geodetic2DPoint at the center of this Geometry object
*/
@Override
@NonNull
public Geodetic2DPoint getCenter() {
// for point feature just return the point
return pt;
}
/* (non-Javadoc)
* @see org.mitre.giscore.geometry.Geometry#computeBoundingBox()
*/
protected void computeBoundingBox() {
// make bbox unmodifiable
bbox = is3D ? new UnmodifiableGeodetic3DBounds(new Geodetic3DBounds((Geodetic3DPoint) pt))
: new UnmodifiableGeodetic2DBounds(new Geodetic2DBounds(pt));
}
/**
* This method simply returns the Geodetic point object (modeled like a cast
* operation).
*
* @return the Geodetic2DPoint object that defines this Point.
*/
@NonNull
public Geodetic2DPoint asGeodetic2DPoint() {
return pt;
}
/**
* This method returns a hash code for this Point object.
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
return pt.hashCode();
}
/**
* This method is used to test whether two Points are equal in the sense
* that have the same coordinate value.
*
* @param that
* Point to compare against this one.
* @return true if specified Point is equal in value to this Point.
*/
public boolean equals(Point that) {
return that != null && this.pt.equals(that.pt);
}
/**
* This method is used to test whether two Points are equal in the sense
* that have the same coordinate value.
*
* @param that
* Point to compare against this one.
* @return true if specified Point is equal in value to this Point.
*/
@Override
public boolean equals(Object that) {
return (that instanceof Point) && this.equals((Point) that);
}
/**
* The toString method returns a String representation of this Object
* suitable for debugging
*
* @return String containing Geometry Object type, bounding coordintates,
* and number of parts.
*/
public String toString() {
return "Point at (" + pt.getLongitude() + ", " + pt.getLatitude() + ")";
}
public void accept(IStreamVisitor visitor) {
visitor.visit(this);
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.geometry.Geometry#readData(org.mitre.giscore.utils.
* SimpleObjectInputStream)
*/
@Override
public void readData(SimpleObjectInputStream in) throws IOException,
ClassNotFoundException, InstantiationException,
IllegalAccessException {
super.readData(in);
boolean is3d = in.readBoolean();
double elevation = 0.0;
if (is3d) {
elevation = in.readDouble();
}
Angle lat = readAngle(in);
Angle lon = readAngle(in);
if (is3d)
pt = new Geodetic3DPoint(new Longitude(lon), new Latitude(lat), elevation);
else
pt = new Geodetic2DPoint(new Longitude(lon), new Latitude(lat));
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.geometry.Geometry#writeData(org.mitre.giscore.utils
* .SimpleObjectOutputStream)
*/
@Override
public void writeData(SimpleObjectOutputStream out) throws IOException {
super.writeData(out);
boolean is3d = pt instanceof Geodetic3DPoint;
out.writeBoolean(is3d);
if (is3d) {
out.writeDouble(((Geodetic3DPoint) pt).getElevation());
}
writeAngle(out, pt.getLatitude());
writeAngle(out, pt.getLongitude());
}
@Override
public int getNumParts() {
return 1;
}
@Override
public int getNumPoints() {
return 1;
}
@Override
@NonNull
public List<Point> getPoints() {
return Collections.singletonList(new Point(pt));
}
}
| 30.990506 | 98 | 0.691106 |
00f4ba757b1e19e89b1728cdab0540641ca49e1b | 23,702 | /*-
* ===============LICENSE_START=======================================================
* Acumos
* ===================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ===================================================================================
* This Acumos software file is distributed by AT&T
* 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
*
* 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.
* ===============LICENSE_END=========================================================
*/
package org.acumos.streamercatalog.connection;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.acumos.streamercatalog.common.DataStreamerCatalogUtil;
import org.acumos.streamercatalog.exception.DataStreamerException;
import org.acumos.streamercatalog.model.CatalogObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
@Component
public class DbUtilities {
private static final String DETAIL = "detail";
private static final String _ID = "_id";
private static final String MESSAGE_ROUTER_DETAILS = "messageRouterDetails";
private static final String DE_SERIALIZER = "deSerializer";
private static final String SERIALIZER = "serializer";
private static final String TOPIC_NAME = "topicName";
private static final String PASSWORD = "password";
private static final String USER_NAME = "userName";
private static final String SERVER_PORT = "serverPort";
private static final String SERVER_NAME = "serverName";
private static final String AUTHORIZATION2 = "authorization";
private static final String STATUS = "status";
private static final String STREAMER_NAME = "streamerName";
private static final String SUBSCRIBER_URL = "subscriberUrl";
private static final String DESCRIPTION = "description";
private static final String MSG_ROUTER = "MsgRouter";
private static final String CATEGORY = "category";
private static final String DMAAP = "DMaaP";
private static final String NAMESPACE = "namespace";
private static final String POLLING_INTERVAL = "pollingInterval";
private static final String UPDATE_TIME = "updateTime";
private static final String UPDATED_BY = "updatedBy";
private static final String UPDATE = "update";
private static final String CREATE_TIME = "createTime";
private static final String CREATED_BY = "createdBy";
private static final String CREATE = "create";
private static final String SUBSCRIBER_USERNAME = "subscriberUsername";
private static final String SUBSCRIBER_PASSWORD = "subscriberPassword";
private static final String PUBLISHER_URL = "publisherUrl";
private static final String PUBLISHER_PASSWORD = "publisherPassword";
private static final String PUBLISHER_USER_NAME = "publisherUserName";
private static final String PREDICTOR_URL = "predictorUrl";
private static final String MODEL_VERSION = "modelVersion";
private static final String MODEL_KEY = "modelKey";
private static final String CATALOG_KEY = "catalogKey";
private static final String MONGO_PORT = "mongo_port";
private static final String MONGO_HOSTNAME = "mongo_hostname";
private static final String MONGO_PASSWORD = "mongo_password";
private static final String MONGO_DBNAME = "mongo_dbname";
private static final String MONGO_USERNAME = "mongo_username";
private static Logger log = LoggerFactory.getLogger(DbUtilities.class);
private MongoClient mongoClient = null;
private DB datasrcDB = null;
private DBCollection datasrcCollection = null;
@Autowired
private Environment env;
@Autowired
private DataStreamerCatalogUtil dataStreamerCatalogUtil;
public DbUtilities() {
}
private DBCollection getMongoCollection() throws IOException {
log.info("DbUtilities::getMongoCollection()::trying to get a mongo client instance");
if (mongoClient == null) {
log.info(
"DbUtilities::getMongoCollection()::checking if mongo client is intialised or not, will intialise a copy of it if not intialised.");
MongoCredential mongoCredential = MongoCredential.createCredential(
dataStreamerCatalogUtil.getEnv(MONGO_USERNAME, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_USERNAME)),
dataStreamerCatalogUtil.getEnv(MONGO_DBNAME, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_DBNAME)),
dataStreamerCatalogUtil.getEnv(MONGO_PASSWORD, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_PASSWORD))
.toCharArray());
ServerAddress server = new ServerAddress(
dataStreamerCatalogUtil.getEnv(MONGO_HOSTNAME, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_HOSTNAME)),
Integer.parseInt(
dataStreamerCatalogUtil.getEnv(MONGO_PORT, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_PORT))));
mongoClient = new MongoClient(server, Arrays.asList(mongoCredential));
log.info("DbUtilities::getMongoCollection():: a new mongo client has been intialised.");
}
log.info("DbUtilities::getMongoCollection()::using mongo client to get db connection.");
datasrcDB = mongoClient
.getDB(dataStreamerCatalogUtil.getEnv(MONGO_DBNAME, dataStreamerCatalogUtil.getComponentPropertyValue(MONGO_DBNAME)));
log.info("DbUtilities::getMongoCollection()::using mongo client to get collection.");
datasrcCollection = datasrcDB.getCollection(dataStreamerCatalogUtil.getEnv("mongo_collection_name",
dataStreamerCatalogUtil.getComponentPropertyValue("mongo_collection_name")));
log.info("DbUtilities::getMongoCollection()::returning collection.");
return datasrcCollection;
}
private DBObject createDBObject(CatalogObject objCatalog, String authorization,String mode) throws IOException {
log.info("DbUtilities::createDBObject()::intializing db object builder.");
BasicDBObjectBuilder catalogBuilder = BasicDBObjectBuilder.start();
log.info("DbUtilities::createDBObject()::intializing _id value.");
catalogBuilder.append(_ID, objCatalog.getCatalogKey());
log.info("DbUtilities::createDBObject()::intializing catalog collection value.");
if (objCatalog.getCatalogKey() != null) {
catalogBuilder.append(CATALOG_KEY, objCatalog.getCatalogKey());
}
if (objCatalog.getModelKey() != null) {
catalogBuilder.append(MODEL_KEY, objCatalog.getModelKey());
}
if (objCatalog.getModelVersion() != null) {
catalogBuilder.append(MODEL_VERSION, objCatalog.getModelVersion());
}
if (objCatalog.getPredictorUrl() != null) {
catalogBuilder.append(PREDICTOR_URL, objCatalog.getPredictorId());
}
if (objCatalog.getPublisherUserName() != null) {
catalogBuilder.append(PUBLISHER_USER_NAME, objCatalog.getPublisherUserName());
}
if (objCatalog.getPublisherPassword() != null) {
catalogBuilder.append(PUBLISHER_PASSWORD, objCatalog.getPublisherPassword());
}
if (objCatalog.getPublisherUrl() != null) {
catalogBuilder.append(PUBLISHER_URL, objCatalog.getPublisherUrl());
}
if (objCatalog.getSubscriberPassword() != null) {
catalogBuilder.append(SUBSCRIBER_PASSWORD, objCatalog.getSubscriberPassword());
}
if (objCatalog.getSubscriberUsername() != null) {
catalogBuilder.append(SUBSCRIBER_USERNAME, objCatalog.getSubscriberUsername());
}
if (objCatalog.getCreatedBy() != null && mode.equals(CREATE)) {
catalogBuilder.append(CREATED_BY, objCatalog.getCreatedBy());
catalogBuilder.append(CREATE_TIME, Instant.now().toString());
}
if (objCatalog.getModifiedBy() != null && mode.equals(UPDATE)) {
catalogBuilder.append(UPDATED_BY, objCatalog.getModifiedBy());
catalogBuilder.append(UPDATE_TIME, Instant.now().toString());
}
catalogBuilder.append(POLLING_INTERVAL, objCatalog.getPollingInterval());
catalogBuilder.append(NAMESPACE,
dataStreamerCatalogUtil.getEnv(NAMESPACE, dataStreamerCatalogUtil.getComponentPropertyValue(NAMESPACE)));
if (objCatalog.getCategory() != null) {
if (objCatalog.getCategory().equalsIgnoreCase(DMAAP))
catalogBuilder.append(CATEGORY, DMAAP);
else if (objCatalog.getCategory().equalsIgnoreCase(MSG_ROUTER))
catalogBuilder.append(CATEGORY, MSG_ROUTER);
else
catalogBuilder.append(CATEGORY, objCatalog.getCategory());
} /*else if(objCatalog.getCategory() == null &&
objCatalog.getMessageRouterDetails() != null &&
objCatalog.getMessageRouterDetails().getServerName() != null) {
catalogBuilder.append("category", "MsgRouter");
} else {
catalogBuilder.append("category", "DMaaP");
}*/
if (objCatalog.getDescription() != null) {
catalogBuilder.append(DESCRIPTION, objCatalog.getDescription());
}
if (objCatalog.getSubscriberUrl() != null) {
catalogBuilder.append(SUBSCRIBER_URL, objCatalog.getSubscriberUrl());
}
if (objCatalog.getStreamerName() != null) {
catalogBuilder.append(STREAMER_NAME, objCatalog.getStreamerName());
}
catalogBuilder.append(STATUS, objCatalog.isStatus());
catalogBuilder.append(AUTHORIZATION2, authorization);
if(objCatalog.getMessageRouterDetails() != null) {
BasicDBObject messageRouterDetails = new BasicDBObject();
if (objCatalog.getMessageRouterDetails().getServerName() != null) {
messageRouterDetails.append(SERVER_NAME, objCatalog.getMessageRouterDetails().getServerName());
}
messageRouterDetails.append(SERVER_PORT, objCatalog.getMessageRouterDetails().getServerPort());
if (objCatalog.getMessageRouterDetails().getUserName() != null) {
messageRouterDetails.append(USER_NAME, objCatalog.getMessageRouterDetails().getUserName());
}
if (objCatalog.getMessageRouterDetails().getPassword() != null) {
messageRouterDetails.append(PASSWORD, objCatalog.getMessageRouterDetails().getPassword());
}
if (objCatalog.getMessageRouterDetails().getTopicName() != null) {
messageRouterDetails.append(TOPIC_NAME, objCatalog.getMessageRouterDetails().getTopicName());
}
if (objCatalog.getMessageRouterDetails().getSerializer() != null) {
messageRouterDetails.append(SERIALIZER, objCatalog.getMessageRouterDetails().getSerializer());
}
if (objCatalog.getMessageRouterDetails().getDeSerializer() != null) {
messageRouterDetails.append(DE_SERIALIZER, objCatalog.getMessageRouterDetails().getDeSerializer());
}
catalogBuilder.append(MESSAGE_ROUTER_DETAILS, messageRouterDetails);
}
return catalogBuilder.get();
}
public void insertCatalogDetails(String user, String authorization,CatalogObject objCatalog) throws DataStreamerException, IOException {
DBObject result = null;
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::insertCatalogDetails()::checking user before insertion");
if (user != null) {
query.add(CREATED_BY, user);
} else {
log.info("DbUtilities::insertCatalogDetails()::user value is null");
throw new DataStreamerException("OOPS. User not available");
}
log.info("DbUtilities::insertCatalogDetails()::checking predictor id");
if (objCatalog.getStreamerName() != null) {
query.add(STREAMER_NAME, objCatalog.getStreamerName());
} else {
log.info("DbUtilities::insertCatalogDetails()::streamer name is null");
throw new DataStreamerException("OOPS. Please provide staremer name.");
}
log.info("DbUtilities::insertCatalogDetails()::checking predictor id");
if (objCatalog.getPredictorUrl() != null) {
query.add(PREDICTOR_URL, objCatalog.getPredictorUrl());
} else {
log.info("DbUtilities::insertCatalogDetails()::predictor id is null");
throw new DataStreamerException("OOPS. Please provide predictor id.");
}
log.info("DbUtilities::insertCatalogDetails()::checking publisher url");
if (objCatalog.getPublisherUrl() != null) {
query.add(PUBLISHER_URL, objCatalog.getPublisherUrl());
} else {
log.info("DbUtilities::insertCatalogDetails()::publisher url is null");
throw new DataStreamerException("OOPS. Please provide publisher url");
}
query.add(POLLING_INTERVAL, objCatalog.getPollingInterval());
/* if (!query.isEmpty()) { */
result = getMongoCollection().findOne(query.get());
/*
* } else { throw new CmlpDataSrcException(
* "OOPS. Please check catalog key provided and ser persmission for this operation"
* ); }
*/
if (result == null) {
WriteResult insertResult = getMongoCollection()
.insert(createDBObject(objCatalog, authorization,CREATE));
log.info("DbUtilities::insertCatalogDetails()::id of the inserted mongo object: "
+ insertResult.getUpsertedId());
} else {
log.info(
"DbUtilities::insertCatalogDetails()::Please check publisher URL and predictor id, since this association is already present");
throw new DataStreamerException(
"OOPS. Please check publisher URL and predictor id, since this association is already present");
}
}
public ArrayList<String> getCatalogDetails(String user, String category, String textSearch, String authorization)
throws DataStreamerException, IOException {
ArrayList<String> retrieved = new ArrayList<String>();
DBCursor cursor = null;
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::getCatalogDetails()::checking inputs");
if (textSearch != null) {
return getCatalogDetailsByTextSearch(user, textSearch);
} else {
if (user != null) {
log.info(
"DbUtilities::getCatalogDetails()::checking user, get operation is being performed by " + user);
query.add(CREATED_BY, user);
} else if (user == null) {
throw new DataStreamerException("user can't be null");
}
if (category != null) {
log.info("DbUtilities::getCatalogDetails(), checking category, get operation is being performed for "
+ category + " category.");
query.add(CATEGORY, category);
}
}
//query.add("status", true);
log.info("DbUtilities::getCatalogDetails(), running query");
cursor = getMongoCollection().find(query.get());
log.info("DbUtilities::getCatalogDetails(), processing resultset");
DBObject tempStorage;
while (cursor.hasNext()) {
tempStorage = cursor.next();
retrieved.add(tempStorage.toString());
}
return retrieved;
}
private ArrayList<String> getCatalogDetailsByTextSearch(String user, String textSearch)
throws DataStreamerException, IOException {
ArrayList<String> results = new ArrayList<String>();
DBCursor cursor = null;
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::getCatalogDetailsByTextSearch()::checking inputs");
if (user == null) {
throw new DataStreamerException("user can't be null");
}
log.info("DbUtilities::getCatalogDetailsByTextSearch()::checking user, get operation is being performed by "
+ user);
query.add(CREATED_BY, user);
//query.add("status", true);
if (textSearch != null && !textSearch.isEmpty()) {
log.info("DbUtilities::getCatalogDetailsByTextSearch()::running mongodb query");
cursor = getMongoCollection().find(query.get());
log.info("Creating Regular Expression Pattern of the textSearch input" + textSearch);
Pattern pattern = Pattern.compile(textSearch, Pattern.CASE_INSENSITIVE);
Matcher m;
String str_doc;
log.info("DbUtilities::getCatalogDetailsByTextSearch()::processing resultset");
while (cursor.hasNext()) {
DBObject tempResult = cursor.next();
str_doc = tempResult.toString();
m = pattern.matcher(str_doc);
log.info("DbUtilities::getCatalogDetailsByTextSearch()::matching regex textSearch pattern");
if (m.find()) {
log.info(
"DbUtilities::getCatalogDetailsByTextSearch()::document matching regex textSearch pattern added to results List");
results.add(str_doc);
}
}
} else {
log.info("DbUtilities::getCatalogDetailsByTextSearch()::textSearch value is null or is empty");
throw new DataStreamerException(
"OOPS. TextSearch field is required. Please provide a value for textSearch.");
}
return results;
}
public boolean deleteCatalog(String user, String catalogKey) throws IOException, DataStreamerException {
boolean delete = false;
DBCursor cursor = null;
WriteResult result = null;
log.info("DbUtilities::deletecatalog(), intializing query object");
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::deletecatalog(), checking user");
if (user != null && !user.isEmpty()) {
query.add(CREATED_BY, user);
} else {
log.info("DbUtilities::deletecatalog(), user value is null");
throw new DataStreamerException("OOPS. User not available. Please provide a user.");
}
log.info("DbUtilities::deletecatalog(), checking catalogKey");
if (catalogKey != null && !catalogKey.isEmpty()) {
query.add(_ID, catalogKey);
} else {
log.info("DbUtilities::deletecatalog(), datsourceKey value is null");
throw new DataStreamerException("OOPS. Please provide catalog key");
}
log.info("DbUtilities::deletecatalog(), populating cursor with collection that is to be deleted");
cursor = getMongoCollection().find(query.get());
log.info("DbUtilities::deletecatalog(), checking cursor for value");
if (cursor.hasNext()) {
log.info("DbUtilities::deletecatalog(), issuing command to delete object with id: " + catalogKey);
result = getMongoCollection().remove(query.get());
log.info("result for deletion: " + result.toString());
delete = !result.isUpdateOfExisting();
} else {
log.info("DbUtilities::deletecatalog(), deletion failed for object with id: " + catalogKey
+ " .Please check catalog key provided and user persmission for this operation");
throw new DataStreamerException(
"OOPS. Please check catalog key provided and user persmission for this operation");
}
return delete;
}
public boolean softDeleteCatalog(String user, String catalogKey) throws DataStreamerException, IOException {
boolean delete = false;
DBCursor cursor = null;
WriteResult result = null;
DBObject DBObj = null;
log.info("DbUtilities::softDeletecatalog(), intializing query object");
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::softDeletecatalog(), checking user");
if (user != null && !user.isEmpty()) {
query.add(CREATED_BY, user);
} else {
log.info("DbUtilities::softDeletecatalog(), user value is null");
throw new DataStreamerException("OOPS. User not available. Please provide a user.");
}
log.info("DbUtilities::softDeletecatalog(), checking catalogKey");
if (catalogKey != null && !catalogKey.isEmpty()) {
query.add(_ID, catalogKey);
} else {
log.info("DbUtilities::softDeletecatalog()::datsourceKey value is null");
throw new DataStreamerException("OOPS. Please provide catalog key");
}
log.info("DbUtilities::softDeletecatalog()::populating cursor with collection that is to be deleted");
cursor = getMongoCollection().find(query.get());
log.info("DbUtilities::softDeletecatalog(), checking cursor for value");
if (cursor.hasNext()) {
log.info("DbUtilities::softDeletecatalog(), issuing command to delete object with id: " + catalogKey);
DBObj = cursor.next();
DBObj.put(STATUS, new Boolean(false));
result = getMongoCollection().update(query.get(), new BasicDBObject().append("$set", DBObj));
log.info("result for deletion: " + result.toString());
delete = result.isUpdateOfExisting();
} else {
log.info("DbUtilities::softDeletecatalog(), deletion failed for object with id: " + catalogKey
+ " .Please check catalog key provided and user persmission for this operation");
throw new DataStreamerException(
"OOPS. Please check catalog key provided and user persmission for this operation");
}
return delete;
}
public boolean updateCatalog(String user, String catalogKey, String authorization,CatalogObject objCatalog) throws DataStreamerException, IOException {
boolean update = false;
WriteResult result = null;
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::updatecatalog()::checking user");
if (user != null) {
query.add(CREATED_BY, user);
} else {
log.info("DbUtilities::updatecatalog()::user value is null");
throw new DataStreamerException("OOPS. User not available");
}
log.info("DbUtilities::updatecatalog()::checking catalogkey");
if (catalogKey != null) {
query.add(_ID, catalogKey);
} else {
log.info("DbUtilities::updatecatalog()::catalogKey value is null");
throw new DataStreamerException("OOPS. Please provide catalog key");
}
if (!query.isEmpty()) {
log.info("DbUtilities::updatecatalog(), issuing command to update object with id: " + catalogKey);
result = getMongoCollection().update(query.get(), new BasicDBObject().append("$set",
createDBObject(objCatalog, authorization, UPDATE)));
update = result.isUpdateOfExisting();
} else {
log.info("DbUtilities::updatecatalog()::updation failed for object with id: " + catalogKey
+ " .Please check catalog key provided and user persmission for this operation");
throw new DataStreamerException(
"OOPS. Please check catalog key provided and ser persmission for this operation");
}
return update;
}
public DBObject getCatalogDetailsByKey(String user, String catalogKey, String mode)
throws IOException, DataStreamerException {
BasicDBObjectBuilder query = BasicDBObjectBuilder.start();
log.info("DbUtilities::getCatalogDetailsByKey()::checking inputs");
if (user != null) {
log.info("DbUtilities::getCatalogDetailsByKey()::checking user, get operation is being performed by user: "
+ user);
query.add(CREATED_BY, user);
} else {
log.info("DbUtilities::getCatalogDetailsByKey()::user has not been provided");
throw new DataStreamerException("Please provide proper AAF authentication");
}
if (catalogKey != null) {
log.info(
"DbUtilities::getCatalogDetailsByKey()::checking category, get operation is being performed for id: "
+ catalogKey);
query.add(_ID, catalogKey);
} else {
log.info("DbUtilities::getCatalogDetailsByKey()::catalog key has not been provided");
throw new DataStreamerException("Please provide a catalog key");
}
//query.add("status", true);
log.info("DbUtilities::getCatalogDetailsByKey()::running query");
DBObject result = getMongoCollection().findOne(query.get());
if (result == null) {
log.info(
"DbUtilities::getCatalogDetailsByKey()::No data is available for provided catalog key. Either the key doesn't exist or user doesn't has permission for the record for user: "
+ user + " and record: " + catalogKey);
throw new DataStreamerException(
"No data is available for provided catalog key. Either the key doesn't exist or user doesn't has permission for the record.");
}
if (mode.equals(DETAIL)) {
result.removeField(AUTHORIZATION2);
}
return result;
}
}
| 38.792144 | 178 | 0.735634 |
d7ae0e77551f4acf0f81181317b575ad4b24fa95 | 2,959 | package com.xydroid.dbutils.persistence.repository;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.xydroid.dbutils.persistence.sqlite.Entity;
import com.xydroid.dbutils.persistence.sqlite.SQLExecutor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class RepositoryStub implements CrudRepository {
private SQLExecutor mExecutor;
private SQLiteOpenHelper mHelper;
private Entity mEntity;
private String table;
public RepositoryStub(SQLExecutor executor, SQLiteOpenHelper helper, Entity entity) {
mExecutor = executor;
mHelper = helper;
mEntity = entity;
table = mEntity.getTableName();
}
@Override
public boolean save(Object entity) {
return mExecutor.execSave(table, mEntity.convertToCV(entity));
}
@Override
public boolean save(Iterable entities) {
List<ContentValues> contentValuesList = new ArrayList<>();
for (Object entity : entities) {
contentValuesList.add(mEntity.convertToCV(entity));
}
return mExecutor.execSave(table, contentValuesList);
}
@Override
public Object findOne(Serializable serializable) {
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = mHelper.getReadableDatabase();
cursor = db.query(table, null, mEntity.getIdColumnName() + " = ?", new String[]{serializable.toString()}, null, null, null);
return mEntity.convertToOJ(cursor, 0);
} catch (Exception e) {
} finally {
if (null != db) {
db.close();
}
}
return null;
}
@Override
public boolean exists(Serializable serializable) {
return null != findOne(serializable);
}
@Override
public List findAll() {
List allObject = new ArrayList();
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = mHelper.getReadableDatabase();
cursor = db.query(table, null, null, null, null, null, null);
for (int i = 0; i < cursor.getCount(); i++) {
allObject.add(mEntity.convertToOJ(cursor, i));
}
} catch (Exception e) {
} finally {
if (null != db) {
db.close();
}
}
return allObject;
}
@Override
public long count() {
return mExecutor.count(table);
}
@Override
public boolean delete(Serializable serializable) {
return mExecutor.deleteById(table, mEntity.getIdColumnName(), serializable);
}
@Override
public boolean deleteAll() {
return mExecutor.deleteAll(table);
}
@Override
public boolean dropTable() {
return mExecutor.dropTable(table);
}
}
| 27.398148 | 136 | 0.620818 |
ba94876a80ff655c3371ef0ef6b113af90d7959d | 9,527 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.search.join;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
public class TestBlockJoinValidation extends LuceneTestCase {
public static final int AMOUNT_OF_SEGMENTS = 5;
public static final int AMOUNT_OF_PARENT_DOCS = 10;
public static final int AMOUNT_OF_CHILD_DOCS = 5;
public static final int AMOUNT_OF_DOCS_IN_SEGMENT =
AMOUNT_OF_PARENT_DOCS + AMOUNT_OF_PARENT_DOCS * AMOUNT_OF_CHILD_DOCS;
private Directory directory;
private IndexReader indexReader;
private IndexSearcher indexSearcher;
private BitSetProducer parentsFilter;
@Override
public void setUp() throws Exception {
super.setUp();
directory = newDirectory();
final IndexWriterConfig config = new IndexWriterConfig(new MockAnalyzer(random()));
final IndexWriter indexWriter = new IndexWriter(directory, config);
for (int i = 0; i < AMOUNT_OF_SEGMENTS; i++) {
List<Document> segmentDocs = createDocsForSegment(i);
indexWriter.addDocuments(segmentDocs);
indexWriter.commit();
}
indexReader = DirectoryReader.open(indexWriter);
indexWriter.close();
indexSearcher = new IndexSearcher(indexReader);
parentsFilter = new QueryBitSetProducer(new WildcardQuery(new Term("parent", "*")));
}
@Override
public void tearDown() throws Exception {
indexReader.close();
directory.close();
super.tearDown();
}
public void testNextDocValidationForToParentBjq() throws Exception {
Query parentQueryWithRandomChild = createChildrenQueryWithOneParent(getRandomChildNumber(0));
ToParentBlockJoinQuery blockJoinQuery =
new ToParentBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, ScoreMode.None);
IllegalStateException expected =
expectThrows(
IllegalStateException.class,
() -> {
indexSearcher.search(blockJoinQuery, 1);
});
assertTrue(
expected.getMessage() != null
&& expected
.getMessage()
.contains("Child query must not match same docs with parent filter"));
}
public void testNextDocValidationForToChildBjq() throws Exception {
Query parentQueryWithRandomChild = createParentsQueryWithOneChild(getRandomChildNumber(0));
ToChildBlockJoinQuery blockJoinQuery =
new ToChildBlockJoinQuery(parentQueryWithRandomChild, parentsFilter);
IllegalStateException expected =
expectThrows(
IllegalStateException.class,
() -> {
indexSearcher.search(blockJoinQuery, 1);
});
assertTrue(
expected.getMessage() != null
&& expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));
}
public void testAdvanceValidationForToChildBjq() throws Exception {
Query parentQuery = new MatchAllDocsQuery();
ToChildBlockJoinQuery blockJoinQuery = new ToChildBlockJoinQuery(parentQuery, parentsFilter);
final LeafReaderContext context = indexSearcher.getIndexReader().leaves().get(0);
Weight weight =
indexSearcher.createWeight(
indexSearcher.rewrite(blockJoinQuery), org.apache.lucene.search.ScoreMode.COMPLETE, 1);
Scorer scorer = weight.scorer(context);
final Bits parentDocs = parentsFilter.getBitSet(context);
int target;
do {
// make the parent scorer advance to a doc ID which is not a parent
target = TestUtil.nextInt(random(), 0, context.reader().maxDoc() - 2);
} while (parentDocs.get(target + 1));
final int illegalTarget = target;
IllegalStateException expected =
expectThrows(
IllegalStateException.class,
() -> {
scorer.iterator().advance(illegalTarget);
});
assertTrue(
expected.getMessage() != null
&& expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));
}
private static List<Document> createDocsForSegment(int segmentNumber) {
List<List<Document>> blocks = new ArrayList<>(AMOUNT_OF_PARENT_DOCS);
for (int i = 0; i < AMOUNT_OF_PARENT_DOCS; i++) {
blocks.add(createParentDocWithChildren(segmentNumber, i));
}
List<Document> result = new ArrayList<>(AMOUNT_OF_DOCS_IN_SEGMENT);
for (List<Document> block : blocks) {
result.addAll(block);
}
return result;
}
private static List<Document> createParentDocWithChildren(int segmentNumber, int parentNumber) {
List<Document> result = new ArrayList<>(AMOUNT_OF_CHILD_DOCS + 1);
for (int i = 0; i < AMOUNT_OF_CHILD_DOCS; i++) {
result.add(createChildDoc(segmentNumber, parentNumber, i));
}
result.add(createParentDoc(segmentNumber, parentNumber));
return result;
}
private static Document createParentDoc(int segmentNumber, int parentNumber) {
Document result = new Document();
result.add(
newStringField(
"id",
createFieldValue(segmentNumber * AMOUNT_OF_PARENT_DOCS + parentNumber),
Field.Store.YES));
result.add(newStringField("parent", createFieldValue(parentNumber), Field.Store.NO));
result.add(newStringField("common_field", "1", Field.Store.NO));
return result;
}
private static Document createChildDoc(int segmentNumber, int parentNumber, int childNumber) {
Document result = new Document();
result.add(
newStringField(
"id",
createFieldValue(segmentNumber * AMOUNT_OF_PARENT_DOCS + parentNumber, childNumber),
Field.Store.YES));
result.add(newStringField("child", createFieldValue(childNumber), Field.Store.NO));
result.add(newStringField("common_field", "1", Field.Store.NO));
return result;
}
private static String createFieldValue(int... documentNumbers) {
StringBuilder stringBuilder = new StringBuilder();
for (int documentNumber : documentNumbers) {
if (stringBuilder.length() > 0) {
stringBuilder.append("_");
}
stringBuilder.append(documentNumber);
}
return stringBuilder.toString();
}
private static Query createChildrenQueryWithOneParent(int childNumber) {
TermQuery childQuery = new TermQuery(new Term("child", createFieldValue(childNumber)));
Query randomParentQuery = new TermQuery(new Term("id", createFieldValue(getRandomParentId())));
BooleanQuery.Builder childrenQueryWithRandomParent = new BooleanQuery.Builder();
childrenQueryWithRandomParent.add(new BooleanClause(childQuery, BooleanClause.Occur.SHOULD));
childrenQueryWithRandomParent.add(
new BooleanClause(randomParentQuery, BooleanClause.Occur.SHOULD));
return childrenQueryWithRandomParent.build();
}
private static Query createParentsQueryWithOneChild(int randomChildNumber) {
BooleanQuery.Builder childQueryWithRandomParent = new BooleanQuery.Builder();
Query parentsQuery =
new TermQuery(new Term("parent", createFieldValue(getRandomParentNumber())));
childQueryWithRandomParent.add(new BooleanClause(parentsQuery, BooleanClause.Occur.SHOULD));
childQueryWithRandomParent.add(
new BooleanClause(randomChildQuery(randomChildNumber), BooleanClause.Occur.SHOULD));
return childQueryWithRandomParent.build();
}
private static int getRandomParentId() {
return random().nextInt(AMOUNT_OF_PARENT_DOCS * AMOUNT_OF_SEGMENTS);
}
private static int getRandomParentNumber() {
return random().nextInt(AMOUNT_OF_PARENT_DOCS);
}
private static Query randomChildQuery(int randomChildNumber) {
return new TermQuery(new Term("id", createFieldValue(getRandomParentId(), randomChildNumber)));
}
private static int getRandomChildNumber(int notLessThan) {
return notLessThan + random().nextInt(AMOUNT_OF_CHILD_DOCS - notLessThan);
}
}
| 40.368644 | 99 | 0.732025 |
1b4507d363247ac007ea05529d0eea59b3365400 | 2,895 | /**
* Copyright 2010 Molindo GmbH
*
* 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 at.molindo.mysqlcollations.lib;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Comparator;
import at.molindo.utils.io.StreamUtils;
import at.molindo.utils.properties.SystemProperty;
final class CollationCompare {
static {
String dirName = System.getProperty(Collation.PROP_LIB_COLLATION_COMPARE_DIR, ".");
String fileName = System.getProperty(Collation.PROP_LIB_COLLATION_COMPARE_NAME, "libCollationCompare."
+ SystemProperty.OS_ARCH + ".so");
File dir = new File(dirName);
if (!dir.isDirectory()) {
throw new RuntimeException("directory does not exist: " + dir.getAbsolutePath());
}
File file = new File(dir, fileName);
if (file.exists()) {
file.delete();
}
// copy from classpath
InputStream in = CollationCompare.class.getResourceAsStream("/" + fileName);
OutputStream out = null;
if (in == null) {
throw new RuntimeException("can't find /" + fileName + " on classpath");
}
try {
out = new BufferedOutputStream(new FileOutputStream(file));
StreamUtils.copy(in, out);
} catch (IOException e) {
throw new RuntimeException("can't write library to " + file.getAbsolutePath());
} finally {
StreamUtils.close(in, out);
}
Runtime.getRuntime().load(file.getAbsolutePath());
System.setProperty(Collation.PROP_LIB_COLLATION_COMPARE_LOADED, file.getAbsolutePath());
// in memory and safe to delete immediately
file.delete();
}
private CollationCompare() {
}
/**
* @param collation
* name of collation
* @return an index > 0 if collation name exists
*/
static native int index(String collation);
// /**
// * @return one of {-1,0,1} for comparison, something else in case of error
// *
// * @see Comparator#compare(Object, Object)
// *
// * @deprecated use {@link String#getBytes(java.nio.charset.Charset)} to
// * convert Strings to correct byte representation
// */
// @Deprecated
// static native int compare(int idx, String a, String b);
/**
* @return one of {-1,0,1} for comparison, something else in case of error
*
* @see Comparator#compare(Object, Object)
*/
static native int compareBytes(int idx, byte[] a, byte[] b);
}
| 29.540816 | 104 | 0.711917 |
9a9842ff5cd03a246e2f5a591c10c7bf4880c960 | 3,694 | package com.zup.edu.mercadolivre.compra;
import com.zup.edu.mercadolivre.compra.dtos.CompraRequest;
import com.zup.edu.mercadolivre.compra.dtos.FinalizaCompraRequest;
import com.zup.edu.mercadolivre.compra.simulacoeslocais.GerarNotaFiscal;
import com.zup.edu.mercadolivre.compra.simulacoeslocais.GerarPontuacaoRanking;
import com.zup.edu.mercadolivre.exceptions.ExceptionNotFound;
import com.zup.edu.mercadolivre.pagamento.EnumStatusTransacao;
import com.zup.edu.mercadolivre.pagamento.Transacao;
import com.zup.edu.mercadolivre.pergunta.email.EnviarEmail;
import com.zup.edu.mercadolivre.usuario.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.validation.Valid;
@RestController
public class CompraController {
private final EntityManager entityManager;
private final EnviarEmail enviarEmail;
private final CompraRepository compraRepository;
private final GerarNotaFiscal gerarNotaFiscal;
private final GerarPontuacaoRanking gerarPontuacaoRanking;
@Autowired
public CompraController(EntityManager entityManager, EnviarEmail enviarEmail, CompraRepository compraRepository, GerarNotaFiscal gerarNotaFiscal, GerarPontuacaoRanking gerarPontuacaoRanking) {
this.entityManager = entityManager;
this.enviarEmail = enviarEmail;
this.compraRepository = compraRepository;
this.gerarNotaFiscal = gerarNotaFiscal;
this.gerarPontuacaoRanking = gerarPontuacaoRanking;
}
@Transactional
@PostMapping(value = "/compras")
public ResponseEntity<?> insert(@Valid @RequestBody CompraRequest compraRequest, Authentication authentication) {
Usuario usuario = (Usuario) authentication.getPrincipal();
Compra compra = compraRequest.toModel(entityManager, usuario);
entityManager.persist(compra);
enviarEmail.desejoDeCompra(compra);
String pagar = compra.getGateway().financeiro().pagar(compra.getId());
return ResponseEntity.status(302).body(pagar);
}
@Transactional
@PostMapping(value = "/compra/{idCompra}")
public ResponseEntity<?> fecharCompra(@PathVariable String idCompra) {
Compra compra = compraRepository
.findById(idCompra)
.orElseThrow(() -> new ExceptionNotFound("Id: " + idCompra + " não encontrado", HttpStatus.NOT_FOUND));
String retornoGateway = compra.getGateway().financeiro().processarTransacao(compra.getId()).toString();
FinalizaCompraRequest finalizaCompraRequest = new FinalizaCompraRequest(compra.getId(), retornoGateway, compra.getGateway());
Transacao transacao = finalizaCompraRequest.toModel(compraRepository);
entityManager.persist(transacao);
if (transacao.getStatusCompra() == EnumStatusTransacao.SUCESSO) {
compra.alterarStatusCompra(EnumStatusCompra.FINALIZADA);
compraRepository.save(compra);
gerarNotaFiscal.processar(compra);
gerarPontuacaoRanking.processar(compra);
enviarEmail.transacaoEfetuada(transacao);
} else {
enviarEmail.avisoTransacaoRecusada(transacao);
}
return ResponseEntity.ok().build();
}
}
| 45.04878 | 196 | 0.765836 |
368ca613a9d7f99390b5078f0c8f5894c5abdc5c | 12,515 | package edu.upc.eetac.dsa.group7.dao;
import edu.upc.eetac.dsa.group7.db.Database;
import edu.upc.eetac.dsa.group7.entity.User;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Alex on 29/11/15.
*/
public class UserDAOImpl implements UserDAO {
@Override
public User getUserById(String id) throws SQLException {
User user = null;
Connection connection = null;
PreparedStatement stmt = null;
try {
//Stablish the connection
connection = Database.getConnection();
//Prepare the query
stmt = connection.prepareStatement(UserDAOQuery.GET_USER_BY_ID);
//Set values
stmt.setString(1, id);
//Execute the query
ResultSet rs = stmt.executeQuery();
//Store the results
if (rs.next()) {
user = new User();
user.setId(rs.getString("id"));
user.setLoginid(rs.getString("loginid"));
user.setEmail(rs.getString("email"));
user.setFullname(rs.getString("fullname"));
}
} catch (SQLException e) {
//Catch errors
throw e;
} finally {
//Close the connection
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
// Returns the user for printing it
return user;
}
@Override
public User updateProfile(String id, String email, String fullname) throws SQLException {
User user = null;
//Prepare the connection
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
//prepare and set parameters of the query
stmt = connection.prepareStatement(UserDAOQuery.UPDATE_USER);
stmt.setString(1, email);
stmt.setString(2, fullname);
stmt.setString(3, id);
int rows = stmt.executeUpdate();
if (rows == 1)
user = getUserById(id);
} catch (SQLException e) {
//catch errors
throw e;
} finally {
//close the connection
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
//return user for printing
return user;
}
@Override
//get user by loginid
public User getUserByLoginid(String loginid) throws SQLException {
User user = null;
//prepare the connection
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
//prepare and set the parameters of the query
stmt = connection.prepareStatement(UserDAOQuery.GET_USER_BY_USERNAME);
stmt.setString(1, loginid);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
user = new User();
//Store the results
user.setId(rs.getString("id"));
user.setLoginid(rs.getString("loginid"));
user.setEmail(rs.getString("email"));
user.setFullname(rs.getString("fullname"));
}
} catch (SQLException e) {
//catch exceptions
throw e;
} finally {
//close connection
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
//return user for printing
return user;
}
@Override
public boolean deleteUser(String id) throws SQLException {
//prepare the connection with database
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
//set is and execute the query
stmt = connection.prepareStatement(UserDAOQuery.DELETE_USER);
stmt.setString(1, id);
int rows = stmt.executeUpdate();
return (rows == 1);
} catch (SQLException e) {
//catch errors
throw e;
} finally {
//close connection
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
//check password for login
public boolean checkPassword(String id, String password) throws SQLException {
Connection connection = null;
PreparedStatement stmt = null;
//prepare the connection
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.GET_PASSWORD);
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String storedPassword = rs.getString("password");
try {
//encrypt the password
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
String passedPassword = new BigInteger(1, md.digest()).toString(16);
return passedPassword.equalsIgnoreCase(storedPassword);
} catch (NoSuchAlgorithmException e) {
}
}
return false;
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
public User createUser(String loginid, String password, String email, String fullname) throws SQLException, UserAlreadyExistsException {
Connection connection = null;
PreparedStatement stmt = null;
//prepare the connection
String id = null;
try {
User user = getUserByLoginid(loginid);
if (user != null)
throw new UserAlreadyExistsException();
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.UUID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
id = rs.getString(1);
else
throw new SQLException();
connection.setAutoCommit(false);
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.CREATE_USER);
//store data in database
stmt.setString(1, id);
stmt.setString(2, loginid);
stmt.setString(3, password);
stmt.setString(4, email);
stmt.setString(5, fullname);
stmt.executeUpdate();
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.ASSIGN_ROLE_REGISTERED);
//call to set the role registered
stmt.setString(1, id);
stmt.executeUpdate();
connection.commit();
} catch (SQLException e) {
throw e;
//catch errors
} finally {
//close connection
if (stmt != null) stmt.close();
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
}
//return the user for printing
return getUserById(id);
}
@Override
//method to create an admin user. The same as normal user
public User createAdmin() throws SQLException {
String loginid = "admin", password = "admin", email = "admin@admin", fullname = "I'm the admin.";
Connection connection = null;
PreparedStatement stmt = null;
String id = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.UUID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
id = rs.getString(1);
else
throw new SQLException();
connection.setAutoCommit(false);
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.CREATE_USER);
stmt.setString(1, id);
stmt.setString(2, loginid);
stmt.setString(3, password);
stmt.setString(4, email);
stmt.setString(5, fullname);
stmt.executeUpdate();
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.ASSIGN_ROLE_ADMIN);
stmt.setString(1, id);
stmt.executeUpdate();
connection.commit();
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
}
return getUserByLoginid(loginid);
}
@Override
//method to create an owner user. The same as normal user
public User createOwner() throws SQLException {
String loginid = "alex", password = "alex", email = "alex@alex", fullname = "Hi, I'm Alex";
Connection connection = null;
PreparedStatement stmt = null;
String id = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.UUID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
id = rs.getString(1);
else
throw new SQLException();
connection.setAutoCommit(false);
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.CREATE_USER);
stmt.setString(1, id);
stmt.setString(2, loginid);
stmt.setString(3, password);
stmt.setString(4, email);
stmt.setString(5, fullname);
stmt.executeUpdate();
stmt.close();
stmt = connection.prepareStatement(UserDAOQuery.ASSIGN_ROLE_OWNER);
stmt.setString(1, id);
stmt.executeUpdate();
connection.commit();
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) {
connection.setAutoCommit(true);
connection.close();
}
}
return getUserByLoginid(loginid);
}
@Override
//method to check if a user is an owner or an admin
public boolean owner(String id) throws SQLException {
Connection connection = null;
String auth = null;
String owner = "owner";
String admin = "admin";
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.GET_ROLES_OF_USER);
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
auth = rs.getString("role");
}
if (auth.equals(admin) || auth.equals(owner)) {
return true;
} else {
return false;
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
@Override
//method to check if a user is an admin
public boolean admin(String id) throws SQLException {
Connection connection = null;
String auth = null;
String admin = "admin";
PreparedStatement stmt = null;
try {
connection = Database.getConnection();
stmt = connection.prepareStatement(UserDAOQuery.GET_ROLES_OF_USER);
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
auth = rs.getString("role");
}
if (auth.equals(admin)) {
return true;
} else {
return false;
}
} catch (SQLException e) {
throw e;
} finally {
if (stmt != null) stmt.close();
if (connection != null) connection.close();
}
}
} | 32.338501 | 140 | 0.539912 |
ce0d663540a6bab606ffc166065cc9a9145fdded | 3,575 | //The MIT License
//
//Copyright (c) 2009 nodchip
//
//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 tv.dyndns.kishibe.qmaclone.client.packet;
import java.util.Date;
import tv.dyndns.kishibe.qmaclone.client.constant.Constant;
import tv.dyndns.kishibe.qmaclone.client.game.ProblemGenre;
import tv.dyndns.kishibe.qmaclone.client.game.ProblemType;
import tv.dyndns.kishibe.qmaclone.client.game.RandomFlag;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.gwt.user.client.rpc.IsSerializable;
public class PacketProblemMinimum implements IsSerializable {
public static final int CREATING_PROBLEM_ID = -1;
/**
* 問題番号
*
* 新規問題の場合は CREATING_PROBLEM_ID
*/
public int id;
/**
* ジャンル
*/
public ProblemGenre genre;
/**
* 出題形式
*/
public ProblemType type;
/**
* 正答数
*/
public int good;
/**
* 誤答数
*/
public int bad;
/**
* ランダムフラグ
*/
public RandomFlag randomFlag;
/**
* 作問者文字列ハッシュ
*/
public int creatorHash;
/**
* 作問者ユーザーコード
*/
public int userCode;
/**
* 指摘日時。指摘されていない場合はnull。
*/
public Date indication;
public int getAccuracyRate() {
if (good == 0 && bad == 0) {
return -1;
}
return (100 * good) / (good + bad);
}
public double getNormalizedAccuracyRate() {
return type.getNormalizedAccuracyRate(this);
}
public boolean isNew() {
return good + bad < Constant.MAX_RATIO_CALCULATING;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PacketProblemMinimum)) {
return false;
}
PacketProblemMinimum rh = (PacketProblemMinimum) obj;
return Objects.equal(id, rh.id) && Objects.equal(genre, rh.genre)
&& Objects.equal(type, rh.type) && Objects.equal(good, rh.good)
&& Objects.equal(bad, rh.bad) && Objects.equal(randomFlag, rh.randomFlag)
&& Objects.equal(creatorHash, rh.creatorHash) && Objects.equal(userCode, rh.userCode)
&& Objects.equal(indication, rh.indication);
}
@Override
public int hashCode() {
// [userCode, creatorHash, shuffledAnswers,
// shuffledChoices]はハッシュコードに含めない
return Objects.hashCode(id, genre, type, good, bad, randomFlag);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("id", id).add("genre", genre).add("type", type)
.add("good", good).add("bad", bad).add("randomFlag", randomFlag)
.add("creatorHash", creatorHash).add("userCode", userCode).add("indication", indication)
.toString();
}
}
| 29.545455 | 96 | 0.69986 |
5ef7fa63a4d000c1a50b2391b8d689ea7aaacd0d | 647 | package com.seedapp.springrest.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = { "com.seedapp.springrest.domain", "com.seedapp.springrest.service" })
@Profile("default")
public class AppConfig {
@Autowired
private Environment env;
}
| 32.35 | 100 | 0.834621 |
96a439e922c40b5068cef7198a1f298d2ff5128b | 1,002 | package io.renren.wcs.client.dto.condition;
import java.io.Serializable;
/**
* 消息05制作条件
*
* @Author: CalmLake
* @date 2019/8/15 10:46
* @Version: V1.0.0
**/
public class MsgCycleOrderFinishReportAckConditionDTO implements Serializable {
private String msgMcKey;
private String plcName;
private String blockName;
private String cycleCommand;
public MsgCycleOrderFinishReportAckConditionDTO(String msgMcKey, String plcName, String blockName, String cycleCommand) {
this.msgMcKey = msgMcKey;
this.plcName = plcName;
this.blockName = blockName;
this.cycleCommand = cycleCommand;
}
@Override
public String toString() {
return super.toString();
}
public String getMsgMcKey() {
return msgMcKey;
}
public String getPlcName() {
return plcName;
}
public String getBlockName() {
return blockName;
}
public String getCycleCommand() {
return cycleCommand;
}
}
| 21.782609 | 125 | 0.664671 |
8ea71f0339554bb6470aa8322f6c22bd7b4c4e41 | 3,848 | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. 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.j_spaces.kernel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.util.Date;
public class CloudifyVersion implements ProductVersion {
private String EDITION = "Cloudify";
// !!!IMPORTANT, read below
// Must be of this format otherwise PlatformLogicalVersion will fail
// parsing!!!
private String VERSION = "2.7.1";
private String MILESTONE = "ga";
private String BUILD_TYPE = "regular";
private String V_NUM = VERSION + '-' + EDITION + '-' + MILESTONE;
private String V_LICENSE_NUM = "2.2" + EDITION;
// !!!IMPORTANT, read below
// Must be of either "int-int-string", "int-int" or "int" format otherwise
// PlatformLogicalVersion will fail parsing!!!
private final String BUILD_NUM = "6300-6";
private final String V_NAME = "GigaSpaces";
private final String PRODUCT_HELP_URL = "http://www.cloudifysource.org/guide";
private final String BUILD_TIMESTAMP = "6300-6";
/** default constructor for Class.forName() - see com.j_spaces.kernel.PlatformVersion */
public CloudifyVersion() {
}
@Override
public String getOfficialVersion() {
return V_NAME + " " + getShortOfficialVersion() + " (build "
+ BUILD_NUM + ", timestamp " + BUILD_TIMESTAMP + ")";
}
@Override
public String getShortOfficialVersion() {
String edition = EDITION;
final String XAP_Prefix = "XAP";
if (EDITION.startsWith("XAP")) {
edition = XAP_Prefix + " " + EDITION.substring(XAP_Prefix.length());
}
return edition + " " + VERSION + " " + MILESTONE.toUpperCase();
}
@Override
public String getVersionAndBuild() {
return VERSION + "." + BUILD_NUM;
}
@Override
public void createBuildNumberPropertyFile() {
FileOutputStream fileOut = null;
PrintStream ps = null;
try {
fileOut = new FileOutputStream("build.properties", true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ps = new PrintStream(fileOut);
ps.println("buildnumber=" + BUILD_NUM);
ps.println("tag=" + getTag());
ps.println("versionnumber=" + V_NUM);
ps.println("milestone=" + MILESTONE);
ps.println("productversion=" + VERSION);
ps.close();
}
@Override
public String getTag() {
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String date = dateFormat.format(new Date());
String tag = "build" + BUILD_NUM + "_" + date;
return tag;
}
@Override
public String getEdition() {
return EDITION;
}
@Override
public String getVersion() {
return VERSION;
}
@Override
public String getLicenseVersion() {
return V_LICENSE_NUM;
}
@Override
public String getBuildNumber() {
return BUILD_NUM;
}
@Override
public String getVersionNumber() {
return V_NUM;
}
@Override
public String getMilestone() {
return MILESTONE;
}
@Override
public String getBuildType() {
return BUILD_TYPE;
}
@Override
public String getProductHelpUrl() {
return PRODUCT_HELP_URL;
}
@Override
public String getBuildTimestamp() {
return BUILD_TIMESTAMP;
}
}
| 26.722222 | 89 | 0.679834 |
bbbcb598eb2bbcdab083321a7d27d9472afb0a48 | 3,336 | package com.example.poxiaoge.tvserver.utils;
import android.os.Environment;
//import com.zxt.dlna.util.DevMountInfo.DevInfo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DevMountInfo implements IDev {
/**
* ***
*/
public final String HEAD = "dev_mount";
public final String LABEL = "<label>";
public final String MOUNT_POINT = "<mount_point>";
public final String PATH = "<part>";
public final String SYSFS_PATH = "<sysfs_path1...>";
/**
* Label for the volume
*/
private final int NLABEL = 1;
/**
* Partition
*/
private final int NPATH = 2;
/**
* Where the volume will be mounted
*/
private final int NMOUNT_POINT = 3;
private final int NSYSFS_PATH = 4;
private final int DEV_INTERNAL = 0;
private final int DEV_EXTERNAL = 1;
private ArrayList<String> cache = new ArrayList<String>();
private static DevMountInfo dev;
private DevInfo info;
private final File VOLD_FSTAB = new File(Environment.getRootDirectory()
.getAbsoluteFile()
+ File.separator
+ "etc"
+ File.separator
+ "vold.fstab");
public static DevMountInfo getInstance() {
if (null == dev)
dev = new DevMountInfo();
return dev;
}
private DevInfo getInfo(final int device) {
// for(String str:cache)
// System.out.println(str);
if (null == info)
info = new DevInfo();
try {
initVoldFstabToCache();
} catch (IOException e) {
e.printStackTrace();
}
if (device >= cache.size())
return null;
String[] sinfo = cache.get(device).split(" ");
info.setLabel(sinfo[NLABEL]);
info.setMount_point(sinfo[NMOUNT_POINT]);
info.setPath(sinfo[NPATH]);
info.setSysfs_path(sinfo[NSYSFS_PATH]);
return info;
}
/**
* init the words into the cache array
*
* @throws IOException
*/
private void initVoldFstabToCache() throws IOException {
cache.clear();
BufferedReader br = new BufferedReader(new FileReader(VOLD_FSTAB));
String tmp = null;
while ((tmp = br.readLine()) != null) {
// the words startsWith "dev_mount" are the SD info
if (tmp.startsWith(HEAD)) {
cache.add(tmp);
}
}
br.close();
cache.trimToSize();
}
public class DevInfo {
private String label, mount_point, path, sysfs_path;
/**
* return the label name of the SD card
*
* @return
*/
public String getLabel() {
return label;
}
private void setLabel(String label) {
this.label = label;
}
/**
* the mount point of the SD card
*
* @return
*/
public String getMount_point() {
return mount_point;
}
private void setMount_point(String mount_point) {
this.mount_point = mount_point;
}
/**
* SD mount path
*
* @return
*/
public String getPath() {
return path;
}
private void setPath(String path) {
this.path = path;
}
/**
* "unknow"
*
* @return
*/
public String getSysfs_path() {
return sysfs_path;
}
private void setSysfs_path(String sysfs_path) {
this.sysfs_path = sysfs_path;
}
}
@Override
public DevInfo getInternalInfo() {
return getInfo(DEV_INTERNAL);
}
@Override
public DevInfo getExternalInfo() {
return getInfo(DEV_EXTERNAL);
}
}
interface IDev {
DevMountInfo.DevInfo getInternalInfo();
DevMountInfo.DevInfo getExternalInfo();
}
| 19.062857 | 72 | 0.666966 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.