hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e15f326455f6efde9f0bff94bcf933140254de7 | 531 | java | Java | src/main/java/dev/warrant/model/UsersetWarrant.java | warrant-dev/warrant-java | 45823bf22289c21448e509148cd6b7a2049b214d | [
"MIT"
] | 2 | 2021-09-15T22:16:48.000Z | 2022-01-17T15:58:26.000Z | src/main/java/dev/warrant/model/UsersetWarrant.java | warrant-dev/warrant-java | 45823bf22289c21448e509148cd6b7a2049b214d | [
"MIT"
] | null | null | null | src/main/java/dev/warrant/model/UsersetWarrant.java | warrant-dev/warrant-java | 45823bf22289c21448e509148cd6b7a2049b214d | [
"MIT"
] | null | null | null | 23.086957 | 94 | 0.687382 | 9,338 | package dev.warrant.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" })
public class UsersetWarrant extends Warrant {
private Userset user;
public UsersetWarrant() {
// For json serialization
}
public UsersetWarrant(String objectType, String objectId, String relation, Userset user) {
super(objectType, objectId, relation);
this.user = user;
}
public Userset getUser() {
return user;
}
}
|
3e15f3685f41d8332181bfd81e3cc797dd83ef63 | 15,093 | java | Java | csv-importer/src/main/java/com/coremedia/csv/importer/ContentPublishHelper.java | blackappsolutions/csv-reporting | 32c75d91e941a3c5cfbb43d27294012f8aa2314b | [
"Apache-1.1"
] | null | null | null | csv-importer/src/main/java/com/coremedia/csv/importer/ContentPublishHelper.java | blackappsolutions/csv-reporting | 32c75d91e941a3c5cfbb43d27294012f8aa2314b | [
"Apache-1.1"
] | 5 | 2021-04-20T08:56:24.000Z | 2021-07-15T13:06:03.000Z | csv-importer/src/main/java/com/coremedia/csv/importer/ContentPublishHelper.java | blackappsolutions/csv-reporting | 32c75d91e941a3c5cfbb43d27294012f8aa2314b | [
"Apache-1.1"
] | 2 | 2021-04-20T09:36:20.000Z | 2021-06-17T17:32:47.000Z | 40.463807 | 160 | 0.598556 | 9,339 | package com.coremedia.csv.importer;
import com.coremedia.cap.common.FlushFailedException;
import com.coremedia.cap.common.SessionNotOpenException;
import com.coremedia.cap.content.Content;
import com.coremedia.cap.content.ContentException;
import com.coremedia.cap.content.ContentRepository;
import com.coremedia.cap.content.Version;
import com.coremedia.cap.content.publication.PublicationException;
import com.coremedia.cap.content.publication.PublicationFailedException;
import com.coremedia.cap.content.publication.PublicationService;
import com.coremedia.cap.content.publication.PublicationSet;
import com.coremedia.cap.content.publication.results.PublicationResult;
import com.coremedia.cap.content.publication.results.PublicationResultItem;
import com.google.common.collect.Iterables;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* Helper class to handle the content checkout/checkin and publishing.
*/
public class ContentPublishHelper {
private ContentRepository contentRepository;
private Logger logger;
private List<String> invalidFileNameChars = Collections.singletonList("/");
private List<String> invalidFileNames = Arrays.asList(".", "..");
@NonNull
private final Collection<String> warnings = Collections.synchronizedList(new ArrayList<String>());
public ContentPublishHelper(ContentRepository contentRepository, Logger logger) {
this.contentRepository = contentRepository;
this.logger = logger;
}
/**
* Performs a checkIn on all the given content objects using a batch process
*
* @param contents The collection of content objects to check-in
*/
public void checkInAll(Collection<Content> contents) {
new BatchTemplate<Content>(contentRepository, BatchTemplate.DEFAULT_BATCH_SIZE, logger) {
@Override
protected void process(com.coremedia.cap.undoc.content.ContentRepository.Batch batch, Content content) {
if (null != content && content.isCheckedOut()) {
batch.checkIn(content);
}
}
}.execute(contents);
}
/**
* Approves and/or publishes updated content depending on state of prior version.
*
* @param contents The collection of content objects that were updated
* @param autoPublish Whether content should automatically be published if prior version was published
*/
public void applyPreviousState(Collection<Content> contents, boolean autoPublish) {
try {
contentRepository.getConnection().flush();
if (contents.size() > 0) {
List<Content> toBeApproved = new ArrayList<>();
List<Content> toBePublished = new ArrayList<>();
PublicationService publicationService = contentRepository.getPublicationService();
// assemble list of content to be approved/published based on prior version
for (Content content : contents) {
Version priorVersion = content.getCheckedOutVersion();
if (priorVersion == null)
continue;
if (publicationService.isPublished(priorVersion)) {
toBeApproved.add(content);
if(autoPublish) {
toBePublished.add(content);
} else {
logger.info("No autopublish specified, skipping automatic publication of updated content " + content.getId());
}
} else if (publicationService.isApproved(priorVersion)) {
toBeApproved.add(content);
}
}
// check in updated content
checkInAll(contents);
// approve content
logger.info("Approving " + toBeApproved.size() + " documents");
for(Content content : toBeApproved) {
Version version = content.getCheckedInVersion();
if(!publicationService.isPlaceApproved(content))
publicationService.approvePlace(content);
if(!publicationService.isApproved(version))
publicationService.approve(version);
}
// publish content
Collection<Version> toBePublishedVersions = new ArrayList<>();
for(Content content : toBePublished) {
Version version = content.getCheckedInVersion();
if(!publicationService.isPlaceApproved(content))
publicationService.approvePlace(content);
if(!publicationService.isPublished(version))
toBePublishedVersions.add(version);
}
if(autoPublish) {
logger.info("Publishing " + toBePublished.size() + " documents");
publish(toBePublishedVersions);
}
}
} catch (SessionNotOpenException snoe) {
logger.error("SessionNotOpenException: Can't establish session with the content repository.", snoe);
} catch (FlushFailedException ffe) {
logger.error("FlushFailedException: Can't flush connection with the content repository.", ffe);
} catch (Exception e) {
logger.error("Could not publish documents ", e);
}
}
/**
* Publish a collection of documents.
*
* @param toBePublishedContent The collection of CoreMedia documents to publish
*/
private void publish(Collection<Version> toBePublishedContent) {
PublicationService publicationService = contentRepository.getPublicationService();
PublicationSet publicationSet = publicationService.createPublicationSet(toBePublishedContent);
try {
publicationService.publish(publicationSet);
} catch (PublicationFailedException e) {
logger.error(MessageFormat.format("Cannot bulk publish places and versions: {0}", e.getMessage()), e);
PublicationResult publicationResult = e.getPublicationResult();
for (PublicationResultItem item : publicationResult.getResults()) {
if (item.isError()) {
logger.error("Publication Error " + item.toString());
}
}
}
}
/**
* Converts a string to a CoreMedia document acceptable name. The document name may not be empty, may not be '.'or '..',
* may not contain '/' characters and must not be too long (234 digits).
*
* @param title The potential title of the document
* @param documentTitle_prefix The static prefix for a title which doesn't start with any type of a letter
* @return A string ready to be used as a CoreMedia document name
*/
public String getCleanCoreMediaDocumentTitle(String title, String documentTitle_prefix) {
String fileName = replaceInvalidChars(title);
if (StringUtils.isEmpty(fileName) || !startsWithLetter(fileName) || getInvalidFileNames().contains(fileName)) {
fileName = documentTitle_prefix + fileName;
}
if (fileName.length() > 234) {
fileName = fileName.substring(0, 233);
}
return fileName.trim();
}
/**
* Removing invalid chars (defined in property invalidFileNameChars) in a string with.
*
* @param s The string to handle
* @return The input string, stripped of all invalid chars
*/
private String replaceInvalidChars(String s) {
for (String ch : invalidFileNameChars) {
s = s.replaceAll(ch, "");
}
return s;
}
/**
* Returns true, if the given string starts with a letter (multi-language!).
*
* @param s The string to test
* @return TRUE, if the given string starts with any type of a letter (multi-language!). FALSE otherwise.
*/
public boolean startsWithLetter(String s) {
return Pattern.compile("^\\p{L}").matcher(s).find();
}
/**
* Check out the given content for editing.
*
* @param c The content object
* @return The content if checkout was successful, else return null
*/
Content checkOutContent(Content c) {
if (c.isCheckedOutByCurrentSession()) {
return c;
}
if (c.isCheckedOut()) {
logger.warn("Content " + c.getId() + " is checked out, can't check it out");
return null;
}
if (c.isDeleted()) {
logger.warn("Content " + c.getId() + " is deleted , can't check it out");
return null;
}
if (c.isDestroyed()) {
logger.warn("Content is destroyed, can't check it out");
return null;
}
try {
c.checkOut();
if (logger.isDebugEnabled()) {
logger.debug("Checked out content " + c.getId());
}
return c;
} catch (ContentException e) {
logger.error("Error checking out content " + c.getId());
}
return null;
}
/**
* Check in the given content, if it was checked out by the current session.
*
* @param c The content object
*/
void checkInContent(Content c) {
if (c != null && c.isCheckedOutByCurrentSession()) {
if (logger.isDebugEnabled()) {
logger.debug("Checking in content " + c.getId());
}
c.checkIn();
}
}
/**
* Check in the given content, if it was checked out by the current session.
*
* @param c The content object
* @return TRUE, if the publication was successfull, FALSE if not.
*/
boolean publishContent(Content c) {
if (c != null) {
checkInContent(c);
if (logger.isDebugEnabled()) {
logger.debug("Published content " + c.getId());
}
try {
if (!contentRepository.getPublicationService().isPublished(c)) {
if (!contentRepository.getPublicationService().isPlaceApproved(c)) {
contentRepository.getPublicationService().approvePlace(c);
}
if (!c.isFolder()) {
Version version = c.getCheckedInVersion();
if (version != null) {
contentRepository.getPublicationService().approve(version);
}
}
contentRepository.getPublicationService().publish(c);
}
return true;
} catch (ContentException ce) {
logger.error("ContentException: Could not publish content with id " + c.getId() + " (" + c.getPath() + ")", ce);
} catch (PublicationFailedException pfe) {
logger.error("PublicationFailedException: Could not publish content with id " + c.getId() + " (" + c.getPath() + ")", pfe);
logger.error("isPublished " + contentRepository.getPublicationService().isPublished(c));
logger.error("isPlaceApproved " + contentRepository.getPublicationService().isPlaceApproved(c));
logger.error("isFolder " + c.isFolder());
} catch (PublicationException pe) {
logger.error("PublicationException: Could not publish content with id " + c.getId() + " (" + c.getPath() + ")", pe);
} catch (Exception e) {
logger.error("Exception: Could not publish content with id " + c.getId() + " (" + c.getPath() + ")", e);
}
}
return false;
}
/**
* Updates a CoreMedia content object with the given parameters. The child will not be
* created if it does not exist.
*
* @param child The CoreMedia content object for which to update properties
* @param properties The properties for the new CoreMedia document
* @return The newly created or updated content object.
*/
@Nullable
public Content updateContent(@Nullable Content child, @NonNull Map<String, Object> properties) {
Content result = child;
if (child == null || child.isDestroyed()) {
logger.error("Content with has either does not exist or has been destroyed. Skipped writing properties" +
" to content.");
} else {
updateProperties(child, properties);
}
return result;
}
/**
* Helper method to format a error message during a failure.
*
* @param msg The message which should contain insight about the nature of the issue
*/
public void handleImportFailure(String msg) {
handleImportFailure(msg, null);
}
/**
* Helper method to format a error message during a failure.
*
* @param msg The message which should contain insight about the nature of the issue
* @param e The Exception object for a stack trace
*/
public void handleImportFailure(String msg, @Nullable Exception e) {
StringBuilder sb = new StringBuilder(msg);
if (e != null) {
logger.debug(sb.toString(), e);
sb.append("\nCaused by: ").append(e).append("\nSee debug log for Exception stack trace");
}
warnings.add(sb.toString());
logger.warn(sb.toString());
}
/**
* Set the given properties in the given content.
*
* @param content The content to update
* @param properties The new properties
*/
public void updateProperties(Content content, Map<String, Object> properties) {
if (content == null || properties == null) {
logger.error("Can't update contents properties if the content object (" + content + ") or the properties object (" + properties + ") are null!");
return;
}
boolean needsCheckout = content.isCheckedIn();
if (needsCheckout) {
content.checkOut();
}
boolean success = false;
try {
content.setProperties(properties);
success = true;
} finally {
if (!success && needsCheckout) {
try {
content.revert();
} catch (ContentException ce) {
logger.error("Can't revert the attempted but unsuccessful update of a content objects properties. (content id : " + content.getId() + " )");
}
}
}
}
public List<String> getInvalidFileNames() {
return invalidFileNames;
}
public Collection<String> getWarnings() {
return warnings;
}
public ContentRepository getContentRepository() {
return contentRepository;
}
}
|
3e15f3b9fd5fbc53bcecf2a6652a5a3b37384891 | 282 | java | Java | java101-training-code-example/src/au/com/fujitsu/java101/basics/EnumExample.java | SeabookChen/java101training | 2cd0cd5de5b9a5fe53747e49389c390c264fd306 | [
"MIT"
] | null | null | null | java101-training-code-example/src/au/com/fujitsu/java101/basics/EnumExample.java | SeabookChen/java101training | 2cd0cd5de5b9a5fe53747e49389c390c264fd306 | [
"MIT"
] | null | null | null | java101-training-code-example/src/au/com/fujitsu/java101/basics/EnumExample.java | SeabookChen/java101training | 2cd0cd5de5b9a5fe53747e49389c390c264fd306 | [
"MIT"
] | null | null | null | 16.588235 | 41 | 0.684397 | 9,340 | package au.com.fujitsu.java101.basics;
public class EnumExample {
public static void main(String[] args) {
}
}
enum Color {
// TODO add a new color yellow
// TODO and print it's color
RED, BLUE, BLACK, PINK;
public String printMyColor() {
return this.toString();
}
} |
3e15f43523ef83579d00547b6bc7b854b633bd89 | 10,169 | java | Java | wear/src/main/java/hsyeo/watchmi/ActivityTechTwist.java | tcboy88/watchmi | f095488af48866702fca43a18f988d375f57a888 | [
"MIT"
] | 11 | 2017-07-21T09:25:02.000Z | 2020-04-18T03:29:28.000Z | wear/src/main/java/hsyeo/watchmi/ActivityTechTwist.java | tcboy88/watchmi | f095488af48866702fca43a18f988d375f57a888 | [
"MIT"
] | null | null | null | wear/src/main/java/hsyeo/watchmi/ActivityTechTwist.java | tcboy88/watchmi | f095488af48866702fca43a18f988d375f57a888 | [
"MIT"
] | 4 | 2017-07-16T08:40:18.000Z | 2019-05-24T09:44:52.000Z | 37.249084 | 130 | 0.567116 | 9,341 | package hsyeo.watchmi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.support.wearable.view.BoxInsetLayout;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowInsets;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class ActivityTechTwist extends WearableActivity implements SensorEventListener {
private BoxInsetLayout mContainerView;
private DrawView drawView;
private TextView tv1, tv2, tv3;
TwoFingersDoubleTapDetector twoFingersListener;
private SensorManager mSensorManager;
private Sensor mSensor;
private float[] mRotationMatrix = new float[16];
float[] rotValues = new float[3];
double yaw;
float startZ;
float diffZ;
boolean started = false;
boolean stopped = true;
boolean isStudy = false;
boolean reset = false;
int trialCount = 0;
Util util;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core_stub);
//region Bundle getIntent
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.getBoolean("study") == true) {
isStudy = true;
Toast.makeText(getApplicationContext(), "User study mode", Toast.LENGTH_SHORT).show();
} else isStudy = false;
}
//endregion
WatchViewStub stub = (WatchViewStub) findViewById(R.id.stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
mContainerView = (BoxInsetLayout) findViewById(R.id.container);
drawView = (DrawView) findViewById(R.id.draw_view);
mContainerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
int mChinSize = insets.getSystemWindowInsetBottom();
v.onApplyWindowInsets(insets);
drawView.setShape(mContainerView.isRound(), mChinSize);
drawView.setDrawModes(DrawView.DrawModes.TWIST);
drawView.setStudyModes(isStudy);
return insets;
}
});
setTouchListener();
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
if (!isStudy) {
tv1.setText("Grab the watch and TWIST left and right, keep 1 finger on screen (anywhere is ok)!");
tv3.setText("double tap with 2 fingers to exit");
} else {
InitTrials();
SetNextTrial();
tv1.setText("Correct/Wrong");
tv3.setText("Trial:" + trialCount);
}
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
if (mSensor == null) {
Log.w("YEO", "Failed to attach to game rot vec.");
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (mSensor == null)
Log.w("YEO", "Failed to attach to rot vec.");
}
//region Exit by two fingers double tap
twoFingersListener = new TwoFingersDoubleTapDetector() {
@Override
public void onTwoFingersDoubleTap() {
// Toast.makeText(getApplicationContext(), "Exit by Two Fingers Double Tap", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), ActivitySelectTech.class);
if (isStudy) {
Bundle b = new Bundle();
b.putBoolean("study", isStudy);
i.putExtras(b);
}
startActivity(i);
finish();
}
};
//endregion
util = new Util();
}
void setTouchListener() {
mContainerView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
twoFingersListener.onTouchEvent(event);
float x = event.getX();
float y = event.getY();
int maskedAction = event.getActionMasked();
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
started = true;
stopped = false;
return true;
case MotionEvent.ACTION_POINTER_DOWN:
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
started = false;
stopped = true;
return true;
}
return false;
}
});
}
//region Not important, onResume(), onPause(), onAccuracyChanged()
@Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
//endregion
@Override
public void onSensorChanged(SensorEvent event) {
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { return; }
if (event.sensor.getType() == Sensor.TYPE_GAME_ROTATION_VECTOR || event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
SensorManager.getOrientation(mRotationMatrix, rotValues);
yaw = rotValues[0];
float currentZ = (float)yaw + (float)(Math.PI * 2); // make it 0 to 6.284, easier to understand
int inclination = (int) Math.round(Math.toDegrees(Math.acos(mRotationMatrix[10])));
if (inclination > 90) {
// face down
// when inclination near 90 (such as 85 or 95), roll is very sensitive
currentZ = -currentZ;
}
if (started) {
startZ = currentZ;
started = false; // only need get value once when touched down, don't constantly update
}
if (!stopped) {
diffZ = currentZ - startZ;
if (diffZ < -Math.PI){ // this is to avoid sudden jump when crossing zero
diffZ += (Math.PI * 2);
} else if (diffZ > Math.PI){
diffZ -= (Math.PI * 2);
}
if (isStudy)
if (trialCount <= Constants.NUM_TRIALS)
Checking(diffZ * Constants.MAGIC_TWIST);
drawView.setXYZ(0, 0, diffZ);
if (reset) {
diffZ = 0;
drawView.setXYZ(0, 0, 0);
stopped = true;
reset = false;
}
} else {
diffZ = 0;
}
if (drawView != null)
drawView.invalidate();
}
}
List<Integer> trials = new ArrayList<>();
void InitTrials(){
for (int j = 0; j < Constants.TWIST_INTERVALS; j++) {
trials.add(j + 1);
}
long seed = System.nanoTime();
Collections.shuffle(trials, new Random(seed));
}
void SetNextTrial(){
if (trialCount >= Constants.NUM_TRIALS) {
Toast.makeText(getApplicationContext(), "THANKS " + trialCount, Toast.LENGTH_SHORT).show();
tv2.setText("THANKS, GOODBYE");
} else {
currentTrialPos = trials.get(trialCount);
drawView.setTrial(currentTrialPos, 0);
trialCount++;
}
}
int pos = 0;
int currentTrialPos;
int previousPos = 0;
int unitAngle = 360 / Constants.TWIST_INTERVALS;
long currentTime, startTime, askTime = 0;
void Checking(float z){
float value = (z<0)? 360+z:z; // clockwise and anti-clockwise
pos = (int)(value / unitAngle) + 1;
if (pos == currentTrialPos)
drawView.paintHighlightTask.setColor(Color.argb(150, 0, 255, 0));
else drawView.paintHighlightTask.setColor(Color.argb(150, 255, 0, 0));
if (pos != previousPos){
startTime = System.currentTimeMillis(); // restart timer whenever changed box
previousPos = pos;
} else { // remained in the same box, check elapsed time
currentTime = System.currentTimeMillis();
if (currentTime - startTime >= Constants.TIME_OUT) { // remained in box more than 1000ms
if (pos == currentTrialPos) {
tv1.setText("CORRECT");
SetNextTrial();
} else {
tv1.setText("WRONG");
}
pos = previousPos = -1;
reset = true;
drawView.paintHighlightTask.setColor(Color.argb(150, 255, 0, 0));
tv3.setText(trialCount + "/" + Constants.NUM_TRIALS + " Pos:" + currentTrialPos);
askTime = System.currentTimeMillis();
}
}
}
}
|
3e15f5cdbd2e2b5cae71a0141ebd2f0e9e9d3081 | 260 | java | Java | src/main/java/com/hubspot/imap/protocol/command/ImapCommandType.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 35 | 2017-03-28T19:57:40.000Z | 2021-10-09T03:14:26.000Z | src/main/java/com/hubspot/imap/protocol/command/ImapCommandType.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 20 | 2017-03-28T21:43:35.000Z | 2021-09-03T13:23:01.000Z | src/main/java/com/hubspot/imap/protocol/command/ImapCommandType.java | hs-jenkins-bot/NioImapClient | 8f148566137ed382f7c000065caa756168413e68 | [
"Apache-2.0"
] | 14 | 2017-03-28T20:12:34.000Z | 2021-08-12T07:02:53.000Z | 10.833333 | 42 | 0.653846 | 9,342 | package com.hubspot.imap.protocol.command;
public enum ImapCommandType {
LOGIN,
LOGOUT,
NOOP,
EXPUNGE,
IDLE,
AUTHENTICATE,
LIST,
EXAMINE,
SELECT,
FETCH,
BLANK,
STORE,
SEARCH,
CAPABILITY,
COPY,
STARTTLS,
APPEND,
PROXY
;
}
|
3e15f66da04e65631433c93f9a577c60872fe256 | 4,177 | java | Java | persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Product.java | devgateway/gtp | 4bad1118089324722a59e9382f53df51d9381c25 | [
"MIT"
] | null | null | null | persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Product.java | devgateway/gtp | 4bad1118089324722a59e9382f53df51d9381c25 | [
"MIT"
] | 7 | 2020-12-21T17:07:07.000Z | 2021-09-02T17:43:43.000Z | persistence/src/main/java/org/devgateway/toolkit/persistence/dao/categories/Product.java | devgateway/gtp | 4bad1118089324722a59e9382f53df51d9381c25 | [
"MIT"
] | null | null | null | 29.835714 | 117 | 0.728992 | 9,343 | package org.devgateway.toolkit.persistence.dao.categories;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.devgateway.toolkit.persistence.dao.AbstractAuditableEntity;
import org.devgateway.toolkit.persistence.dao.Labelable;
import org.devgateway.toolkit.persistence.excel.annotation.ExcelExport;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.envers.Audited;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* @author Octavian Ciubotaru
*/
@Entity
@Audited
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@BatchSize(size = 100)
@JsonIgnoreProperties({"new"})
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"product_type_id", "name"}))
public class Product extends AbstractAuditableEntity implements Comparable<Product>, Labelable {
private static final long serialVersionUID = 3176446575063348309L;
private static final Comparator<Product> NATURAL = Comparator.comparing(Product::getName);
@ExcelExport(name = "productType", justExport = true, useTranslation = true)
@NotNull
@ManyToOne(optional = false)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty("productTypeId")
private ProductType productType;
@ExcelExport(name = "productName", useTranslation = true)
@NotNull
private String name;
@ExcelExport(name = "productUnit", justExport = true, useTranslation = true)
@NotNull
@ManyToOne(optional = false)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "label")
@JsonIdentityReference(alwaysAsId = true)
private MeasurementUnit unit;
@NotNull @NotEmpty
@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@BatchSize(size = 100)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty("priceTypeIds")
private List<PriceType> priceTypes = new ArrayList<>();
public Product() {
}
public Product(Long id, ProductType productType, String name, MeasurementUnit unit, List<PriceType> priceTypes) {
setId(id);
this.productType = productType;
this.name = name;
this.unit = unit;
this.priceTypes = priceTypes;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MeasurementUnit getUnit() {
return unit;
}
public void setUnit(MeasurementUnit unit) {
this.unit = unit;
}
public List<PriceType> getPriceTypes() {
return priceTypes;
}
public void setPriceTypes(List<PriceType> priceTypes) {
this.priceTypes = priceTypes;
}
@Override
@JsonIgnore
public AbstractAuditableEntity getParent() {
return null;
}
@Override
public int compareTo(Product o) {
return NATURAL.compare(this, o);
}
@Override
public void setLabel(String label) {
name = label;
}
@Override
@JsonIgnore
public String getLabel() {
return name;
}
@Override
public String getLabel(String lang) {
return name;
}
}
|
3e15f7244fae352db3156d241ff36e13a2edf807 | 427 | java | Java | src/FileHandling/FileRead.java | yakshisharma/Codes-B-19-SDET- | 3420ddf282c1732625230856895479d81a131deb | [
"Apache-2.0"
] | null | null | null | src/FileHandling/FileRead.java | yakshisharma/Codes-B-19-SDET- | 3420ddf282c1732625230856895479d81a131deb | [
"Apache-2.0"
] | null | null | null | src/FileHandling/FileRead.java | yakshisharma/Codes-B-19-SDET- | 3420ddf282c1732625230856895479d81a131deb | [
"Apache-2.0"
] | 1 | 2020-11-04T07:56:12.000Z | 2020-11-04T07:56:12.000Z | 14.724138 | 60 | 0.676815 | 9,344 | package FileHandling;
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedWriter bf=null;
try
{
FileWriter fw= new FileWriter("F://Program//Agam.txt");
bf=new BufferedWriter(fw);
char[] aa= {'a','b'};
for(int i=0;i<aa.length;i++)
{
bf.write(aa[i]);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
bf.close();
}
}
}
|
3e15f7a750125e2aa1f99334c384e9fc0f1db880 | 1,072 | java | Java | restaurants-initial/src/main/java/com/lambdaschool/restaurants/models/RestaurantPaymentsId.java | dstemple7/java-restaurants | e430567e39d86e9ce801df1faf42df264d635381 | [
"MIT"
] | null | null | null | restaurants-initial/src/main/java/com/lambdaschool/restaurants/models/RestaurantPaymentsId.java | dstemple7/java-restaurants | e430567e39d86e9ce801df1faf42df264d635381 | [
"MIT"
] | null | null | null | restaurants-initial/src/main/java/com/lambdaschool/restaurants/models/RestaurantPaymentsId.java | dstemple7/java-restaurants | e430567e39d86e9ce801df1faf42df264d635381 | [
"MIT"
] | null | null | null | 18.807018 | 61 | 0.580224 | 9,345 | package com.lambdaschool.restaurants.models;
import java.io.Serializable;
import java.util.Objects;
public class RestaurantPaymentsId implements Serializable
{
private long restaurant;
private long payment;
public RestaurantPaymentsId()
{
}
public long getRestaurant()
{
return restaurant;
}
public void setRestaurant(long restaurant)
{
this.restaurant = restaurant;
}
public long getPayment()
{
return payment;
}
public void setPayment(long payment)
{
this.payment = payment;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
RestaurantPaymentsId that = (RestaurantPaymentsId) o;
return restaurant == that.restaurant &&
payment == that.payment;
}
@Override
public int hashCode()
{
return Objects.hash(restaurant, payment);
}
}
|
3e15f8dcfc8f4396ee272042468ccb14bf48a404 | 20,976 | java | Java | src/test/java/com/tiyb/tev/xml/ManualConversationUnitTests.java | tiyb/tev | 6db52f0f3587b06493ee3a2ef4f7c31b3ebee318 | [
"MIT"
] | null | null | null | src/test/java/com/tiyb/tev/xml/ManualConversationUnitTests.java | tiyb/tev | 6db52f0f3587b06493ee3a2ef4f7c31b3ebee318 | [
"MIT"
] | 169 | 2019-02-13T22:12:37.000Z | 2021-05-12T15:18:24.000Z | src/test/java/com/tiyb/tev/xml/ManualConversationUnitTests.java | tiyb/tev | 6db52f0f3587b06493ee3a2ef4f7c31b3ebee318 | [
"MIT"
] | null | null | null | 49.942857 | 120 | 0.713148 | 9,346 | package com.tiyb.tev.xml;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.ResourceUtils;
import com.tiyb.tev.TevTestingClass;
import com.tiyb.tev.controller.TEVConvoRestController;
import com.tiyb.tev.controller.TEVMetadataRestController;
import com.tiyb.tev.datamodel.Conversation;
import com.tiyb.tev.datamodel.ConversationMessage;
import com.tiyb.tev.datamodel.FullConversation;
import com.tiyb.tev.datamodel.Metadata;
import com.tiyb.tev.exception.XMLParsingException;
public class ManualConversationUnitTests extends TevTestingClass {
@Autowired
private TEVConvoRestController convoRestController;
@Autowired
private TEVMetadataRestController mdRestController;
private static final String convo1Participant = "participant1";
private static final String convo2Participant = "participant2";
private static final String convo3Participant = "participant3";
private static final String convo4Participant = "participant4";
private static final String convo5Participant = "participant5";
private static final String oldNameParticipantId = "foaiehoihafoei";
private static final String tobeDeactivatedId = "afoiehaifeh";
private static final String blankParticipant = "NO NAME";
private static final String duplicateParticipant = "participant1 1";
private static final int TOTAL_NUM_CONVOS = 8;
@Before
public void setup() {
initMainBlogMetadataata(mdRestController, Optional.empty());
convoRestController.deleteAllConvoMsgsForBlog(MAIN_BLOG_NAME);
convoRestController.deleteAllConversationsForBlog(MAIN_BLOG_NAME);
for (FullConversation fc : conversationsToUpload) {
Conversation convoOnServer = convoRestController.createConversationForBlog(fc.getConversation().getBlog(),
fc.getConversation());
for (ConversationMessage message : fc.getMessages()) {
message.setConversationId(convoOnServer.getId());
convoRestController.createConvoMessageForBlog(convoOnServer.getBlog(), message);
}
}
}
/**
* Verifies that all of the conversations in the test XML input file have been
* properly imported into the database. Since it is known how many conversation
* messages are part of each conversation, as well as the participant avatar
* URLs, this information is asserted to be present.
*/
@Test
public void checkConversations() {
List<Conversation> convos = convoRestController.getAllConversationsForBlog(MAIN_BLOG_NAME);
assertThat(convos).isNotNull();
assertThat(convos.size()).isEqualTo(TOTAL_NUM_CONVOS);
Conversation firstConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
convo1Participant);
assertThat(firstConvo).isNotNull();
assertThat(firstConvo.getNumMessages()).isEqualTo(9);
assertThat(firstConvo.getParticipantAvatarUrl()).isEqualTo("http://participant1/avatar");
Conversation secondConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
convo2Participant);
assertThat(secondConvo).isNotNull();
assertThat(secondConvo.getNumMessages()).isEqualTo(9);
assertThat(secondConvo.getParticipantAvatarUrl()).isEqualTo("http://participant2/avatar");
Conversation thirdConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
convo3Participant);
assertThat(thirdConvo).isNotNull();
assertThat(thirdConvo.getNumMessages()).isEqualTo(1);
Conversation fourthConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
convo4Participant);
assertThat(fourthConvo).isNotNull();
assertThat(fourthConvo.getNumMessages()).isEqualTo(1);
Conversation changedConvo = convoRestController.getConversationForBlogByParticipantIdOrName(MAIN_BLOG_NAME,
oldNameParticipantId, "");
assertThat(changedConvo).isNotNull();
assertThat(changedConvo.getNumMessages()).isEqualTo(1);
assertThat(changedConvo.getParticipant()).isEqualTo("participant-oldname");
assertThat(changedConvo.getParticipantAvatarUrl()).isEqualTo("http://participanton/avatar");
Conversation toBeDeactConvo = convoRestController.getConversationForBlogByParticipantIdOrName(MAIN_BLOG_NAME,
tobeDeactivatedId, "");
assertThat(toBeDeactConvo).isNotNull();
assertThat(toBeDeactConvo.getNumMessages()).isEqualTo(2);
assertThat(toBeDeactConvo.getParticipant()).isEqualTo("goingtobedeactivated");
assertThat(toBeDeactConvo.getParticipantAvatarUrl()).isEqualTo("http://goingtobedeac/avatar");
Conversation blankParticipantConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
blankParticipant);
assertThat(blankParticipantConvo).isNotNull();
assertThat(blankParticipantConvo.getNumMessages()).isEqualTo(1);
assertThat(blankParticipantConvo.getParticipant()).isEqualTo("NO NAME");
assertThat(blankParticipantConvo.getParticipantAvatarUrl()).isEmpty();
Conversation dupNameConvo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME,
duplicateParticipant);
assertThat(dupNameConvo).isNotNull();
assertThat(dupNameConvo.getNumMessages()).isEqualTo(1);
assertThat(dupNameConvo.getParticipant()).isEqualTo("participant1 1");
assertThat(dupNameConvo.getParticipantAvatarUrl()).isEqualTo("http://duplicatename/avatar");
}
/**
* Verifies that cases where a participant is blank (which happens sometimes)
* are handled correctly; the solution <i>should</i> insert a default name for
* that participant name.
*/
@Test
public void checkBlankParticipantLoading() {
List<Conversation> convos = convoRestController.getAllConversationsForBlog(MAIN_BLOG_NAME);
assertThat(convos).isNotNull();
assertThat(convos.size()).isEqualTo(TOTAL_NUM_CONVOS);
for (Conversation c : convos) {
assertThat(c.getParticipant()).isNotBlank();
}
}
/**
* Tests that Conversations with only sent messages can still be retrieved via
* participant name, even though no ID was created. (The
* <code>testAddingConvos()</code> method will test that the conversation can be
* updated properly.) Would make more logical sense to put this test in the
* {@link com.tiyb.tev.controller.TevPostRestControllerUnitTests
* TevRestControllerUnitTests} class, but is included here instead since the
* proper set has been done for inserting the data into the DB.
*/
@Test
public void testRetrieveConvoWithNoId() {
Conversation returnedConvo = convoRestController.getConversationForBlogByParticipantIdOrName(MAIN_BLOG_NAME, "",
convo3Participant);
assertThat(returnedConvo).isNotNull();
assertThat(returnedConvo.getNumMessages()).isEqualTo(1);
assertThat(returnedConvo.getParticipant()).isEqualTo(convo3Participant);
assertThat(returnedConvo.getParticipantAvatarUrl()).isEqualTo("http://participant3/avatar");
assertThat(returnedConvo.getParticipantId()).isBlank();
}
/**
* Verifies that all of the conversation messages in the test XML input file
* have been properly imported into the database for Conversation 1. Since the
* message, type, and timestamp is known for each conversation message, this
* information is asserted to be present.
*/
@Test
public void checkConvo1Messages() {
Conversation convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo1Participant);
List<ConversationMessage> msgs = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(msgs).isNotNull();
assertThat(msgs.size()).isEqualTo(9);
assertThat(msgs.get(0).getMessage()).isEqualTo("Message 1");
assertThat(msgs.get(0).getType()).isEqualTo("TEXT");
assertThat(msgs.get(0).getReceived()).isEqualTo(false);
assertThat(msgs.get(0).getTimestamp()).isEqualTo(1544197586L);
assertThat(msgs.get(1).getMessage()).isEqualTo("Message 2");
assertThat(msgs.get(1).getType()).isEqualTo("TEXT");
assertThat(msgs.get(1).getReceived()).isEqualTo(false);
assertThat(msgs.get(1).getTimestamp()).isEqualTo(1544197605L);
assertThat(msgs.get(2).getMessage()).isEqualTo("Message 3");
assertThat(msgs.get(2).getType()).isEqualTo("TEXT");
assertThat(msgs.get(2).getReceived()).isEqualTo(false);
assertThat(msgs.get(2).getTimestamp()).isEqualTo(1544197624L);
assertThat(msgs.get(3).getMessage()).isEqualTo("http://www.photourl.com/photo.png");
assertThat(msgs.get(3).getType()).isEqualTo("IMAGE");
assertThat(msgs.get(3).getReceived()).isEqualTo(false);
assertThat(msgs.get(3).getTimestamp()).isEqualTo(1544197647L);
assertThat(msgs.get(4).getMessage()).isEqualTo("Message 5");
assertThat(msgs.get(4).getType()).isEqualTo("TEXT");
assertThat(msgs.get(4).getReceived()).isEqualTo(false);
assertThat(msgs.get(4).getTimestamp()).isEqualTo(1544198315L);
assertThat(msgs.get(5).getMessage()).isEqualTo("Message 6");
assertThat(msgs.get(5).getType()).isEqualTo("TEXT");
assertThat(msgs.get(5).getReceived()).isEqualTo(true);
assertThat(msgs.get(5).getTimestamp()).isEqualTo(1544221130L);
assertThat(msgs.get(6).getMessage()).isEqualTo("Message 7");
assertThat(msgs.get(6).getType()).isEqualTo("TEXT");
assertThat(msgs.get(6).getReceived()).isEqualTo(false);
assertThat(msgs.get(6).getTimestamp()).isEqualTo(1544221197L);
assertThat(msgs.get(7).getMessage()).isEqualTo("Message 8");
assertThat(msgs.get(7).getType()).isEqualTo("TEXT");
assertThat(msgs.get(7).getReceived()).isEqualTo(true);
assertThat(msgs.get(7).getTimestamp()).isEqualTo(1544221203L);
assertThat(msgs.get(8).getMessage()).isEqualTo("http://www.tumblr.com/somepost");
assertThat(msgs.get(8).getType()).isEqualTo("POSTREF");
assertThat(msgs.get(8).getReceived()).isEqualTo(false);
assertThat(msgs.get(8).getTimestamp()).isEqualTo(1544221221L);
}
/**
* Verifies that all of the conversation messages in the test XML input file
* have been properly imported into the database for Conversation 2. Since the
* message, type, and timestamp is known for each conversation message, this
* information is asserted to be present.
*/
@Test
public void checkConvo2Messages() {
Conversation convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo2Participant);
List<ConversationMessage> msgs = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(msgs).isNotNull();
assertThat(msgs.size()).isEqualTo(9);
assertThat(msgs.get(0).getMessage()).isEqualTo("Message 1");
assertThat(msgs.get(0).getType()).isEqualTo("TEXT");
assertThat(msgs.get(0).getReceived()).isEqualTo(true);
assertThat(msgs.get(0).getTimestamp()).isEqualTo(1544012468L);
assertThat(msgs.get(1).getMessage()).isEqualTo("Message 2");
assertThat(msgs.get(1).getType()).isEqualTo("TEXT");
assertThat(msgs.get(1).getReceived()).isEqualTo(false);
assertThat(msgs.get(1).getTimestamp()).isEqualTo(1544016206L);
assertThat(msgs.get(2).getMessage()).isEqualTo("Message 3");
assertThat(msgs.get(2).getType()).isEqualTo("TEXT");
assertThat(msgs.get(2).getReceived()).isEqualTo(true);
assertThat(msgs.get(2).getTimestamp()).isEqualTo(1544016402L);
assertThat(msgs.get(3).getMessage()).isEqualTo("Message 4");
assertThat(msgs.get(3).getType()).isEqualTo("TEXT");
assertThat(msgs.get(3).getReceived()).isEqualTo(true);
assertThat(msgs.get(3).getTimestamp()).isEqualTo(1544016410L);
assertThat(msgs.get(4).getMessage()).isEqualTo("Message 5");
assertThat(msgs.get(4).getType()).isEqualTo("TEXT");
assertThat(msgs.get(4).getReceived()).isEqualTo(true);
assertThat(msgs.get(4).getTimestamp()).isEqualTo(1544016579L);
assertThat(msgs.get(5).getMessage()).isEqualTo("Message 6");
assertThat(msgs.get(5).getType()).isEqualTo("TEXT");
assertThat(msgs.get(5).getReceived()).isEqualTo(true);
assertThat(msgs.get(5).getTimestamp()).isEqualTo(1544016582L);
assertThat(msgs.get(6).getMessage()).isEqualTo("Message 7");
assertThat(msgs.get(6).getType()).isEqualTo("TEXT");
assertThat(msgs.get(6).getReceived()).isEqualTo(false);
assertThat(msgs.get(6).getTimestamp()).isEqualTo(1544022051L);
assertThat(msgs.get(7).getMessage()).isEqualTo("Message 8");
assertThat(msgs.get(7).getType()).isEqualTo("TEXT");
assertThat(msgs.get(7).getReceived()).isEqualTo(true);
assertThat(msgs.get(7).getTimestamp()).isEqualTo(1544115936L);
assertThat(msgs.get(8).getMessage()).isEqualTo("Message 9");
assertThat(msgs.get(8).getType()).isEqualTo("TEXT");
assertThat(msgs.get(8).getReceived()).isEqualTo(false);
assertThat(msgs.get(8).getTimestamp()).isEqualTo(1544126671L);
}
/**
* Verifies that all of the conversation messages in the test XML input file
* have been properly imported into the database for Conversation 3. Since the
* message, type, and timestamp is known for each conversation message, this
* information is asserted to be present.
*/
@Test
public void checkConvo3Messages() {
Conversation convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo3Participant);
List<ConversationMessage> msgs = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(msgs).isNotNull();
assertThat(msgs.size()).isEqualTo(1);
assertThat(msgs.get(0).getMessage()).isEqualTo("Message 1");
assertThat(msgs.get(0).getType()).isEqualTo("TEXT");
assertThat(msgs.get(0).getReceived()).isEqualTo(false);
assertThat(msgs.get(0).getTimestamp()).isEqualTo(1544012468L);
}
/**
* Verifies that all of the conversation messages in the test XML input file
* have been properly imported into the database for Conversation 4. Since the
* message, type, and timestamp is known for each conversation message, this
* information is asserted to be present.
*/
@Test
public void checkConvo4Messages() {
Conversation convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo4Participant);
List<ConversationMessage> msgs = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(msgs).isNotNull();
assertThat(msgs.size()).isEqualTo(1);
assertThat(msgs.get(0).getMessage()).isEqualTo("Message 1");
assertThat(msgs.get(0).getType()).isEqualTo("TEXT");
assertThat(msgs.get(0).getReceived()).isEqualTo(true);
assertThat(msgs.get(0).getTimestamp()).isEqualTo(1544012468L);
}
/**
* Tests parsing of the Conversation XML in cases where the "overwrite
* conversations" flag is set to false; unchanged conversations should be left
* alone, new conversations should be uploaded, and conversations that have had
* new messages added should have those messages uploaded, and be marked as
* un-hidden.
*
* @throws IOException
*/
@Test
public void addConvo() throws IOException {
List<Conversation> convos = convoRestController.getAllConversationsForBlog(MAIN_BLOG_NAME);
assertThat(convos.size()).isEqualTo(TOTAL_NUM_CONVOS);
for (Conversation convo : convos) {
convo.setHideConversation(true);
convoRestController.updateConversationForBlog(MAIN_BLOG_NAME, convo.getId(), convo);
}
Metadata md = mdRestController.getMetadataForBlog(MAIN_BLOG_NAME);
md.setOverwriteConvoData(false);
md = mdRestController.updateMetadata(md.getId(), md);
File rawXmlFile = ResourceUtils.getFile("classpath:XML/test-messages-extended-xml.xml");
InputStream xmlFile = new FileInputStream(rawXmlFile);
MockMultipartFile mockFile = new MockMultipartFile("testmessages", xmlFile);
ConversationXmlReader.parseDocument(mockFile, mdRestController, convoRestController, MAIN_BLOG_NAME);
convos = convoRestController.getAllConversationsForBlog(MAIN_BLOG_NAME);
assertThat(convos).isNotNull();
assertThat(convos.size()).isEqualTo(TOTAL_NUM_CONVOS + 1);
Conversation convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo1Participant);
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(false);
List<ConversationMessage> messages = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME,
convo.getId());
assertThat(messages).isNotNull();
assertThat(messages.size()).isEqualTo(10);
convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo2Participant);
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(true);
convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo3Participant);
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(false);
assertThat(convo.getNumMessages()).isEqualTo(2);
messages = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(messages).isNotNull();
assertThat(messages.size()).isEqualTo(2);
convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo4Participant);
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(true);
convo = convoRestController.getConversationForBlogByParticipant(MAIN_BLOG_NAME, convo5Participant);
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(false);
messages = convoRestController.getConvoMsgForBlogByConvoID(MAIN_BLOG_NAME, convo.getId());
assertThat(messages).isNotNull();
assertThat(messages.size()).isEqualTo(1);
ConversationMessage message = messages.get(0);
assertThat(message.getMessage()).isEqualTo("Message 1");
assertThat(message.getType()).isEqualTo("TEXT");
assertThat(message.getReceived()).isEqualTo(true);
assertThat(message.getTimestamp()).isEqualTo(1544012468L);
convo = convoRestController.getConversationForBlogByParticipantIdOrName(MAIN_BLOG_NAME, oldNameParticipantId,
"");
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(false);
assertThat(convo.getNumMessages()).isEqualTo(1);
assertThat(convo.getParticipant()).isEqualTo("participant-newname");
assertThat(convo.getParticipantAvatarUrl()).isEqualTo("http://participantnn/avatar");
convo = convoRestController.getConversationForBlogByParticipantIdOrName(MAIN_BLOG_NAME, tobeDeactivatedId, "");
assertThat(convo).isNotNull();
assertThat(convo.getHideConversation()).isEqualTo(true);
assertThat(convo.getNumMessages()).isEqualTo(2);
assertThat(convo.getParticipant()).isEqualTo("goingtobedeactivated");
assertThat(convo.getParticipantAvatarUrl()).isEqualTo("http://goingtobedeac/avatar");
}
/**
* Tests that parsing an invalid XML file throws the proper exception
*
* @throws IOException
*/
@Test(expected = XMLParsingException.class)
public void testBadXml() throws IOException {
File rawXmlFile = ResourceUtils.getFile("classpath:XML/test-messages-badxml.txt");
InputStream xmlFile = new FileInputStream(rawXmlFile);
MockMultipartFile mockFile = new MockMultipartFile("testmessages", xmlFile);
ConversationXmlReader.parseDocument(mockFile, mdRestController, convoRestController, MAIN_BLOG_NAME);
}
}
|
3e15f9b59ee277506b7718b89f6d8c2d75dfd08f | 1,235 | java | Java | services-common/src/main/java/edu/pitt/apollo/ApolloServiceConstants.java | ApolloDev/apollo | 935b9f7ab00966fc3480a5cc9de722b604700044 | [
"Apache-2.0"
] | 2 | 2015-05-19T18:22:14.000Z | 2015-11-05T20:14:11.000Z | services-common/src/main/java/edu/pitt/apollo/ApolloServiceConstants.java | ApolloDev/apollo | 935b9f7ab00966fc3480a5cc9de722b604700044 | [
"Apache-2.0"
] | 66 | 2015-10-27T14:43:20.000Z | 2022-02-01T01:03:41.000Z | services-common/src/main/java/edu/pitt/apollo/ApolloServiceConstants.java | ApolloDev/apollo | 935b9f7ab00966fc3480a5cc9de722b604700044 | [
"Apache-2.0"
] | 5 | 2015-04-10T18:10:23.000Z | 2016-09-22T14:52:03.000Z | 26.956522 | 88 | 0.642742 | 9,347 | package edu.pitt.apollo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Map;
/**
*
* Author: Nick Millett
* Email: efpyi@example.com
* Date: May 7, 2014
* Time: 1:14:20 PM
* Class: ApolloServiceConstants
* IDE: NetBeans 6.9.1
*/
public class ApolloServiceConstants {
public static final String APOLLO_DIR;
public static final int END_USER_APPLICATION_SOURCE_ID = 12;
static final Logger logger = LoggerFactory.getLogger(ApolloServiceConstants.class);
static {
Map<String, String> env = System.getenv();
String apolloDir = env.get(GlobalConstants.APOLLO_WORKDIR_ENVIRONMENT_VARIABLE);
if (apolloDir != null) {
if (!apolloDir.endsWith(File.separator)) {
apolloDir += File.separator;
}
APOLLO_DIR = apolloDir;
logger.info(GlobalConstants.APOLLO_WORKDIR_ENVIRONMENT_VARIABLE + " is now:"
+ APOLLO_DIR);
} else {
logger.error(GlobalConstants.APOLLO_WORKDIR_ENVIRONMENT_VARIABLE
+ " environment variable not found!");
APOLLO_DIR = "";
}
}
public static void main(String[] args) {
}
}
|
3e15fa33d5b1f93f1894c47e56f8796903273de3 | 44 | java | Java | src/main/java/com/jatheon/demo/weather/repository/package-info.java | staleks/weather-service | 15e5e3c8eb23cf2c918a2fc88516f26f65f19f52 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jatheon/demo/weather/repository/package-info.java | staleks/weather-service | 15e5e3c8eb23cf2c918a2fc88516f26f65f19f52 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jatheon/demo/weather/repository/package-info.java | staleks/weather-service | 15e5e3c8eb23cf2c918a2fc88516f26f65f19f52 | [
"Apache-2.0"
] | null | null | null | 44 | 44 | 0.863636 | 9,348 | package com.jatheon.demo.weather.repository; |
3e15fa6736fb63c53f69f97ffde564d5046fdad7 | 2,342 | java | Java | nipa-user/src/main/java/kr/nipa/mgps/persistence/SearchMapMapper.java | Gaia3D/nipa | 083bae3e4fc1032348c2f0c5a3bccb3912fa240f | [
"Apache-2.0"
] | 7 | 2018-08-29T02:28:54.000Z | 2019-04-10T20:49:50.000Z | nipa-user/src/main/java/kr/nipa/mgps/persistence/SearchMapMapper.java | Gaia3D/nipa | 083bae3e4fc1032348c2f0c5a3bccb3912fa240f | [
"Apache-2.0"
] | 1 | 2018-09-14T04:32:46.000Z | 2018-09-14T04:32:46.000Z | nipa-user/src/main/java/kr/nipa/mgps/persistence/SearchMapMapper.java | Gaia3D/nipa | 083bae3e4fc1032348c2f0c5a3bccb3912fa240f | [
"Apache-2.0"
] | 1 | 2020-12-23T15:27:24.000Z | 2020-12-23T15:27:24.000Z | 18.015385 | 91 | 0.682323 | 9,349 | package kr.nipa.mgps.persistence;
import java.util.List;
import org.springframework.stereotype.Repository;
import kr.nipa.mgps.domain.AddrJibun;
import kr.nipa.mgps.domain.CountryPlaceNumber;
import kr.nipa.mgps.domain.District;
import kr.nipa.mgps.domain.NewAddress;
import kr.nipa.mgps.domain.PlaceName;
import kr.nipa.mgps.domain.SkEmd;
import kr.nipa.mgps.domain.SkSdo;
import kr.nipa.mgps.domain.SkSgg;
@Repository
public interface SearchMapMapper {
/**
* Sdo 목록(geom 은 제외)
* @return
*/
List<SkSdo> getListSdoExceptGeom();
/**
* Sgg 목록(geom 은 제외)
* @param sdo_code
* @return
*/
List<SkSgg> getListSggBySdoExceptGeom(String sdo_code);
/**
* emd 목록(geom 은 제외)
* @param skEmd
* @return
*/
List<SkEmd> getListEmdBySdoAndSggExceptGeom(SkEmd skEmd);
/**
* 선택한 시도의 center point를 구함
* @param skSdo
* @return
*/
public String getCentroidSdo(SkSdo skSdo);
/**
* 선택한 시군구 center point를 구함
* @param skSgg
* @return
*/
public String getCentroidSgg(SkSgg skSgg);
/**
* 선택한 읍면동 center point를 구함
* @param skEmd
* @return
*/
public String getCentroidEmd(SkEmd skEmd);
/**
* 행정구역 검색 총 건수
* @param district
* @return
*/
Long getDistrictTotalCount(District district);
/**
* 지명 검색 총 건수
* @param placeName
* @return
*/
Long getPlaceNameTotalCount(PlaceName placeName);
/**
* 지번 검색 총 건수
* @param addrJibun
* @return
*/
Long getJibunTotalCount(AddrJibun addrJibun);
/**
* 새 주소 검색 총 건수
* @param newAddress
* @return
*/
Long getNewAddressTotalCount(NewAddress newAddress);
/**
* 국가 지점 번호 검색 총 건수
* @param countryPlaceNumber
* @return
*/
Long getCountryPlaceNumberTotalCount(CountryPlaceNumber countryPlaceNumber);
/**
* 행정 구역 검색
* @param district
* @return
*/
List<District> getListDistrict(District district);
/**
* 지명 구역 검색
* @param placeName
* @return
*/
List<PlaceName> getListPlaceName(PlaceName placeName);
/**
* 지번 검색 목록
* @param addrJibun
* @return
*/
List<AddrJibun> getListJibun(AddrJibun addrJibun);
/**
* 새 주소 검색
* @param newAddress
* @return
*/
List<NewAddress> getListNewAddress(NewAddress newAddress);
/**
* 국가 지점번호 검색 검색
* @param countryPlaceNumber
* @return
*/
List<CountryPlaceNumber> getListCountryPlaceNumber(CountryPlaceNumber countryPlaceNumber);
}
|
3e15fa74cc87912102a5635293c8c6d7d59cefb2 | 4,720 | java | Java | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/UpdateNodeResourceRequest.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/UpdateNodeResourceRequest.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/UpdateNodeResourceRequest.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 20 | 814 | 0.79428 | 9,350 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.api.protocolrecords
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|api
operator|.
name|protocolrecords
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
operator|.
name|Public
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
operator|.
name|Evolving
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|NodeId
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceOption
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|api
operator|.
name|ResourceManagerAdministrationProtocol
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|util
operator|.
name|Records
import|;
end_import
begin_comment
comment|/** *<p>The request sent by admin to change a list of nodes' resource to the *<code>ResourceManager</code>.</p> * *<p>The request contains details such as a map from {@link NodeId} to * {@link ResourceOption} for updating the RMNodes' resources in *<code>ResourceManager</code>. * * @see ResourceManagerAdministrationProtocol#updateNodeResource( * UpdateNodeResourceRequest) */
end_comment
begin_class
annotation|@
name|Public
annotation|@
name|Evolving
DECL|class|UpdateNodeResourceRequest
specifier|public
specifier|abstract
class|class
name|UpdateNodeResourceRequest
block|{
annotation|@
name|Public
annotation|@
name|Evolving
DECL|method|newInstance ( Map<NodeId, ResourceOption> nodeResourceMap)
specifier|public
specifier|static
name|UpdateNodeResourceRequest
name|newInstance
parameter_list|(
name|Map
argument_list|<
name|NodeId
argument_list|,
name|ResourceOption
argument_list|>
name|nodeResourceMap
parameter_list|)
block|{
name|UpdateNodeResourceRequest
name|request
init|=
name|Records
operator|.
name|newRecord
argument_list|(
name|UpdateNodeResourceRequest
operator|.
name|class
argument_list|)
decl_stmt|;
name|request
operator|.
name|setNodeResourceMap
argument_list|(
name|nodeResourceMap
argument_list|)
expr_stmt|;
return|return
name|request
return|;
block|}
comment|/** * Get the map from<code>NodeId</code> to<code>ResourceOption</code>. * @return the map of {@code<NodeId, ResourceOption>} */
annotation|@
name|Public
annotation|@
name|Evolving
DECL|method|getNodeResourceMap ()
specifier|public
specifier|abstract
name|Map
argument_list|<
name|NodeId
argument_list|,
name|ResourceOption
argument_list|>
name|getNodeResourceMap
parameter_list|()
function_decl|;
comment|/** * Set the map from<code>NodeId</code> to<code>ResourceOption</code>. * @param nodeResourceMap the map of {@code<NodeId, ResourceOption>} */
annotation|@
name|Public
annotation|@
name|Evolving
DECL|method|setNodeResourceMap (Map<NodeId, ResourceOption> nodeResourceMap)
specifier|public
specifier|abstract
name|void
name|setNodeResourceMap
parameter_list|(
name|Map
argument_list|<
name|NodeId
argument_list|,
name|ResourceOption
argument_list|>
name|nodeResourceMap
parameter_list|)
function_decl|;
block|}
end_class
end_unit
|
3e15fadc4a3126d63ebd2139a857512caf9112bc | 607 | java | Java | kitty-admin/src/main/java/com/louis/kitty/admin/vo/LoginBean.java | wsj1198878990/alipay-project | be3dadf4420645128541bacc386b3a8a2a3824b4 | [
"MIT"
] | 2 | 2020-12-26T03:45:28.000Z | 2020-12-26T03:45:45.000Z | kitty-admin/src/main/java/com/louis/kitty/admin/vo/LoginBean.java | wenbiao2019/kitty | e36f4a6881352cac9767de643e8ed84064d82b7e | [
"MIT"
] | 1 | 2019-11-14T10:42:57.000Z | 2019-11-14T10:42:57.000Z | kitty-admin/src/main/java/com/louis/kitty/admin/vo/LoginBean.java | wenbiao2019/kitty | e36f4a6881352cac9767de643e8ed84064d82b7e | [
"MIT"
] | 5 | 2019-08-24T05:58:42.000Z | 2020-11-13T04:46:13.000Z | 17.852941 | 44 | 0.665568 | 9,351 | package com.louis.kitty.admin.vo;
/**
* 登录接口封装对象
* @author Louis
* @date Oct 29, 2018
*/
public class LoginBean {
private String account;
private String password;
private String captcha;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
}
|
3e15fb2d38b3c92bd1e2d1862d115fcb650344c3 | 1,408 | java | Java | src/main/java/com/github/monosoul/spring/order/support/OrderQualifier.java | monosoul/spring-orderconfig | f25c433b8ab876654838948368ab59b76f24c575 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/monosoul/spring/order/support/OrderQualifier.java | monosoul/spring-orderconfig | f25c433b8ab876654838948368ab59b76f24c575 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/monosoul/spring/order/support/OrderQualifier.java | monosoul/spring-orderconfig | f25c433b8ab876654838948368ab59b76f24c575 | [
"Apache-2.0"
] | null | null | null | 27.076923 | 82 | 0.700284 | 9,352 | package com.github.monosoul.spring.order.support;
import com.github.monosoul.spring.order.OrderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
/**
* Qualifier that is used internally by the {@link OrderConfig} processors.<br>
* Points to the dependent class where containing class should be injected.<br>
* Basically it's just reversed {@link Qualifier} and could be used like that.<br>
* <br>
* Example:
* <pre><code>
* public interface SomeInterface {}
*
* {@literal @}Component
* public class SomeClass implements SomeInterface {
* private final SomeInterface dependency;
*
* {@literal @}Autowired
* public SomeClass(final SomeInterface dependency) {
* this.dependency = dependency;
* }
* }
*
* {@literal @}OrderQualifier(SomeClass.class)
* {@literal @}Component
* public class AnotherClass implements SomeInterface {
* //some logic here
* }
*
* </code></pre>
* Requires {@link OrderConfigConfiguration} to work.
*
* @see Qualifier
* @see Component
* @see Autowired
* @see OrderConfig
*/
public @interface OrderQualifier {
/**
* Dependent class
*
* @return a class instance
*/
@NonNull
Class<?> value() default Void.class;
}
|
3e15fbdd7b69f4db5cba743a8361f6b86c445cbe | 31,023 | java | Java | common/src/main/java/org/apache/nemo/common/ir/IRDAG.java | deploy-soon/incubator-nemo | a1af520189be7d0d83bd4b7af75a62762aa8f9a0 | [
"Apache-2.0"
] | 1 | 2019-12-02T09:42:10.000Z | 2019-12-02T09:42:10.000Z | common/src/main/java/org/apache/nemo/common/ir/IRDAG.java | deploy-soon/incubator-nemo | a1af520189be7d0d83bd4b7af75a62762aa8f9a0 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/org/apache/nemo/common/ir/IRDAG.java | deploy-soon/incubator-nemo | a1af520189be7d0d83bd4b7af75a62762aa8f9a0 | [
"Apache-2.0"
] | 2 | 2019-12-03T06:44:19.000Z | 2021-11-08T13:00:10.000Z | 41.809973 | 120 | 0.713954 | 9,353 | /*
* 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.nemo.common.ir;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
import org.apache.nemo.common.PairKeyExtractor;
import org.apache.nemo.common.Util;
import org.apache.nemo.common.coder.BytesDecoderFactory;
import org.apache.nemo.common.coder.BytesEncoderFactory;
import org.apache.nemo.common.dag.DAG;
import org.apache.nemo.common.dag.DAGBuilder;
import org.apache.nemo.common.dag.DAGInterface;
import org.apache.nemo.common.exception.CompileTimeOptimizationException;
import org.apache.nemo.common.exception.IllegalEdgeOperationException;
import org.apache.nemo.common.ir.edge.IREdge;
import org.apache.nemo.common.ir.edge.executionproperty.*;
import org.apache.nemo.common.ir.vertex.IRVertex;
import org.apache.nemo.common.ir.vertex.LoopVertex;
import org.apache.nemo.common.ir.vertex.executionproperty.MessageIdVertexProperty;
import org.apache.nemo.common.ir.vertex.executionproperty.ParallelismProperty;
import org.apache.nemo.common.ir.vertex.utility.MessageAggregatorVertex;
import org.apache.nemo.common.ir.vertex.utility.TriggerVertex;
import org.apache.nemo.common.ir.vertex.utility.RelayVertex;
import org.apache.nemo.common.ir.vertex.utility.SamplingVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* An IRDAG object captures a high-level data processing application (e.g., Spark/Beam application).
* - IRVertex: A data-parallel operation. (e.g., map)
* - IREdge: A data dependency between two operations. (e.g., shuffle)
* <p>
* Largely two types of IRDAG optimization(modification) methods are provided.
* All of these methods preserve application semantics.
* - Annotation: setProperty(), getPropertyValue() on each IRVertex/IREdge
* - Reshaping: insert(), delete() on the IRDAG
* <p>
* TODO #341: Rethink IRDAG insert() signatures
*/
@NotThreadSafe
public final class IRDAG implements DAGInterface<IRVertex, IREdge> {
private static final Logger LOG = LoggerFactory.getLogger(IRDAG.class.getName());
private DAG<IRVertex, IREdge> dagSnapshot; // the DAG that was saved most recently.
private DAG<IRVertex, IREdge> modifiedDAG; // the DAG that is being updated.
// To remember original encoders/decoders, and etc
private final Map<RelayVertex, IREdge> streamVertexToOriginalEdge;
// To remember sampling vertex groups
private final Map<SamplingVertex, Set<SamplingVertex>> samplingVertexToGroup;
// To remember message barrier/aggregator vertex groups
private final Map<IRVertex, Set<IRVertex>> messageVertexToGroup;
/**
* @param originalUserApplicationDAG the initial DAG.
*/
public IRDAG(final DAG<IRVertex, IREdge> originalUserApplicationDAG) {
this.modifiedDAG = originalUserApplicationDAG;
this.dagSnapshot = originalUserApplicationDAG;
this.streamVertexToOriginalEdge = new HashMap<>();
this.samplingVertexToGroup = new HashMap<>();
this.messageVertexToGroup = new HashMap<>();
}
public IRDAGChecker.CheckerResult checkIntegrity() {
return IRDAGChecker.get().doCheck(modifiedDAG);
}
//////////////////////////////////////////////////
/**
* Used internally by Nemo to advance the DAG snapshot after applying each pass.
*
* @param checker that compares the dagSnapshot and the modifiedDAG
* to determine if the snapshot can be set the current modifiedDAG.
* @return true if the checker passes, false otherwise.
*/
public boolean advanceDAGSnapshot(final BiFunction<IRDAG, IRDAG, Boolean> checker) {
final boolean canAdvance = checker.apply(new IRDAG(dagSnapshot), new IRDAG(modifiedDAG));
if (canAdvance) {
dagSnapshot = modifiedDAG;
}
return canAdvance;
}
/**
* @return a IR DAG summary string, consisting of only the vertices generated from the frontend.
*/
public String irDAGSummary() {
return "rv" + getRootVertices().size()
+ "_v" + getVertices().stream()
.filter(v -> !v.isUtilityVertex()) // Exclude utility vertices
.count()
+ "_e" + getVertices().stream()
.filter(v -> !v.isUtilityVertex()) // Exclude utility vertices
.mapToInt(v -> getIncomingEdgesOf(v).size())
.sum();
}
////////////////////////////////////////////////// Methods for reshaping the DAG topology.
/**
* Deletes a previously inserted utility vertex.
* (e.g., TriggerVertex, RelayVertex, SamplingVertex)
* <p>
* Notice that the actual number of vertices that will be deleted after this call returns can be more than one.
* We roll back the changes made with the previous insert(), while preserving application semantics.
*
* @param vertexToDelete to delete.
*/
public void delete(final IRVertex vertexToDelete) {
assertExistence(vertexToDelete);
deleteRecursively(vertexToDelete, new HashSet<>());
// Build again, with source/sink checks on
modifiedDAG = rebuildExcluding(modifiedDAG, Collections.emptySet()).build();
}
private Set<IRVertex> getVertexGroupToDelete(final IRVertex vertexToDelete) {
if (vertexToDelete instanceof RelayVertex) {
return Sets.newHashSet(vertexToDelete);
} else if (vertexToDelete instanceof SamplingVertex) {
final Set<SamplingVertex> samplingVertexGroup = samplingVertexToGroup.get(vertexToDelete);
final Set<IRVertex> converted = new HashSet<>(samplingVertexGroup.size());
for (final IRVertex sv : samplingVertexGroup) {
converted.add(sv); // explicit conversion to IRVertex is needed.. otherwise the compiler complains :(
}
return converted;
} else if (vertexToDelete instanceof MessageAggregatorVertex || vertexToDelete instanceof TriggerVertex) {
return messageVertexToGroup.get(vertexToDelete);
} else {
throw new IllegalArgumentException(vertexToDelete.getId());
}
}
/**
* Delete a group of vertex that corresponds to the specified vertex.
* And then recursively delete neighboring utility vertices.
* <p>
* (WARNING) Only call this method inside delete(), or inside this method itself.
* This method uses buildWithoutSourceSinkCheck() for intermediate DAGs,
* which will be finally checked in delete().
*
* @param vertexToDelete to delete
* @param visited vertex groups (because cyclic dependencies between vertex groups are possible)
*/
private void deleteRecursively(final IRVertex vertexToDelete, final Set<IRVertex> visited) {
if (!Util.isUtilityVertex(vertexToDelete)) {
throw new IllegalArgumentException(vertexToDelete.getId());
}
if (visited.contains(vertexToDelete)) {
return;
}
// Three data structures
final Set<IRVertex> vertexGroupToDelete = getVertexGroupToDelete(vertexToDelete);
final Set<IRVertex> utilityParents = vertexGroupToDelete.stream()
.map(modifiedDAG::getIncomingEdgesOf)
.flatMap(inEdgeList -> inEdgeList.stream().map(IREdge::getSrc))
.filter(Util::isUtilityVertex)
.collect(Collectors.toSet());
final Set<IRVertex> utilityChildren = vertexGroupToDelete.stream()
.map(modifiedDAG::getOutgoingEdgesOf)
.flatMap(outEdgeList -> outEdgeList.stream().map(IREdge::getDst))
.filter(Util::isUtilityVertex)
.collect(Collectors.toSet());
// We have 'visited' this group
visited.addAll(vertexGroupToDelete);
// STEP 1: Delete parent utility vertices
// Vertices that are 'in between' the group are also deleted here
Sets.difference(utilityParents, vertexGroupToDelete).forEach(ptd -> deleteRecursively(ptd, visited));
// STEP 2: Delete the specified vertex(vertices)
if (vertexToDelete instanceof RelayVertex) {
final DAGBuilder<IRVertex, IREdge> builder = rebuildExcluding(modifiedDAG, vertexGroupToDelete);
// Add a new edge that directly connects the src of the stream vertex to its dst
modifiedDAG.getOutgoingEdgesOf(vertexToDelete).stream()
.filter(e -> !Util.isControlEdge(e))
.map(IREdge::getDst)
.forEach(dstVertex ->
modifiedDAG.getIncomingEdgesOf(vertexToDelete).stream()
.filter(e -> !Util.isControlEdge(e))
.map(IREdge::getSrc)
.forEach(srcVertex -> builder.connectVertices(
Util.cloneEdge(streamVertexToOriginalEdge.get(vertexToDelete), srcVertex, dstVertex))));
modifiedDAG = builder.buildWithoutSourceSinkCheck();
} else if (vertexToDelete instanceof MessageAggregatorVertex || vertexToDelete instanceof TriggerVertex) {
modifiedDAG = rebuildExcluding(modifiedDAG, vertexGroupToDelete).buildWithoutSourceSinkCheck();
final Optional<Integer> deletedMessageIdOptional = vertexGroupToDelete.stream()
.filter(vtd -> vtd instanceof MessageAggregatorVertex)
.map(vtd -> vtd.getPropertyValue(MessageIdVertexProperty.class).orElseThrow(
() -> new IllegalArgumentException(
"MessageAggregatorVertex " + vtd.getId() + " does not have MessageIdVertexProperty.")))
.findAny();
deletedMessageIdOptional.ifPresent(deletedMessageId ->
modifiedDAG.getEdges().forEach(e ->
e.getPropertyValue(MessageIdEdgeProperty.class).ifPresent(
hashSet -> hashSet.remove(deletedMessageId))));
} else if (vertexToDelete instanceof SamplingVertex) {
modifiedDAG = rebuildExcluding(modifiedDAG, vertexGroupToDelete).buildWithoutSourceSinkCheck();
} else {
throw new IllegalArgumentException(vertexToDelete.getId());
}
// STEP 3: Delete children utility vertices
Sets.difference(utilityChildren, vertexGroupToDelete).forEach(ctd -> deleteRecursively(ctd, visited));
}
private DAGBuilder<IRVertex, IREdge> rebuildExcluding(final DAG<IRVertex, IREdge> dag, final Set<IRVertex> excluded) {
final DAGBuilder<IRVertex, IREdge> builder = new DAGBuilder<>();
dag.getVertices().stream().filter(v -> !excluded.contains(v)).forEach(builder::addVertex);
dag.getEdges().stream().filter(e -> !excluded.contains(e.getSrc()) && !excluded.contains(e.getDst()))
.forEach(builder::connectVertices);
return builder;
}
/**
* Inserts a new vertex that streams data.
* <p>
* Before: src - edgeToStreamize - dst
* After: src - edgeToStreamizeWithNewDestination - relayVertex - oneToOneEdge - dst
* (replaces the "Before" relationships)
* <p>
* This preserves semantics as the relayVertex simply forwards data elements from the input edge to the output edge.
*
* @param relayVertex to insert.
* @param edgeToStreamize to modify.
*/
public void insert(final RelayVertex relayVertex, final IREdge edgeToStreamize) {
assertNonExistence(relayVertex);
assertNonControlEdge(edgeToStreamize);
// Create a completely new DAG with the vertex inserted.
final DAGBuilder<IRVertex, IREdge> builder = new DAGBuilder<>();
// Integrity check
if (edgeToStreamize.getPropertyValue(MessageIdEdgeProperty.class).isPresent()
&& !edgeToStreamize.getPropertyValue(MessageIdEdgeProperty.class).get().isEmpty()) {
throw new CompileTimeOptimizationException(edgeToStreamize.getId() + " has a MessageId, and cannot be removed");
}
// Insert the vertex.
final IRVertex vertexToInsert = wrapSamplingVertexIfNeeded(relayVertex, edgeToStreamize.getSrc());
builder.addVertex(vertexToInsert);
edgeToStreamize.getSrc().getPropertyValue(ParallelismProperty.class)
.ifPresent(p -> vertexToInsert.setProperty(ParallelismProperty.of(p)));
// Build the new DAG to reflect the new topology.
modifiedDAG.topologicalDo(v -> {
builder.addVertex(v); // None of the existing vertices are deleted.
for (final IREdge edge : modifiedDAG.getIncomingEdgesOf(v)) {
if (edge.equals(edgeToStreamize)) {
// MATCH!
// Edge to the relayVertex
final IREdge toSV = new IREdge(
edgeToStreamize.getPropertyValue(CommunicationPatternProperty.class).get(),
edgeToStreamize.getSrc(),
vertexToInsert);
edgeToStreamize.copyExecutionPropertiesTo(toSV);
// Edge from the relayVertex.
final IREdge fromSV = new IREdge(CommunicationPatternProperty.Value.ONE_TO_ONE, vertexToInsert, v);
fromSV.setProperty(EncoderProperty.of(edgeToStreamize.getPropertyValue(EncoderProperty.class).get()));
fromSV.setProperty(DecoderProperty.of(edgeToStreamize.getPropertyValue(DecoderProperty.class).get()));
// Annotations for efficient data transfers - toSV
toSV.setPropertyPermanently(DecoderProperty.of(BytesDecoderFactory.of()));
toSV.setPropertyPermanently(CompressionProperty.of(CompressionProperty.Value.LZ4));
toSV.setPropertyPermanently(DecompressionProperty.of(CompressionProperty.Value.NONE));
// Annotations for efficient data transfers - fromSV
fromSV.setPropertyPermanently(EncoderProperty.of(BytesEncoderFactory.of()));
fromSV.setPropertyPermanently(CompressionProperty.of(CompressionProperty.Value.NONE));
fromSV.setPropertyPermanently(DecompressionProperty.of(CompressionProperty.Value.LZ4));
fromSV.setPropertyPermanently(PartitionerProperty.of(PartitionerProperty.Type.DEDICATED_KEY_PER_ELEMENT));
// Track the new edges.
builder.connectVertices(toSV);
builder.connectVertices(fromSV);
} else {
// NO MATCH, so simply connect vertices as before.
builder.connectVertices(edge);
}
}
});
if (edgeToStreamize.getSrc() instanceof RelayVertex) {
streamVertexToOriginalEdge.put(relayVertex, streamVertexToOriginalEdge.get(edgeToStreamize.getSrc()));
} else if (edgeToStreamize.getDst() instanceof RelayVertex) {
streamVertexToOriginalEdge.put(relayVertex, streamVertexToOriginalEdge.get(edgeToStreamize.getDst()));
} else {
streamVertexToOriginalEdge.put(relayVertex, edgeToStreamize);
}
modifiedDAG = builder.build(); // update the DAG.
}
/**
* Inserts a new vertex that analyzes intermediate data, and triggers a dynamic optimization.
* <p>
* For each edge in edgesToGetStatisticsOf...
* <p>
* Before: src - edge - dst
* After: src - oneToOneEdge(a clone of edge) - triggerVertex -
* shuffleEdge - messageAggregatorVertex - broadcastEdge - dst
* (the "Before" relationships are unmodified)
* <p>
* This preserves semantics as the results of the inserted message vertices are never consumed by the original IRDAG.
* <p>
* TODO #345: Simplify insert(TriggerVertex)
*
* @param triggerVertex to insert.
* @param messageAggregatorVertex to insert.
* @param triggerOutputEncoder to use.
* @param triggerOutputDecoder to use.
* @param edgesToGetStatisticsOf to examine.
* @param edgesToOptimize to optimize.
*/
public void insert(final TriggerVertex triggerVertex,
final MessageAggregatorVertex messageAggregatorVertex,
final EncoderProperty triggerOutputEncoder,
final DecoderProperty triggerOutputDecoder,
final Set<IREdge> edgesToGetStatisticsOf,
final Set<IREdge> edgesToOptimize) {
assertNonExistence(triggerVertex);
assertNonExistence(messageAggregatorVertex);
edgesToGetStatisticsOf.forEach(this::assertNonControlEdge);
edgesToOptimize.forEach(this::assertNonControlEdge);
if (edgesToGetStatisticsOf.stream().map(edge -> edge.getDst().getId()).collect(Collectors.toSet()).size() != 1) {
throw new IllegalArgumentException("Not destined to the same vertex: " + edgesToOptimize.toString());
}
if (edgesToOptimize.stream().map(edge -> edge.getDst().getId()).collect(Collectors.toSet()).size() != 1) {
throw new IllegalArgumentException("Not destined to the same vertex: " + edgesToOptimize.toString());
}
// Create a completely new DAG with the vertex inserted.
final DAGBuilder<IRVertex, IREdge> builder = new DAGBuilder<>();
// All of the existing vertices and edges remain intact
modifiedDAG.topologicalDo(v -> {
builder.addVertex(v);
modifiedDAG.getIncomingEdgesOf(v).forEach(builder::connectVertices);
});
////////////////////////////////// STEP 1: Insert new vertices and edges (src - trigger - agg - dst)
// From src to trigger
final List<IRVertex> triggerList = new ArrayList<>();
for (final IREdge edge : edgesToGetStatisticsOf) {
final IRVertex triggerToAdd = wrapSamplingVertexIfNeeded(
new TriggerVertex<>(triggerVertex.getMessageFunction()), edge.getSrc());
builder.addVertex(triggerToAdd);
triggerList.add(triggerToAdd);
edge.getSrc().getPropertyValue(ParallelismProperty.class)
.ifPresent(p -> triggerToAdd.setProperty(ParallelismProperty.of(p)));
final IREdge edgeToClone;
if (edge.getSrc() instanceof RelayVertex) {
edgeToClone = streamVertexToOriginalEdge.get(edge.getSrc());
} else if (edge.getDst() instanceof RelayVertex) {
edgeToClone = streamVertexToOriginalEdge.get(edge.getDst());
} else {
edgeToClone = edge;
}
final IREdge clone = Util.cloneEdge(
CommunicationPatternProperty.Value.ONE_TO_ONE, edgeToClone, edge.getSrc(), triggerToAdd);
builder.connectVertices(clone);
}
// Add agg (no need to wrap inside sampling vertices)
builder.addVertex(messageAggregatorVertex);
// From trigger to agg
for (final IRVertex trigger : triggerList) {
final IREdge edgeToMav = edgeToMessageAggregator(
trigger, messageAggregatorVertex, triggerOutputEncoder, triggerOutputDecoder);
builder.connectVertices(edgeToMav);
}
// From agg to dst
// Add a control dependency (no output) from the messageAggregatorVertex to the destination.
builder.connectVertices(
Util.createControlEdge(messageAggregatorVertex, edgesToGetStatisticsOf.iterator().next().getDst()));
////////////////////////////////// STEP 2: Annotate the MessageId on optimization target edges
modifiedDAG.topologicalDo(v -> {
modifiedDAG.getIncomingEdgesOf(v).forEach(inEdge -> {
if (edgesToOptimize.contains(inEdge)) {
final HashSet<Integer> msgEdgeIds =
inEdge.getPropertyValue(MessageIdEdgeProperty.class).orElse(new HashSet<>(0));
msgEdgeIds.add(messageAggregatorVertex.getPropertyValue(MessageIdVertexProperty.class).get());
inEdge.setProperty(MessageIdEdgeProperty.of(msgEdgeIds));
}
});
});
final Set<IRVertex> insertedVertices = new HashSet<>();
insertedVertices.addAll(triggerList);
insertedVertices.add(messageAggregatorVertex);
triggerList.forEach(trigger -> messageVertexToGroup.put(trigger, insertedVertices));
messageVertexToGroup.put(messageAggregatorVertex, insertedVertices);
modifiedDAG = builder.build(); // update the DAG.
}
/**
* Inserts a set of samplingVertices that process sampled data.
* <p>
* This method automatically inserts the following three types of edges.
* (1) Edges between samplingVertices to reflect the original relationship
* (2) Edges from the original IRDAG to samplingVertices that clone the inEdges of the original vertices
* (3) Edges from the samplingVertices to the original IRDAG to respect executeAfterSamplingVertices
* <p>
* Suppose the caller supplies the following arguments to perform a "sampled run" of vertices {V1, V2},
* prior to executing them.
* - samplingVertices: {V1', V2'}
* - childrenOfSamplingVertices: {V1}
* <p>
* Before: V1 - oneToOneEdge - V2 - shuffleEdge - V3
* After: V1' - oneToOneEdge - V2' - controlEdge - V1 - oneToOneEdge - V2 - shuffleEdge - V3
* <p>
* This preserves semantics as the original IRDAG remains unchanged and unaffected.
* <p>
* (Future calls to insert() can add new vertices that connect to sampling vertices. Such new vertices will also be
* wrapped with sampling vertices, as new vertices that consume outputs from sampling vertices will process
* a subset of data anyways, and no such new vertex will reach the original DAG except via control edges)
* <p>
* TODO #343: Extend SamplingVertex control edges
*
* @param toInsert sampling vertices.
* @param executeAfter that must be executed after toInsert.
*/
public void insert(final Set<SamplingVertex> toInsert,
final Set<IRVertex> executeAfter) {
toInsert.forEach(this::assertNonExistence);
executeAfter.forEach(this::assertExistence);
// Create a completely new DAG with the vertex inserted.
final DAGBuilder<IRVertex, IREdge> builder = new DAGBuilder<>();
// All of the existing vertices and edges remain intact
modifiedDAG.topologicalDo(v -> {
builder.addVertex(v);
modifiedDAG.getIncomingEdgesOf(v).forEach(builder::connectVertices);
});
// Add the sampling vertices
toInsert.forEach(builder::addVertex);
// Get the original vertices
final Map<IRVertex, IRVertex> originalToSampling = toInsert.stream()
.collect(Collectors.toMap(sv -> modifiedDAG.getVertexById(sv.getOriginalVertexId()), Function.identity()));
final Set<IREdge> inEdgesOfOriginals = originalToSampling.keySet()
.stream()
.flatMap(ov -> modifiedDAG.getIncomingEdgesOf(ov).stream())
.collect(Collectors.toSet());
// [EDGE TYPE 1] Between sampling vertices
final Set<IREdge> betweenOriginals = inEdgesOfOriginals
.stream()
.filter(ovInEdge -> originalToSampling.containsKey(ovInEdge.getSrc()))
.collect(Collectors.toSet());
betweenOriginals.stream().map(boEdge -> Util.cloneEdge(
boEdge,
originalToSampling.get(boEdge.getSrc()),
originalToSampling.get(boEdge.getDst()))).forEach(builder::connectVertices);
// [EDGE TYPE 2] From original IRDAG to sampling vertices
final Set<IREdge> notBetweenOriginals = inEdgesOfOriginals
.stream()
.filter(ovInEdge -> !originalToSampling.containsKey(ovInEdge.getSrc()))
.collect(Collectors.toSet());
notBetweenOriginals.stream().map(nboEdge -> {
final IREdge cloneEdge = Util.cloneEdge(
nboEdge,
nboEdge.getSrc(), // sampling vertices consume a subset of original data partitions here
originalToSampling.get(nboEdge.getDst()));
nboEdge.copyExecutionPropertiesTo(cloneEdge); // exec properties must be exactly the same
return cloneEdge;
}).forEach(builder::connectVertices);
// [EDGE TYPE 3] From sampling vertices to vertices that should be executed after
final Set<IRVertex> sinks = getSinksWithinVertexSet(modifiedDAG, originalToSampling.keySet())
.stream()
.map(originalToSampling::get)
.collect(Collectors.toSet());
for (final IRVertex ea : executeAfter) {
for (final IRVertex sink : sinks) {
// Control edge that enforces execution ordering
builder.connectVertices(Util.createControlEdge(sink, ea));
}
}
toInsert.forEach(tiv -> samplingVertexToGroup.put(tiv, toInsert));
modifiedDAG = builder.build(); // update the DAG.
}
/**
* Reshape unsafely, without guarantees on preserving application semantics.
* TODO #330: Refactor Unsafe Reshaping Passes
*
* @param unsafeReshapingFunction takes as input the underlying DAG, and outputs a reshaped DAG.
*/
public void reshapeUnsafely(final Function<DAG<IRVertex, IREdge>, DAG<IRVertex, IREdge>> unsafeReshapingFunction) {
modifiedDAG = unsafeReshapingFunction.apply(modifiedDAG);
}
////////////////////////////////////////////////// Private helper methods.
private Set<IRVertex> getSinksWithinVertexSet(final DAG<IRVertex, IREdge> dag,
final Set<IRVertex> vertexSet) {
final Set<IRVertex> parentsOfAnotherVertex = vertexSet.stream()
.flatMap(v -> dag.getOutgoingEdgesOf(v).stream())
.filter(e -> vertexSet.contains(e.getDst()))
.map(IREdge::getSrc) // makes the result a subset of the input vertexSet
.collect(Collectors.toSet());
return Sets.difference(vertexSet, parentsOfAnotherVertex);
}
private IRVertex wrapSamplingVertexIfNeeded(final IRVertex newVertex, final IRVertex existingVertexToConnectWith) {
// If the connecting vertex is a sampling vertex, the new vertex must be wrapped inside a sampling vertex too.
return existingVertexToConnectWith instanceof SamplingVertex
? new SamplingVertex(newVertex, ((SamplingVertex) existingVertexToConnectWith).getDesiredSampleRate())
: newVertex;
}
private void assertNonControlEdge(final IREdge e) {
if (Util.isControlEdge(e)) {
throw new IllegalArgumentException(e.getId());
}
}
private void assertExistence(final IRVertex v) {
if (!getVertices().contains(v)) {
throw new IllegalArgumentException(v.getId());
}
}
private void assertNonExistence(final IRVertex v) {
if (getVertices().contains(v)) {
throw new IllegalArgumentException(v.getId());
}
}
/**
* @param trigger src.
* @param agg dst.
* @param encoder src-dst encoder.
* @param decoder src-dst decoder.
* @return the edge.
*/
private IREdge edgeToMessageAggregator(final IRVertex trigger,
final IRVertex agg,
final EncoderProperty encoder,
final DecoderProperty decoder) {
final IREdge newEdge = new IREdge(CommunicationPatternProperty.Value.SHUFFLE, trigger, agg);
newEdge.setProperty(DataStoreProperty.of(DataStoreProperty.Value.LOCAL_FILE_STORE));
newEdge.setProperty(DataPersistenceProperty.of(DataPersistenceProperty.Value.KEEP));
newEdge.setProperty(DataFlowProperty.of(DataFlowProperty.Value.PUSH));
newEdge.setPropertyPermanently(encoder);
newEdge.setPropertyPermanently(decoder);
newEdge.setPropertyPermanently(KeyExtractorProperty.of(new PairKeyExtractor()));
// TODO #345: Simplify insert(TriggerVertex)
// these are obviously wrong, but hacks for now...
newEdge.setPropertyPermanently(KeyEncoderProperty.of(encoder.getValue()));
newEdge.setPropertyPermanently(KeyDecoderProperty.of(decoder.getValue()));
return newEdge;
}
////////////////////////////////////////////////// DAGInterface methods - forward calls to the underlying DAG.
@Override
public void topologicalDo(final Consumer<IRVertex> function) {
modifiedDAG.topologicalDo(function);
}
@Override
public void dfsTraverse(final Consumer<IRVertex> function, final TraversalOrder traversalOrder) {
modifiedDAG.dfsTraverse(function, traversalOrder);
}
@Override
public void dfsDo(final IRVertex vertex,
final Consumer<IRVertex> vertexConsumer,
final TraversalOrder traversalOrder,
final Set<IRVertex> visited) {
modifiedDAG.dfsDo(vertex, vertexConsumer, traversalOrder, visited);
}
@Override
public Boolean pathExistsBetween(final IRVertex v1, final IRVertex v2) {
return modifiedDAG.pathExistsBetween(v1, v2);
}
@Override
public Boolean isCompositeVertex(final IRVertex irVertex) {
return modifiedDAG.isCompositeVertex(irVertex);
}
@Override
public Integer getLoopStackDepthOf(final IRVertex irVertex) {
return modifiedDAG.getLoopStackDepthOf(irVertex);
}
@Override
public LoopVertex getAssignedLoopVertexOf(final IRVertex irVertex) {
return modifiedDAG.getAssignedLoopVertexOf(irVertex);
}
@Override
public ObjectNode asJsonNode() {
return modifiedDAG.asJsonNode();
}
@Override
public void storeJSON(final String directory, final String name, final String description) {
modifiedDAG.storeJSON(directory, name, description);
}
@Override
public IRVertex getVertexById(final String id) {
return modifiedDAG.getVertexById(id);
}
@Override
public IREdge getEdgeById(final String id) {
return modifiedDAG.getEdgeById(id);
}
@Override
public List<IRVertex> getVertices() {
return modifiedDAG.getVertices();
}
@Override
public List<IREdge> getEdges() {
return modifiedDAG.getEdges();
}
@Override
public List<IRVertex> getRootVertices() {
return modifiedDAG.getRootVertices();
}
@Override
public List<IREdge> getIncomingEdgesOf(final IRVertex v) {
return modifiedDAG.getIncomingEdgesOf(v);
}
@Override
public List<IREdge> getIncomingEdgesOf(final String vertexId) {
return modifiedDAG.getIncomingEdgesOf(vertexId);
}
@Override
public List<IREdge> getOutgoingEdgesOf(final IRVertex v) {
return modifiedDAG.getOutgoingEdgesOf(v);
}
@Override
public List<IREdge> getOutgoingEdgesOf(final String vertexId) {
return modifiedDAG.getOutgoingEdgesOf(vertexId);
}
@Override
public List<IRVertex> getParents(final String vertexId) {
return modifiedDAG.getParents(vertexId);
}
@Override
public List<IRVertex> getChildren(final String vertexId) {
return modifiedDAG.getChildren(vertexId);
}
@Override
public IREdge getEdgeBetween(final String srcVertexId,
final String dstVertexId) throws IllegalEdgeOperationException {
return modifiedDAG.getEdgeBetween(srcVertexId, dstVertexId);
}
@Override
public List<IRVertex> getTopologicalSort() {
return modifiedDAG.getTopologicalSort();
}
@Override
public List<IRVertex> getAncestors(final String vertexId) {
return modifiedDAG.getAncestors(vertexId);
}
@Override
public List<IRVertex> getDescendants(final String vertexId) {
return modifiedDAG.getDescendants(vertexId);
}
@Override
public List<IRVertex> filterVertices(final Predicate<IRVertex> condition) {
return modifiedDAG.filterVertices(condition);
}
@Override
public String toString() {
return asJsonNode().toString();
}
}
|
3e15fc3213b162815b6ed12e624a712825879e2d | 1,616 | java | Java | src/main/java/frc/robot/commands/TurretCommands/AimCommand.java | CAVALIER-ROBOTICS/ArtemisCode | ce14ee9c23c0ed2277293a41d341ab2702aa5159 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/TurretCommands/AimCommand.java | CAVALIER-ROBOTICS/ArtemisCode | ce14ee9c23c0ed2277293a41d341ab2702aa5159 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/TurretCommands/AimCommand.java | CAVALIER-ROBOTICS/ArtemisCode | ce14ee9c23c0ed2277293a41d341ab2702aa5159 | [
"BSD-3-Clause"
] | null | null | null | 35.130435 | 89 | 0.676361 | 9,354 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.TurretCommands;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.wpilibj2.command.PIDCommand;
import frc.robot.subsystems.LimelightSubsystem;
import frc.robot.subsystems.TurretSubsystem;
// NOTE: Consider using this command inline, rather than writing a subclass. For more
// information, see:
// https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html
public class AimCommand extends PIDCommand {
/** Creates a new AimCommand. */
public AimCommand(TurretSubsystem turretSub, LimelightSubsystem limeSub) {
super(
// The controller that the command will use
new PIDController(0.01, 0.025 , 0),
// This should return the measurement
limeSub::getX,
// This should return the setpoint (can al6o be a constant)
() -> 0,
// This uses the output
output -> {
// if(turretSub.isTurning()) {
// turretSub.turn();
// }
// else {
// turretSub.setTurret(output);
// }
turretSub.aim(output);
});
// Use addRequirements() here to declare subsystem dependencies.
// Configure additional PID options by calling `getController` here.
addRequirements(turretSub);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}
}
|
3e15fc414c0e9a075c10f89af49ea0bf9d6c2d49 | 939 | java | Java | ServerlessSocialApp/src/main/java/com/ozayduman/socialapp/firends/user/authentication/AuthTokenChecker.java | ozayduman/AWS | 0392f917b43c1353a935163782c43667aa651dc3 | [
"Apache-2.0"
] | null | null | null | ServerlessSocialApp/src/main/java/com/ozayduman/socialapp/firends/user/authentication/AuthTokenChecker.java | ozayduman/AWS | 0392f917b43c1353a935163782c43667aa651dc3 | [
"Apache-2.0"
] | null | null | null | ServerlessSocialApp/src/main/java/com/ozayduman/socialapp/firends/user/authentication/AuthTokenChecker.java | ozayduman/AWS | 0392f917b43c1353a935163782c43667aa651dc3 | [
"Apache-2.0"
] | null | null | null | 29.34375 | 107 | 0.792332 | 9,355 | package com.ozayduman.socialapp.firends.user.authentication;
import java.util.Optional;
import com.amazonaws.util.StringUtils;
import com.ozayduman.socialapp.firends.user.AbstractAuthorizedRequestDTO;
import com.ozayduman.socialapp.firends.user.User;
import com.ozayduman.socialapp.firends.user.dao.UserDao;
public class AuthTokenChecker {
private UserDao userDao;
public AuthTokenChecker(UserDao userDao) {
super();
this.userDao = userDao;
}
public boolean check(AbstractAuthorizedRequestDTO request) {
if(isAuthRequestDataValid(request))
{
return false;
}
Optional<User> user = userDao.findUserByUsername(request.getUsername());
return user.isPresent() && user.get().getOpenIdToken().equals(request.getToken());
}
private boolean isAuthRequestDataValid(AbstractAuthorizedRequestDTO request) {
return StringUtils.isNullOrEmpty(request.getUsername()) || StringUtils.isNullOrEmpty(request.getToken());
}
}
|
3e15fcfae1a4787e910c5e83b2ee69fdaf235993 | 10,381 | java | Java | jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java | xinxing0913/jetty-9.2-note-deprecated | 28cd2b42e141dee8459047776591b0dfc167def9 | [
"Apache-2.0"
] | 3 | 2018-01-26T12:28:09.000Z | 2018-02-01T02:19:38.000Z | jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java | xinxing0913/jetty-note | 28cd2b42e141dee8459047776591b0dfc167def9 | [
"Apache-2.0"
] | 5 | 2021-01-31T21:11:55.000Z | 2021-01-31T21:12:10.000Z | jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/parser/ResponseContentParser.java | cuba-platform/jetty.project | fdca6109cea36decc16f9e2d6366638fb1701256 | [
"Apache-2.0"
] | 1 | 2020-10-27T07:24:10.000Z | 2020-10-27T07:24:10.000Z | 31.64939 | 122 | 0.498025 | 9,356 | //
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.fcgi.parser;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jetty.fcgi.FCGI;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class ResponseContentParser extends StreamContentParser
{
private static final Logger LOG = Log.getLogger(ResponseContentParser.class);
private final Map<Integer, ResponseParser> parsers = new ConcurrentHashMap<>();
private final ClientParser.Listener listener;
public ResponseContentParser(HeaderParser headerParser, ClientParser.Listener listener)
{
super(headerParser, FCGI.StreamType.STD_OUT, listener);
this.listener = listener;
}
@Override
public void noContent()
{
// Does nothing, since for responses the end of content is signaled via a FCGI_END_REQUEST frame
}
@Override
protected boolean onContent(ByteBuffer buffer)
{
int request = getRequest();
ResponseParser parser = parsers.get(request);
if (parser == null)
{
parser = new ResponseParser(listener, request);
parsers.put(request, parser);
}
return parser.parse(buffer);
}
@Override
protected void end(int request)
{
super.end(request);
parsers.remove(request);
}
private class ResponseParser implements HttpParser.ResponseHandler<ByteBuffer>
{
private final HttpFields fields = new HttpFields();
private ClientParser.Listener listener;
private final int request;
private final FCGIHttpParser httpParser;
private State state = State.HEADERS;
private boolean seenResponseCode;
private ResponseParser(ClientParser.Listener listener, int request)
{
this.listener = listener;
this.request = request;
this.httpParser = new FCGIHttpParser(this);
}
public boolean parse(ByteBuffer buffer)
{
if (LOG.isDebugEnabled())
LOG.debug("Response {} {} content {} {}", request, FCGI.StreamType.STD_OUT, state, buffer);
int remaining = buffer.remaining();
while (remaining > 0)
{
switch (state)
{
case HEADERS:
{
if (httpParser.parseNext(buffer))
state = State.CONTENT_MODE;
remaining = buffer.remaining();
break;
}
case CONTENT_MODE:
{
// If we have no indication of the content, then
// the HTTP parser will assume there is no content
// and will not parse it even if it is provided,
// so we have to parse it raw ourselves here.
boolean rawContent = fields.size() == 0 ||
(fields.get(HttpHeader.CONTENT_LENGTH) == null &&
fields.get(HttpHeader.TRANSFER_ENCODING) == null);
state = rawContent ? State.RAW_CONTENT : State.HTTP_CONTENT;
break;
}
case RAW_CONTENT:
{
if (notifyContent(buffer))
return true;
remaining = 0;
break;
}
case HTTP_CONTENT:
{
if (httpParser.parseNext(buffer))
return true;
remaining = buffer.remaining();
break;
}
default:
{
throw new IllegalStateException();
}
}
}
return false;
}
@Override
public int getHeaderCacheSize()
{
// TODO: configure this
return 0;
}
@Override
public boolean startResponse(HttpVersion version, int status, String reason)
{
// The HTTP request line does not exist in FCGI responses
throw new IllegalStateException();
}
@Override
public boolean parsedHeader(HttpField httpField)
{
try
{
String name = httpField.getName();
if ("Status".equalsIgnoreCase(name))
{
if (!seenResponseCode)
{
seenResponseCode = true;
// Need to set the response status so the
// HttpParser can handle the content properly.
String value = httpField.getValue();
String[] parts = value.split(" ");
String status = parts[0];
int code = Integer.parseInt(status);
httpParser.setResponseStatus(code);
String reason = parts.length > 1 ? value.substring(status.length()) : HttpStatus.getMessage(code);
notifyBegin(code, reason.trim());
notifyHeaders(fields);
}
}
else
{
fields.add(httpField);
if (seenResponseCode)
notifyHeader(httpField);
}
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while invoking listener " + listener, x);
}
return false;
}
private void notifyBegin(int code, String reason)
{
try
{
listener.onBegin(request, code, reason);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while invoking listener " + listener, x);
}
}
private void notifyHeader(HttpField httpField)
{
try
{
listener.onHeader(request, httpField);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while invoking listener " + listener, x);
}
}
private void notifyHeaders(HttpFields fields)
{
if (fields != null)
{
for (HttpField field : fields)
notifyHeader(field);
}
}
private void notifyHeaders()
{
try
{
listener.onHeaders(request);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while invoking listener " + listener, x);
}
}
@Override
public boolean headerComplete()
{
if (!seenResponseCode)
{
// No Status header but we have other headers, assume 200 OK
notifyBegin(200, "OK");
notifyHeaders(fields);
}
notifyHeaders();
// Return from parsing so that we can parse the content
return true;
}
@Override
public boolean content(ByteBuffer buffer)
{
return notifyContent(buffer);
}
private boolean notifyContent(ByteBuffer buffer)
{
try
{
return listener.onContent(request, FCGI.StreamType.STD_OUT, buffer);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while invoking listener " + listener, x);
return false;
}
}
@Override
public boolean messageComplete()
{
// Return from parsing so that we can parse the next headers or the raw content.
// No need to notify the listener because it will be done by FCGI_END_REQUEST.
return true;
}
@Override
public void earlyEOF()
{
// TODO
}
@Override
public void badMessage(int status, String reason)
{
// TODO
}
}
// Methods overridden to make them visible here
private static class FCGIHttpParser extends HttpParser
{
private FCGIHttpParser(ResponseHandler<ByteBuffer> handler)
{
super(handler, 65 * 1024, true);
reset();
}
@Override
public void reset()
{
super.reset();
setResponseStatus(200);
setState(State.HEADER);
}
@Override
protected void setResponseStatus(int status)
{
super.setResponseStatus(status);
}
}
private enum State
{
HEADERS, CONTENT_MODE, RAW_CONTENT, HTTP_CONTENT
}
}
|
3e15fd3dce63e0a268f7255fed0e8933712b4b28 | 9,324 | java | Java | ui/cli/mailtransfer/src/java/com/echothree/ui/cli/mailtransfer/util/MailTransferUtility.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | 1 | 2020-09-01T08:39:01.000Z | 2020-09-01T08:39:01.000Z | ui/cli/mailtransfer/src/java/com/echothree/ui/cli/mailtransfer/util/MailTransferUtility.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | null | null | null | ui/cli/mailtransfer/src/java/com/echothree/ui/cli/mailtransfer/util/MailTransferUtility.java | echothreellc/echothree | 1744df7654097cc000e5eca32de127b5dc745302 | [
"Apache-2.0"
] | 1 | 2020-05-31T08:34:46.000Z | 2020-05-31T08:34:46.000Z | 45.043478 | 131 | 0.608215 | 9,357 | // --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.echothree.ui.cli.mailtransfer.util;
import com.echothree.control.user.authentication.common.AuthenticationService;
import com.echothree.control.user.authentication.common.AuthenticationUtil;
import com.echothree.control.user.communication.common.CommunicationService;
import com.echothree.control.user.communication.common.CommunicationUtil;
import com.echothree.control.user.communication.common.form.CommunicationFormFactory;
import com.echothree.control.user.communication.common.form.CreateCommunicationEventForm;
import com.echothree.control.user.communication.common.form.GetCommunicationSourcesForm;
import com.echothree.control.user.communication.common.result.GetCommunicationSourcesResult;
import com.echothree.model.control.communication.common.CommunicationConstants;
import com.echothree.model.control.communication.common.CommunicationOptions;
import com.echothree.model.control.communication.common.transfer.CommunicationEmailSourceTransfer;
import com.echothree.model.control.communication.common.transfer.CommunicationSourceTransfer;
import com.echothree.model.data.user.common.pk.UserVisitPK;
import com.echothree.util.common.command.CommandResult;
import com.echothree.util.common.command.ExecutionResult;
import com.echothree.util.common.persistence.type.ByteArray;
import com.google.common.base.Charsets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.net.SocketException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.naming.NamingException;
import org.apache.commons.net.pop3.POP3;
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MailTransferUtility {
private boolean doVerbose;
public boolean isDoVerbose() {
return doVerbose;
}
public void setDoVerbose(boolean doVerbose) {
this.doVerbose = doVerbose;
}
private static Logger logger = LoggerFactory.getLogger(MailTransferUtility.class);
private UserVisitPK userVisitPK = null;
private AuthenticationService getAuthenticationService()
throws NamingException {
return AuthenticationUtil.getHome();
}
private CommunicationService getCommunicationService()
throws NamingException {
return CommunicationUtil.getHome();
}
private UserVisitPK getUserVisit() {
if(userVisitPK == null) {
try {
userVisitPK = getAuthenticationService().getDataLoaderUserVisit();
} catch (NamingException ne) {
System.err.println("Unable to locate authentication service");
}
}
return userVisitPK;
}
private void clearUserVisit() {
if(userVisitPK != null) {
try {
getAuthenticationService().invalidateUserVisit(userVisitPK);
userVisitPK = null;
} catch (NamingException ne) {
System.err.println("Unable to locate authentication service");
}
userVisitPK = null;
}
}
public void transfer()
throws Exception {
try {
GetCommunicationSourcesForm commandForm = CommunicationFormFactory.getGetCommunicationSourcesForm();
commandForm.setCommunicationSourceTypeName(CommunicationConstants.CommunicationSourceType_EMAIL);
Set<String> options = new HashSet<>();
options.add(CommunicationOptions.CommunicationSourceIncludeRelated);
commandForm.setOptions(options);
CommandResult commandResult = getCommunicationService().getCommunicationSources(getUserVisit(), commandForm);
ExecutionResult executionResult = commandResult.getExecutionResult();
GetCommunicationSourcesResult result = (GetCommunicationSourcesResult)executionResult.getResult();
List<CommunicationSourceTransfer> communicationSources = result.getCommunicationSources();
for(CommunicationSourceTransfer communicationSource: communicationSources) {
transferFromServer(communicationSource);
}
} catch (NamingException ne) {
System.err.println("Unable to locate communication service");
}
clearUserVisit();
}
private void transferFromServer(CommunicationSourceTransfer communicationSource)
throws Exception {
CommunicationEmailSourceTransfer communicationEmailSource = communicationSource.getCommunicationEmailSource();
POP3Client pop3Client = null;
try {
String serverName = communicationEmailSource.getServer().getServerName();
pop3Client = new POP3Client();
pop3Client.connect(serverName);
if(pop3Client.getState() == POP3.AUTHORIZATION_STATE) {
String username = communicationEmailSource.getUsername();
pop3Client.login(username, communicationEmailSource.getPassword());
if(pop3Client.getState() == POP3.TRANSACTION_STATE) {
POP3MessageInfo[] pop3MessageInfos = pop3Client.listMessages();
logger.info("message count: " + pop3MessageInfos.length);
if(pop3MessageInfos.length > 0) {
int successfulMessages = 0;
for(int i = 0; i < pop3MessageInfos.length && successfulMessages < 10; i++) {
POP3MessageInfo pop3MessageInfo = pop3MessageInfos[i];
int messageId = pop3MessageInfo.number;
Reader reader = pop3Client.retrieveMessage(messageId);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
logger.info("message " + pop3MessageInfo.number + ", size = " + pop3MessageInfo.size);
for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
CreateCommunicationEventForm form = CommunicationFormFactory.getCreateCommunicationEventForm();
form.setCommunicationSourceName(communicationSource.getCommunicationSourceName());
form.setCommunicationEventTypeName(CommunicationConstants.CommunicationEventType_EMAIL);
form.setBlobDocument(new ByteArray(stringBuilder.toString().getBytes(Charsets.UTF_8)));
CommandResult commandResult = getCommunicationService().createCommunicationEvent(getUserVisit(), form);
if(!commandResult.hasErrors()) {
successfulMessages++;
pop3Client.deleteMessage(messageId);
} else {
logger.error(commandResult.toString());
}
}
}
pop3Client.logout();
} else {
logger.error("login to " + username + "@" + serverName + " failed");
}
} else {
logger.error("connection to " + serverName + " failed");
}
} catch(SocketException se) {
logger.error("An Exception occurred:", se);
} catch(IOException ioe) {
logger.error("An Exception occurred:", ioe);
} finally {
if(pop3Client != null) {
try {
if(pop3Client.getState() == POP3.TRANSACTION_STATE) {
pop3Client.logout();
}
pop3Client.disconnect();
} catch(IOException ioe) {
logger.error("An Exception occurred:", ioe);
}
}
}
}
}
|
3e15fd8496ffc01f55ef2e982a2d92983a134511 | 2,896 | java | Java | pcgen/code/src/java/plugin/bonustokens/Skill.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | 1 | 2020-01-12T22:28:29.000Z | 2020-01-12T22:28:29.000Z | pcgen/code/src/java/plugin/bonustokens/Skill.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | null | null | null | pcgen/code/src/java/plugin/bonustokens/Skill.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | null | null | null | 24.542373 | 83 | 0.691989 | 9,358 | /*
* Skill.java
* Copyright 2002 (C) Greg Bingleman <lyhxr@example.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Created on December 13, 2002, 9:19 AM
*
* Current Ver: $Revision$
* Last Editor: $Author$
* Last Edited: $Date$
*
*/
package plugin.bonustokens;
import pcgen.cdom.base.Constants;
import pcgen.core.bonus.BonusObj;
import pcgen.rules.context.LoadContext;
import pcgen.rules.persistence.TokenUtilities;
/**
* Handles the BONUS:SKILL token.
*/
public final class Skill extends BonusObj
{
private static final String[] BONUS_TAGS = {"LIST", "ALL"};
private static final Class<pcgen.core.Skill> SKILL_CLASS = pcgen.core.Skill.class;
/**
* Parse the bonus token.
* @see pcgen.core.bonus.BonusObj#parseToken(LoadContext, java.lang.String)
* @return True if successfully parsed.
*/
@Override
protected boolean parseToken(LoadContext context, final String token)
{
for (int i = 0; i < BONUS_TAGS.length; ++i)
{
if (BONUS_TAGS[i].equals(token))
{
addBonusInfo(i);
return true;
}
}
if (token.startsWith("STAT=")
|| token.startsWith(Constants.LST_TYPE_EQUAL))
{
addBonusInfo(token.replace('=', '.'));
}
else
{
addBonusInfo(token);
}
if (!token.equals("LIST") && !token.startsWith("STAT.")
&& !token.equals("%CHOICE") && !token.startsWith("STAT=")
&& !token.equals("%LIST") && !token.equals("%VAR")
&& !token.equals("TYPE=%LIST"))
{
//This is done entirely for the side effects
context.forgetMeNot(TokenUtilities.getReference(context, SKILL_CLASS, token));
}
return true;
}
/**
* Unparse the bonus token.
* @see pcgen.core.bonus.BonusObj#unparseToken(java.lang.Object)
* @param obj The object to unparse
* @return The unparsed string.
*/
@Override
protected String unparseToken(final Object obj)
{
if (obj instanceof Integer)
{
return BONUS_TAGS[(Integer) obj];
}
return (String) obj;
}
/**
* Return the bonus tag handled by this class.
* @return The bonus handled by this class.
*/
@Override
public String getBonusHandled()
{
return "SKILL";
}
/**
* @{inheritdoc}
*/
@Override
protected boolean requiresRealCaseTarget()
{
return true;
}
}
|
3e15fe04334587947f7050ed074ac33af65380ba | 534 | java | Java | hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/index/jpa/IndexTest.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/index/jpa/IndexTest.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/index/jpa/IndexTest.java | lauracristinaes/aula-java | cb8d5b314b65a9914b93f3b5792bc98b548fe260 | [
"Apache-2.0"
] | null | null | null | 24.363636 | 94 | 0.705224 | 9,359 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.annotations.index.jpa;
/**
* @author Strong Liu <nnheo@example.com>
*/
public class IndexTest extends AbstractJPAIndexTest {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
Car.class,
Dealer.class,
Importer.class
};
}
}
|
3e15feee3ec26408158d9c95a89a54eee6f789b0 | 409 | java | Java | scorpio-security-starter/src/main/java/top/jshanet/scorpio/security/autoconfig/properties/ScorpioSecurityProperties.java | jshanet/scorpio | 476f99c1b561460b7326fd7c6023baa381e5e939 | [
"MIT"
] | 1 | 2020-08-24T15:13:05.000Z | 2020-08-24T15:13:05.000Z | scorpio-security-starter/src/main/java/top/jshanet/scorpio/security/autoconfig/properties/ScorpioSecurityProperties.java | jshanet/scorpio | 476f99c1b561460b7326fd7c6023baa381e5e939 | [
"MIT"
] | null | null | null | scorpio-security-starter/src/main/java/top/jshanet/scorpio/security/autoconfig/properties/ScorpioSecurityProperties.java | jshanet/scorpio | 476f99c1b561460b7326fd7c6023baa381e5e939 | [
"MIT"
] | null | null | null | 20.45 | 75 | 0.809291 | 9,360 | package top.jshanet.scorpio.security.autoconfig.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author seanjiang
* @since 2020-04-23
*/
@Setter
@Getter
@ConfigurationProperties(prefix="scorpio.security")
public class ScorpioSecurityProperties {
}
|
3e160086ec46ed2fff98036ce63a8b5461322c9a | 471 | java | Java | spring-lihongjie/spring-security-tutorial/spring-security-docs/src/main/java/com/lihongjie/spring/security/docs/controller/SpringSecurityDocsController.java | lihongjie/tutorials | afa839b0fe0350e33bb46fd42b8f26808f54377e | [
"MIT"
] | null | null | null | spring-lihongjie/spring-security-tutorial/spring-security-docs/src/main/java/com/lihongjie/spring/security/docs/controller/SpringSecurityDocsController.java | lihongjie/tutorials | afa839b0fe0350e33bb46fd42b8f26808f54377e | [
"MIT"
] | 1 | 2018-04-01T06:27:14.000Z | 2018-04-01T06:27:14.000Z | spring-lihongjie/spring-security-tutorial/spring-security-docs/src/main/java/com/lihongjie/spring/security/docs/controller/SpringSecurityDocsController.java | lihongjie/tutorials | afa839b0fe0350e33bb46fd42b8f26808f54377e | [
"MIT"
] | null | null | null | 24.789474 | 107 | 0.789809 | 9,361 | package com.lihongjie.spring.security.docs.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class SpringSecurityDocsController {
@RequestMapping(value = "/docs/spring-security/4.1.2.RELEASE/reference/html/", method = RequestMethod.GET)
public String doc412RELEASE() {
return "4.1.2.RELEASE";
}
}
|
3e1601055ad14de511b3ccdc8d5a82264a217293 | 913 | java | Java | src/strings/ValidPalindrome.java | cool-dude/leetcode | 87bfed73dbdc058f191ab5d4a2f55e2ce602e5cb | [
"MIT"
] | null | null | null | src/strings/ValidPalindrome.java | cool-dude/leetcode | 87bfed73dbdc058f191ab5d4a2f55e2ce602e5cb | [
"MIT"
] | null | null | null | src/strings/ValidPalindrome.java | cool-dude/leetcode | 87bfed73dbdc058f191ab5d4a2f55e2ce602e5cb | [
"MIT"
] | null | null | null | 27.666667 | 94 | 0.576123 | 9,362 | /*LC125:Valid Palindrome
https://leetcode.com/problems/valid-palindrome/
Given a string, determine if it is a palindrome,
* considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem,
* we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
* Example 2:
Input: "race a car"
Output: false*/
class Sln {
public boolean isPalindrome(String s) {
int l=0,r=s.length()-1;
while(l<s.length() && r>=0 && l<r){
if(!Character.isLetterOrDigit(s.charAt(l)))
l++;
else if(!Character.isLetterOrDigit(s.charAt(r)))
r--;
else if(Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))){
l++;
r--;
}
else
return false;
}
return true;
}
} |
3e160162547b746638e8e93f13c1ffefd486f2f4 | 1,459 | java | Java | src/main/java/com/hp/autonomy/types/requests/idol/actions/tags/params/GetQueryTagValuesParams.java | hpautonomy/java-aci-types | 35e806adaca8efde14a8075a3e3120b29ab4d253 | [
"MIT"
] | null | null | null | src/main/java/com/hp/autonomy/types/requests/idol/actions/tags/params/GetQueryTagValuesParams.java | hpautonomy/java-aci-types | 35e806adaca8efde14a8075a3e3120b29ab4d253 | [
"MIT"
] | 1 | 2020-06-16T10:41:56.000Z | 2020-06-16T10:41:56.000Z | src/main/java/com/hp/autonomy/types/requests/idol/actions/tags/params/GetQueryTagValuesParams.java | hpautonomy/java-aci-types | 35e806adaca8efde14a8075a3e3120b29ab4d253 | [
"MIT"
] | 4 | 2017-07-18T04:29:45.000Z | 2017-07-31T15:26:07.000Z | 29.77551 | 82 | 0.708019 | 9,363 | /*
* (c) Copyright 2015-2016 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.types.requests.idol.actions.tags.params;
public enum GetQueryTagValuesParams {
AllowNonParametricFields,
CustomWeight,
DateOffset,
DatePeriod,
DocumentCount,
FieldDependence,
FieldDependenceMultiLevel,
FieldName,
MaxValues,
Merge,
Predict,
Ranges,
RestrictedValues,
Sort,
Start,
Synchronous,
TotalValues,
ValueDetails,
ValuePercentiles,
ValueRestriction;
public static GetQueryTagValuesParams fromValue(final String value) {
for (final GetQueryTagValuesParams param : values()) {
if (param.name().equalsIgnoreCase(value)) {
return param;
}
}
throw new IllegalArgumentException("Unknown parameter " + value);
}
}
|
3e1601f4dc885227b7ea7ee55a93bc6bbfbf66fd | 8,372 | java | Java | terminalapp/android/support/design/internal/BottomNavigationItemView.java | ydong08/GooglePay_AP | 8063f2946cb74a070f2009cefae29887bfae0dbb | [
"MIT"
] | null | null | null | terminalapp/android/support/design/internal/BottomNavigationItemView.java | ydong08/GooglePay_AP | 8063f2946cb74a070f2009cefae29887bfae0dbb | [
"MIT"
] | null | null | null | terminalapp/android/support/design/internal/BottomNavigationItemView.java | ydong08/GooglePay_AP | 8063f2946cb74a070f2009cefae29887bfae0dbb | [
"MIT"
] | null | null | null | 40.25 | 117 | 0.674869 | 9,364 | package android.support.design.internal;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.support.design.R;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.PointerIconCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.view.menu.MenuItemImpl;
import android.support.v7.view.menu.MenuView.ItemView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
public class BottomNavigationItemView extends FrameLayout implements ItemView {
private static final int[] CHECKED_STATE_SET = new int[]{16842912};
private final int mDefaultMargin;
private ImageView mIcon;
private ColorStateList mIconTint;
private MenuItemImpl mItemData;
private int mItemPosition;
private final TextView mLargeLabel;
private final float mScaleDownFactor;
private final float mScaleUpFactor;
private final int mShiftAmount;
private boolean mShiftingMode;
private final TextView mSmallLabel;
public BottomNavigationItemView(Context context) {
this(context, null);
}
public BottomNavigationItemView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public BottomNavigationItemView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.mItemPosition = -1;
Resources resources = getResources();
int dimensionPixelSize = resources.getDimensionPixelSize(R.dimen.design_bottom_navigation_text_size);
int dimensionPixelSize2 = resources.getDimensionPixelSize(R.dimen.design_bottom_navigation_active_text_size);
this.mDefaultMargin = resources.getDimensionPixelSize(R.dimen.design_bottom_navigation_margin);
this.mShiftAmount = dimensionPixelSize - dimensionPixelSize2;
this.mScaleUpFactor = (((float) dimensionPixelSize2) * 1.0f) / ((float) dimensionPixelSize);
this.mScaleDownFactor = (((float) dimensionPixelSize) * 1.0f) / ((float) dimensionPixelSize2);
LayoutInflater.from(context).inflate(R.layout.design_bottom_navigation_item, this, true);
setBackgroundResource(R.drawable.design_bottom_navigation_item_background);
this.mIcon = (ImageView) findViewById(R.id.icon);
this.mSmallLabel = (TextView) findViewById(R.id.smallLabel);
this.mLargeLabel = (TextView) findViewById(R.id.largeLabel);
}
public void initialize(MenuItemImpl menuItemImpl, int i) {
this.mItemData = menuItemImpl;
setCheckable(menuItemImpl.isCheckable());
setChecked(menuItemImpl.isChecked());
setEnabled(menuItemImpl.isEnabled());
setIcon(menuItemImpl.getIcon());
setTitle(menuItemImpl.getTitle());
setId(menuItemImpl.getItemId());
}
public void setItemPosition(int i) {
this.mItemPosition = i;
}
public int getItemPosition() {
return this.mItemPosition;
}
public void setShiftingMode(boolean z) {
this.mShiftingMode = z;
}
public MenuItemImpl getItemData() {
return this.mItemData;
}
public void setTitle(CharSequence charSequence) {
this.mSmallLabel.setText(charSequence);
this.mLargeLabel.setText(charSequence);
}
public void setCheckable(boolean z) {
refreshDrawableState();
}
public void setChecked(boolean z) {
ViewCompat.setPivotX(this.mLargeLabel, (float) (this.mLargeLabel.getWidth() / 2));
ViewCompat.setPivotY(this.mLargeLabel, (float) this.mLargeLabel.getBaseline());
ViewCompat.setPivotX(this.mSmallLabel, (float) (this.mSmallLabel.getWidth() / 2));
ViewCompat.setPivotY(this.mSmallLabel, (float) this.mSmallLabel.getBaseline());
LayoutParams layoutParams;
if (this.mShiftingMode) {
if (z) {
layoutParams = (LayoutParams) this.mIcon.getLayoutParams();
layoutParams.gravity = 49;
layoutParams.topMargin = this.mDefaultMargin;
this.mIcon.setLayoutParams(layoutParams);
this.mLargeLabel.setVisibility(0);
ViewCompat.setScaleX(this.mLargeLabel, 1.0f);
ViewCompat.setScaleY(this.mLargeLabel, 1.0f);
} else {
layoutParams = (LayoutParams) this.mIcon.getLayoutParams();
layoutParams.gravity = 17;
layoutParams.topMargin = this.mDefaultMargin;
this.mIcon.setLayoutParams(layoutParams);
this.mLargeLabel.setVisibility(4);
ViewCompat.setScaleX(this.mLargeLabel, 0.5f);
ViewCompat.setScaleY(this.mLargeLabel, 0.5f);
}
this.mSmallLabel.setVisibility(4);
} else if (z) {
layoutParams = (LayoutParams) this.mIcon.getLayoutParams();
layoutParams.gravity = 49;
layoutParams.topMargin = this.mDefaultMargin + this.mShiftAmount;
this.mIcon.setLayoutParams(layoutParams);
this.mLargeLabel.setVisibility(0);
this.mSmallLabel.setVisibility(4);
ViewCompat.setScaleX(this.mLargeLabel, 1.0f);
ViewCompat.setScaleY(this.mLargeLabel, 1.0f);
ViewCompat.setScaleX(this.mSmallLabel, this.mScaleUpFactor);
ViewCompat.setScaleY(this.mSmallLabel, this.mScaleUpFactor);
} else {
layoutParams = (LayoutParams) this.mIcon.getLayoutParams();
layoutParams.gravity = 49;
layoutParams.topMargin = this.mDefaultMargin;
this.mIcon.setLayoutParams(layoutParams);
this.mLargeLabel.setVisibility(4);
this.mSmallLabel.setVisibility(0);
ViewCompat.setScaleX(this.mLargeLabel, this.mScaleDownFactor);
ViewCompat.setScaleY(this.mLargeLabel, this.mScaleDownFactor);
ViewCompat.setScaleX(this.mSmallLabel, 1.0f);
ViewCompat.setScaleY(this.mSmallLabel, 1.0f);
}
refreshDrawableState();
}
public void setEnabled(boolean z) {
super.setEnabled(z);
this.mSmallLabel.setEnabled(z);
this.mLargeLabel.setEnabled(z);
this.mIcon.setEnabled(z);
if (z) {
ViewCompat.setPointerIcon(this, PointerIconCompat.getSystemIcon(getContext(), 1002));
} else {
ViewCompat.setPointerIcon(this, null);
}
}
public int[] onCreateDrawableState(int i) {
int[] onCreateDrawableState = super.onCreateDrawableState(i + 1);
if (this.mItemData != null && this.mItemData.isCheckable() && this.mItemData.isChecked()) {
mergeDrawableStates(onCreateDrawableState, CHECKED_STATE_SET);
}
return onCreateDrawableState;
}
public void setShortcut(boolean z, char c) {
}
public void setIcon(Drawable drawable) {
if (drawable != null) {
ConstantState constantState = drawable.getConstantState();
if (constantState != null) {
drawable = constantState.newDrawable();
}
drawable = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTintList(drawable, this.mIconTint);
}
this.mIcon.setImageDrawable(drawable);
}
public boolean prefersCondensedTitle() {
return false;
}
public void setIconTintList(ColorStateList colorStateList) {
this.mIconTint = colorStateList;
if (this.mItemData != null) {
setIcon(this.mItemData.getIcon());
}
}
public void setTextColor(ColorStateList colorStateList) {
this.mSmallLabel.setTextColor(colorStateList);
this.mLargeLabel.setTextColor(colorStateList);
}
public void setItemBackground(int i) {
Drawable drawable;
if (i == 0) {
drawable = null;
} else {
drawable = ContextCompat.getDrawable(getContext(), i);
}
ViewCompat.setBackground(this, drawable);
}
}
|
3e160246d62f21e6fa2f1a54f78db7999fda1725 | 546 | java | Java | boot-service/src/main/java/com/xwbing/service/domain/entity/vo/SysAuthVo.java | xiangwbs/springboot | ab1c3e0ed9db44c2b1da710f94f2c1cd9438bbcc | [
"Apache-2.0"
] | 230 | 2018-07-10T10:40:52.000Z | 2020-02-28T08:23:00.000Z | boot-service/src/main/java/com/xwbing/service/domain/entity/vo/SysAuthVo.java | xiangwbs/springboot | ab1c3e0ed9db44c2b1da710f94f2c1cd9438bbcc | [
"Apache-2.0"
] | 8 | 2018-07-13T07:16:12.000Z | 2022-03-14T01:30:38.000Z | boot-service/src/main/java/com/xwbing/service/domain/entity/vo/SysAuthVo.java | xiangwbs/springboot | ab1c3e0ed9db44c2b1da710f94f2c1cd9438bbcc | [
"Apache-2.0"
] | 82 | 2018-07-12T02:55:10.000Z | 2022-03-11T08:09:18.000Z | 20.222222 | 70 | 0.725275 | 9,365 | package com.xwbing.service.domain.entity.vo;
import com.xwbing.service.domain.entity.sys.SysAuthority;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import java.util.List;
/**
* 创建时间: 2017/11/14 15:43
* 作者: xiangwb
* 说明: 权限树信息
*/
@Data
public class SysAuthVo extends SysAuthority {
private static final long serialVersionUID = 2292744062645600313L;
public SysAuthVo() {
}
public SysAuthVo(SysAuthority orig) {
BeanUtils.copyProperties(orig, this);
}
private List<SysAuthVo> children;
}
|
3e16031d83d877c804f5ca49cd85ad8a4b51b3ea | 979 | java | Java | das-20200116/java/src/main/java/com/aliyun/das20200116/models/CreateDiagnosticReportRequest.java | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | das-20200116/java/src/main/java/com/aliyun/das20200116/models/CreateDiagnosticReportRequest.java | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | das-20200116/java/src/main/java/com/aliyun/das20200116/models/CreateDiagnosticReportRequest.java | alibabacloud-sdk-swift/alibabacloud-sdk | afd43b41530abb899076a34ceb96bdef55f74460 | [
"Apache-2.0"
] | null | null | null | 22.767442 | 102 | 0.701736 | 9,366 | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.das20200116.models;
import com.aliyun.tea.*;
public class CreateDiagnosticReportRequest extends TeaModel {
@NameInMap("Uid")
public String uid;
@NameInMap("accessKey")
public String accessKey;
@NameInMap("signature")
public String signature;
@NameInMap("timestamp")
public String timestamp;
@NameInMap("__context")
public String context;
@NameInMap("skipAuth")
public String skipAuth;
@NameInMap("UserId")
public String userId;
@NameInMap("DBInstanceId")
public String DBInstanceId;
@NameInMap("StartTime")
public String startTime;
@NameInMap("EndTime")
public String endTime;
public static CreateDiagnosticReportRequest build(java.util.Map<String, ?> map) throws Exception {
CreateDiagnosticReportRequest self = new CreateDiagnosticReportRequest();
return TeaModel.build(map, self);
}
}
|
3e1603d27c633c30f6c97b5302e21aca570a77d4 | 1,415 | java | Java | modules/federation/src/main/java/org/picketlink/identity/federation/ws/trust/SimpleAnyType.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 77 | 2015-01-04T09:34:46.000Z | 2022-02-18T10:53:09.000Z | modules/federation/src/main/java/org/picketlink/identity/federation/ws/trust/SimpleAnyType.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 47 | 2015-01-05T17:01:28.000Z | 2019-06-10T13:40:51.000Z | modules/federation/src/main/java/org/picketlink/identity/federation/ws/trust/SimpleAnyType.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 74 | 2015-01-06T13:49:55.000Z | 2022-02-02T09:48:32.000Z | 28.44 | 108 | 0.689873 | 9,367 | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.picketlink.identity.federation.ws.trust;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author ychag@example.com
* @since Jun 16, 2011
*/
public class SimpleAnyType implements SimpleCollectionUsage<Object> {
protected List<Object> any = new ArrayList<Object>();
/**
* Gets the value of the any property.
*
* <p>
* Objects of the following type(s) are allowed in the list {@link Object } {@link org.w3c.dom.Element }
*/
public List<Object> getAny() {
return Collections.unmodifiableList(this.any);
}
public void add(Object t) {
this.any.add(t);
}
public boolean remove(Object t) {
return any.remove(t);
}
} |
3e1603f2c66e99ad94e738d551a5098640dc37b9 | 6,127 | java | Java | Mpgenerator.java | lyunsen/Proj1 | eb80e73eac7facbefe6df9457a730db0b8f22b64 | [
"Apache-2.0"
] | null | null | null | Mpgenerator.java | lyunsen/Proj1 | eb80e73eac7facbefe6df9457a730db0b8f22b64 | [
"Apache-2.0"
] | null | null | null | Mpgenerator.java | lyunsen/Proj1 | eb80e73eac7facbefe6df9457a730db0b8f22b64 | [
"Apache-2.0"
] | null | null | null | 39.025478 | 90 | 0.579892 | 9,368 | package codeGenerator;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* Created by ZhiYu on 2018/3/14.
*/
public class Mpgenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("src\\test");
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
// .setKotlin(true) 是否生成 kotlin 代码
gc.setAuthor("ZhiYu");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
gc.setServiceName("%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.SQL_SERVER);
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dsc.setUsername("sa");
dsc.setPassword("1q2w3e4rQ");
dsc.setUrl("jdbc:sqlserver://192.168.15.41:1433;DatabaseName=d0");
mpg.setDataSource(dsc);
// dsc.setDriverName("com.mysql.jdbc.Driver");
// dsc.setUsername("root");
// dsc.setPassword("root");
// dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8");
// mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
// strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
// strategy.setInclude(new String[] { "user" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定义实体父类
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定义实体,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定义 mapper 父类
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.vcyber");
pc.setModuleName("ccqc");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
// InjectionConfig cfg = new InjectionConfig() {
// @Override
// public void initMap() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
// this.setMap(map);
// }
// };
// 自定义 xxList.jsp 生成
// List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// focList.add(new FileOutConfig("/template/list.jsp.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) {
// // 自定义输入文件名称
// return "D://codeGenerator/my_" + tableInfo.getEntityName() + ".jsp";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg);
// 调整 xml 生成目录演示
// focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
// @Override
// public String outputFile(TableInfo tableInfo) {
// return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
// }
// });
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg);
// 关闭默认 xml 生成,调整生成 至 根目录
TemplateConfig tc = new TemplateConfig();
// tc.setXml(null);
mpg.setTemplate(tc);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
// mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
|
3e16042d7f97b4a77b2e21a9c2f26113357d93ef | 2,618 | java | Java | weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java | fjarcticfox/weixin-java-tools | 8db9ca299b4a75551125a4b48dbaad05f5c60895 | [
"Apache-2.0"
] | 15 | 2019-08-24T10:23:19.000Z | 2021-09-08T06:44:14.000Z | weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java | apple006/weixin-java-tools | 361c696374c2156d4bf3343475cc675482340cee | [
"Apache-2.0"
] | 11 | 2020-11-16T20:24:44.000Z | 2022-02-01T00:56:00.000Z | weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java | apple006/weixin-java-tools | 361c696374c2156d4bf3343475cc675482340cee | [
"Apache-2.0"
] | 4 | 2019-04-20T04:28:30.000Z | 2021-01-16T20:55:38.000Z | 36.873239 | 79 | 0.752483 | 9,369 | package me.chanjar.weixin.mp.demo;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceApacheHttpClientImpl;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.io.IOException;
import java.io.InputStream;
public class WxMpDemoServer {
private static WxMpConfigStorage wxMpConfigStorage;
private static WxMpService wxMpService;
private static WxMpMessageRouter wxMpMessageRouter;
public static void main(String[] args) throws Exception {
initWeixin();
Server server = new Server(8080);
ServletHandler servletHandler = new ServletHandler();
server.setHandler(servletHandler);
ServletHolder endpointServletHolder = new ServletHolder(
new WxMpEndpointServlet(wxMpConfigStorage, wxMpService,
wxMpMessageRouter));
servletHandler.addServletWithMapping(endpointServletHolder, "/*");
ServletHolder oauthServletHolder = new ServletHolder(
new WxMpOAuth2Servlet(wxMpService));
servletHandler.addServletWithMapping(oauthServletHolder, "/oauth2/*");
server.start();
server.join();
}
private static void initWeixin() {
try (InputStream is1 = ClassLoader
.getSystemResourceAsStream("test-config.xml")) {
WxMpDemoInMemoryConfigStorage config = WxMpDemoInMemoryConfigStorage
.fromXml(is1);
wxMpConfigStorage = config;
wxMpService = new WxMpServiceApacheHttpClientImpl();
wxMpService.setWxMpConfigStorage(config);
WxMpMessageHandler logHandler = new DemoLogHandler();
WxMpMessageHandler textHandler = new DemoTextHandler();
WxMpMessageHandler imageHandler = new DemoImageHandler();
WxMpMessageHandler oauth2handler = new DemoOAuth2Handler();
DemoGuessNumberHandler guessNumberHandler = new DemoGuessNumberHandler();
wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
wxMpMessageRouter.rule().handler(logHandler).next().rule()
.msgType(WxConsts.XML_MSG_TEXT).matcher(guessNumberHandler)
.handler(guessNumberHandler).end().rule().async(false).content("哈哈")
.handler(textHandler).end().rule().async(false).content("图片")
.handler(imageHandler).end().rule().async(false).content("oauth")
.handler(oauth2handler).end();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3e1604de7747abfce382f605bc94a723f26dc0e0 | 667 | java | Java | src/main/java/com/chizganov/puzzlers/hackerrank/algorithms/MaxArraySum.java | chizganov/puzzlers | b0e76fa2a1938337806b0910b756590b0a9ed4e4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chizganov/puzzlers/hackerrank/algorithms/MaxArraySum.java | chizganov/puzzlers | b0e76fa2a1938337806b0910b756590b0a9ed4e4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chizganov/puzzlers/hackerrank/algorithms/MaxArraySum.java | chizganov/puzzlers | b0e76fa2a1938337806b0910b756590b0a9ed4e4 | [
"Apache-2.0"
] | null | null | null | 23.821429 | 100 | 0.535232 | 9,370 | package com.chizganov.puzzlers.hackerrank.algorithms;
/**
* <a href="https://www.hackerrank.com/challenges/max-array-sum/problem">Max Array Sum challenge</a>
*
* @author Ev Chizganov
*/
class MaxArraySum {
int maxSubsetSum(int[] arr) {
int n = arr.length;
int[] maxSum = new int[n];
maxSum[n - 1] = arr[n - 1];
if (n >= 2) maxSum[n - 2] = Math.max(arr[n - 2], maxSum[n - 1]);
for (int i = n - 3; i >= 0; i--)
maxSum[i] = max(arr[i], arr[i] + maxSum[i + 2], maxSum[i + 1]);
return maxSum[0];
}
private int max(int a, int b, int c) {
return Math.max(Math.max(a, b), c);
}
}
|
3e16057f554fb421c69debbf51c3d48d6c83b264 | 398 | java | Java | app/src/main/java/com/marc0x71/mydagger1app/provider/ResourceProvider.java | marc0x71/MyDagger1App | 7f81f9927e9a17ea735ba6ea3c0faa877884e5ee | [
"Apache-2.0"
] | 1 | 2016-03-08T22:33:36.000Z | 2016-03-08T22:33:36.000Z | app/src/main/java/com/marc0x71/mydagger1app/provider/ResourceProvider.java | marc0x71/MyDagger1App | 7f81f9927e9a17ea735ba6ea3c0faa877884e5ee | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/marc0x71/mydagger1app/provider/ResourceProvider.java | marc0x71/MyDagger1App | 7f81f9927e9a17ea735ba6ea3c0faa877884e5ee | [
"Apache-2.0"
] | null | null | null | 18.952381 | 60 | 0.698492 | 9,371 | package com.marc0x71.mydagger1app.provider;
import android.content.Context;
/**
* Created by marc0x71 on 03/03/2016.
*/
public class ResourceProvider implements IResourceProvider {
Context context;
public ResourceProvider(Context context) {
this.context = context;
}
@Override
public String getString(int resId) {
return context.getString(resId);
}
}
|
3e1605ae021328a1521fb4ac35b722a360ce02ad | 7,718 | java | Java | server/talk-turn/src/main/java/org/jitsi/turnserver/listeners/ConnectionAttemptIndicationListener.java | ccfish86/sctalk | aa5b8d185d180b841c17d452a75d16821d96a3bc | [
"Apache-2.0"
] | 168 | 2017-05-20T15:33:27.000Z | 2022-03-03T04:03:59.000Z | server/talk-turn/src/main/java/org/jitsi/turnserver/listeners/ConnectionAttemptIndicationListener.java | tanbinh123/sctalk | aa5b8d185d180b841c17d452a75d16821d96a3bc | [
"Apache-2.0"
] | 9 | 2017-07-05T09:48:36.000Z | 2021-08-06T06:55:09.000Z | server/talk-turn/src/main/java/org/jitsi/turnserver/listeners/ConnectionAttemptIndicationListener.java | tanbinh123/sctalk | aa5b8d185d180b841c17d452a75d16821d96a3bc | [
"Apache-2.0"
] | 94 | 2017-05-20T15:50:15.000Z | 2022-03-25T03:45:15.000Z | 46.215569 | 100 | 0.61376 | 9,372 | /*
* TurnServer, the OpenSource Java Solution for TURN protocol. Maintained by the Jitsi community
* (http://jitsi.org).
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.jitsi.turnserver.listeners;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.ice4j.StunException;
import org.ice4j.StunMessageEvent;
import org.ice4j.Transport;
import org.ice4j.TransportAddress;
import org.ice4j.attribute.Attribute;
import org.ice4j.attribute.ConnectionIdAttribute;
import org.ice4j.attribute.XorPeerAddressAttribute;
import org.ice4j.message.Indication;
import org.ice4j.message.Message;
import org.ice4j.message.MessageFactory;
import org.ice4j.message.Request;
import org.ice4j.socket.IceTcpSocketWrapper;
import org.ice4j.stack.RawMessage;
import org.ice4j.stack.TransactionID;
import org.ice4j.stunclient.BlockingRequestSender;
import org.jitsi.turnserver.IndicationListener;
import org.jitsi.turnserver.stack.Allocation;
import org.jitsi.turnserver.stack.TurnStack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to handle events when a Connection Attempt Indication is received on CLient Side.
*
* @author Aakash Garg
*
*/
public class ConnectionAttemptIndicationListener extends IndicationListener {
/**
* The <tt>Logger</tt> used by the <tt>DataIndicationListener</tt> class and its instances for
* logging output.
*/
private static final Logger logger =
LoggerFactory.getLogger(ConnectionAttemptIndicationListener.class.getName());
/**
* The request sender to use to send request to Turn server.
*/
private BlockingRequestSender requestSender;
/**
* Constructor to create a ConnectionAttemptIndicationListener with specified turnStack to use
* the requestSender will be null and a new {@link BlockingRequestSender} will be created with
* new TCP socket to send request to server.
*
* @param turnStack the turnStack to use for processing.
*/
public ConnectionAttemptIndicationListener(TurnStack turnStack) {
super(turnStack);
}
/**
* Constructor to create a ConnectionAttemptIndicationListener with specified turnStack to use.
*
* @param turnStack the turnStack to use for processing.
* @param requestSender the requestSender to use to send request to server.
*/
public ConnectionAttemptIndicationListener(TurnStack turnStack,
BlockingRequestSender requestSender) {
super(turnStack);
this.requestSender = requestSender;
}
/**
* The method to handle the incoming ConnectionAttempt Indications from Turn Server.
*/
@Override
public void handleIndication(Indication ind, Allocation alloc) {
if (ind.getMessageType() == Message.CONNECTION_ATTEMPT_INDICATION) {
logger.trace("Received a connection attempt indication.");
byte[] tranId = ind.getTransactionID();
ConnectionIdAttribute connectionId =
(ConnectionIdAttribute) ind.getAttribute(Attribute.CONNECTION_ID);
XorPeerAddressAttribute peerAddress =
(XorPeerAddressAttribute) ind.getAttribute(Attribute.XOR_PEER_ADDRESS);
peerAddress.setAddress(peerAddress.getAddress(), tranId);
logger.trace("Received a Connection Attempt Indication with connectionId-"
+ connectionId.getConnectionIdValue() + ", for peerAddress-"
+ peerAddress.getAddress());
Socket socket;
try {
socket = new Socket(InetAddress.getLocalHost().getHostAddress(), 3478);
IceTcpSocketWrapper sockWrapper = new IceTcpSocketWrapper(socket);
this.getTurnStack().addSocket(sockWrapper);
TransportAddress localAddr = new TransportAddress(sockWrapper.getLocalAddress(),
sockWrapper.getLocalPort(), Transport.TCP);
logger.trace("New Local TCP socket chosen - " + localAddr);
TransportAddress serverAddress =
new TransportAddress(InetAddress.getLocalHost(), 3478, Transport.TCP);
StunMessageEvent evt = null;
try {
Request connectionBindRequest = MessageFactory
.createConnectionBindRequest(connectionId.getConnectionIdValue());
TransactionID tranID = TransactionID.createNewTransactionID();
connectionBindRequest.setTransactionID(tranID.getBytes());
if (this.requestSender == null) {
logger.trace("Setting RequestSender");
this.requestSender =
new BlockingRequestSender(this.getTurnStack(), localAddr);
}
logger.trace("Sending ConnectionBind Request to " + serverAddress);
evt = requestSender.sendRequestAndWaitForResponse(connectionBindRequest,
serverAddress);
if (evt != null) {
Message msg = evt.getMessage();
if (msg.getMessageType() == Message.CONNECTION_BIND_SUCCESS_RESPONSE) {
logger.trace("Received a ConnectionBind Sucess Response.");
String myMessage = "Aakash Garg";
RawMessage rawMessage = RawMessage.build(myMessage.getBytes(),
myMessage.length(), serverAddress, localAddr);
try {
logger.trace("--------------- Thread will now sleep for 20 sec.");
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
logger.error("Unable to stop thread");
}
logger.trace(">>>>>>>>>>>> Sending a Test message : ");
byte[] data = myMessage.getBytes();
for (int i = 0; i < data.length; i++) {
logger.debug(String.format("%02X, ", data[i]));
}
this.getTurnStack().sendUdpMessage(rawMessage, serverAddress,
requestSender.getLocalAddress());
} else {
logger.trace("Received a ConnectionBind error Response - "
+ msg.getAttribute(Attribute.ERROR_CODE));
}
} else {
logger.debug("No response received to ConnectionBind request");
}
} catch (StunException e) {
logger.trace("Unable to send ConnectionBind request");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
3e16072d2da09bce1c1b9723fea21ca4abb514db | 581 | java | Java | Examples/src/AsposeCellsExamples/TechnicalArticles/RemoveUnusedStyles.java | mnote/Aspose.Cells-for-Java | bf71d5a86806effd279af93fd511dbefd90106e5 | [
"MIT"
] | 90 | 2016-04-14T10:14:58.000Z | 2022-03-29T07:40:21.000Z | Examples/src/AsposeCellsExamples/TechnicalArticles/RemoveUnusedStyles.java | mnote/Aspose.Cells-for-Java | bf71d5a86806effd279af93fd511dbefd90106e5 | [
"MIT"
] | 19 | 2018-03-23T09:50:42.000Z | 2021-11-01T09:37:38.000Z | Examples/src/AsposeCellsExamples/TechnicalArticles/RemoveUnusedStyles.java | mnote/Aspose.Cells-for-Java | bf71d5a86806effd279af93fd511dbefd90106e5 | [
"MIT"
] | 72 | 2016-04-09T07:16:12.000Z | 2022-03-23T20:28:09.000Z | 25.26087 | 91 | 0.772806 | 9,373 | package AsposeCellsExamples.TechnicalArticles;
import com.aspose.cells.Workbook;
import AsposeCellsExamples.Utils;
public class RemoveUnusedStyles {
public static void main(String[] args) throws Exception {
String dataDir = Utils.getSharedDataDir(RemoveUnusedStyles.class) + "TechnicalArticles/";
String inputPath = dataDir + "Styles.xlsx";
String outputPath = dataDir + "RemoveUnusedStyles_out.xlsx";
Workbook workbook = new Workbook(inputPath);
workbook.removeUnusedStyles();
workbook.save(outputPath);
System.out.println("File saved " + outputPath);
}
}
|
3e16074eff4788246d35f76d008e9c138a12c638 | 4,374 | java | Java | backend/de.metas.adempiere.adempiere/serverRoot/de.metas.adempiere.adempiere.serverRoot.base/src/main/java/de/metas/adempiere/process/ManageScheduler.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/serverRoot/de.metas.adempiere.adempiere.serverRoot.base/src/main/java/de/metas/adempiere/process/ManageScheduler.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/serverRoot/de.metas.adempiere.adempiere.serverRoot.base/src/main/java/de/metas/adempiere/process/ManageScheduler.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | 26.834356 | 108 | 0.719707 | 9,374 | package de.metas.adempiere.process;
/*
* #%L
* de.metas.adempiere.adempiere.serverRoot.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import org.adempiere.exceptions.FillMandatoryException;
import org.compiere.model.MScheduler;
import org.compiere.model.MTable;
import org.compiere.server.AdempiereServer;
import org.compiere.server.AdempiereServerMgr;
import de.metas.process.ProcessInfoParameter;
import de.metas.process.JavaProcess;
public class ManageScheduler extends JavaProcess
{
private static final String PARAM_ACTION = "Action";
private static final String PARAM_RETRY_IF_STOP_FAILS = "RetryIfStopFails";
private static final String ACTION_RESTART = "RESTART";
private static final String ACTION_STOP = "STOP";
private static final String ACTION_START = "START";
private int p_AD_Scheduler_ID = -1;
private boolean retryIfStopFails = false;
private String action;
@Override
protected void prepare()
{
if (getTable_ID() == MTable.getTable_ID(MScheduler.Table_Name))
{
p_AD_Scheduler_ID = getRecord_ID();
}
final ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
final String name = para[i].getParameterName();
if (para[i].getParameter() == null)
{
;
}
else if (name.equals(PARAM_RETRY_IF_STOP_FAILS))
{
retryIfStopFails = "Y".equals(para[i].getParameter());
}
else if (name.equals(PARAM_ACTION))
{
action = (String)para[i].getParameter();
}
}
}
@Override
protected String doIt() throws Exception
{
if (p_AD_Scheduler_ID <= 0)
throw new FillMandatoryException("AD_Scheduler_ID");
final MScheduler schedulerModel = new MScheduler(getCtx(), p_AD_Scheduler_ID, null);
if (isStop() && !stop(schedulerModel))
{
return "@Error@";
}
if (isStart() && !start(schedulerModel))
{
return "@Error@";
}
return "@Success@";
}
private boolean isStart()
{
return ACTION_START.equals(action) || ACTION_RESTART.equals(action);
}
private boolean isStop()
{
return ACTION_STOP.equals(action) || ACTION_RESTART.equals(action);
}
private boolean start(final MScheduler schedulerModel)
{
final AdempiereServerMgr adempiereServerMgr = AdempiereServerMgr.get();
final AdempiereServer scheduler = adempiereServerMgr.getServer(schedulerModel.getServerID());
if (scheduler == null)
{
adempiereServerMgr.add(schedulerModel);
addLog("Created server scheduler for " + schedulerModel.getName());
}
adempiereServerMgr.start(schedulerModel.getServerID());
addLog("Started " + schedulerModel.getName());
return true;
}
private boolean stop(final MScheduler schedulerModel) throws InterruptedException
{
final AdempiereServerMgr adempiereServerMgr = AdempiereServerMgr.get(); // adempiereAlreadyStarted == true
// making sure that the scheduler exists on the server
final AdempiereServer scheduler = adempiereServerMgr.getServer(schedulerModel.getServerID());
if (scheduler == null)
{
addLog("Scheduler " + schedulerModel.getName() + " is not registered on the server");
return false;
}
addLog("Stopping scheduler " + schedulerModel.getName());
if (!adempiereServerMgr.stop(schedulerModel.getServerID()))
{
if (retryIfStopFails)
{
addLog("Scheduler " + schedulerModel.getName() + " seems to be running right now");
do
{
addLog("Will retry in 5 seconds...");
Thread.sleep(5000);
}
while (!adempiereServerMgr.stop(schedulerModel.getServerID()));
}
else
{
addLog("Failed to stop scheduler " + schedulerModel.getName());
return false;
}
}
addLog("Sucessfully stopped scheduler " + schedulerModel.getName());
return true;
}
}
|
3e160758dd11eb8f151ec5f818212afa83b66ebe | 335 | java | Java | smg-public-common/smg-public-common-core/src/main/java/org/clc/common/core/annotation/Excels.java | clouker/smg-public | 9012927781cb5ee215d452ea73c054ba26c872fa | [
"Apache-2.0"
] | null | null | null | smg-public-common/smg-public-common-core/src/main/java/org/clc/common/core/annotation/Excels.java | clouker/smg-public | 9012927781cb5ee215d452ea73c054ba26c872fa | [
"Apache-2.0"
] | null | null | null | smg-public-common/smg-public-common-core/src/main/java/org/clc/common/core/annotation/Excels.java | clouker/smg-public | 9012927781cb5ee215d452ea73c054ba26c872fa | [
"Apache-2.0"
] | null | null | null | 20.9375 | 44 | 0.78209 | 9,375 | package org.clc.common.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解集
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
Excel[] value();
} |
3e1608f1223a5b06af403a1507d07406e306861f | 366 | java | Java | src/main/java/devos/jlsl/fragments/CodeFragment.java | devOS-Sanity-Edition/JLSL | 7477299dc9818dac6319cd835a0b8a25e2930be7 | [
"MIT"
] | null | null | null | src/main/java/devos/jlsl/fragments/CodeFragment.java | devOS-Sanity-Edition/JLSL | 7477299dc9818dac6319cd835a0b8a25e2930be7 | [
"MIT"
] | null | null | null | src/main/java/devos/jlsl/fragments/CodeFragment.java | devOS-Sanity-Edition/JLSL | 7477299dc9818dac6319cd835a0b8a25e2930be7 | [
"MIT"
] | null | null | null | 17.428571 | 76 | 0.745902 | 9,376 | package devos.jlsl.fragments;
import java.util.*;
public abstract class CodeFragment
{
public boolean forbiddenToPrint = false;
private ArrayList<CodeFragment> children = new ArrayList<CodeFragment>();
public void addChild(CodeFragment fragment)
{
children.add(fragment);
}
public ArrayList<CodeFragment> getChildren()
{
return children;
}
}
|
3e1608ff4dc69f8de910cc92555c7974eca1159a | 2,318 | java | Java | Variant Programs/2-5/9/spreadsheet/EriePlanner.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | Variant Programs/2-5/9/spreadsheet/EriePlanner.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | Variant Programs/2-5/9/spreadsheet/EriePlanner.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | 30.5 | 90 | 0.689819 | 9,377 | package spreadsheet;
import consignor.Dealer;
import spreadsheet.Database;
import spreadsheet.Procedure;
import java.util.ArrayDeque;
public class EriePlanner extends spreadsheet.Database {
private static final boolean synX863boolean = false;
private static final int synX862int = 0;
private static final boolean synX861boolean = true;
private static final int synX860int = 0;
private static final boolean synX859boolean = true;
private static final int synX858int = 1;
private static final String synX857String = "RR:";
private java.util.ArrayDeque<Procedure> preparedWait = null;
private int meterLeftover = 0;
public EriePlanner() {
this.preparedWait = (new java.util.ArrayDeque<>());
meterLeftover = (MinutesEnormous);
}
public synchronized String controllerSurname() {
return synX857String;
}
public synchronized void optiBeat() {
if (prevalentMethod != null) {
prevalentMethod.fitSquirtingYear(prevalentMethod.canLengthwaysYears() + synX858int);
meterLeftover--;
if (prevalentMethod.canLengthwaysYears() == prevalentMethod.canChairmanAmount()) {
prevalentMethod.fitDieYear(this.arriveFlowIndicate());
this.doneAppendage.addLast(prevalentMethod);
prevalentMethod = (null);
this.malcolmIris = (synX859boolean);
}
if (meterLeftover == synX860int && prevalentMethod != null) {
if (preparedWait.isEmpty()) {
meterLeftover = (MinutesEnormous);
} else {
preparedWait.addLast(prevalentMethod);
prevalentMethod = (null);
this.malcolmIris = (synX861boolean);
}
}
}
if (this.malcolmIris && prevalentMethod == null) {
this.additionalDikMonth--;
if (additionalDikMonth == synX862int) {
this.malcolmIris = (synX863boolean);
this.additionalDikMonth = (Dealer.HitPeriods);
}
} else {
if (prevalentMethod == null && !preparedWait.isEmpty()) {
prevalentMethod = (preparedWait.removeFirst());
ladeProcedures(prevalentMethod);
prevalentMethod.markKickoffHours(this.arriveFlowIndicate());
meterLeftover = (MinutesEnormous);
}
}
}
public synchronized void mechanismArrivals(Procedure negotiations) {
preparedWait.addLast(negotiations);
}
}
|
3e16093ac8af521d056ca104286661d367a0008a | 1,574 | java | Java | src/main/java/fr/dawoox/akasuki/commands/owner/ListGuildsCmd.java | Akasuki-bot/Akasuki | 3ea425b42ac5204982b1c09ef4b3168b053ab8ce | [
"MIT"
] | 2 | 2021-06-23T08:02:36.000Z | 2021-06-26T06:25:18.000Z | src/main/java/fr/dawoox/akasuki/commands/owner/ListGuildsCmd.java | Akasuki-bot/Akasuki | 3ea425b42ac5204982b1c09ef4b3168b053ab8ce | [
"MIT"
] | 1 | 2021-09-03T11:37:22.000Z | 2021-09-03T19:57:47.000Z | src/main/java/fr/dawoox/akasuki/commands/owner/ListGuildsCmd.java | Akasuki-bot/Akasuki | 3ea425b42ac5204982b1c09ef4b3168b053ab8ce | [
"MIT"
] | null | null | null | 31.48 | 102 | 0.609911 | 9,378 | package fr.dawoox.akasuki.commands.owner;
import discord4j.core.event.domain.interaction.ChatInputInteractionEvent;
import discord4j.core.object.entity.Guild;
import discord4j.discordjson.json.ApplicationCommandRequest;
import fr.dawoox.akasuki.core.SlashBaseCmd;
import java.util.List;
public class ListGuildsCmd implements SlashBaseCmd {
private final int maxShowServers = 10;
@Override
public String getName() {
return "listguilds";
}
@Override
public ApplicationCommandRequest getRequest() {
return ApplicationCommandRequest.builder()
.name("listguilds")
.description("List all servers the bot is in (max "+maxShowServers+" servers render)")
.build();
}
@Override
public void handle(ChatInputInteractionEvent event) {
List<Guild> guilds = event.getClient().getGuilds().collectList().block();
StringBuilder content = new StringBuilder();
if (guilds.size() < maxShowServers) {
for (Guild value : guilds) {
content.append(value.getName()+" ("+value.getId().asString()+")\n");
}
} else {
for (int i = 0; i < maxShowServers; i++) {
content.append(guilds.get(i).getName()+" ("+guilds.get(i).getId().asString()+")\n");
}
content.append("\n"+(guilds.size()-maxShowServers)+" more servers.");
}
event.reply()
.withEphemeral(true)
.withContent(content.toString())
.block();
}
}
|
3e16099706c70698f96b1b94f4c175f80c9b87d1 | 77,554 | java | Java | src/main/java/com/fincatto/documentofiscal/nfe310/webservices/gerado/NfeAutorizacaoStub.java | jpweit/nfe | d21d45cdd19474b046ff42664c1089130fde04fc | [
"Apache-2.0"
] | 568 | 2015-10-13T23:56:37.000Z | 2022-03-21T13:11:48.000Z | src/main/java/com/fincatto/documentofiscal/nfe310/webservices/gerado/NfeAutorizacaoStub.java | jpweit/nfe | d21d45cdd19474b046ff42664c1089130fde04fc | [
"Apache-2.0"
] | 531 | 2015-10-14T11:39:43.000Z | 2022-03-14T08:02:53.000Z | src/main/java/com/fincatto/documentofiscal/nfe310/webservices/gerado/NfeAutorizacaoStub.java | jpweit/nfe | d21d45cdd19474b046ff42664c1089130fde04fc | [
"Apache-2.0"
] | 481 | 2015-10-14T13:23:56.000Z | 2022-03-15T17:42:01.000Z | 58.931611 | 368 | 0.616564 | 9,379 | package com.fincatto.documentofiscal.nfe310.webservices.gerado;
import org.apache.axiom.om.OMAttribute;
import org.apache.axis2.client.Stub;
import org.apache.axis2.databinding.utils.Constants;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import com.fincatto.documentofiscal.DFConfig;
import com.fincatto.documentofiscal.utils.MessageContextFactory;
/*
* NfeAutorizacaoStub java implementation
*/
public class NfeAutorizacaoStub extends org.apache.axis2.client.Stub {
protected org.apache.axis2.description.AxisOperation[] _operations;
// hashmaps to keep the fault mapping
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultExceptionNameMap = new java.util.HashMap();
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultExceptionClassNameMap = new java.util.HashMap();
@SuppressWarnings("rawtypes")
private final java.util.HashMap faultMessageMap = new java.util.HashMap();
private static int counter = 0;
private static synchronized java.lang.String getUniqueSuffix() {
// reset the counter if it is greater than 99999
if (NfeAutorizacaoStub.counter > 99999) {
NfeAutorizacaoStub.counter = 0;
}
NfeAutorizacaoStub.counter = NfeAutorizacaoStub.counter + 1;
return System.currentTimeMillis() + "_" + NfeAutorizacaoStub.counter;
}
private void populateAxisService() {
// creating the Service with a unique name
this._service = new org.apache.axis2.description.AxisService("NfeAutorizacao" + NfeAutorizacaoStub.getUniqueSuffix());
this.addAnonymousOperations();
// creating the operations
org.apache.axis2.description.AxisOperation __operation;
this._operations = new org.apache.axis2.description.AxisOperation[2];
__operation = new org.apache.axis2.description.OutInAxisOperation();
__operation.setName(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteZip"));
this._service.addOperation(__operation);
this._operations[0] = __operation;
__operation = new org.apache.axis2.description.OutInAxisOperation();
__operation.setName(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLote"));
this._service.addOperation(__operation);
this._operations[1] = __operation;
}
// populates the faults
private void populateFaults() {
}
public NfeAutorizacaoStub(final org.apache.axis2.context.ConfigurationContext configurationContext, final java.lang.String targetEndpoint, DFConfig config) throws org.apache.axis2.AxisFault {
this(configurationContext, targetEndpoint, false, config);
}
public NfeAutorizacaoStub(final org.apache.axis2.context.ConfigurationContext configurationContext, final java.lang.String targetEndpoint, final boolean useSeparateListener, DFConfig config) throws org.apache.axis2.AxisFault {
// To populate AxisService
this.populateAxisService();
this.populateFaults();
this._serviceClient = new org.apache.axis2.client.ServiceClient(configurationContext, this._service);
this._serviceClient.getOptions().setTo(new org.apache.axis2.addressing.EndpointReference(targetEndpoint));
this._serviceClient.getOptions().setUseSeparateListener(useSeparateListener);
// Set the soap version
this._serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
this.config = config;
}
public NfeAutorizacaoStub(final java.lang.String targetEndpoint, DFConfig config) throws org.apache.axis2.AxisFault {
this(null, targetEndpoint, config);
}
public NfeAutorizacaoStub.NfeAutorizacaoLoteZipResult nfeAutorizacaoLoteZip(final NfeAutorizacaoStub.NfeDadosMsgZip nfeDadosMsgZip, final NfeAutorizacaoStub.NfeCabecMsgE nfeCabecMsg) throws java.rmi.RemoteException {
org.apache.axis2.context.MessageContext _messageContext = null;
try {
final org.apache.axis2.client.OperationClient _operationClient = this._serviceClient.createClient(this._operations[0].getName());
_operationClient.getOptions().setAction("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao/nfeAutorizacaoLoteZip");
_operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
this.addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&");
// create a message context
_messageContext = MessageContextFactory.INSTANCE.create(config);
// create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env;
env = this.toEnvelope(Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()), nfeDadosMsgZip, this.optimizeContent(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteZip")), new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteZip"));
env.build();
// add the children only if the parameter is not null
if (nfeCabecMsg != null) {
final org.apache.axiom.om.OMElement omElementnfeCabecMsg = this.toOM(nfeCabecMsg, this.optimizeContent(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteZip")));
this.addHeader(omElementnfeCabecMsg, env);
}
// adding SOAP soap_headers
this._serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);
// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);
// execute the operation client
_operationClient.execute(true);
final org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();
final java.lang.Object object = this.fromOM(_returnEnv.getBody().getFirstElement(), NfeAutorizacaoStub.NfeAutorizacaoLoteZipResult.class, this.getEnvelopeNamespaces(_returnEnv));
return (NfeAutorizacaoStub.NfeAutorizacaoLoteZipResult) object;
} catch (final org.apache.axis2.AxisFault f) {
final org.apache.axiom.om.OMElement faultElt = f.getDetail();
if (faultElt != null) {
if (this.faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLoteZip"))) {
// make the fault by reflection
try {
final java.lang.String exceptionClassName = (java.lang.String) this.faultExceptionClassNameMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLoteZip"));
final Class<?> exceptionClass = java.lang.Class.forName(exceptionClassName);
final Constructor<?> constructor = exceptionClass.getConstructor(String.class);
final java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage());
// message class
final java.lang.String messageClassName = (java.lang.String) this.faultMessageMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLoteZip"));
final Class<?> messageClass = java.lang.Class.forName(messageClassName);
final java.lang.Object messageObject = this.fromOM(faultElt, messageClass, null);
final java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", messageClass);
m.invoke(ex, messageObject);
throw new java.rmi.RemoteException(ex.getMessage(), ex);
} catch (final ClassCastException | InstantiationException | IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
// we cannot intantiate the class - throw the original Axis fault
throw f;
}
} else {
throw f;
}
} else {
throw f;
}
} finally {
if (_messageContext.getTransportOut() != null) {
_messageContext.getTransportOut().getSender().cleanup(_messageContext);
}
}
}
public NfeAutorizacaoStub.NfeAutorizacaoLoteResult nfeAutorizacaoLote(final NfeAutorizacaoStub.NfeDadosMsg nfeDadosMsg, final NfeAutorizacaoStub.NfeCabecMsgE nfeCabecMsg0) throws java.rmi.RemoteException {
org.apache.axis2.context.MessageContext _messageContext = null;
try {
final org.apache.axis2.client.OperationClient _operationClient = this._serviceClient.createClient(this._operations[1].getName());
_operationClient.getOptions().setAction("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao/nfeAutorizacaoLote");
_operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);
this.addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&");
// create a message context
_messageContext = MessageContextFactory.INSTANCE.create(config);
// create SOAP envelope with that payload
org.apache.axiom.soap.SOAPEnvelope env;
env = this.toEnvelope(Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()), nfeDadosMsg, this.optimizeContent(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLote")), new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLote"));
env.build();
// add the children only if the parameter is not null
if (nfeCabecMsg0 != null) {
final org.apache.axiom.om.OMElement omElementnfeCabecMsg0 = this.toOM(nfeCabecMsg0, this.optimizeContent(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLote")));
this.addHeader(omElementnfeCabecMsg0, env);
}
// adding SOAP soap_headers
this._serviceClient.addHeadersToEnvelope(env);
// set the message context with that soap envelope
_messageContext.setEnvelope(env);
// add the message contxt to the operation client
_operationClient.addMessageContext(_messageContext);
// execute the operation client
_operationClient.execute(true);
final org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient.getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();
final java.lang.Object object = this.fromOM(_returnEnv.getBody().getFirstElement(), NfeAutorizacaoStub.NfeAutorizacaoLoteResult.class, this.getEnvelopeNamespaces(_returnEnv));
return (NfeAutorizacaoStub.NfeAutorizacaoLoteResult) object;
} catch (final org.apache.axis2.AxisFault f) {
final org.apache.axiom.om.OMElement faultElt = f.getDetail();
if (faultElt != null) {
if (this.faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLote"))) {
// make the fault by reflection
try {
final java.lang.String exceptionClassName = (java.lang.String) this.faultExceptionClassNameMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLote"));
final java.lang.Class<?> exceptionClass = java.lang.Class.forName(exceptionClassName);
final Constructor<?> constructor = exceptionClass.getConstructor(String.class);
final java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage());
// message class
final java.lang.String messageClassName = (java.lang.String) this.faultMessageMap.get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "nfeAutorizacaoLote"));
final Class<?> messageClass = java.lang.Class.forName(messageClassName);
final java.lang.Object messageObject = this.fromOM(faultElt, messageClass, null);
final java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", messageClass);
m.invoke(ex, messageObject);
throw new java.rmi.RemoteException(ex.getMessage(), ex);
} catch (final ClassCastException | InstantiationException | IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) {
// we cannot intantiate the class - throw the original Axis fault
throw f;
}
} else {
throw f;
}
} else {
throw f;
}
} finally {
if (_messageContext.getTransportOut() != null) {
_messageContext.getTransportOut().getSender().cleanup(_messageContext);
}
}
}
private java.util.Map<String, String> getEnvelopeNamespaces(final org.apache.axiom.soap.SOAPEnvelope env) {
final java.util.Map<String, String> returnMap = new java.util.HashMap<>();
@SuppressWarnings("rawtypes") final java.util.Iterator namespaceIterator = env.getAllDeclaredNamespaces();
while (namespaceIterator.hasNext()) {
final org.apache.axiom.om.OMNamespace ns = (org.apache.axiom.om.OMNamespace) namespaceIterator.next();
returnMap.put(ns.getPrefix(), ns.getNamespaceURI());
}
return returnMap;
}
private final javax.xml.namespace.QName[] opNameArray = null;
private final DFConfig config;
private boolean optimizeContent(final javax.xml.namespace.QName opName) {
if (this.opNameArray == null) {
return false;
}
for (QName anOpNameArray : this.opNameArray) {
if (opName.equals(anOpNameArray)) {
return true;
}
}
return false;
}
// https://nfe.rs.gov.br/ws/NfeAutorizacao/NFeAutorizacao.asmx
public static class NfeAutorizacaoLoteZipResult implements org.apache.axis2.databinding.ADBBean {
private static final long serialVersionUID = -4497325525608446064L;
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteZipResult", "");
protected org.apache.axiom.om.OMElement localExtraElement;
public org.apache.axiom.om.OMElement getExtraElement() {
return this.localExtraElement;
}
public void setExtraElement(final org.apache.axiom.om.OMElement param) {
this.localExtraElement = param;
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, NfeAutorizacaoLoteZipResult.MY_QNAME);
return factory.createOMElement(dataSource, NfeAutorizacaoLoteZipResult.MY_QNAME);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":nfeAutorizacaoLoteZipResult", xmlWriter);
} else {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "nfeAutorizacaoLoteZipResult", xmlWriter);
}
}
if (this.localExtraElement != null) {
this.localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao")) {
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeAutorizacaoLoteZipResult.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeAutorizacaoLoteZipResult.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
final java.util.ArrayList<Object> elementList = new java.util.ArrayList<>();
if (this.localExtraElement != null) {
elementList.add(org.apache.axis2.databinding.utils.Constants.OM_ELEMENT_KEY);
elementList.add(this.localExtraElement);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), new java.util.ArrayList<>().toArray());
}
public static class Factory {
public static NfeAutorizacaoLoteZipResult parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeAutorizacaoLoteZipResult object = new NfeAutorizacaoLoteZipResult();
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
final java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeAutorizacaoLoteZipResult".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeAutorizacaoLoteZipResult) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// use the QName from the parser as the name for the builder
final javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
final org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 = new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(new org.apache.axis2.util.StreamWrapper(reader), startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else {
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
public static class NfeCabecMsgE implements org.apache.axis2.databinding.ADBBean {
private static final long serialVersionUID = -4943739405977852705L;
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeCabecMsg", "");
protected NfeCabecMsg localNfeCabecMsg;
public NfeCabecMsg getNfeCabecMsg() {
return this.localNfeCabecMsg;
}
public void setNfeCabecMsg(final NfeCabecMsg param) {
this.localNfeCabecMsg = param;
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, NfeCabecMsgE.MY_QNAME);
return factory.createOMElement(dataSource, NfeCabecMsgE.MY_QNAME);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
// We can safely assume an element has only one type associated with it
if (this.localNfeCabecMsg == null) {
throw new org.apache.axis2.databinding.ADBException("nfeCabecMsg cannot be null!");
}
this.localNfeCabecMsg.serialize(NfeCabecMsgE.MY_QNAME, xmlWriter);
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
// We can safely assume an element has only one type associated with it
return this.localNfeCabecMsg.getPullParser(NfeCabecMsgE.MY_QNAME);
}
public static class Factory {
public static NfeCabecMsgE parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeCabecMsgE object = new NfeCabecMsgE();
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
while (!reader.isEndElement()) {
if (reader.isStartElement()) {
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeCabecMsg").equals(reader.getName())) {
object.setNfeCabecMsg(NfeCabecMsg.Factory.parse(reader));
} // End of if for expected property start element
else {
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} else {
reader.next();
}
} // end of while loop
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
public static class NfeAutorizacaoLoteResult implements org.apache.axis2.databinding.ADBBean {
private static final long serialVersionUID = -6861369626109193017L;
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeAutorizacaoLoteResult", "");
protected org.apache.axiom.om.OMElement localExtraElement;
public org.apache.axiom.om.OMElement getExtraElement() {
return this.localExtraElement;
}
public void setExtraElement(final org.apache.axiom.om.OMElement param) {
this.localExtraElement = param;
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, NfeAutorizacaoLoteResult.MY_QNAME);
return factory.createOMElement(dataSource, NfeAutorizacaoLoteResult.MY_QNAME);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":nfeAutorizacaoLoteResult", xmlWriter);
} else {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "nfeAutorizacaoLoteResult", xmlWriter);
}
}
if (this.localExtraElement != null) {
this.localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao")) {
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeAutorizacaoLoteResult.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeAutorizacaoLoteResult.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
final java.util.ArrayList<Object> elementList = new java.util.ArrayList<>();
if (this.localExtraElement != null) {
elementList.add(org.apache.axis2.databinding.utils.Constants.OM_ELEMENT_KEY);
elementList.add(this.localExtraElement);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), new java.util.ArrayList<>().toArray());
}
public static class Factory {
public static NfeAutorizacaoLoteResult parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeAutorizacaoLoteResult object = new NfeAutorizacaoLoteResult();
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
final java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeAutorizacaoLoteResult".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeAutorizacaoLoteResult) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// use the QName from the parser as the name for the builder
final javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
final org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 = new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(new org.apache.axis2.util.StreamWrapper(reader), startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else {
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
public static class NfeCabecMsg implements org.apache.axis2.databinding.ADBBean {
/*
* This type was generated from the piece of schema that had name = nfeCabecMsg Namespace URI = http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao Namespace Prefix = ns1
*/
private static final long serialVersionUID = -9105774718141008668L;
protected java.lang.String localCUF;
/*
* This tracker boolean wil be used to detect whether the user called the set method for this attribute. It will be used to determine whether to include this field in the serialized XML
*/
protected boolean localCUFTracker = false;
public boolean isCUFSpecified() {
return this.localCUFTracker;
}
public java.lang.String getCUF() {
return this.localCUF;
}
public void setCUF(final java.lang.String param) {
this.localCUFTracker = param != null;
this.localCUF = param;
}
protected java.lang.String localVersaoDados;
/*
* This tracker boolean wil be used to detect whether the user called the set method for this attribute. It will be used to determine whether to include this field in the serialized XML
*/
protected boolean localVersaoDadosTracker = false;
public boolean isVersaoDadosSpecified() {
return this.localVersaoDadosTracker;
}
public java.lang.String getVersaoDados() {
return this.localVersaoDados;
}
public void setVersaoDados(final java.lang.String param) {
this.localVersaoDadosTracker = param != null;
this.localVersaoDados = param;
}
protected org.apache.axiom.om.OMAttribute[] localExtraAttributes;
public org.apache.axiom.om.OMAttribute[] getExtraAttributes() {
return this.localExtraAttributes;
}
protected void validateExtraAttributes(final org.apache.axiom.om.OMAttribute[] param) {
if ((param != null) && (param.length > 1)) {
throw new java.lang.RuntimeException();
}
if ((param != null) && (param.length < 1)) {
throw new java.lang.RuntimeException();
}
}
public void setExtraAttributes(final org.apache.axiom.om.OMAttribute[] param) {
this.validateExtraAttributes(param);
this.localExtraAttributes = param;
}
public void addExtraAttributes(final org.apache.axiom.om.OMAttribute param) {
if (this.localExtraAttributes == null) {
this.localExtraAttributes = new org.apache.axiom.om.OMAttribute[]{};
}
@SuppressWarnings("unchecked") final java.util.List<OMAttribute> list = org.apache.axis2.databinding.utils.ConverterUtil.toList(this.localExtraAttributes);
list.add(param);
this.localExtraAttributes = list.toArray(new OMAttribute[0]);
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, parentQName);
return factory.createOMElement(dataSource, parentQName);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":nfeCabecMsg", xmlWriter);
} else {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "nfeCabecMsg", xmlWriter);
}
}
if (this.localExtraAttributes != null) {
for (OMAttribute localExtraAttribute : this.localExtraAttributes) {
this.writeAttribute(localExtraAttribute.getNamespace().getNamespaceURI(), localExtraAttribute.getLocalName(), localExtraAttribute.getAttributeValue(), xmlWriter);
}
}
if (this.localCUFTracker) {
namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao";
this.writeStartElement(null, namespace, "cUF", xmlWriter);
if (this.localCUF == null) {
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("cUF cannot be null!!");
} else {
xmlWriter.writeCharacters(this.localCUF);
}
xmlWriter.writeEndElement();
}
if (this.localVersaoDadosTracker) {
namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao";
this.writeStartElement(null, namespace, "versaoDados", xmlWriter);
if (this.localVersaoDados == null) {
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("versaoDados cannot be null!!");
} else {
xmlWriter.writeCharacters(this.localVersaoDados);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao")) {
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeCabecMsg.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private void writeAttribute(final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attValue);
} else {
this.registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attValue);
}
}
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeCabecMsg.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
final java.util.ArrayList<Serializable> elementList = new java.util.ArrayList<>();
final java.util.ArrayList<Object> attribList = new java.util.ArrayList<>();
if (this.localCUFTracker) {
elementList.add(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "cUF"));
if (this.localCUF != null) {
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localCUF));
} else {
throw new org.apache.axis2.databinding.ADBException("cUF cannot be null!!");
}
}
if (this.localVersaoDadosTracker) {
elementList.add(new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "versaoDados"));
if (this.localVersaoDados != null) {
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localVersaoDados));
} else {
throw new org.apache.axis2.databinding.ADBException("versaoDados cannot be null!!");
}
}
for (OMAttribute localExtraAttribute : this.localExtraAttributes) {
attribList.add(Constants.OM_ATTRIBUTE_KEY);
attribList.add(localExtraAttribute);
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
public static class Factory {
public static NfeCabecMsg parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeCabecMsg object = new NfeCabecMsg();
java.lang.String nillableValue;
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
final java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeCabecMsg".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeCabecMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
final java.util.Vector<String> handledAttributes = new java.util.Vector<>();
// now run through all any or extra attributes
// which were not reflected until now
for (int i = 0; i < reader.getAttributeCount(); i++) {
if (!handledAttributes.contains(reader.getAttributeLocalName(i))) {
// this is an anyAttribute and we create
// an OMAttribute for this
final org.apache.axiom.om.OMFactory factory = org.apache.axiom.om.OMAbstractFactory.getOMFactory();
final org.apache.axiom.om.OMAttribute attr = factory.createOMAttribute(reader.getAttributeLocalName(i), factory.createOMNamespace(reader.getAttributeNamespace(i), reader.getAttributePrefix(i)), reader.getAttributeValue(i));
// and add it to the extra attributes
object.addExtraAttributes(attr);
}
}
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "cUF").equals(reader.getName())) {
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
throw new org.apache.axis2.databinding.ADBException("The element: " + "cUF" + " cannot be null");
}
final java.lang.String content = reader.getElementText();
object.setCUF(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "versaoDados").equals(reader.getName())) {
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
throw new org.apache.axis2.databinding.ADBException("The element: " + "versaoDados" + " cannot be null");
}
final java.lang.String content = reader.getElementText();
object.setVersaoDados(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
public static class ExtensionMapper {
public static java.lang.Object getTypeObject(final java.lang.String namespaceURI, final java.lang.String typeName, final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
if ("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao".equals(namespaceURI) && "nfeCabecMsg".equals(typeName)) {
return NfeCabecMsg.Factory.parse(reader);
}
throw new org.apache.axis2.databinding.ADBException("Unsupported type " + namespaceURI + " " + typeName);
}
}
public static class NfeDadosMsgZip implements org.apache.axis2.databinding.ADBBean {
private static final long serialVersionUID = 3787993308790482193L;
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeDadosMsgZip", "");
protected java.lang.String localNfeDadosMsgZip;
public java.lang.String getNfeDadosMsgZip() {
return this.localNfeDadosMsgZip;
}
public void setNfeDadosMsgZip(final java.lang.String param) {
this.localNfeDadosMsgZip = param;
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, NfeDadosMsgZip.MY_QNAME);
return factory.createOMElement(dataSource, NfeDadosMsgZip.MY_QNAME);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
// We can safely assume an element has only one type associated with it
final java.lang.String namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao";
final java.lang.String _localName = "nfeDadosMsgZip";
this.writeStartElement(null, namespace, _localName, xmlWriter);
// add the type details if this is used in a simple type
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":nfeDadosMsgZip", xmlWriter);
} else {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "nfeDadosMsgZip", xmlWriter);
}
}
if (this.localNfeDadosMsgZip == null) {
throw new org.apache.axis2.databinding.ADBException("nfeDadosMsgZip cannot be null !!");
} else {
xmlWriter.writeCharacters(this.localNfeDadosMsgZip);
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao")) {
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeDadosMsgZip.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeDadosMsgZip.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) {
// We can safely assume an element has only one type associated with it
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(NfeDadosMsgZip.MY_QNAME, new java.lang.Object[]{org.apache.axis2.databinding.utils.reader.ADBXMLStreamReader.ELEMENT_TEXT, org.apache.axis2.databinding.utils.ConverterUtil.convertToString(this.localNfeDadosMsgZip)}, null);
}
public static class Factory {
public static NfeDadosMsgZip parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeDadosMsgZip object = new NfeDadosMsgZip();
java.lang.String nillableValue;
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
while (!reader.isEndElement()) {
if (reader.isStartElement()) {
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeDadosMsgZip").equals(reader.getName())) {
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
throw new org.apache.axis2.databinding.ADBException("The element: " + "nfeDadosMsgZip" + " cannot be null");
}
final java.lang.String content = reader.getElementText();
object.setNfeDadosMsgZip(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
} // End of if for expected property start element
else {
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} else {
reader.next();
}
} // end of while loop
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
public static class NfeDadosMsg implements org.apache.axis2.databinding.ADBBean {
private static final long serialVersionUID = -5672939740534282441L;
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao", "nfeDadosMsg", "");
protected org.apache.axiom.om.OMElement localExtraElement;
public org.apache.axiom.om.OMElement getExtraElement() {
return this.localExtraElement;
}
public void setExtraElement(final org.apache.axiom.om.OMElement param) {
this.localExtraElement = param;
}
@Override
public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) {
final org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, NfeDadosMsg.MY_QNAME);
return factory.createOMElement(dataSource, NfeDadosMsg.MY_QNAME);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
this.serialize(parentQName, xmlWriter, false);
}
@Override
public void serialize(final javax.xml.namespace.QName parentQName, final javax.xml.stream.XMLStreamWriter xmlWriter, final boolean serializeType) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix;
java.lang.String namespace;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
this.writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType) {
final java.lang.String namespacePrefix = this.registerPrefix(xmlWriter, "http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":nfeDadosMsg", xmlWriter);
} else {
this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "nfeDadosMsg", xmlWriter);
}
}
if (this.localExtraElement != null) {
this.localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(final java.lang.String namespace) {
if (namespace.equals("http://www.portalfiscal.inf.br/nfe/wsdl/NfeAutorizacao")) {
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
private void writeStartElement(java.lang.String prefix, final java.lang.String namespace, final java.lang.String localPart, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
final java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = NfeDadosMsg.generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
private void writeAttribute(final java.lang.String prefix, final java.lang.String namespace, final java.lang.String attName, final java.lang.String attValue, final javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace, attName, attValue);
}
private java.lang.String registerPrefix(final javax.xml.stream.XMLStreamWriter xmlWriter, final java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = NfeDadosMsg.generatePrefix(namespace);
final javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
final java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
@Override
public javax.xml.stream.XMLStreamReader getPullParser(final javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException {
final java.util.ArrayList<Object> elementList = new java.util.ArrayList<>();
if (this.localExtraElement != null) {
elementList.add(org.apache.axis2.databinding.utils.Constants.OM_ELEMENT_KEY);
elementList.add(this.localExtraElement);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), new ArrayList<>().toArray());
}
public static class Factory {
public static NfeDadosMsg parse(final javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
final NfeDadosMsg object = new NfeDadosMsg();
try {
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) {
final java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
if (fullTypeName != null) {
java.lang.String nsPrefix = null;
if (fullTypeName.contains(":")) {
nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix == null ? "" : nsPrefix;
final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"nfeDadosMsg".equals(type)) {
// find namespace for the prefix
final java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (NfeDadosMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// use the QName from the parser as the name for the builder
final javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
final org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 = new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(new org.apache.axis2.util.StreamWrapper(reader), startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else {
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) {
reader.next();
}
if (reader.isStartElement()) {
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
} catch (final javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}// end of factory class
}
private org.apache.axiom.om.OMElement toOM(final NfeAutorizacaoStub.NfeCabecMsgE param, final boolean optimizeContent) {
// try {
return param.getOMElement(NfeAutorizacaoStub.NfeCabecMsgE.MY_QNAME, org.apache.axiom.om.OMAbstractFactory.getOMFactory());
// } catch (final org.apache.axis2.databinding.ADBException e) {
// throw org.apache.axis2.AxisFault.makeFault(e);
// }
}
private org.apache.axiom.soap.SOAPEnvelope toEnvelope(final org.apache.axiom.soap.SOAPFactory factory, final NfeAutorizacaoStub.NfeDadosMsgZip param, final boolean optimizeContent, final javax.xml.namespace.QName methodQName) {
// try {
final org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
emptyEnvelope.getBody().addChild(param.getOMElement(NfeAutorizacaoStub.NfeDadosMsgZip.MY_QNAME, factory));
return emptyEnvelope;
// } catch (final org.apache.axis2.databinding.ADBException e) {
// throw org.apache.axis2.AxisFault.makeFault(e);
// }
}
/* methods to provide back word compatibility */
private org.apache.axiom.soap.SOAPEnvelope toEnvelope(final org.apache.axiom.soap.SOAPFactory factory, final NfeAutorizacaoStub.NfeDadosMsg param, final boolean optimizeContent, final javax.xml.namespace.QName methodQName) {
// try {
final org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
emptyEnvelope.getBody().addChild(param.getOMElement(NfeAutorizacaoStub.NfeDadosMsg.MY_QNAME, factory));
return emptyEnvelope;
// } catch (final org.apache.axis2.databinding.ADBException e) {
// throw org.apache.axis2.AxisFault.makeFault(e);
// }
}
/* methods to provide back word compatibility */
private java.lang.Object fromOM(final org.apache.axiom.om.OMElement param, final java.lang.Class<?> type, final java.util.Map<String, String> extraNamespaces) throws org.apache.axis2.AxisFault {
try {
if (NfeAutorizacaoStub.NfeDadosMsgZip.class.equals(type)) {
return NfeAutorizacaoStub.NfeDadosMsgZip.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeAutorizacaoStub.NfeAutorizacaoLoteZipResult.class.equals(type)) {
return NfeAutorizacaoStub.NfeAutorizacaoLoteZipResult.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeAutorizacaoStub.NfeCabecMsgE.class.equals(type)) {
return NfeAutorizacaoStub.NfeCabecMsgE.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeAutorizacaoStub.NfeDadosMsg.class.equals(type)) {
return NfeAutorizacaoStub.NfeDadosMsg.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeAutorizacaoStub.NfeAutorizacaoLoteResult.class.equals(type)) {
return NfeAutorizacaoStub.NfeAutorizacaoLoteResult.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
if (NfeAutorizacaoStub.NfeCabecMsgE.class.equals(type)) {
return NfeAutorizacaoStub.NfeCabecMsgE.Factory.parse(param.getXMLStreamReaderWithoutCaching());
}
} catch (final java.lang.Exception e) {
throw org.apache.axis2.AxisFault.makeFault(e);
}
return null;
}
}
|
3e160a6ffcb15215841ed1d340917c8612ee57e9 | 2,542 | java | Java | invoice/src/office/PropertyTests.java | rdejong81/SI-Planner | 4ae6098d4e36456779d257bdbf2500aa8798146e | [
"Apache-2.0"
] | null | null | null | invoice/src/office/PropertyTests.java | rdejong81/SI-Planner | 4ae6098d4e36456779d257bdbf2500aa8798146e | [
"Apache-2.0"
] | 1 | 2020-07-27T18:25:25.000Z | 2020-07-27T18:25:25.000Z | invoice/src/office/PropertyTests.java | rdejong81/SI-Planner | 4ae6098d4e36456779d257bdbf2500aa8798146e | [
"Apache-2.0"
] | null | null | null | 27.333333 | 87 | 0.68096 | 9,380 | /*
* Copyright © 2020 Richard de Jong
*
* 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 office ;
import com4j.*;
@IID("{000C0334-0000-0000-C000-000000000046}")
public interface PropertyTests extends office._IMsoDispObj,Iterable<Com4jObject> {
// Methods:
/**
* <p>
* Getter method for the COM property "Item"
* </p>
* @param index Mandatory int parameter.
* @param lcid Mandatory int parameter.
* @return Returns a value of type office.PropertyTest
*/
@DISPID(0) //= 0x0. The runtime will prefer the VTID if present
@VTID(9)
@DefaultMethod
office.PropertyTest getItem(
int index,
@LCID int lcid);
/**
* <p>
* Getter method for the COM property "Count"
* </p>
* @return Returns a value of type int
*/
@DISPID(4) //= 0x4. The runtime will prefer the VTID if present
@VTID(10)
int getCount();
/**
* @param name Mandatory java.lang.String parameter.
* @param condition Mandatory office.MsoCondition parameter.
* @param value Optional parameter. Default value is com4j.Variant.getMissing()
* @param secondValue Optional parameter. Default value is com4j.Variant.getMissing()
* @param connector Optional parameter. Default value is 1
*/
@DISPID(5) //= 0x5. The runtime will prefer the VTID if present
@VTID(11)
void add(
java.lang.String name,
office.MsoCondition condition,
@Optional @MarshalAs(NativeType.VARIANT) java.lang.Object value,
@Optional @MarshalAs(NativeType.VARIANT) java.lang.Object secondValue,
@Optional @DefaultValue("1") office.MsoConnector connector);
/**
* @param index Mandatory int parameter.
*/
@DISPID(6) //= 0x6. The runtime will prefer the VTID if present
@VTID(12)
void remove(
int index);
/**
* <p>
* Getter method for the COM property "_NewEnum"
* </p>
*/
@DISPID(-4) //= 0xfffffffc. The runtime will prefer the VTID if present
@VTID(13)
java.util.Iterator<Com4jObject> iterator();
// Properties:
}
|
3e160aa62f125e562ab9bcc09228f32ffcb40351 | 1,809 | java | Java | app/src/main/java/wannabit/io/cosmostaion/widget/txDetail/kava/TxWithdrawHardHolder.java | shieldwallets/cosmostation-android | 49e05a336f01c7c95e232612e971ba182a9af0d4 | [
"MIT"
] | 35 | 2021-11-02T02:37:42.000Z | 2022-03-30T21:17:44.000Z | app/src/main/java/wannabit/io/cosmostaion/widget/txDetail/kava/TxWithdrawHardHolder.java | shieldwallets/cosmostation-android | 49e05a336f01c7c95e232612e971ba182a9af0d4 | [
"MIT"
] | 9 | 2021-12-20T13:20:38.000Z | 2022-03-31T08:38:04.000Z | app/src/main/java/wannabit/io/cosmostaion/widget/txDetail/kava/TxWithdrawHardHolder.java | shieldwallets/cosmostation-android | 49e05a336f01c7c95e232612e971ba182a9af0d4 | [
"MIT"
] | 12 | 2021-12-01T18:31:36.000Z | 2022-03-25T12:07:50.000Z | 43.071429 | 165 | 0.763958 | 9,381 | package wannabit.io.cosmostaion.widget.txDetail.kava;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import cosmos.tx.v1beta1.ServiceOuterClass;
import kava.hard.v1beta1.Tx;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.base.BaseChain;
import wannabit.io.cosmostaion.base.BaseData;
import wannabit.io.cosmostaion.utils.WDp;
import wannabit.io.cosmostaion.widget.txDetail.TxHolder;
public class TxWithdrawHardHolder extends TxHolder {
ImageView itemMsgImg;
TextView itemDepositor, itemDepositType, itemWithdrawAmount, itemWithdrawAmountDenom;
public TxWithdrawHardHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemDepositor = itemView.findViewById(R.id.tx_depositor);
itemDepositType = itemView.findViewById(R.id.tx_deposit_type);
itemWithdrawAmount = itemView.findViewById(R.id.tx_withdraw_amount);
itemWithdrawAmountDenom = itemView.findViewById(R.id.tx_withdraw_symbol);
}
public void onBindMsg(Context c, BaseData baseData, BaseChain baseChain, ServiceOuterClass.GetTxResponse response, int position, String address, boolean isGen) {
itemMsgImg.setColorFilter(WDp.getChainColor(c, baseChain), android.graphics.PorterDuff.Mode.SRC_IN);
try {
Tx.MsgWithdraw msg = Tx.MsgWithdraw.parseFrom(response.getTx().getBody().getMessages(position).getValue());
itemDepositor.setText(msg.getDepositor());
WDp.showCoinDp(c, baseData, msg.getAmount(0).getDenom(), msg.getAmount(0).getAmount(), itemWithdrawAmountDenom, itemWithdrawAmount, BaseChain.KAVA_MAIN);
} catch (Exception e) { }
}
}
|
3e160acaa5c3ad443c6166be00b7f8bcb448c9df | 1,033 | java | Java | src/main/java/io/github/hnosmium0001/stevestasks/Config.java | hnOsmium0001/StevesTasks | a044756078fe86694c1da6726af4f5269665bfc4 | [
"MIT"
] | null | null | null | src/main/java/io/github/hnosmium0001/stevestasks/Config.java | hnOsmium0001/StevesTasks | a044756078fe86694c1da6726af4f5269665bfc4 | [
"MIT"
] | 1 | 2019-12-16T23:58:16.000Z | 2019-12-16T23:58:16.000Z | src/main/java/io/github/hnosmium0001/stevestasks/Config.java | hnOsmium0001/StevesTasks | a044756078fe86694c1da6726af4f5269665bfc4 | [
"MIT"
] | null | null | null | 30.382353 | 135 | 0.701839 | 9,382 | package io.github.hnosmium0001.stevestasks;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.BooleanValue;
public final class Config {
private Config() {
}
public static final CommonCategory COMMON;
public static final class CommonCategory {
public final BooleanValue enableRSTrigger;
public final BooleanValue enableAE2Trigger;
public CommonCategory(ForgeConfigSpec.Builder builder) {
builder.comment("Procedures config options", "Run '/sfm componentGroups reload' after updating config").push("procedures");
enableRSTrigger = builder.define("enableRSTrigger", true);
enableAE2Trigger = builder.define("enableAE2Trigger", true);
builder.pop();
}
}
static final ForgeConfigSpec COMMON_SPEC;
static {
ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
COMMON = new CommonCategory(builder);
COMMON_SPEC = builder.build();
}
}
|
3e160b1967f8e4826fdea71e8305359011eb202f | 4,933 | java | Java | src/main/java/org/magic/gui/components/shops/TransactionsPanel.java | nicho92/MtgDesktopCompanion | 2fd540eba429d1f32688a6ac7583f0f2757c8258 | [
"Apache-2.0"
] | 87 | 2016-03-17T10:10:20.000Z | 2022-03-11T07:28:52.000Z | src/main/java/org/magic/gui/components/shops/TransactionsPanel.java | nicho92/MtgDesktopCompanion | 2fd540eba429d1f32688a6ac7583f0f2757c8258 | [
"Apache-2.0"
] | 198 | 2016-10-25T14:39:58.000Z | 2022-03-28T07:39:11.000Z | src/main/java/org/magic/gui/components/shops/TransactionsPanel.java | nicho92/MtgDesktopCompanion | 2fd540eba429d1f32688a6ac7583f0f2757c8258 | [
"Apache-2.0"
] | 36 | 2017-12-20T06:32:37.000Z | 2022-03-20T19:15:19.000Z | 26.100529 | 129 | 0.73809 | 9,383 | package org.magic.gui.components.shops;
import java.awt.BorderLayout;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import org.jdesktop.swingx.JXTable;
import org.magic.api.beans.shop.Transaction;
import org.magic.gui.abstracts.MTGUIComponent;
import org.magic.gui.components.ContactPanel;
import org.magic.gui.components.ObjectViewerPanel;
import org.magic.gui.models.TransactionsTableModel;
import org.magic.gui.renderer.standard.DateTableCellEditorRenderer;
import org.magic.services.MTGConstants;
import org.magic.services.MTGControler;
import org.magic.services.TransactionService;
import org.magic.tools.UITools;
import com.jogamp.newt.event.KeyEvent;
public class TransactionsPanel extends MTGUIComponent {
private static final long serialVersionUID = 1L;
private JXTable table;
private TransactionsTableModel model;
private ContactPanel contactPanel;
private TransactionManagementPanel managementPanel;
private ObjectViewerPanel viewerPanel;
private JPanel panneauHaut;
public TransactionsPanel() {
setLayout(new BorderLayout(0, 0));
panneauHaut = new JPanel();
var stockDetailPanel = new StockItemPanel();
var tabbedPane = new JTabbedPane();
contactPanel = new ContactPanel(true);
managementPanel= new TransactionManagementPanel();
model = new TransactionsTableModel();
viewerPanel = new ObjectViewerPanel();
var btnRefresh = UITools.createBindableJButton("", MTGConstants.ICON_REFRESH,KeyEvent.VK_R,"reload");
var btnMerge = UITools.createBindableJButton("", MTGConstants.ICON_MERGE,KeyEvent.VK_M,"merge");
var btnDelete = UITools.createBindableJButton("", MTGConstants.ICON_DELETE,KeyEvent.VK_D,"delete");
btnMerge.setEnabled(false);
btnDelete.setEnabled(false);
table = UITools.createNewTable(model);
table.setDefaultRenderer(Date.class, new DateTableCellEditorRenderer(true));
UITools.initTableFilter(table);
var stockManagementPanel = new JPanel();
stockManagementPanel.setLayout(new BorderLayout());
stockManagementPanel.add(stockDetailPanel,BorderLayout.CENTER);
stockManagementPanel.add(managementPanel,BorderLayout.EAST);
UITools.addTab(tabbedPane, MTGUIComponent.build(stockManagementPanel, stockDetailPanel.getName(), stockDetailPanel.getIcon()));
UITools.addTab(tabbedPane, contactPanel);
if(MTGControler.getInstance().get("debug-json-panel").equals("true"))
UITools.addTab(tabbedPane, viewerPanel);
table.packAll();
add(new JScrollPane(table));
add(panneauHaut, BorderLayout.NORTH);
add(tabbedPane,BorderLayout.SOUTH);
panneauHaut.add(btnRefresh);
panneauHaut.add(btnMerge);
panneauHaut.add(btnDelete);
table.getSelectionModel().addListSelectionListener(lsl->{
List<Transaction> t = UITools.getTableSelections(table, 0);
if(t.isEmpty())
return;
btnMerge.setEnabled(t.size()>1);
btnDelete.setEnabled(!t.isEmpty());
stockDetailPanel.initItems(t.get(0).getItems());
contactPanel.setContact(t.get(0).getContact());
managementPanel.setTransaction(t.get(0));
viewerPanel.show(t.get(0));
});
btnRefresh.addActionListener(al->reload());
btnDelete.addActionListener(al->{
int res = JOptionPane.showConfirmDialog(this, "Delete Transaction will NOT update stock","Sure ?",JOptionPane.YES_NO_OPTION);
if(res == JOptionPane.YES_OPTION) {
List<Transaction> t = UITools.getTableSelections(table, 0);
try {
TransactionService.deleteTransaction(t);
reload();
} catch (Exception e) {
MTGControler.getInstance().notify(e);
}
}
});
btnMerge.addActionListener(al->{
List<Transaction> t = UITools.getTableSelections(table, 0);
try {
TransactionService.mergeTransactions(t);
reload();
} catch (Exception e) {
MTGControler.getInstance().notify(e);
}
});
}
public JTable getTable() {
return table;
}
public TransactionsTableModel getModel() {
return model;
}
public void init(List<Transaction> list)
{
try {
model.clear();
model.addItems(list);
model.fireTableDataChanged();
} catch (Exception e) {
logger.error("error loading transactions",e);
}
}
private void reload()
{
try {
model.clear();
model.addItems(TransactionService.listTransactions());
model.fireTableDataChanged();
} catch (Exception e) {
logger.error("error loading transactions",e);
}
}
@Override
public void onFirstShowing() {
reload();
}
@Override
public String getTitle() {
return "Transaction";
}
@Override
public ImageIcon getIcon() {
return MTGConstants.ICON_EURO;
}
public void disableCommands() {
managementPanel.setVisible(false);
panneauHaut.setVisible(false);
model.setWritable(false);
}
}
|
3e160bf0f61b0b4aefc381865f28cb852ec61260 | 6,068 | java | Java | src/view/InterfaceEditor.java | andresort28/text-processor | 1c5a65982289ccb5e9d9596607aa6e4fef7e76b2 | [
"MIT"
] | null | null | null | src/view/InterfaceEditor.java | andresort28/text-processor | 1c5a65982289ccb5e9d9596607aa6e4fef7e76b2 | [
"MIT"
] | null | null | null | src/view/InterfaceEditor.java | andresort28/text-processor | 1c5a65982289ccb5e9d9596607aa6e4fef7e76b2 | [
"MIT"
] | null | null | null | 19.895082 | 127 | 0.656065 | 9,384 | package view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import controller.FileManager;
import model.Processor;
public class InterfaceEditor extends JFrame
{
private MenuBar menuBar;
private ToolBar toolBar;
private LanguagePanel languagePanel;
private ContentPanel contentPanel;
private Processor processor;
private boolean saved;
private String path;
private boolean popUp;
private PopUpMenu popUpMenu;
public InterfaceEditor ()
{
setTitle("TextEditor");
setSize(530, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setLocationRelativeTo(this);
setResizable(false);
saved = false;
path = "";
popUp = false;
popUpMenu = null;
processor = new Processor();
menuBar = new MenuBar(this);
toolBar = new ToolBar(this);
contentPanel = new ContentPanel(this);
JScrollPane scroll = new JScrollPane(contentPanel);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
languagePanel = new LanguagePanel(this);
setJMenuBar(menuBar);
add(toolBar, BorderLayout.PAGE_START);
add(scroll, BorderLayout.CENTER);
add(languagePanel, BorderLayout.PAGE_END);
}
public void newDocument ()
{
int r = JOptionPane.showConfirmDialog(this, "Do you want to save the current document ?");
if(r == JOptionPane.OK_OPTION)
{
saveFile();
refreshData();
}
if(r == JOptionPane.NO_OPTION)
refreshData();
saved = false;
}
public void openFile ()
{
String text = FileManager.openFile(this);
if( text != null)
{
setContent(text);
refreshWords();
}
}
public void saveFile ()
{
if(!saved)
saveAsFile();
else
{
FileManager.saveFile(contentPanel.getText(), path);
}
}
public void saveAsFile ()
{
path = FileManager.saveAsFile(this, contentPanel.getText());
if(path != null)
saved = true;
}
public void refreshData ()
{
contentPanel.setText("");
}
public void copy ()
{
contentPanel.copy();
}
public void cut ()
{
contentPanel.cut();
}
public void paste ()
{
contentPanel.paste();
refreshWords();
}
public void savePDF ()
{
JOptionPane.showMessageDialog(this, "Not yet available", "Information", JOptionPane.INFORMATION_MESSAGE);
//FileManager.savePDF(contentPanel.getText());
}
public void print ()
{
FileManager.print(contentPanel);
}
public void search ()
{
JOptionPane.showMessageDialog(this, "Not yet available", "Information", JOptionPane.INFORMATION_MESSAGE);
}
public void replace ()
{
JOptionPane.showMessageDialog(this, "Not yet available", "Information", JOptionPane.INFORMATION_MESSAGE);
}
public void selectAll ()
{
JOptionPane.showMessageDialog(this, "Not yet available", "Information", JOptionPane.INFORMATION_MESSAGE);
}
public void autoCorrect ()
{
JOptionPane.showMessageDialog(this, "Please, right click on the wrong word", "Information", JOptionPane.INFORMATION_MESSAGE);
}
public void exit ()
{
int r = JOptionPane.showConfirmDialog(this, "Do you want to save the current document ?");
if(r == JOptionPane.OK_OPTION)
{
saveFile();
dispose();
}
if(r == JOptionPane.NO_OPTION)
dispose();
}
public void correctWord (String word, Point p)
{
if(!processor.verifyWord(word))
{
ArrayList<String> list = processor.getPossible(word);
PopUpMenu popUp = new PopUpMenu(this, p, list);
popUp.setVisible(true);
}
}
public void changeWord (String word2)
{
String[] text = contentPanel.getText().split(" ");
String text2 = "";
for (int i = 0; i < text.length; i++)
{
String word = text[i];
word = word.trim();
if(!word.equalsIgnoreCase(" "))
{
if( word2.equalsIgnoreCase(word) )
text2 += "<font color=\"black\">" + word2 + "</font> ";
else if(!processor.verifyWord(word))
{
if(processor.isOmitted(word))
text2 += "<font color=\"black\">" + word + "</font> ";
else
text2 += "<font color=\"red\">" + word + "</font> ";
}
else
{
if(text2.length() == 0)
text2 += word + " ";
else
text2 += " " + word + " ";
}
}
else
text2 += "<font color=\"black\">" + " " + "</font>";
}
contentPanel.setText(text2);
languagePanel.refreshWords();
}
public void refreshWords ()
{
String[] text = contentPanel.getText().split(" ");
String text2 = "";
for (int i = 0; i < text.length; i++)
{
String word = text[i];
word = word.trim();
if(!word.equalsIgnoreCase(" "))
{
if(!processor.verifyWord(word))
{
if(processor.isOmitted(word))
text2 += "<font color=\"black\">" + word + "</font> ";
else
text2 += "<font color=\"red\">" + word + "</font> ";
}
else
{
if(text2.length() == 0)
text2 += word + " ";
else
text2 += " " + word + " ";
}
}
else
text2 += "<font color=\"black\">" + " " + "</font>";
}
contentPanel.setText(text2);
languagePanel.refreshWords();
}
public void setContent (String text)
{
contentPanel.setText(text);
}
public void changeLanguage (int language)
{
if(getLanguage() != language)
{
processor.setUpLanguage(language);
languagePanel.changeLanguage();
refreshWords();
}
}
public int getLanguage ()
{
return processor.getLanguage();
}
public ArrayList<String> getLanguages ()
{
return processor.getLanguages();
}
public int getTextLenght ()
{
return contentPanel.getLength();
}
public void setPopUpStatus (boolean status)
{
popUp = status;
}
public boolean getPopUpStatus ()
{
return popUp;
}
}
|
3e160c97c632772e061a410efdcbf511c64d860a | 1,944 | java | Java | src/main/java/mx/infotec/dads/sekc/admin/practice/dto/WorkProductsLevelofDetail.java | dads-software-brotherhood/sekc | 96835b107a0ef39f601bc505ef37aa349133e6cb | [
"Apache-2.0"
] | 4 | 2017-05-16T22:44:55.000Z | 2021-12-23T07:11:25.000Z | src/main/java/mx/infotec/dads/sekc/admin/practice/dto/WorkProductsLevelofDetail.java | dads-software-brotherhood/sekc | 96835b107a0ef39f601bc505ef37aa349133e6cb | [
"Apache-2.0"
] | 1 | 2017-07-20T18:10:03.000Z | 2017-07-20T18:10:09.000Z | src/main/java/mx/infotec/dads/sekc/admin/practice/dto/WorkProductsLevelofDetail.java | dads-software-brotherhood/sekc | 96835b107a0ef39f601bc505ef37aa349133e6cb | [
"Apache-2.0"
] | null | null | null | 27.771429 | 85 | 0.73251 | 9,385 | package mx.infotec.dads.sekc.admin.practice.dto;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"description",
"idWorkProduct",
"idLevelOfDetail"
})
public class WorkProductsLevelofDetail {
@JsonProperty("description")
private String description;
@JsonProperty("idWorkProduct")
private String idWorkProduct;
@JsonProperty("idLevelOfDetail")
private String idLevelOfDetail;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("idWorkProduct")
public String getIdWorkProduct() {
return idWorkProduct;
}
@JsonProperty("idWorkProduct")
public void setIdWorkProduct(String idWorkProduct) {
this.idWorkProduct = idWorkProduct;
}
@JsonProperty("idLevelOfDetail")
public String getIdLevelOfDetail() {
return idLevelOfDetail;
}
@JsonProperty("idLevelOfDetail")
public void setIdLevelOfDetail(String idLevelOfDetail) {
this.idLevelOfDetail = idLevelOfDetail;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
3e160ce4534185d6a44efc48328b65747e31b389 | 372 | java | Java | gulimall-product/src/main/java/com/xc/gulimall/product/dao/SpuImagesDao.java | xc1980505/gulimall | f03ddddd73fe0f1fcf36b8d02bfb567f49989130 | [
"Apache-2.0"
] | null | null | null | gulimall-product/src/main/java/com/xc/gulimall/product/dao/SpuImagesDao.java | xc1980505/gulimall | f03ddddd73fe0f1fcf36b8d02bfb567f49989130 | [
"Apache-2.0"
] | 3 | 2021-04-22T17:11:59.000Z | 2021-09-20T21:01:41.000Z | gulimall-product/src/main/java/com/xc/gulimall/product/dao/SpuImagesDao.java | xc1980505/gulimall | f03ddddd73fe0f1fcf36b8d02bfb567f49989130 | [
"Apache-2.0"
] | null | null | null | 20.611111 | 67 | 0.762803 | 9,386 | package com.xc.gulimall.product.dao;
import com.xc.gulimall.product.entity.SpuImagesEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* spu图片
*
* @author xuchong
* @email hzdkv@example.com
* @date 2020-08-07 00:07:36
*/
@Mapper
public interface SpuImagesDao extends BaseMapper<SpuImagesEntity> {
}
|
3e160e10067650339d1a7417cdfcb3d7633c040e | 68,381 | java | Java | main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java | rsudev/c-geo-opensource | 2c6df013dd0641b835f013a6e6177a2a364a2538 | [
"Apache-2.0"
] | 1 | 2017-02-21T06:21:56.000Z | 2017-02-21T06:21:56.000Z | main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java | rsudev/c-geo-opensource | 2c6df013dd0641b835f013a6e6177a2a364a2538 | [
"Apache-2.0"
] | 74 | 2015-03-15T21:43:01.000Z | 2022-03-30T19:21:31.000Z | main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java | rsudev/c-geo-opensource | 2c6df013dd0641b835f013a6e6177a2a364a2538 | [
"Apache-2.0"
] | null | null | null | 39.209289 | 239 | 0.637867 | 9,387 | package cgeo.geocaching.maps.mapsforge.v6;
import cgeo.geocaching.AbstractDialogFragment;
import cgeo.geocaching.AbstractDialogFragment.TargetInfo;
import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.CachePopup;
import cgeo.geocaching.CompassActivity;
import cgeo.geocaching.EditWaypointActivity;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.WaypointPopup;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.FilteredActivity;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.connector.internal.InternalConnector;
import cgeo.geocaching.downloader.DownloaderUtils;
import cgeo.geocaching.enumerations.CacheListType;
import cgeo.geocaching.enumerations.CoordinatesType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.filters.core.GeocacheFilter;
import cgeo.geocaching.filters.core.GeocacheFilterContext;
import cgeo.geocaching.filters.gui.GeocacheFilterActivity;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.ProximityNotification;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.maps.MapMode;
import cgeo.geocaching.maps.MapOptions;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.MapSettingsUtils;
import cgeo.geocaching.maps.MapState;
import cgeo.geocaching.maps.MapUtils;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.mapsforge.AbstractMapsforgeMapSource;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider;
import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle;
import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemLayer;
import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef;
import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.RouteLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.TrackLayer;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.maps.routing.RoutingMode;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.IndividualRoute;
import cgeo.geocaching.models.Route;
import cgeo.geocaching.models.RouteItem;
import cgeo.geocaching.models.TrailHistoryElement;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.ViewUtils;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.ApplicationSettings;
import cgeo.geocaching.utils.CompactIconModeUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.FilterUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.HistoryTrackUtils;
import cgeo.geocaching.utils.IndividualRouteUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MapMarkerUtils;
import cgeo.geocaching.utils.TrackUtils;
import static cgeo.geocaching.filters.core.GeocacheFilterContext.FilterType.LIVE;
import static cgeo.geocaching.filters.gui.GeocacheFilterActivity.EXTRA_FILTER_CONTEXT;
import static cgeo.geocaching.maps.MapProviderFactory.MAP_LANGUAGE_DEFAULT_ID;
import static cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle.NO_OVERLAY_ID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.core.text.HtmlCompat;
import androidx.core.util.Supplier;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.graphics.AndroidResourceBitmap;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.model.common.Observer;
@SuppressLint("ClickableViewAccessibility")
@SuppressWarnings("PMD.ExcessiveClassLength") // This is definitely a valid issue, but can't be refactored in one step
public class NewMap extends AbstractActionBarActivity implements Observer, FilteredActivity {
private static final String STATE_INDIVIDUAlROUTEUTILS = "indrouteutils";
private static final String STATE_TRACKUTILS = "trackutils";
private static final String ROUTING_SERVICE_KEY = "NewMap";
private MfMapView mapView;
private TileCache tileCache;
private MapSource mapSource;
private ITileLayer tileLayer;
private HistoryLayer historyLayer;
private PositionLayer positionLayer;
private NavigationLayer navigationLayer;
private RouteLayer routeLayer;
private TrackLayer trackLayer;
private CachesBundle caches;
private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this));
private RenderThemeHelper renderThemeHelper = null; //must be initialized in onCreate();
private DistanceView distanceView;
private View mapAttribution;
private final ArrayList<TrailHistoryElement> trailHistory = null;
private String targetGeocode = null;
private Geopoint lastNavTarget = null;
private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>();
private ProgressDialog waitDialog;
private LoadDetails loadDetailsThread;
private ProgressBar spinner;
private final UpdateLoc geoDirUpdate = new UpdateLoc(this);
/**
* initialization with an empty subscription to make static code analysis tools more happy
*/
private ProximityNotification proximityNotification;
private final CompositeDisposable resumeDisposables = new CompositeDisposable();
private CheckBox myLocSwitch;
private MapOptions mapOptions;
private TargetView targetView;
private IndividualRoute individualRoute = null;
private Route tracks = null;
private static boolean followMyLocation = true;
private static final String BUNDLE_MAP_STATE = "mapState";
private static final String BUNDLE_PROXIMITY_NOTIFICATION = "proximityNotification";
private static final String BUNDLE_ROUTE = "route";
// Handler messages
// DisplayHandler
public static final int UPDATE_TITLE = 0;
// ShowProgressHandler
public static final int HIDE_PROGRESS = 0;
public static final int SHOW_PROGRESS = 1;
// LoadDetailsHandler
public static final int UPDATE_PROGRESS = 0;
public static final int FINISHED_LOADING_DETAILS = 1;
private Viewport lastViewport = null;
private boolean lastCompactIconMode = false;
private MapMode mapMode;
private TrackUtils trackUtils = null;
private IndividualRouteUtils individualRouteUtils = null;
@Override
public void onCreate(final Bundle savedInstanceState) {
ApplicationSettings.setLocale(this);
super.onCreate(savedInstanceState);
Log.d("NewMap: onCreate");
trackUtils = new TrackUtils(this, savedInstanceState == null ? null : savedInstanceState.getBundle(STATE_TRACKUTILS), this::setTracks, this::centerOnPosition);
individualRouteUtils = new IndividualRouteUtils(this, savedInstanceState == null ? null : savedInstanceState.getBundle(STATE_INDIVIDUAlROUTEUTILS), this::clearIndividualRoute, this::reloadIndividualRoute);
ResourceBitmapCacheMonitor.addRef();
AndroidGraphicFactory.createInstance(this.getApplication());
MapsforgeMapProvider.getInstance().updateOfflineMaps();
this.renderThemeHelper = new RenderThemeHelper(this);
// Support for multi-threaded map painting
Parameters.NUMBER_OF_THREADS = Settings.getMapOsmThreads();
Log.i("OSM #threads=" + Parameters.NUMBER_OF_THREADS);
// Use fast parent tile rendering to increase performance when zooming in
Parameters.PARENT_TILES_RENDERING = Parameters.ParentTilesRendering.SPEED;
// Get parameters from the intent
mapOptions = new MapOptions(this, getIntent().getExtras());
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE);
proximityNotification = savedInstanceState.getParcelable(BUNDLE_PROXIMITY_NOTIFICATION);
individualRoute = savedInstanceState.getParcelable(BUNDLE_ROUTE);
followMyLocation = mapOptions.mapState.followsMyLocation();
} else {
individualRoute = null;
followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE;
proximityNotification = Settings.isGeneralProximityNotificationActive() ? new ProximityNotification(true, false) : null;
}
if (null != proximityNotification) {
proximityNotification.setTextNotifications(this);
}
ActivityMixin.onCreate(this, true);
// set layout
ActivityMixin.setTheme(this);
setContentView(R.layout.map_mapsforge_v6);
setTitle();
this.mapAttribution = findViewById(R.id.map_attribution);
// map settings popup
findViewById(R.id.map_settings_popup).setOnClickListener(v -> MapSettingsUtils.showSettingsPopup(this, individualRoute, this::refreshMapData, this::routingModeChanged, this::compactIconModeChanged, mapOptions.filterContext));
// prepare circular progress spinner
spinner = (ProgressBar) findViewById(R.id.map_progressbar);
spinner.setVisibility(View.GONE);
// initialize map
mapView = (MfMapView) findViewById(R.id.mfmapv5);
mapView.setClickable(true);
mapView.getMapScaleBar().setVisible(true);
mapView.setBuiltInZoomControls(true);
//make room for map attribution icon button
final int mapAttPx = Math.round(this.getResources().getDisplayMetrics().density * 30);
mapView.getMapScaleBar().setMarginHorizontal(mapAttPx);
// create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles)
tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor());
// attach drag handler
final DragHandler dragHandler = new DragHandler(this);
mapView.setOnMapDragListener(dragHandler);
mapMode = (mapOptions != null && mapOptions.mapMode != null) ? mapOptions.mapMode : MapMode.LIVE;
// prepare initial settings of mapView
if (mapOptions.mapState != null) {
this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter()));
this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel());
this.targetGeocode = mapOptions.mapState.getTargetGeocode();
this.lastNavTarget = mapOptions.mapState.getLastNavTarget();
mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled();
mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled();
} else if (mapOptions.searchResult != null) {
final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes());
if (viewport != null) {
postZoomToViewport(viewport);
}
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport viewport = DataStore.getBounds(mapOptions.geocode, Settings.getZoomIncludingWaypoints());
if (viewport != null) {
postZoomToViewport(viewport);
}
targetGeocode = mapOptions.geocode;
} else if (mapOptions.coords != null) {
postZoomToViewport(new Viewport(mapOptions.coords, 0, 0));
if (mapOptions.mapMode == MapMode.LIVE) {
mapOptions.coords = null; // no direction line, even if enabled in settings
followMyLocation = false; // do not center on GPS position, even if in LIVE mode
}
} else {
postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0));
}
FilterUtils.initializeFilterBar(this, this);
MapUtils.updateFilterBar(this, mapOptions.filterContext);
Routing.connect(ROUTING_SERVICE_KEY, () -> resumeRoute(true));
CompactIconModeUtils.setCompactIconModeThreshold(getResources());
MapsforgeMapProvider.getInstance().updateOfflineMaps();
MapUtils.showMapOneTimeMessages(this);
}
private void postZoomToViewport(final Viewport viewport) {
mapView.post(() -> mapView.zoomToViewport(viewport, this.mapMode));
}
@Override
public boolean onCreateOptionsMenu(@NonNull final Menu menu) {
final boolean result = super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.map_activity, menu);
MapProviderFactory.addMapviewMenuItems(this, menu);
MapProviderFactory.addMapViewLanguageMenuItems(menu);
initMyLocationSwitchButton(MapProviderFactory.createLocSwitchMenuItem(this, menu));
FilterUtils.initializeFilterMenu(this, this);
return result;
}
@Override
public boolean onPrepareOptionsMenu(@NonNull final Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mapOptions != null && (mapOptions.isLiveEnabled || mapOptions.isStoredEnabled)) {
ViewUtils.extendMenuActionBarDisplayItemCount(this, menu);
}
for (final MapSource mapSource : MapProviderFactory.getMapSources()) {
final MenuItem menuItem = menu.findItem(mapSource.getNumericalId());
if (menuItem != null) {
menuItem.setVisible(mapSource.isAvailable());
}
}
try {
final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live);
if (mapOptions.isLiveEnabled) {
itemMapLive.setIcon(R.drawable.ic_menu_refresh);
itemMapLive.setTitle(res.getString(R.string.map_live_disable));
} else {
itemMapLive.setIcon(R.drawable.ic_menu_sync_disabled);
itemMapLive.setTitle(res.getString(R.string.map_live_enable));
}
itemMapLive.setVisible(mapOptions.coords == null || mapOptions.mapMode == MapMode.LIVE);
final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes();
menu.findItem(R.id.menu_store_caches).setVisible(false);
menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty());
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false);
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches());
menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes());
menu.findItem(R.id.menu_theme_options).setVisible(tileLayerHasThemes() && this.renderThemeHelper.themeOptionsAvailable());
menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1);
this.individualRouteUtils.onPrepareOptionsMenu(menu, individualRoute, StringUtils.isNotBlank(targetGeocode) && null != lastNavTarget);
menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE);
menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE);
HistoryTrackUtils.onPrepareOptionsMenu(menu);
this.trackUtils.onPrepareOptionsMenu(menu);
} catch (final RuntimeException e) {
Log.e("NewMap.onPrepareOptionsMenu", e);
}
return true;
}
@Override
public void onConfigurationChanged(@NonNull final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
invalidateOptionsMenu();
}
@Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
final int id = item.getItemId();
if (id == android.R.id.home) {
ActivityMixin.navigateUp(this);
} else if (id == R.id.menu_map_live) {
mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled;
if (mapOptions.isLiveEnabled) {
mapOptions.isStoredEnabled = true;
mapOptions.filterContext = new GeocacheFilterContext(LIVE);
caches.setFilterContext(mapOptions.filterContext);
refreshMapData(false);
}
if (mapOptions.mapMode == MapMode.LIVE) {
Settings.setLiveMap(mapOptions.isLiveEnabled);
}
caches.handleStoredLayers(this, mapOptions);
caches.handleLiveLayers(this, mapOptions);
ActivityMixin.invalidateOptionsMenu(this);
if (mapOptions.mapMode != MapMode.SINGLE) {
mapOptions.title = StringUtils.EMPTY;
} else {
// reset target cache on single mode map
targetGeocode = mapOptions.geocode;
}
setTitle();
} else if (id == R.id.menu_filter) {
showFilterMenu(null);
} else if (id == R.id.menu_store_caches) {
return storeCaches(caches.getVisibleCacheGeocodes());
} else if (id == R.id.menu_store_unsaved_caches) {
return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes()));
} else if (id == R.id.menu_theme_mode) {
this.renderThemeHelper.selectMapTheme(this.tileLayer, this.tileCache);
} else if (id == R.id.menu_theme_options) {
this.renderThemeHelper.selectMapThemeOptions();
} else if (id == R.id.menu_as_list) {
CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes()));
} else if (id == R.id.menu_hint) {
menuShowHint();
} else if (id == R.id.menu_compass) {
menuCompass();
} else if (!HistoryTrackUtils.onOptionsItemSelected(this, id, () -> historyLayer.requestRedraw(), this::clearTrailHistory)
&& !this.trackUtils.onOptionsItemSelected(id, tracks)
&& !this.individualRouteUtils.onOptionsItemSelected(id, individualRoute, this::centerOnPosition, this::setTarget)
&& !DownloaderUtils.onOptionsItemSelected(this, id)) {
final String language = MapProviderFactory.getLanguage(id);
if (language != null || id == MAP_LANGUAGE_DEFAULT_ID) {
item.setChecked(true);
changeLanguage(language);
return true;
} else {
final MapSource mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
item.setChecked(true);
changeMapSource(mapSource);
} else {
return false;
}
}
}
return true;
}
private void refreshMapData(final boolean circlesSwitched) {
if (circlesSwitched) {
caches.switchCircles();
}
if (caches != null) {
caches.invalidate();
}
Tile.cache.clear();
if (null != trackLayer) {
trackLayer.setHidden(Settings.isHideTrack());
trackLayer.requestRedraw();
}
MapUtils.updateFilterBar(this, mapOptions.filterContext);
}
private void routingModeChanged(final RoutingMode newValue) {
Settings.setRoutingMode(newValue);
if ((null != individualRoute && individualRoute.getNumSegments() > 0) || null != tracks) {
Toast.makeText(this, R.string.brouter_recalculating, Toast.LENGTH_SHORT).show();
}
individualRoute.reloadRoute(routeLayer);
if (null != tracks) {
try {
AndroidRxUtils.andThenOnUi(Schedulers.computation(), () -> {
tracks.calculateNavigationRoute();
trackLayer.updateRoute(tracks);
}, () -> trackLayer.requestRedraw());
} catch (RejectedExecutionException e) {
Log.e("NewMap.routingModeChanged: RejectedExecutionException: " + e.getMessage());
}
}
navigationLayer.requestRedraw();
}
private void compactIconModeChanged(final int newValue) {
Settings.setCompactIconMode(newValue);
caches.invalidateAll(NO_OVERLAY_ID);
}
private void clearTrailHistory() {
this.historyLayer.reset();
this.historyLayer.requestRedraw();
showToast(res.getString(R.string.map_trailhistory_cleared));
}
private void clearIndividualRoute() {
individualRoute.clearRoute(routeLayer);
distanceView.showRouteDistance();
ActivityMixin.invalidateOptionsMenu(this);
showToast(res.getString(R.string.map_individual_route_cleared));
}
private void centerOnPosition(final double latitude, final double longitude, final Viewport viewport) {
followMyLocation = false;
switchMyLocationButton();
mapView.getModel().mapViewPosition.setMapPosition(new MapPosition(new LatLong(latitude, longitude), (byte) mapView.getMapZoomLevel()));
postZoomToViewport(viewport);
}
private Set<String> getUnsavedGeocodes(final Set<String> geocodes) {
final Set<String> unsavedGeocodes = new HashSet<>();
for (final String geocode : geocodes) {
if (!DataStore.isOffline(geocode, null)) {
unsavedGeocodes.add(geocode);
}
}
return unsavedGeocodes;
}
private boolean storeCaches(final Set<String> geocodes) {
if (!caches.isDownloading()) {
if (geocodes.isEmpty()) {
ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing));
return true;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.lists_title, selectedListIds -> storeCaches(geocodes, selectedListIds), true, Collections.emptySet(), false);
} else {
storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
return true;
}
private void menuCompass() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
CompassActivity.startActivityCache(this, cache);
}
}
private void menuShowHint() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
cache.showHintToast(this);
}
}
/**
* @param view Not used here, required by layout
*/
@Override
public void showFilterMenu(final View view) {
FilterUtils.openFilterActivity(this, mapOptions.filterContext,
new SearchResult(caches.getVisibleCacheGeocodes()).getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB));
}
@Override
public boolean showFilterList(final View view) {
return FilterUtils.openFilterList(this, mapOptions.filterContext);
}
@Override
public void refreshWithFilter(final GeocacheFilter filter) {
mapOptions.filterContext.set(filter);
refreshMapData(false);
}
private void changeMapSource(@NonNull final MapSource newSource) {
final MapSource oldSource = Settings.getMapSource();
final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource);
// Update MapSource in settings
Settings.setMapSource(newSource);
if (restartRequired) {
mapRestart();
} else if (mapView != null) { // changeMapSource can be called by onCreate()
switchTileLayer(newSource);
}
}
private void changeLanguage(final String language) {
Settings.setMapLanguage(language);
mapRestart();
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
mapOptions.mapState = currentMapState();
finish();
mapOptions.startIntent(this, Settings.getMapProvider().getMapClass());
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private MapState currentMapState() {
if (mapView == null) {
return null;
}
final Geopoint mapCenter = mapView.getViewport().getCenter();
return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, Settings.isShowCircles(), targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void switchTileLayer(final MapSource newSource) {
final ITileLayer oldLayer = this.tileLayer;
ITileLayer newLayer = null;
mapSource = newSource;
if (this.mapAttribution != null) {
this.mapAttribution.setOnClickListener(
new MapAttributionDisplayHandler(() -> this.mapSource.calculateMapAttribution(this)));
}
if (newSource instanceof AbstractMapsforgeMapSource) {
newLayer = ((AbstractMapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition);
}
ActivityMixin.invalidateOptionsMenu(this);
// Exchange layer
if (newLayer != null) {
mapView.setZoomLevelMax(newLayer.getZoomLevelMax());
mapView.setZoomLevelMin(newLayer.getZoomLevelMin());
// make sure map zoom level is within new zoom level boundaries
final int currentZoomLevel = mapView.getMapZoomLevel();
if (currentZoomLevel < newLayer.getZoomLevelMin()) {
mapView.setMapZoomLevel(newLayer.getZoomLevelMin());
} else if (currentZoomLevel > newLayer.getZoomLevelMax()) {
mapView.setMapZoomLevel(newLayer.getZoomLevelMax());
}
final Layers layers = this.mapView.getLayerManager().getLayers();
int index = 0;
if (oldLayer != null) {
index = layers.indexOf(oldLayer.getTileLayer()) + 1;
}
layers.add(index, newLayer.getTileLayer());
this.tileLayer = newLayer;
this.renderThemeHelper.reapplyMapTheme(this.tileLayer, this.tileCache);
this.tileLayer.onResume();
} else {
this.tileLayer = null;
}
// Cleanup
if (oldLayer != null) {
this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer());
oldLayer.getTileLayer().onDestroy();
}
tileCache.purge();
}
private void resumeTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onResume();
}
}
private void pauseTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onPause();
}
}
private boolean tileLayerHasThemes() {
if (tileLayer != null) {
return tileLayer.hasThemes();
}
return false;
}
private void resumeRoute(final boolean force) {
if (null == individualRoute || force) {
individualRoute = new IndividualRoute(this::setTarget);
individualRoute.reloadRoute(routeLayer);
} else {
individualRoute.updateRoute(routeLayer);
}
}
private void resumeTrack(final boolean preventReloading) {
if (null == tracks && !preventReloading) {
this.trackUtils.loadTracks(this::setTracks);
} else if (null != trackLayer) {
trackLayer.updateRoute(tracks);
}
}
@Override
protected void onResume() {
super.onResume();
Log.d("NewMap: onResume");
resumeTileLayer();
resumeRoute(false);
resumeTrack(false);
mapView.getModel().mapViewPosition.addObserver(this);
MapUtils.updateFilterBar(this, mapOptions.filterContext);
}
@Override
protected void onStart() {
super.onStart();
Log.d("NewMap: onStart");
initializeLayers();
}
private void initializeLayers() {
switchTileLayer(Settings.getMapSource());
// History Layer
this.historyLayer = new HistoryLayer(trailHistory);
this.mapView.getLayerManager().getLayers().add(this.historyLayer);
// RouteLayer
this.routeLayer = new RouteLayer(realRouteDistance -> {
if (null != this.distanceView) {
this.distanceView.setRouteDistance(realRouteDistance);
}
});
this.mapView.getLayerManager().getLayers().add(this.routeLayer);
// TrackLayer
this.trackLayer = new TrackLayer(Settings.isHideTrack());
this.mapView.getLayerManager().getLayers().add(this.trackLayer);
// NavigationLayer
Geopoint navTarget = lastNavTarget;
if (navTarget == null) {
navTarget = mapOptions.coords;
if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport bounds = DataStore.getBounds(mapOptions.geocode);
if (bounds != null) {
navTarget = bounds.center;
}
}
}
this.navigationLayer = new NavigationLayer(navTarget, realDistance -> {
if (null != this.distanceView) {
this.distanceView.setRealDistance(realDistance);
}
});
this.mapView.getLayerManager().getLayers().add(this.navigationLayer);
// GeoitemLayer
GeoitemLayer.resetColors();
// TapHandler
final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler());
this.mapView.getLayerManager().getLayers().add(tapHandlerLayer);
// Caches bundle
if (mapOptions.searchResult != null) {
this.caches = new CachesBundle(this, mapOptions.searchResult, this.mapView, this.mapHandlers);
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
this.caches = new CachesBundle(this, mapOptions.geocode, this.mapView, this.mapHandlers);
} else if (mapOptions.coords != null) {
this.caches = new CachesBundle(this, mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers);
} else {
caches = new CachesBundle(this, this.mapView, this.mapHandlers);
}
// Stored enabled map
caches.handleStoredLayers(this, mapOptions);
// Live enabled map
caches.handleLiveLayers(this, mapOptions);
caches.setFilterContext(mapOptions.filterContext);
// Position layer
this.positionLayer = new PositionLayer();
this.mapView.getLayerManager().getLayers().add(positionLayer);
//Distance view
this.distanceView = new DistanceView(findViewById(R.id.distance1).getRootView(), navTarget, Settings.isBrouterShowBothDistances());
//Target view
this.targetView = new TargetView((TextView) findViewById(R.id.target), (TextView) findViewById(R.id.targetSupersize), StringUtils.EMPTY, StringUtils.EMPTY);
final Geocache target = getCurrentTargetCache();
if (target != null) {
targetView.setTarget(target.getShortGeocode(), target.getName());
}
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this,
new RestartLocationPermissionGrantedCallback(PermissionRequestContext.NewMap) {
@Override
public void executeAfter() {
resumeDisposables.add(geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR));
}
});
}
@Override
public void onPause() {
Log.d("NewMap: onPause");
savePrefs();
pauseTileLayer();
mapView.getModel().mapViewPosition.removeObserver(this);
super.onPause();
}
@Override
protected void onStop() {
Log.d("NewMap: onStop");
waitDialog = null;
terminateLayers();
super.onStop();
}
private void terminateLayers() {
this.resumeDisposables.clear();
this.caches.onDestroy();
this.caches = null;
this.mapView.getLayerManager().getLayers().remove(this.positionLayer);
this.positionLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.navigationLayer);
this.navigationLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.routeLayer);
this.routeLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.trackLayer);
this.trackLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.historyLayer);
this.historyLayer = null;
if (this.tileLayer != null) {
this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer());
this.tileLayer.getTileLayer().onDestroy();
this.tileLayer = null;
}
}
/**
* store caches, invoked by "store offline" menu item
*
* @param listIds the lists to store the caches in
*/
private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) {
final int count = geocodes.size();
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this);
waitDialog = new ProgressDialog(this);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage());
waitDialog.setMax(count);
waitDialog.setOnCancelListener(arg0 -> {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
} catch (final Exception e) {
Log.e("CGeoMap.storeCaches.onCancel", e);
}
});
final float etaTime = count * 7.0f / 60.0f;
final int roundedEta = Math.round(etaTime);
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta));
}
loadDetailsHandler.setStart();
waitDialog.show();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds);
loadDetailsThread.start();
}
@Override
protected void onDestroy() {
Log.d("NewMap: onDestroy");
if (this.renderThemeHelper != null) {
this.renderThemeHelper.onDestroy();
this.renderThemeHelper = null;
}
this.tileCache.destroy();
this.mapView.getModel().mapViewPosition.destroy();
this.mapView.destroy();
ResourceBitmapCacheMonitor.release();
Routing.disconnect(ROUTING_SERVICE_KEY);
if (this.mapAttribution != null) {
this.mapAttribution.setOnClickListener(null);
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle(STATE_INDIVIDUAlROUTEUTILS, individualRouteUtils.getState());
outState.putBundle(STATE_TRACKUTILS, trackUtils.getState());
Log.d("New map: onSaveInstanceState");
final MapState state = prepareMapState();
outState.putParcelable(BUNDLE_MAP_STATE, state);
if (proximityNotification != null) {
outState.putParcelable(BUNDLE_PROXIMITY_NOTIFICATION, proximityNotification);
}
if (individualRoute != null) {
outState.putParcelable(BUNDLE_ROUTE, individualRoute);
}
}
private MapState prepareMapState() {
return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void centerMap(final Geopoint geopoint) {
mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude()));
}
public Location getCoordinates() {
final LatLong center = mapView.getModel().mapViewPosition.getCenter();
final Location loc = new Location("newmap");
loc.setLatitude(center.latitude);
loc.setLongitude(center.longitude);
return loc;
}
private void initMyLocationSwitchButton(final CheckBox locSwitch) {
myLocSwitch = locSwitch;
/*
* TODO: Switch back to ImageSwitcher for animations?
* myLocSwitch.setFactory(this);
* myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
* myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
*/
myLocSwitch.setOnClickListener(new MyLocationListener(this));
switchMyLocationButton();
}
// switch My Location button image
private void switchMyLocationButton() {
myLocSwitch.setChecked(followMyLocation);
if (followMyLocation) {
myLocationInMiddle(Sensors.getInstance().currentGeo());
}
}
public void showAddWaypoint(final LatLong tapLatLong) {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude));
} else if (Settings.isLongTapOnMapActivated()) {
InternalConnector.interactiveCreateCache(this, new Geopoint(tapLatLong.latitude, tapLatLong.longitude), mapOptions.fromList, true);
}
}
// set my location listener
private static class MyLocationListener implements View.OnClickListener {
@NonNull
private final WeakReference<NewMap> mapRef;
MyLocationListener(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
private void onFollowMyLocationClicked() {
followMyLocation = !followMyLocation;
final NewMap map = mapRef.get();
if (map != null) {
map.switchMyLocationButton();
}
}
@Override
public void onClick(final View view) {
onFollowMyLocationClicked();
}
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final GeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
private static final class DisplayHandler extends Handler {
@NonNull
private final WeakReference<NewMap> mapRef;
DisplayHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
map.setTitle();
map.setSubtitle();
break;
default:
break;
}
}
}
private void setTitle() {
final String title = calculateTitle();
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(MapUtils.getColoredValue(title));
}
}
@NonNull
private String calculateTitle() {
if (mapOptions.isLiveEnabled) {
return res.getString(R.string.map_live);
}
if (mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return cache.getName();
}
}
return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_map));
}
private void setSubtitle() {
final String subtitle = calculateSubtitle();
if (StringUtils.isEmpty(subtitle)) {
return;
}
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(MapUtils.getColoredValue(subtitle));
}
}
@NonNull
private String calculateSubtitle() {
if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return Formatter.formatMapSubtitle(cache);
}
return "";
}
// count caches in the sub title
final int visible = countVisibleCaches();
final int total = countTotalCaches();
final StringBuilder subtitle = new StringBuilder();
if (visible != total && Settings.isDebug()) {
subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total));
} else {
subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible));
}
return subtitle.toString();
}
private void switchCircles() {
caches.switchCircles();
}
private int countVisibleCaches() {
return caches != null ? caches.getVisibleCachesCount() : 0;
}
private int countTotalCaches() {
return caches != null ? caches.getCachesCount() : 0;
}
/**
* Updates the progress.
*/
private static final class ShowProgressHandler extends Handler {
private int counter = 0;
@NonNull
private final WeakReference<NewMap> mapRef;
ShowProgressHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
showProgress(false);
}
} else if (what == SHOW_PROGRESS) {
showProgress(true);
counter++;
}
}
private void showProgress(final boolean show) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
map.spinner.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
private static final class LoadDetailsHandler extends DisposableHandler {
private final int detailTotal;
private int detailProgress;
private long detailProgressTime;
private final WeakReference<NewMap> mapRef;
LoadDetailsHandler(final int detailTotal, final NewMap map) {
super();
this.detailTotal = detailTotal;
this.detailProgress = 0;
this.mapRef = new WeakReference<>(map);
}
public void setStart() {
detailProgressTime = System.currentTimeMillis();
}
@Override
public void handleRegularMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (msg.what == UPDATE_PROGRESS) {
if (detailProgress < detailTotal) {
detailProgress++;
}
if (map.waitDialog != null) {
final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
final int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
map.waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm));
} else {
final int minsRemaining = secondsRemaining / 60;
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) {
map.waitDialog.dismiss();
map.waitDialog.setOnCancelListener(null);
}
}
@Override
public void handleDispose() {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (map.loadDetailsThread != null) {
map.loadDetailsThread.stopIt();
}
}
}
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
@NonNull
Location currentLocation = Sensors.getInstance().currentGeo();
float currentHeading;
private long timeLastPositionOverlayCalculation = 0;
private long timeLastDistanceCheck = 0;
/**
* weak reference to the outer class
*/
@NonNull
private final WeakReference<NewMap> mapRef;
UpdateLoc(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void updateGeoDir(@NonNull final GeoData geo, final float dir) {
currentLocation = geo;
currentHeading = AngleUtils.getDirectionNow(dir);
repaintPositionOverlay();
}
@NonNull
public Location getCurrentLocation() {
return currentLocation;
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > (timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL)) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final NewMap map = mapRef.get();
if (map != null) {
final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) {
map.centerMap(new Geopoint(currentLocation));
}
if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) {
map.historyLayer.setCoordinates(currentLocation);
map.navigationLayer.setCoordinates(currentLocation);
map.distanceView.setCoordinates(currentLocation);
map.distanceView.showRouteDistance();
map.positionLayer.setCoordinates(currentLocation);
map.positionLayer.setHeading(currentHeading);
map.positionLayer.requestRedraw();
if (null != map.proximityNotification && (timeLastDistanceCheck == 0 || currentTimeMillis > (timeLastDistanceCheck + MIN_UPDATE_INTERVAL))) {
map.proximityNotification.checkDistance(map.caches.getClosestDistanceInM(new Geopoint(currentLocation.getLatitude(), currentLocation.getLongitude())));
timeLastDistanceCheck = System.currentTimeMillis();
}
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location", e);
}
}
}
boolean needsRepaintForHeading() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistanceOrAccuracy() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.getCoordinates();
float dist = Float.MAX_VALUE;
if (lastLocation != null) {
if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) {
return true;
}
dist = currentLocation.distanceTo(lastLocation);
}
final float[] mapDimension = new float[1];
if (map.mapView.getWidth() < map.mapView.getHeight()) {
final double span = map.mapView.getLongitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension);
} else {
final double span = map.mapView.getLatitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension);
}
return dist > (mapDimension[0] * MIN_LOCATION_DELTA);
}
}
private static class DragHandler implements OnMapDragListener {
@NonNull
private final WeakReference<NewMap> mapRef;
DragHandler(@NonNull final NewMap parent) {
mapRef = new WeakReference<>(parent);
}
@Override
public void onDrag() {
final NewMap map = mapRef.get();
if (map != null && NewMap.followMyLocation) {
NewMap.followMyLocation = false;
map.switchMyLocationButton();
}
}
}
public void showSelection(@NonNull final List<GeoitemRef> items, final boolean longPressMode) {
if (items.isEmpty()) {
return;
}
if (items.size() == 1) {
if (longPressMode) {
if (Settings.isLongTapOnMapActivated()) {
toggleRouteItem(items.get(0));
}
} else {
showPopup(items.get(0));
}
return;
}
try {
final ArrayList<GeoitemRef> sorted = new ArrayList<>(items);
Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR);
final LayoutInflater inflater = LayoutInflater.from(this);
final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
final View view = convertView == null ? inflater.inflate(R.layout.cacheslist_item_select, parent, false) : convertView;
final TextView tv = (TextView) view.findViewById(R.id.text);
final GeoitemRef item = getItem(position);
tv.setText(item.getName());
final StringBuilder text = new StringBuilder(item.getShortItemCode());
final String geocode = item.getGeocode();
final String shortgeocode = item.getShortGeocode();
if (StringUtils.isNotEmpty(geocode)) {
final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null && item.getType() == CoordinatesType.CACHE) {
tv.setCompoundDrawablesRelativeWithIntrinsicBounds(MapMarkerUtils.getCacheMarker(res, cache, CacheListType.MAP).getDrawable(), null, null, null);
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0);
if (item.getType() == CoordinatesType.WAYPOINT) {
text.append(Formatter.SEPARATOR).append(shortgeocode);
if (cache != null) {
text.append(Formatter.SEPARATOR).append(cache.getName());
}
}
}
} else {
tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0);
}
final TextView infoView = (TextView) view.findViewById(R.id.info);
infoView.setText(text.toString());
return view;
}
};
final AlertDialog dialog = Dialogs.newBuilder(this)
.setTitle(res.getString(R.string.map_select_multiple_items))
.setAdapter(adapter, new SelectionClickListener(sorted, longPressMode))
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
} catch (final NotFoundException e) {
Log.e("NewMap.showSelection", e);
}
}
private class SelectionClickListener implements DialogInterface.OnClickListener {
@NonNull
private final List<GeoitemRef> items;
private final boolean longPressMode;
SelectionClickListener(@NonNull final List<GeoitemRef> items, final boolean longPressMode) {
this.items = items;
this.longPressMode = longPressMode;
}
@Override
public void onClick(final DialogInterface dialog, final int which) {
if (which >= 0 && which < items.size()) {
final GeoitemRef item = items.get(which);
if (longPressMode) {
if (Settings.isLongTapOnMapActivated()) {
toggleRouteItem(item);
}
} else {
showPopup(item);
}
}
}
}
private void showPopup(final GeoitemRef item) {
if (item == null || StringUtils.isEmpty(item.getGeocode())) {
return;
}
try {
if (item.getType() == CoordinatesType.CACHE) {
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
popupGeocodes.add(cache.getGeocode());
CachePopup.startActivityAllowTarget(this, cache.getGeocode());
return;
}
return;
}
if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) {
popupGeocodes.add(item.getGeocode());
WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode());
}
} catch (final NotFoundException e) {
Log.e("NewMap.showPopup", e);
}
}
private void toggleRouteItem(final GeoitemRef item) {
if (item == null || StringUtils.isEmpty(item.getGeocode())) {
return;
}
if (individualRoute == null) {
individualRoute = new IndividualRoute(this::setTarget);
}
individualRoute.toggleItem(this, new RouteItem(item), routeLayer);
distanceView.showRouteDistance();
ActivityMixin.invalidateOptionsMenu(this);
}
@Nullable
private Geocache getSingleModeCache() {
if (StringUtils.isNotBlank(mapOptions.geocode)) {
return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
@Nullable
private Geocache getCurrentTargetCache() {
if (StringUtils.isNotBlank(targetGeocode)) {
return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
private void setTarget(final Geopoint coords, final String geocode) {
lastNavTarget = coords;
if (navigationLayer != null) {
navigationLayer.setDestination(lastNavTarget);
navigationLayer.requestRedraw();
}
if (distanceView != null) {
distanceView.setDestination(lastNavTarget);
distanceView.setCoordinates(geoDirUpdate.getCurrentLocation());
}
if (StringUtils.isNotBlank(geocode)) {
targetGeocode = geocode;
final Geocache target = getCurrentTargetCache();
targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY);
} else {
targetGeocode = null;
targetView.setTarget(null, null);
}
ActivityMixin.invalidateOptionsMenu(this);
}
private void savePrefs() {
Settings.setMapZoom(this.mapMode, mapView.getMapZoomLevel());
Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter()));
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
private final DisposableHandler handler;
private final Collection<String> geocodes;
private final Set<Integer> listIds;
LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) {
this.handler = handler;
this.geocodes = geocodes;
this.listIds = listIds;
}
public void stopIt() {
handler.dispose();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
for (final String geocode : geocodes) {
try {
if (handler.isDisposed()) {
break;
}
if (!DataStore.isOffline(geocode, null)) {
Geocache.storeCache(null, geocode, listIds, false, handler);
}
} catch (final Exception e) {
Log.e("CGeoMap.LoadDetails.run", e);
} finally {
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
}
// we're done, but map might even have been closed.
if (caches != null) {
caches.invalidate(geocodes);
}
invalidateOptionsMenuCompatible();
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) {
if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) {
final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO);
if (targetInfo != null) {
if (Settings.isAutotargetIndividualRoute()) {
Settings.setAutotargetIndividualRoute(false);
Toast.makeText(this, R.string.map_disable_autotarget_individual_route, Toast.LENGTH_SHORT).show();
}
setTarget(targetInfo.coords, targetInfo.geocode);
}
}
final List<String> changedGeocodes = new ArrayList<>();
String geocode = popupGeocodes.poll();
while (geocode != null) {
changedGeocodes.add(geocode);
geocode = popupGeocodes.poll();
}
if (caches != null) {
caches.invalidate(changedGeocodes);
}
}
if (requestCode == GeocacheFilterActivity.REQUEST_SELECT_FILTER && resultCode == Activity.RESULT_OK) {
mapOptions.filterContext = data.getParcelableExtra(EXTRA_FILTER_CONTEXT);
refreshMapData(false);
}
this.trackUtils.onActivityResult(requestCode, resultCode, data);
this.individualRouteUtils.onActivityResult(requestCode, resultCode, data);
}
private void setTracks(final Route route) {
tracks = route;
resumeTrack(null == tracks);
this.trackUtils.showTrackInfo(tracks);
}
private void reloadIndividualRoute() {
if (null != routeLayer) {
individualRoute.reloadRoute(routeLayer);
} else {
// try again in 0.25 second
new Handler(Looper.getMainLooper()).postDelayed(this::reloadIndividualRoute, 250);
}
}
private static class ResourceBitmapCacheMonitor {
private static int refCount = 0;
static synchronized void addRef() {
refCount++;
Log.d("ResourceBitmapCacheMonitor.addRef");
}
static synchronized void release() {
if (refCount > 0) {
refCount--;
Log.d("ResourceBitmapCacheMonitor.release");
if (refCount == 0) {
Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps");
AndroidResourceBitmap.clearResourceBitmaps();
}
}
}
}
public boolean getLastCompactIconMode() {
return lastCompactIconMode;
}
public boolean checkCompactIconMode(final int overlayId, final int newCount) {
boolean newCompactIconMode = lastCompactIconMode;
if (null != caches) {
newCompactIconMode = CompactIconModeUtils.forceCompactIconMode(caches.getVisibleCachesCount(overlayId, newCount));
if (lastCompactIconMode != newCompactIconMode) {
lastCompactIconMode = newCompactIconMode;
// @todo Exchanging & redrawing the icons would be sufficient, do not have to invalidate everything!
caches.invalidateAll(overlayId); // redraw all icons except for the given overlay
}
}
return newCompactIconMode;
}
// get notified for viewport changes (zoom/pan)
public void onChange() {
final Viewport newViewport = mapView.getViewport();
if (!newViewport.equals(lastViewport)) {
lastViewport = newViewport;
checkCompactIconMode(NO_OVERLAY_ID, 0);
}
}
public static class MapAttributionDisplayHandler implements View.OnClickListener {
private Supplier<ImmutablePair<String, Boolean>> attributionSupplier;
private ImmutablePair<String, Boolean> attributionPair;
public MapAttributionDisplayHandler(final Supplier<ImmutablePair<String, Boolean>> attributionSupplier) {
this.attributionSupplier = attributionSupplier;
}
@Override
public void onClick(final View v) {
if (this.attributionPair == null) {
this.attributionPair = attributionSupplier.get();
if (this.attributionPair == null || this.attributionPair.left == null) {
this.attributionPair = new ImmutablePair<>("---", false);
}
this.attributionSupplier = null; //prevent possible memory leaks
}
displayMapAttribution(v.getContext(), this.attributionPair.left, this.attributionPair.right);
}
}
private static void displayMapAttribution(final Context ctx, final String attribution, final boolean linkify) {
//create text message
CharSequence message = HtmlCompat.fromHtml(attribution, HtmlCompat.FROM_HTML_MODE_LEGACY);
if (linkify) {
final SpannableString s = new SpannableString(message);
Linkify.addLinks(s, Linkify.ALL);
message = s;
}
final AlertDialog alertDialog = Dialogs.newBuilder(ctx)
.setTitle(ctx.getString(R.string.map_source_attribution_dialog_title))
.setCancelable(true)
.setMessage(message)
.setPositiveButton(android.R.string.ok, (dialog, pos) -> dialog.dismiss())
.create();
alertDialog.show();
// Make the URLs in TextView clickable. Must be called after show()
// Note: we do NOT use the "setView()" option of AlertDialog because this screws up the layout
((TextView) alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
}
|
3e160ea62a3a660beda8bdc03a999c19a896fe4c | 3,875 | java | Java | kie-pmml-trusty/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-common/src/test/java/org/kie/pmml/models/drools/utils/KiePMMLASTTestUtils.java | baldimir/drools | 3419454727d048a3cb2524ee1916ccaaab6118e1 | [
"Apache-2.0"
] | 3,631 | 2017-03-14T08:54:05.000Z | 2022-03-31T19:59:10.000Z | kie-pmml-trusty/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-common/src/test/java/org/kie/pmml/models/drools/utils/KiePMMLASTTestUtils.java | baldimir/drools | 3419454727d048a3cb2524ee1916ccaaab6118e1 | [
"Apache-2.0"
] | 2,274 | 2017-03-13T14:02:17.000Z | 2022-03-28T17:23:17.000Z | kie-pmml-trusty/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-common/src/test/java/org/kie/pmml/models/drools/utils/KiePMMLASTTestUtils.java | baldimir/drools | 3419454727d048a3cb2524ee1916ccaaab6118e1 | [
"Apache-2.0"
] | 1,490 | 2017-03-14T11:37:37.000Z | 2022-03-31T08:50:22.000Z | 46.686747 | 224 | 0.702452 | 9,388 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.pmml.models.drools.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.DataField;
import org.dmg.pmml.DataType;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.LocalTransformations;
import org.dmg.pmml.OpType;
import org.dmg.pmml.OutputField;
import org.dmg.pmml.Predicate;
import org.dmg.pmml.TransformationDictionary;
import org.kie.pmml.models.drools.ast.KiePMMLDroolsRule;
import org.kie.pmml.models.drools.ast.factories.KiePMMLDataDictionaryASTFactory;
import org.kie.pmml.models.drools.ast.factories.KiePMMLDerivedFieldASTFactory;
import org.kie.pmml.models.drools.ast.factories.PredicateASTFactoryData;
import org.kie.pmml.models.drools.tuples.KiePMMLOriginalTypeGeneratedType;
import static org.kie.pmml.compiler.api.CommonTestingUtils.getFieldsFromDataDictionary;
/**
* Utility methods for other <b>Test</b> classes
*/
public class KiePMMLASTTestUtils {
public static PredicateASTFactoryData getPredicateASTFactoryData(Predicate predicate,
List<OutputField> outputFields,
List<KiePMMLDroolsRule> rules,
String parentPath,
String currentRule,
Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) {
return new PredicateASTFactoryData(predicate, outputFields, rules, parentPath, currentRule, fieldTypeMap);
}
public static Map<String, KiePMMLOriginalTypeGeneratedType> getFieldTypeMap(final DataDictionary dataDictionary, final TransformationDictionary transformationDictionary, final LocalTransformations localTransformations) {
final Map<String, KiePMMLOriginalTypeGeneratedType> toReturn = new HashMap<>();
KiePMMLDerivedFieldASTFactory kiePMMLDerivedFieldASTFactory = KiePMMLDerivedFieldASTFactory.factory(toReturn);
if (transformationDictionary != null && transformationDictionary.getDerivedFields() != null) {
kiePMMLDerivedFieldASTFactory.declareTypes(transformationDictionary.getDerivedFields());
}
if (localTransformations != null && localTransformations.getDerivedFields() != null) {
kiePMMLDerivedFieldASTFactory.declareTypes(localTransformations.getDerivedFields());
}
KiePMMLDataDictionaryASTFactory.factory(toReturn).declareTypes(getFieldsFromDataDictionary(dataDictionary));
return toReturn;
}
public static DataField getTypeDataField() {
DataField toReturn = new DataField();
toReturn.setOpType(OpType.CONTINUOUS);
toReturn.setDataType(DataType.DATE);
toReturn.setName(FieldName.create("dataField"));
return toReturn;
}
public static DataField getDottedTypeDataField() {
DataField toReturn = new DataField();
toReturn.setOpType(OpType.CONTINUOUS);
toReturn.setDataType(DataType.BOOLEAN);
toReturn.setName(FieldName.create("dotted.field"));
return toReturn;
}
}
|
3e1610c7ad9d851ebb4cfca0e91cc82bb4ae2aa2 | 4,022 | java | Java | src/main/java/br/com/juliomendes90/drogaria/bean/PessoaBean.java | juliomendes90/Drogaria | 55c4d66e70d53c14728141bcded0990f6bcf36a0 | [
"MIT"
] | null | null | null | src/main/java/br/com/juliomendes90/drogaria/bean/PessoaBean.java | juliomendes90/Drogaria | 55c4d66e70d53c14728141bcded0990f6bcf36a0 | [
"MIT"
] | 2 | 2020-09-01T12:53:03.000Z | 2020-09-01T14:30:49.000Z | src/main/java/br/com/juliomendes90/drogaria/bean/PessoaBean.java | juliomendes90/Drogaria | 55c4d66e70d53c14728141bcded0990f6bcf36a0 | [
"MIT"
] | null | null | null | 23.248555 | 84 | 0.711835 | 9,389 | package br.com.juliomendes90.drogaria.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.omnifaces.util.Messages;
import br.com.juliomendes90.drogaria.dao.CidadeDAO;
import br.com.juliomendes90.drogaria.dao.EstadoDAO;
import br.com.juliomendes90.drogaria.dao.PessoaDAO;
import br.com.juliomendes90.drogaria.domain.Cidade;
import br.com.juliomendes90.drogaria.domain.Estado;
import br.com.juliomendes90.drogaria.domain.Pessoa;
@ManagedBean
@ViewScoped
public class PessoaBean implements Serializable {
private static final long serialVersionUID = 1772840956527686974L;
private Pessoa pessoa;
private List<Pessoa> pessoas;
private Estado estado;
private List<Estado> estados;
private List<Cidade> cidades;
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public List<Pessoa> getPessoas() {
return pessoas;
}
public void setPessoas(List<Pessoa> pessoas) {
this.pessoas = pessoas;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public List<Estado> getEstados() {
return estados;
}
public void setEstados(List<Estado> estados) {
this.estados = estados;
}
public List<Cidade> getCidades() {
return cidades;
}
public void setCidades(List<Cidade> cidades) {
this.cidades = cidades;
}
@PostConstruct
public void listar() {
try {
PessoaDAO pessoaDAO = new PessoaDAO();
pessoas = pessoaDAO.listar("nome");
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar listar as pessoas");
erro.printStackTrace();
}
}
public void novo() {
try {
pessoa = new Pessoa();
estado = new Estado();
EstadoDAO estadoDAO = new EstadoDAO();
estados = estadoDAO.listar("nome");
cidades = new ArrayList<>();
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar gerar uma nova pessoa");
erro.printStackTrace();
}
}
public void editar(ActionEvent evento) {
try{
pessoa = (Pessoa) evento.getComponent().getAttributes().get("pessoaSelecionada");
estado = pessoa.getCidade().getEstado();
EstadoDAO estadoDAO = new EstadoDAO();
estados = estadoDAO.listar("nome");
CidadeDAO cidadeDAO = new CidadeDAO();
cidades = cidadeDAO.buscarPorEstado(estado.getCodigo());
}catch(RuntimeException erro){
Messages.addGlobalError("Ocorreu um erro ao tentar selecionar uma pessoa");
}
}
public void salvar() {
try {
PessoaDAO pessoaDAO = new PessoaDAO();
pessoaDAO.merge(pessoa);
pessoas = pessoaDAO.listar("nome");
pessoa = new Pessoa();
estado = new Estado();
EstadoDAO estadoDAO = new EstadoDAO();
estados = estadoDAO.listar("nome");
cidades = new ArrayList<>();
Messages.addGlobalInfo("Pessoa salva com sucesso");
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar salvar a pessoa");
erro.printStackTrace();
}
}
public void excluir(ActionEvent evento) {
try {
pessoa = (Pessoa) evento.getComponent().getAttributes().get("pessoaSelecionada");
PessoaDAO pessoaDAO = new PessoaDAO();
pessoaDAO.excluir(pessoa);
pessoas = pessoaDAO.listar();
Messages.addGlobalInfo("Pessoa removida com sucesso");
} catch (RuntimeException erro) {
Messages.addFlashGlobalError("Ocorreu um erro ao tentar remover o estado");
erro.printStackTrace();
}
}
public void popular() {
try {
if (estado != null) {
CidadeDAO cidadeDAO = new CidadeDAO();
cidades = cidadeDAO.buscarPorEstado(estado.getCodigo());
} else {
cidades = new ArrayList<>();
}
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao tentar filtrar as cidades");
erro.printStackTrace();
}
}
}
|
3e1610cf534f5b8b05a8cabaaad81abba6dd6b8f | 901 | java | Java | src/main/java/sw01/Task.java | asdfqwer12345/AD_Ex | c6d3f698a48f0a01a8b8a436e38b26bb78057808 | [
"Apache-2.0"
] | null | null | null | src/main/java/sw01/Task.java | asdfqwer12345/AD_Ex | c6d3f698a48f0a01a8b8a436e38b26bb78057808 | [
"Apache-2.0"
] | null | null | null | src/main/java/sw01/Task.java | asdfqwer12345/AD_Ex | c6d3f698a48f0a01a8b8a436e38b26bb78057808 | [
"Apache-2.0"
] | null | null | null | 22.525 | 61 | 0.566038 | 9,390 | package sw01;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Task {
private static final Logger LOG = LogManager.getLogger();
private static int task1Counter = 0;
private static int task2Counter = 0;
private static int task3Counter = 0;
public static void task(int n){
task1(); task1(); task1();
for(int i = 0;i<n;i++){
task2();task2(); task2();
for(int j = 0; j<n;j++){
task3(); task3();
}
}
LOG.info("Task1 Counter: " + task1Counter);
LOG.info("Task2 Counter: " + task2Counter);
LOG.info("Task3 Counter: " + task3Counter);
}
private static void task1(){
task1Counter++;
}
private static void task2(){
task2Counter++;
}
private static void task3(){
task3Counter++;
}
}
|
3e16128df5f1a607e0f0e931833572fd2d75c477 | 7,744 | java | Java | bridge-impl/src/main/java/com/liferay/faces/bridge/application/internal/ResourceRichFacesPackedJSImpl.java | jgorny/liferay-faces-bridge-impl | 4b3523626f2390401eaf96dbf5f75cdfe3c3baaf | [
"Apache-2.0"
] | 11 | 2015-09-09T13:19:15.000Z | 2022-03-15T09:15:31.000Z | bridge-impl/src/main/java/com/liferay/faces/bridge/application/internal/ResourceRichFacesPackedJSImpl.java | jgorny/liferay-faces-bridge-impl | 4b3523626f2390401eaf96dbf5f75cdfe3c3baaf | [
"Apache-2.0"
] | 333 | 2015-09-30T19:39:31.000Z | 2022-01-28T03:37:19.000Z | bridge-impl/src/main/java/com/liferay/faces/bridge/application/internal/ResourceRichFacesPackedJSImpl.java | jgorny/liferay-faces-bridge-impl | 4b3523626f2390401eaf96dbf5f75cdfe3c3baaf | [
"Apache-2.0"
] | 60 | 2015-09-04T17:35:57.000Z | 2022-03-09T17:00:08.000Z | 38.72 | 185 | 0.713456 | 9,391 | /**
* Copyright (c) 2000-2021 Liferay, 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.liferay.faces.bridge.application.internal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.Resource;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import com.liferay.faces.util.application.FilteredResourceBase;
import com.liferay.faces.util.logging.Logger;
import com.liferay.faces.util.logging.LoggerFactory;
import com.liferay.faces.util.product.Product;
import com.liferay.faces.util.product.ProductFactory;
/**
* @author Kyle Stiemann
*/
public class ResourceRichFacesPackedJSImpl extends FilteredResourceBase {
// Logger
private static final Logger logger = LoggerFactory.getLogger(ResourceRichFacesPackedJSImpl.class);
// Private Members
private Resource wrappedResource;
public ResourceRichFacesPackedJSImpl(Resource wrappedResource) {
// Since we cannot extend two classes, we wrap the default ResourceRichFacesImpl to ensure that all RichFaces
// resource implementations include the base functionality.
this.wrappedResource = new ResourceRichFacesImpl(wrappedResource);
}
@Override
public Resource getWrapped() {
return wrappedResource;
}
@Override
protected String filter(String javaScriptText) {
// Replace the URL used by rich:fileUpload for forum submission.
// http://issues.liferay.com/browse/FACES-1234
// https://issues.jboss.org/browse/RF-12273
String token = "this.form.attr(\"action\", originalAction + delimiter + UID + \"=\" + this.loadableItem.uid);";
int pos = javaScriptText.indexOf(token);
if (pos > 0) {
logger.debug("Found first token in packed.js");
StringBuilder buf = new StringBuilder();
buf.append(javaScriptText.substring(0, pos));
buf.append(
"this.form.attr(\"action\", this.form.children(\"input[name&='javax.faces.encodedURL']\").val() + delimiter + UID + \"=\" + this.loadableItem.uid);");
buf.append(javaScriptText.substring(pos + token.length() + 1));
javaScriptText = buf.toString();
}
javaScriptText = replaceToken(javaScriptText, "this.fileUpload.form.attr(\"action\")",
"this.fileUpload.form.children(\"input[name$='javax.faces.encodedURL']\").val()");
// Fix JavaScript error "TypeError: jQuery.atmosphere is undefined" by inserting checks for undefined variable.
// http://issues.liferay.com/browse/FACES-1532
javaScriptText = prependToken(javaScriptText, "if (jQuery.atmosphere.requests.length > 0) {",
"if (!jQuery.atmosphere) { return; }; ");
javaScriptText = prependToken(javaScriptText, "jQuery.atmosphere.unsubscribe();",
"if (!jQuery.atmosphere) { return; }; ");
javaScriptText = prependToken(javaScriptText, "$.atmosphere.unsubscribe();",
"if (!$.atmosphere) { return; }; ");
// JSF 2.3 incompatibility due to non-namespaced request parameters.
// http://issues.liferay.com/browse/FACES-3014
token = "this.fileUpload.form.find(\"input[name='javax.faces.ViewState']\").val();";
pos = javaScriptText.indexOf(token);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
final Product JSF = ProductFactory.getProductInstance(externalContext, Product.Name.JSF);
final int JSF_MAJOR_VERSION = JSF.getMajorVersion();
if (((JSF_MAJOR_VERSION > 2) || ((JSF_MAJOR_VERSION == 2) && (JSF.getMinorVersion() >= 3))) && (pos > 0)) {
logger.debug("Found javax.faces.ViewState selector in packed.js");
javaScriptText = replaceToken(javaScriptText, token,
"'',vsElem=this.fileUpload.form.find(\"input[name$='javax.faces.ViewState']\"),paramPrefix=vsElem.attr('name').substring(0,vsElem.attr('name').indexOf('javax.faces.ViewState'));");
javaScriptText = replaceToken(javaScriptText, "append(\"javax.faces.ViewState\",",
"append(vsElem.attr('name'),vsElem.val()+");
javaScriptText = replaceToken(javaScriptText, "javax.faces.partial.ajax=",
"\" + paramPrefix + \"javax.faces.partial.ajax=");
javaScriptText = replaceToken(javaScriptText, "javax.faces.partial.execute=",
"\" + paramPrefix + \"javax.faces.partial.execute=");
javaScriptText = replaceToken(javaScriptText, "javax.faces.ViewState=",
"\" + paramPrefix + \"javax.faces.ViewState=");
javaScriptText = replaceToken(javaScriptText, "javax.faces.source=",
"\" + paramPrefix + \"javax.faces.source=");
javaScriptText = replaceToken(javaScriptText, "org.richfaces.ajax.component=",
"\" + paramPrefix + \"org.richfaces.ajax.component=");
// Uncompressed: newAction = originalAction + delimiter + UID + "=" + this.uid
// Compressed: R=T+L+A+"="+this.uid
String regEx = "\\w+\\s*=\\s*\\w+\\s*\\+\\s*\\w+\\s*\\+\\s*\\w+\\s*\\+\\s*\"=\"\\s*\\+\\s*this.uid";
Matcher matcher = Pattern.compile(regEx).matcher(javaScriptText);
if (matcher.find()) {
String matchingText = javaScriptText.substring(matcher.start(), matcher.end());
String[] parts = matchingText.split("\\+");
String fixedMatchingText = parts[0] + "+" + parts[1] + "+ paramPrefix +" + parts[2] + "+" + parts[3] +
"+" + parts[4];
javaScriptText = javaScriptText.substring(0, matcher.start()) + fixedMatchingText +
javaScriptText.substring(matcher.end());
}
else {
logger.warn("Unable fix the javax.faces.ViewState value because newAction can't be found");
}
// Uncompressed: javax.faces.ViewState=" + encodeURIComponent(viewState)
// Compressed: javax.faces.ViewState="+encodeURIComponent(C)
regEx = "javax.faces.ViewState\\=\"\\s*\\+\\s*encodeURIComponent[(]\\w+[)]";
matcher = Pattern.compile(regEx).matcher(javaScriptText);
if (matcher.find()) {
String matchingText = javaScriptText.substring(matcher.start(), matcher.end());
int openParenPos = matchingText.indexOf("(");
String fixedMatchingText = matchingText.substring(0, openParenPos) + "(vsElem.val())";
javaScriptText = javaScriptText.substring(0, matcher.start()) + fixedMatchingText +
javaScriptText.substring(matcher.end());
}
else {
logger.warn("Unable to find and fix encodeURIComponent(viewState)");
}
}
return javaScriptText;
}
private String prependToken(String javaScriptText, String token, String prependText) {
int pos = javaScriptText.indexOf(token);
if (pos > 0) {
logger.debug("Found token=[{0}] in packed.js prependText=[{1}]", token, prependText);
StringBuilder buf = new StringBuilder();
buf.append(javaScriptText.substring(0, pos));
buf.append(prependText);
buf.append(javaScriptText.substring(pos));
javaScriptText = buf.toString();
}
return javaScriptText;
}
private String replaceToken(String javaScriptText, String token, String replacementText) {
int pos = javaScriptText.indexOf(token);
if (pos > 0) {
logger.debug("Found token=[{0}] in packed.js replacementText=[{1}]", token, replacementText);
StringBuilder buf = new StringBuilder();
buf.append(javaScriptText.substring(0, pos));
buf.append(replacementText);
buf.append(javaScriptText.substring(pos + token.length()));
javaScriptText = buf.toString();
}
return javaScriptText;
}
}
|
3e1612bd109c955ade6cfd5f430c3b08fd047f52 | 3,817 | java | Java | btcScammersApp/app/src/main/java/com/example/btcscammerswallets/ui/main/HistoryFragment.java | kamentr/University_Exams | f56218f90031feb5d6c99d722b5a85b8ceaab025 | [
"MIT"
] | null | null | null | btcScammersApp/app/src/main/java/com/example/btcscammerswallets/ui/main/HistoryFragment.java | kamentr/University_Exams | f56218f90031feb5d6c99d722b5a85b8ceaab025 | [
"MIT"
] | null | null | null | btcScammersApp/app/src/main/java/com/example/btcscammerswallets/ui/main/HistoryFragment.java | kamentr/University_Exams | f56218f90031feb5d6c99d722b5a85b8ceaab025 | [
"MIT"
] | null | null | null | 40.178947 | 133 | 0.718889 | 9,392 | package com.example.btcscammerswallets.ui.main;
import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.btcscammerswallets.MainActivity;
import com.example.btcscammerswallets.R;
import com.example.btcscammerswallets.business.data.view.BTCAccountHistory;
import com.example.btcscammerswallets.business.service.BTCAccountHistoryService;
import com.example.btcscammerswallets.ui.main.adapter.BTCAccountHistoryListAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class HistoryFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private final BTCAccountHistoryService BTCAccountHistoryService = new BTCAccountHistoryService();
private List<BTCAccountHistory> accountList = new ArrayList<>();
private BTCAccountHistoryListAdapter accountListAdapter;
private ListView listView;
public static HistoryFragment newInstance(int index) {
HistoryFragment fragment = new HistoryFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PageViewModel pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.tab_history, container, false);
FloatingActionButton refreshButton = root.findViewById(R.id.refreshButton);
refreshContent(root);
refreshButton.setOnClickListener(view -> refreshContent(root));
listView = (ListView) root.findViewById(R.id.addressList);
listView.setOnItemClickListener((parent, view, position, id) -> {
BTCAccountHistory account = (BTCAccountHistory) accountListAdapter.getItem(position);
deleteAccountFromHistory(root, account.getId());
});
return root;
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void deleteAccountFromHistory(View root, int id) {
new AlertDialog.Builder(MainActivity.getContext())
.setTitle(R.string.DELETE_TITLE_MESSAGE)
.setMessage(R.string.DELETE_PROMT_MESSAGE)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
BTCAccountHistoryService.delete(id);
refreshContent(root);
})
.setNegativeButton(android.R.string.cancel, ((dialog, which) -> {
})).show();
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void refreshContent(View root) {
accountList = BTCAccountHistoryService.getBTCAccountHistory();
accountListAdapter = new BTCAccountHistoryListAdapter(MainActivity.getContext(), R.layout.adapter_view_history, accountList);
listView = (ListView) root.findViewById(R.id.addressList);
listView.setAdapter(accountListAdapter);
}
}
|
3e161341c039147a5e3204eab4132a6acd9edbd9 | 703 | java | Java | src/main/java/com/quasiris/qsf/pipeline/filter/elastic/bean/InnerHitNested.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | 2 | 2019-05-14T19:01:34.000Z | 2019-09-20T13:43:42.000Z | src/main/java/com/quasiris/qsf/pipeline/filter/elastic/bean/InnerHitNested.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | 4 | 2018-05-22T08:11:24.000Z | 2020-10-13T07:19:02.000Z | src/main/java/com/quasiris/qsf/pipeline/filter/elastic/bean/InnerHitNested.java | quasiris/qsf-integration | 30bd8c3f82a74d382ca9af1834dea97bc086c49b | [
"MIT"
] | null | null | null | 20.085714 | 61 | 0.59175 | 9,393 | package com.quasiris.qsf.pipeline.filter.elastic.bean;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class InnerHitNested {
private String field;
private Integer offset;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
@Override
public String toString() {
return "Hit{" +
"field='" + field +
", offset='" + offset +
'}';
}
}
|
3e1613b4fc347c9126bb66e80c16cc0d95c9ba23 | 5,006 | java | Java | common/aws/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | 1 | 2019-09-11T01:13:03.000Z | 2019-09-11T01:13:03.000Z | common/aws/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | null | null | null | common/aws/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | null | null | null | 40.096 | 119 | 0.643855 | 9,394 | /**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <nnheo@example.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.jclouds.aws.handlers;
import static org.jclouds.http.HttpUtils.releasePayload;
import java.io.IOException;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.domain.AWSError;
import org.jclouds.aws.util.AWSUtils;
import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException;
import org.jclouds.logging.Logger;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.util.Strings2;
import com.google.common.annotations.VisibleForTesting;
/**
* This will parse and set an appropriate exception on the command object.
*
* @see AWSError
* @author Adrian Cole
*
*/
@Singleton
public class ParseAWSErrorFromXmlContent implements HttpErrorHandler {
@Resource
protected Logger logger = Logger.NULL;
@VisibleForTesting
final AWSUtils utils;
@Inject
public ParseAWSErrorFromXmlContent(AWSUtils utils) {
this.utils = utils;
}
public void handleError(HttpCommand command, HttpResponse response) {
Exception exception = new HttpResponseException(command, response);
try {
AWSError error = null;
String message = null;
if (response.getPayload() != null) {
String contentType = response.getPayload().getContentMetadata().getContentType();
if (contentType != null && (contentType.indexOf("xml") != -1 || contentType.indexOf("unknown") != -1)) {
error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response);
if (error != null) {
message = error.getMessage();
}
exception = new HttpResponseException(command, response, message);
} else {
try {
message = Strings2.toStringAndClose(response.getPayload().getInput());
exception = new HttpResponseException(command, response, message);
} catch (IOException e) {
}
}
}
message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(),
response.getStatusLine());
exception = refineException(command, response, exception, error, message);
} finally {
releasePayload(response);
command.setException(exception);
}
}
protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception, AWSError error,
String message) {
switch (response.getStatusCode()) {
case 400:
if (error != null && error.getCode() != null && (error.getCode().equals("UnsupportedOperation")))
exception = new UnsupportedOperationException(message, exception);
if (error != null && error.getCode() != null
&& (error.getCode().endsWith("NotFound") || error.getCode().endsWith(".Unknown")))
exception = new ResourceNotFoundException(message, exception);
else if ((error != null && error.getCode() != null && (error.getCode().equals("IncorrectState") || error
.getCode().endsWith(".Duplicate"))) || (message != null && (message.indexOf("already exists") != -1)))
exception = new IllegalStateException(message, exception);
else if (error != null && error.getCode() != null && error.getCode().equals("AuthFailure"))
exception = new AuthorizationException(message, exception);
else if (message != null && message.indexOf("Failed to bind the following fields") != -1)// Nova
exception = new IllegalArgumentException(message, exception);
break;
case 401:
case 403:
exception = new AuthorizationException(message, exception);
break;
case 404:
if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
exception = new ResourceNotFoundException(message, exception);
}
break;
case 409:
exception = new IllegalStateException(message, exception);
}
return exception;
}
} |
3e16151bc1d629f9f1413dfbdce7106264255c7f | 15,659 | java | Java | src/main/java/thaumcraft/client/renderers/models/gear/ModelKnightArmor.java | CDAGaming/TC_Research | bd60a75c767fdf20bef275000a06ee927605005f | [
"MIT"
] | null | null | null | src/main/java/thaumcraft/client/renderers/models/gear/ModelKnightArmor.java | CDAGaming/TC_Research | bd60a75c767fdf20bef275000a06ee927605005f | [
"MIT"
] | null | null | null | src/main/java/thaumcraft/client/renderers/models/gear/ModelKnightArmor.java | CDAGaming/TC_Research | bd60a75c767fdf20bef275000a06ee927605005f | [
"MIT"
] | null | null | null | 55.332155 | 146 | 0.652788 | 9,395 | package thaumcraft.client.renderers.models.gear;
import net.minecraft.client.model.*;
import net.minecraft.entity.*;
import net.minecraft.util.math.*;
import org.lwjgl.opengl.*;
public class ModelKnightArmor extends ModelCustomArmor
{
ModelRenderer Frontcloth1;
ModelRenderer Helmet;
ModelRenderer BeltR;
ModelRenderer Mbelt;
ModelRenderer MbeltL;
ModelRenderer MbeltR;
ModelRenderer BeltL;
ModelRenderer Chestplate;
ModelRenderer CloakAtL;
ModelRenderer Backplate;
ModelRenderer Cloak3;
ModelRenderer CloakAtR;
ModelRenderer Tabbard;
ModelRenderer Cloak1;
ModelRenderer Cloak2;
ModelRenderer ShoulderR1;
ModelRenderer GauntletR;
ModelRenderer GauntletstrapR1;
ModelRenderer GauntletstrapR2;
ModelRenderer ShoulderR;
ModelRenderer ShoulderR0;
ModelRenderer ShoulderR2;
ModelRenderer ShoulderL1;
ModelRenderer GauntletL;
ModelRenderer GauntletstrapL1;
ModelRenderer GauntletstrapL2;
ModelRenderer ShoulderL;
ModelRenderer ShoulderL0;
ModelRenderer ShoulderL2;
ModelRenderer SidepanelR3;
ModelRenderer SidepanelR2;
ModelRenderer SidepanelL2;
ModelRenderer SidepanelR0;
ModelRenderer SidepanelL0;
ModelRenderer SidepanelR1;
ModelRenderer SidepanelL3;
ModelRenderer Frontcloth2;
ModelRenderer SidepanelL1;
public ModelKnightArmor(final float f) {
super(f, 0, 128, 64);
this.field_78090_t = 128;
this.field_78089_u = 64;
(this.Helmet = new ModelRenderer((ModelBase)this, 41, 8)).func_78789_a(-4.5f, -9.0f, -4.5f, 9, 9, 9);
this.Helmet.func_78787_b(128, 64);
this.setRotation(this.Helmet, 0.0f, 0.0f, 0.0f);
(this.BeltR = new ModelRenderer((ModelBase)this, 76, 44)).func_78789_a(-5.0f, 4.0f, -3.0f, 1, 3, 6);
this.BeltR.func_78787_b(128, 64);
this.setRotation(this.BeltR, 0.0f, 0.0f, 0.0f);
(this.Mbelt = new ModelRenderer((ModelBase)this, 56, 55)).func_78789_a(-4.0f, 8.0f, -3.0f, 8, 4, 1);
this.Mbelt.func_78787_b(128, 64);
this.setRotation(this.Mbelt, 0.0f, 0.0f, 0.0f);
(this.MbeltL = new ModelRenderer((ModelBase)this, 76, 44)).func_78789_a(4.0f, 8.0f, -3.0f, 1, 3, 6);
this.MbeltL.func_78787_b(128, 64);
this.setRotation(this.MbeltL, 0.0f, 0.0f, 0.0f);
(this.MbeltR = new ModelRenderer((ModelBase)this, 76, 44)).func_78789_a(-5.0f, 8.0f, -3.0f, 1, 3, 6);
this.MbeltR.func_78787_b(128, 64);
this.setRotation(this.MbeltR, 0.0f, 0.0f, 0.0f);
(this.BeltL = new ModelRenderer((ModelBase)this, 76, 44)).func_78789_a(4.0f, 4.0f, -3.0f, 1, 3, 6);
this.BeltL.func_78787_b(128, 64);
this.setRotation(this.BeltL, 0.0f, 0.0f, 0.0f);
(this.Tabbard = new ModelRenderer((ModelBase)this, 114, 52)).func_78789_a(-3.0f, 1.2f, -3.5f, 6, 10, 1);
this.Tabbard.func_78787_b(128, 64);
this.setRotation(this.Tabbard, 0.0f, 0.0f, 0.0f);
(this.CloakAtL = new ModelRenderer((ModelBase)this, 0, 43)).func_78789_a(2.5f, 1.0f, 2.0f, 2, 1, 3);
this.CloakAtL.func_78787_b(128, 64);
this.setRotation(this.CloakAtL, 0.1396263f, 0.0f, 0.0f);
(this.Backplate = new ModelRenderer((ModelBase)this, 36, 45)).func_78789_a(-4.0f, 1.0f, 2.0f, 8, 11, 2);
this.Backplate.func_78787_b(128, 64);
this.setRotation(this.Backplate, 0.0f, 0.0f, 0.0f);
(this.Cloak1 = new ModelRenderer((ModelBase)this, 0, 47)).func_78789_a(0.0f, 0.0f, 0.0f, 9, 12, 1);
this.Cloak1.func_78793_a(-4.5f, 1.3f, 4.2f);
this.Cloak1.func_78787_b(128, 64);
this.setRotation(this.Cloak1, 0.1396263f, 0.0f, 0.0f);
(this.Cloak2 = new ModelRenderer((ModelBase)this, 0, 59)).func_78789_a(0.0f, 11.7f, -2.0f, 9, 4, 1);
this.Cloak2.func_78793_a(-4.5f, 1.3f, 4.2f);
this.Cloak2.func_78787_b(128, 64);
this.setRotation(this.Cloak2, 0.3069452f, 0.0f, 0.0f);
(this.Cloak3 = new ModelRenderer((ModelBase)this, 0, 59)).func_78789_a(0.0f, 15.2f, -4.2f, 9, 4, 1);
this.Cloak3.func_78793_a(-4.5f, 1.3f, 4.2f);
this.Cloak3.func_78787_b(128, 64);
this.setRotation(this.Cloak3, 0.4465716f, 0.0f, 0.0f);
(this.CloakAtR = new ModelRenderer((ModelBase)this, 0, 43)).func_78789_a(-4.5f, 1.0f, 2.0f, 2, 1, 3);
this.CloakAtR.func_78787_b(128, 64);
this.setRotation(this.CloakAtR, 0.1396263f, 0.0f, 0.0f);
(this.Chestplate = new ModelRenderer((ModelBase)this, 56, 45)).func_78789_a(-4.0f, 1.0f, -3.0f, 8, 7, 1);
this.Chestplate.func_78787_b(128, 64);
this.setRotation(this.Chestplate, 0.0f, 0.0f, 0.0f);
(this.ShoulderR1 = new ModelRenderer((ModelBase)this, 0, 19)).func_78789_a(-3.3f, 3.5f, -2.5f, 1, 1, 5);
this.ShoulderR1.func_78787_b(128, 64);
this.setRotation(this.ShoulderR1, 0.0f, 0.0f, 0.7853982f);
(this.GauntletR = new ModelRenderer((ModelBase)this, 100, 26)).func_78789_a(-3.5f, 3.5f, -2.5f, 2, 6, 5);
this.GauntletR.func_78787_b(128, 64);
this.GauntletR.field_78809_i = true;
this.setRotation(this.GauntletR, 0.0f, 0.0f, 0.0f);
(this.GauntletstrapR1 = new ModelRenderer((ModelBase)this, 84, 31)).func_78789_a(-1.5f, 3.5f, -2.5f, 3, 1, 5);
this.GauntletstrapR1.func_78787_b(128, 64);
this.GauntletstrapR1.field_78809_i = true;
this.setRotation(this.GauntletstrapR1, 0.0f, 0.0f, 0.0f);
(this.GauntletstrapR2 = new ModelRenderer((ModelBase)this, 84, 31)).func_78789_a(-1.5f, 6.5f, -2.5f, 3, 1, 5);
this.GauntletstrapR2.func_78787_b(128, 64);
this.GauntletstrapR2.field_78809_i = true;
this.setRotation(this.GauntletstrapR2, 0.0f, 0.0f, 0.0f);
(this.ShoulderR = new ModelRenderer((ModelBase)this, 56, 35)).func_78789_a(-3.5f, -2.5f, -2.5f, 5, 5, 5);
this.ShoulderR.func_78787_b(128, 64);
this.ShoulderR.field_78809_i = true;
this.setRotation(this.ShoulderR, 0.0f, 0.0f, 0.0f);
(this.ShoulderR0 = new ModelRenderer((ModelBase)this, 0, 0)).func_78789_a(-4.3f, -1.5f, -3.0f, 3, 5, 6);
this.ShoulderR0.func_78787_b(128, 64);
this.ShoulderR0.field_78809_i = true;
this.setRotation(this.ShoulderR0, 0.0f, 0.0f, 0.7853982f);
(this.ShoulderR2 = new ModelRenderer((ModelBase)this, 0, 11)).func_78789_a(-2.3f, 3.5f, -3.0f, 1, 2, 6);
this.ShoulderR2.func_78787_b(128, 64);
this.ShoulderR2.field_78809_i = true;
this.setRotation(this.ShoulderR2, 0.0f, 0.0f, 0.7853982f);
this.ShoulderL1 = new ModelRenderer((ModelBase)this, 0, 19);
this.ShoulderL1.field_78809_i = true;
this.ShoulderL1.func_78789_a(2.3f, 3.5f, -2.5f, 1, 1, 5);
this.ShoulderL1.func_78787_b(128, 64);
this.setRotation(this.ShoulderL1, 0.0f, 0.0f, -0.7853982f);
(this.GauntletL = new ModelRenderer((ModelBase)this, 114, 26)).func_78789_a(1.5f, 3.5f, -2.5f, 2, 6, 5);
this.GauntletL.func_78787_b(128, 64);
this.setRotation(this.GauntletL, 0.0f, 0.0f, 0.0f);
this.GauntletstrapL1 = new ModelRenderer((ModelBase)this, 84, 31);
this.GauntletstrapL1.field_78809_i = true;
this.GauntletstrapL1.func_78789_a(-1.5f, 3.5f, -2.5f, 3, 1, 5);
this.GauntletstrapL1.func_78787_b(128, 64);
this.setRotation(this.GauntletstrapL1, 0.0f, 0.0f, 0.0f);
this.GauntletstrapL2 = new ModelRenderer((ModelBase)this, 84, 31);
this.GauntletstrapL2.field_78809_i = true;
this.GauntletstrapL2.func_78789_a(-1.5f, 6.5f, -2.5f, 3, 1, 5);
this.GauntletstrapL2.func_78787_b(128, 64);
this.setRotation(this.GauntletstrapL2, 0.0f, 0.0f, 0.0f);
(this.ShoulderL = new ModelRenderer((ModelBase)this, 56, 35)).func_78789_a(-1.5f, -2.5f, -2.5f, 5, 5, 5);
this.ShoulderL.func_78787_b(128, 64);
this.setRotation(this.ShoulderL, 0.0f, 0.0f, 0.0f);
(this.ShoulderL0 = new ModelRenderer((ModelBase)this, 0, 0)).func_78789_a(1.3f, -1.5f, -3.0f, 3, 5, 6);
this.ShoulderL0.func_78787_b(128, 64);
this.setRotation(this.ShoulderL0, 0.0f, 0.0f, -0.7853982f);
(this.ShoulderL2 = new ModelRenderer((ModelBase)this, 0, 11)).func_78789_a(1.3f, 3.5f, -3.0f, 1, 2, 6);
this.ShoulderL2.func_78787_b(128, 64);
this.setRotation(this.ShoulderL2, 0.0f, 0.0f, -0.7853982f);
(this.SidepanelR3 = new ModelRenderer((ModelBase)this, 116, 13)).func_78789_a(-3.0f, 2.5f, -2.5f, 1, 4, 5);
this.SidepanelR3.func_78787_b(128, 64);
this.setRotation(this.SidepanelR3, 0.0f, 0.0f, 0.1396263f);
this.SidepanelR2 = new ModelRenderer((ModelBase)this, 114, 5);
this.SidepanelR2.field_78809_i = true;
this.SidepanelR2.func_78789_a(-2.0f, 2.5f, -2.5f, 2, 3, 5);
this.SidepanelR2.func_78787_b(128, 64);
this.setRotation(this.SidepanelR2, 0.0f, 0.0f, 0.1396263f);
(this.SidepanelL2 = new ModelRenderer((ModelBase)this, 114, 5)).func_78789_a(0.0f, 2.5f, -2.5f, 2, 3, 5);
this.SidepanelL2.func_78787_b(128, 64);
this.setRotation(this.SidepanelL2, 0.0f, 0.0f, -0.1396263f);
(this.SidepanelR0 = new ModelRenderer((ModelBase)this, 96, 14)).func_78789_a(-3.0f, -0.5f, -2.5f, 5, 3, 5);
this.SidepanelR0.func_78787_b(128, 64);
this.setRotation(this.SidepanelR0, 0.0f, 0.0f, 0.1396263f);
(this.SidepanelL0 = new ModelRenderer((ModelBase)this, 96, 14)).func_78789_a(-2.0f, -0.5f, -2.5f, 5, 3, 5);
this.SidepanelL0.func_78787_b(128, 64);
this.setRotation(this.SidepanelL0, 0.0f, 0.0f, -0.1396263f);
this.SidepanelR1 = new ModelRenderer((ModelBase)this, 96, 7);
this.SidepanelR1.field_78809_i = true;
this.SidepanelR1.func_78789_a(0.0f, 2.5f, -2.5f, 2, 2, 5);
this.SidepanelR1.func_78787_b(128, 64);
this.setRotation(this.SidepanelR1, 0.0f, 0.0f, 0.1396263f);
(this.SidepanelL3 = new ModelRenderer((ModelBase)this, 116, 13)).func_78789_a(2.0f, 2.5f, -2.5f, 1, 4, 5);
this.SidepanelL3.func_78787_b(128, 64);
this.setRotation(this.SidepanelL3, 0.0f, 0.0f, -0.1396263f);
(this.SidepanelL1 = new ModelRenderer((ModelBase)this, 96, 7)).func_78789_a(-2.0f, 2.5f, -2.5f, 2, 2, 5);
this.SidepanelL1.func_78787_b(128, 64);
this.setRotation(this.SidepanelL1, 0.0f, 0.0f, -0.1396263f);
(this.Frontcloth1 = new ModelRenderer((ModelBase)this, 120, 39)).func_78789_a(0.0f, 0.0f, 0.0f, 6, 8, 1);
this.Frontcloth1.func_78793_a(-3.0f, 11.0f, -3.5f);
this.Frontcloth1.func_78787_b(128, 64);
this.setRotation(this.Frontcloth1, -0.1047198f, 0.0f, 0.0f);
(this.Frontcloth2 = new ModelRenderer((ModelBase)this, 100, 37)).func_78789_a(0.0f, 7.5f, 1.8f, 6, 3, 1);
this.Frontcloth2.func_78793_a(-3.0f, 11.0f, -3.5f);
this.Frontcloth2.func_78787_b(128, 64);
this.setRotation(this.Frontcloth2, -0.3316126f, 0.0f, 0.0f);
this.field_178720_f.field_78804_l.clear();
this.field_78116_c.field_78804_l.clear();
this.field_78116_c.func_78792_a(this.Helmet);
this.field_78115_e.field_78804_l.clear();
this.field_178721_j.field_78804_l.clear();
this.field_178722_k.field_78804_l.clear();
this.field_78115_e.func_78792_a(this.Mbelt);
this.field_78115_e.func_78792_a(this.MbeltL);
this.field_78115_e.func_78792_a(this.MbeltR);
if (f >= 1.0f) {
this.field_78115_e.func_78792_a(this.Chestplate);
this.field_78115_e.func_78792_a(this.Frontcloth1);
this.field_78115_e.func_78792_a(this.Frontcloth2);
this.field_78115_e.func_78792_a(this.Tabbard);
this.field_78115_e.func_78792_a(this.Backplate);
this.field_78115_e.func_78792_a(this.Cloak1);
this.field_78115_e.func_78792_a(this.Cloak2);
this.field_78115_e.func_78792_a(this.Cloak3);
this.field_78115_e.func_78792_a(this.CloakAtL);
this.field_78115_e.func_78792_a(this.CloakAtR);
}
this.field_178723_h.field_78804_l.clear();
this.field_178723_h.func_78792_a(this.ShoulderR);
this.field_178723_h.func_78792_a(this.ShoulderR0);
this.field_178723_h.func_78792_a(this.ShoulderR1);
this.field_178723_h.func_78792_a(this.ShoulderR2);
this.field_178723_h.func_78792_a(this.GauntletR);
this.field_178723_h.func_78792_a(this.GauntletstrapR1);
this.field_178723_h.func_78792_a(this.GauntletstrapR2);
this.field_178724_i.field_78804_l.clear();
this.field_178724_i.func_78792_a(this.ShoulderL);
this.field_178724_i.func_78792_a(this.ShoulderL0);
this.field_178724_i.func_78792_a(this.ShoulderL1);
this.field_178724_i.func_78792_a(this.ShoulderL2);
this.field_178724_i.func_78792_a(this.GauntletL);
this.field_178724_i.func_78792_a(this.GauntletstrapL1);
this.field_178724_i.func_78792_a(this.GauntletstrapL2);
this.field_178721_j.func_78792_a(this.SidepanelR0);
this.field_178721_j.func_78792_a(this.SidepanelR1);
this.field_178721_j.func_78792_a(this.SidepanelR2);
this.field_178721_j.func_78792_a(this.SidepanelR3);
this.field_178722_k.func_78792_a(this.SidepanelL0);
this.field_178722_k.func_78792_a(this.SidepanelL1);
this.field_178722_k.func_78792_a(this.SidepanelL2);
this.field_178722_k.func_78792_a(this.SidepanelL3);
}
public void func_78088_a(final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5) {
this.func_78087_a(f, f1, f2, f3, f4, f5, entity);
final float a = MathHelper.func_76134_b(f * 0.6662f) * 1.4f * f1;
final float b = MathHelper.func_76134_b(f * 0.6662f + 3.1415927f) * 1.4f * f1;
final float c = Math.min(a, b);
this.Frontcloth1.field_78795_f = c - 0.1047198f;
this.Frontcloth2.field_78795_f = c - 0.3316126f;
this.Cloak1.field_78795_f = -c / 2.0f + 0.1396263f;
this.Cloak2.field_78795_f = -c / 2.0f + 0.3069452f;
this.Cloak3.field_78795_f = -c / 2.0f + 0.4465716f;
if (this.field_78091_s) {
final float f6 = 2.0f;
GL11.glPushMatrix();
GL11.glScalef(1.5f / f6, 1.5f / f6, 1.5f / f6);
GL11.glTranslatef(0.0f, 16.0f * f5, 0.0f);
this.field_78116_c.func_78785_a(f5);
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glScalef(1.0f / f6, 1.0f / f6, 1.0f / f6);
GL11.glTranslatef(0.0f, 24.0f * f5, 0.0f);
this.field_78115_e.func_78785_a(f5);
this.field_178723_h.func_78785_a(f5);
this.field_178724_i.func_78785_a(f5);
this.field_178721_j.func_78785_a(f5);
this.field_178722_k.func_78785_a(f5);
this.field_178720_f.func_78785_a(f5);
GL11.glPopMatrix();
}
else {
GL11.glPushMatrix();
GL11.glScalef(1.01f, 1.01f, 1.01f);
this.field_78116_c.func_78785_a(f5);
GL11.glPopMatrix();
this.field_78115_e.func_78785_a(f5);
this.field_178723_h.func_78785_a(f5);
this.field_178724_i.func_78785_a(f5);
this.field_178721_j.func_78785_a(f5);
this.field_178722_k.func_78785_a(f5);
this.field_178720_f.func_78785_a(f5);
}
}
private void setRotation(final ModelRenderer model, final float x, final float y, final float z) {
model.field_78795_f = x;
model.field_78796_g = y;
model.field_78808_h = z;
}
}
|
3e1615471392e5f9f8eea8680238cdced32978ad | 6,189 | java | Java | lucene/contrib/misc/src/test/org/apache/lucene/index/codecs/appending/TestAppendingCodec.java | chrismattmann/solrcene | 501a7df450df18d98146c83143ec17530a732aef | [
"Apache-2.0"
] | 3 | 2016-04-27T12:10:00.000Z | 2019-06-12T23:28:18.000Z | lucene/contrib/misc/src/test/org/apache/lucene/index/codecs/appending/TestAppendingCodec.java | chrismattmann/solrcene | 501a7df450df18d98146c83143ec17530a732aef | [
"Apache-2.0"
] | null | null | null | lucene/contrib/misc/src/test/org/apache/lucene/index/codecs/appending/TestAppendingCodec.java | chrismattmann/solrcene | 501a7df450df18d98146c83143ec17530a732aef | [
"Apache-2.0"
] | 5 | 2015-12-29T13:55:22.000Z | 2020-05-10T23:49:45.000Z | 35.164773 | 96 | 0.73566 | 9,396 | package org.apache.lucene.index.codecs.appending;
/*
* 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.
*/
import java.io.IOException;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.index.TermsEnum.SeekStatus;
import org.apache.lucene.index.codecs.Codec;
import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.index.codecs.SegmentInfosReader;
import org.apache.lucene.index.codecs.SegmentInfosWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.Version;
public class TestAppendingCodec extends LuceneTestCase {
static class AppendingCodecProvider extends CodecProvider {
Codec appending = new AppendingCodec();
SegmentInfosWriter infosWriter = new AppendingSegmentInfosWriter();
SegmentInfosReader infosReader = new AppendingSegmentInfosReader();
@Override
public Codec lookup(String name) {
return appending;
}
@Override
public Codec getWriter(SegmentWriteState state) {
return appending;
}
@Override
public SegmentInfosReader getSegmentInfosReader() {
return infosReader;
}
@Override
public SegmentInfosWriter getSegmentInfosWriter() {
return infosWriter;
}
}
private static class AppendingIndexOutputWrapper extends IndexOutput {
IndexOutput wrapped;
public AppendingIndexOutputWrapper(IndexOutput wrapped) {
this.wrapped = wrapped;
}
@Override
public void close() throws IOException {
wrapped.close();
}
@Override
public void flush() throws IOException {
wrapped.flush();
}
@Override
public long getFilePointer() {
return wrapped.getFilePointer();
}
@Override
public long length() throws IOException {
return wrapped.length();
}
@Override
public void seek(long pos) throws IOException {
throw new UnsupportedOperationException("seek() is unsupported");
}
@Override
public void writeByte(byte b) throws IOException {
wrapped.writeByte(b);
}
@Override
public void writeBytes(byte[] b, int offset, int length) throws IOException {
wrapped.writeBytes(b, offset, length);
}
}
@SuppressWarnings("serial")
private static class AppendingRAMDirectory extends MockDirectoryWrapper {
public AppendingRAMDirectory(Directory delegate) {
super(delegate);
}
@Override
public IndexOutput createOutput(String name) throws IOException {
return new AppendingIndexOutputWrapper(super.createOutput(name));
}
}
private static final String text = "the quick brown fox jumped over the lazy dog";
public void testCodec() throws Exception {
Directory dir = new AppendingRAMDirectory(new RAMDirectory());
IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_40, new MockAnalyzer());
cfg.setCodecProvider(new AppendingCodecProvider());
((LogMergePolicy)cfg.getMergePolicy()).setUseCompoundFile(false);
((LogMergePolicy)cfg.getMergePolicy()).setUseCompoundDocStore(false);
IndexWriter writer = new IndexWriter(dir, cfg);
Document doc = new Document();
doc.add(new Field("f", text, Store.YES, Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
writer.commit();
writer.addDocument(doc);
writer.optimize();
writer.close();
IndexReader reader = IndexReader.open(dir, null, true, 1, new AppendingCodecProvider());
assertEquals(2, reader.numDocs());
doc = reader.document(0);
assertEquals(text, doc.get("f"));
Fields fields = MultiFields.getFields(reader);
Terms terms = fields.terms("f");
assertNotNull(terms);
TermsEnum te = terms.iterator();
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("quick")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("brown")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("fox")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("jumped")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("over")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("lazy")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("dog")));
assertEquals(SeekStatus.FOUND, te.seek(new BytesRef("the")));
DocsEnum de = te.docs(null, null);
assertTrue(de.advance(0) != DocsEnum.NO_MORE_DOCS);
assertEquals(2, de.freq());
assertTrue(de.advance(1) != DocsEnum.NO_MORE_DOCS);
assertTrue(de.advance(2) == DocsEnum.NO_MORE_DOCS);
reader.close();
}
}
|
3e16164136a06b9f6e98b6b8129c48f0b82ecc4a | 527 | java | Java | 2.2.1/mylibrary/src/main/java/jianqiang/com/mylibrary/activity/BaseActivity.java | BaoBaoJianqiang/AndroidNetwork | 312e7bbbd134be9d25f27f6c5d99e282f3298c35 | [
"MIT"
] | 39 | 2017-04-27T11:49:28.000Z | 2020-02-25T09:25:45.000Z | 2.2.1/mylibrary/src/main/java/jianqiang/com/mylibrary/activity/BaseActivity.java | BaoBaoJianqiang/AndroidNetwork | 312e7bbbd134be9d25f27f6c5d99e282f3298c35 | [
"MIT"
] | null | null | null | 2.2.1/mylibrary/src/main/java/jianqiang/com/mylibrary/activity/BaseActivity.java | BaoBaoJianqiang/AndroidNetwork | 312e7bbbd134be9d25f27f6c5d99e282f3298c35 | [
"MIT"
] | 13 | 2017-04-27T12:39:46.000Z | 2018-12-14T01:08:06.000Z | 23.954545 | 62 | 0.804554 | 9,397 | package jianqiang.com.mylibrary.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public abstract class BaseActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVariables();
initViews(savedInstanceState);
loadData();
}
protected abstract void initVariables();
protected abstract void initViews(Bundle savedInstanceState);
protected abstract void loadData();
} |
3e161659833aa9fd0737cfde84ef1107739c6758 | 962 | java | Java | src/test/java/com/zl/edu/service/impl/ScServiceImplTest.java | zljxh/EDU | aed52dea6ecd457f014327d9ea6719e8ce1bf64c | [
"Apache-2.0"
] | null | null | null | src/test/java/com/zl/edu/service/impl/ScServiceImplTest.java | zljxh/EDU | aed52dea6ecd457f014327d9ea6719e8ce1bf64c | [
"Apache-2.0"
] | null | null | null | src/test/java/com/zl/edu/service/impl/ScServiceImplTest.java | zljxh/EDU | aed52dea6ecd457f014327d9ea6719e8ce1bf64c | [
"Apache-2.0"
] | null | null | null | 30.0625 | 88 | 0.799376 | 9,398 | package com.zl.edu.service.impl;
import com.zl.edu.service.ScService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by user on 2018/3/7.
*/
@SpringBootTest
@Slf4j
@MapperScan("com.zl.edu.dao.mapper")
@EnableAutoConfiguration(exclude={
JpaRepositoriesAutoConfiguration.class//禁止springboot自动加载持久化bean
})
@RunWith(SpringRunner.class)
public class ScServiceImplTest {
@Autowired
private ScService scService;
@Test
public void saveSc() throws Exception {
scService.saveSc();
}
} |
3e16173546a730e39d08a68597e7f241cd516134 | 6,766 | java | Java | fuse-domain/fuse-domain-knowledge/fuse-domain-knowledge-test/src/main/java/com/yangdb/fuse/assembly/knowledge/domain/Insight.java | YANG-DB/yang-db | 2776fb054faa5f6b86dad83f44628656feabe53f | [
"Apache-2.0"
] | 91 | 2019-04-30T10:40:05.000Z | 2022-02-02T14:08:17.000Z | fuse-domain/fuse-domain-knowledge/fuse-domain-knowledge-test/src/main/java/com/yangdb/fuse/assembly/knowledge/domain/Insight.java | YANG-DB/yang-db | 2776fb054faa5f6b86dad83f44628656feabe53f | [
"Apache-2.0"
] | 124 | 2019-03-26T10:06:24.000Z | 2022-03-30T11:07:58.000Z | fuse-domain/fuse-domain-knowledge/fuse-domain-knowledge-test/src/main/java/com/yangdb/fuse/assembly/knowledge/domain/Insight.java | YANG-DB/yang-db | 2776fb054faa5f6b86dad83f44628656feabe53f | [
"Apache-2.0"
] | 3 | 2019-05-06T05:12:02.000Z | 2020-08-05T10:47:18.000Z | 26.123552 | 85 | 0.671593 | 9,399 | package com.yangdb.fuse.assembly.knowledge.domain;
/*-
* #%L
* fuse-domain-knowledge-test
* %%
* Copyright (C) 2016 - 2019 The YangDb Graph Database Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* Created by lior.perry pc on 5/12/2018.
*/
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"type",
"content",
"context",
"lastUpdateUser",
"creationUser",
"lastUpdateTime",
"creationTime",
"authorizationCount",
"authorization",
"refs",
"entityIds"
})
public class Insight {
@JsonProperty("type")
private String type;
@JsonProperty("content")
private String content;
@JsonProperty("context")
private String context;
@JsonProperty("lastUpdateUser")
private String lastUpdateUser;
@JsonProperty("creationUser")
private String creationUser;
@JsonProperty("lastUpdateTime")
private Date lastUpdateTime;
@JsonProperty("creationTime")
private Date creationTime;
@JsonProperty("authorizationCount")
private Integer authorizationCount;
@JsonProperty("authorization")
private List<String> authorization = null;
@JsonProperty("refs")
private List<String> refs = null;
@JsonProperty("entityIds")
private List<String> entityIds = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("type")
public String getType() {
return type;
}
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
public Insight withType(String type) {
this.type = type;
return this;
}
@JsonProperty("content")
public String getContent() {
return content;
}
@JsonProperty("content")
public void setContent(String content) {
this.content = content;
}
public Insight withContent(String content) {
this.content = content;
return this;
}
@JsonProperty("context")
public String getContext() {
return context;
}
@JsonProperty("context")
public void setContext(String context) {
this.context = context;
}
public Insight withContext(String context) {
this.context = context;
return this;
}
@JsonProperty("lastUpdateUser")
public String getLastUpdateUser() {
return lastUpdateUser;
}
@JsonProperty("lastUpdateUser")
public void setLastUpdateUser(String lastUpdateUser) {
this.lastUpdateUser = lastUpdateUser;
}
public Insight withLastUpdateUser(String lastUpdateUser) {
this.lastUpdateUser = lastUpdateUser;
return this;
}
@JsonProperty("creationUser")
public String getCreationUser() {
return creationUser;
}
@JsonProperty("creationUser")
public void setCreationUser(String creationUser) {
this.creationUser = creationUser;
}
public Insight withCreationUser(String creationUser) {
this.creationUser = creationUser;
return this;
}
@JsonProperty("lastUpdateTime")
public Date getLastUpdateTime() {
return lastUpdateTime;
}
@JsonProperty("lastUpdateTime")
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public Insight withLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
return this;
}
@JsonProperty("creationTime")
public Date getCreationTime() {
return creationTime;
}
@JsonProperty("creationTime")
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Insight withCreationTime(Date creationTime) {
this.creationTime = creationTime;
return this;
}
@JsonProperty("authorizationCount")
public Integer getAuthorizationCount() {
return authorizationCount;
}
@JsonProperty("authorizationCount")
public void setAuthorizationCount(Integer authorizationCount) {
this.authorizationCount = authorizationCount;
}
public Insight withAuthorizationCount(Integer authorizationCount) {
this.authorizationCount = authorizationCount;
return this;
}
@JsonProperty("authorization")
public List<String> getAuthorization() {
return authorization;
}
@JsonProperty("authorization")
public void setAuthorization(List<String> authorization) {
this.authorization = authorization;
}
public Insight withAuthorization(List<String> authorization) {
this.authorization = authorization;
return this;
}
@JsonProperty("refs")
public List<String> getRefs() {
return refs;
}
@JsonProperty("refs")
public void setRefs(List<String> refs) {
this.refs = refs;
}
public Insight withRefs(List<String> refs) {
this.refs = refs;
return this;
}
@JsonProperty("entityIds")
public List<String> getEntityIds() {
return entityIds;
}
@JsonProperty("entityIds")
public void setEntityIds(List<String> entityIds) {
this.entityIds = entityIds;
}
public Insight withEntityIds(List<String> entityIds) {
this.entityIds = entityIds;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Insight withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
|
3e1617929a1afc8cfdac72e6e15f64a6897932d1 | 27,447 | java | Java | RobotCore/src/main/java/com/qualcomm/robotcore/util/RobotLog.java | cybots5975/cybots2018 | 082db31bdf9987c05a15d5c1fc8cf6c1bac33412 | [
"MIT"
] | 2 | 2018-11-02T19:03:00.000Z | 2021-12-10T03:51:41.000Z | RobotCore/src/main/java/com/qualcomm/robotcore/util/RobotLog.java | cybots5975/cybots2018 | 082db31bdf9987c05a15d5c1fc8cf6c1bac33412 | [
"MIT"
] | null | null | null | RobotCore/src/main/java/com/qualcomm/robotcore/util/RobotLog.java | cybots5975/cybots2018 | 082db31bdf9987c05a15d5c1fc8cf6c1bac33412 | [
"MIT"
] | null | null | null | 38.549157 | 202 | 0.613109 | 9,400 | /*
* Copyright (c) 2014, 2015 Qualcomm Technologies Inc
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* (subject to the limitations in the disclaimer below) 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 Qualcomm Technologies Inc nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS
* SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.qualcomm.robotcore.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import com.qualcomm.robotcore.exception.RobotCoreException;
import com.qualcomm.robotcore.robocol.Heartbeat;
import org.firstinspires.ftc.robotcore.internal.system.AppUtil;
import org.firstinspires.ftc.robotcore.internal.files.LogOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.WeakHashMap;
/**
* Allows consistent logging across all RobotCore packages
*/
@SuppressWarnings("WeakerAccess")
public class RobotLog {
/*
* Currently only supports android style logging, but may support more in the future.
*/
/*
* Only contains static utility methods
*/
private RobotLog() {
}
//------------------------------------------------------------------------------------------------
// State
//------------------------------------------------------------------------------------------------
public static final String ERROR_PREPEND = "### ERROR: ";
private static String globalErrorMessage = "";
private static final Object globalWarningLock = new Object();
private static String globalWarningMessage = "";
private static WeakHashMap<GlobalWarningSource, Integer> globalWarningSources = new WeakHashMap<GlobalWarningSource, Integer>();
private static double msTimeOffset = 0.0;
public static final String TAG = "RobotCore";
private static Thread loggingThread = null;
public static String logcatCommand = "logcat";
public static int kbLogcatQuantum = 4 * 1024;
public static int logcatRotatedLogsMax = 4;
public static String logcatFormat = "threadtime";
public static String logcatFilter = "UsbRequestJNI:S UsbRequest:S *:V";
//------------------------------------------------------------------------------------------------
// Time Synchronization
//------------------------------------------------------------------------------------------------
/**
* Processes the reception of a set of NTP timestamps between this device (t0 and t3) and
* a remote device (t1 and t2) with whom it is trying to synchronize time. Our current implementation
* is very, very crude: we just calculate the instantaneous offset, and remember. But that's probably
* good enough for trying to coordinate timestamps in logs.
*/
public static void processTimeSynch(long t0, long t1, long t2, long t3) {
if (t0 == 0 || t1 == 0 || t2 == 0 || t3 == 0) {
return; // invalid packet data
}
// https://en.wikipedia.org/wiki/Network_Time_Protocol
// offset is how much the time source is ahead of us (ie: not behind)
double offset = ((t1 - t0) + (t2 - t3)) / 2.0;
setMsTimeOffset(offset);
}
// Records the time difference between this device and a device with whom we are synchronizing our time
public static void setMsTimeOffset(double offset) {
msTimeOffset = offset;
}
//------------------------------------------------------------------------------------------------
// Logging API
//------------------------------------------------------------------------------------------------
public static void a(String format, Object... args) {
v(String.format(format, args));
}
public static void a(String message) {
internalLog(Log.ASSERT, TAG, message);
}
public static void aa(String tag, String format, Object... args) {
vv(tag, String.format(format, args));
}
public static void aa(String tag, String message) {
internalLog(Log.ASSERT, tag, message);
}
public static void aa(String tag, Throwable throwable, String format, Object... args) {
vv(tag, throwable, String.format(format, args));
}
public static void aa(String tag, Throwable throwable, String message) {
internalLog(Log.ASSERT, tag, throwable, message);
}
public static void v(String format, Object... args) {
v(String.format(format, args));
}
public static void v(String message) {
internalLog(Log.VERBOSE, TAG, message);
}
public static void vv(String tag, String format, Object... args) {
vv(tag, String.format(format, args));
}
public static void vv(String tag, String message) {
internalLog(Log.VERBOSE, tag, message);
}
public static void vv(String tag, Throwable throwable, String format, Object... args) {
vv(tag, throwable, String.format(format, args));
}
public static void vv(String tag, Throwable throwable, String message) {
internalLog(Log.VERBOSE, tag, throwable, message);
}
public static void d(String format, Object... args) {
d(String.format(format, args));
}
public static void d(String message) {
internalLog(Log.DEBUG, TAG, message);
}
public static void dd(String tag, String format, Object... args) {
dd(tag, String.format(format, args));
}
public static void dd(String tag, String message) {
internalLog(Log.DEBUG, tag, message);
}
public static void dd(String tag, Throwable throwable, String format, Object... args) {
dd(tag, throwable, String.format(format, args));
}
public static void dd(String tag, Throwable throwable, String message) {
internalLog(Log.DEBUG, tag, throwable, message);
}
public static void i(String format, Object... args) {
i(String.format(format, args));
}
public static void i(String message) {
internalLog(Log.INFO, TAG, message);
}
public static void ii(String tag, String format, Object... args) {
ii(tag, String.format(format, args));
}
public static void ii(String tag, String message) {
internalLog(Log.INFO, tag, message);
}
public static void ii(String tag, Throwable throwable, String format, Object... args) {
ii(tag, throwable, String.format(format, args));
}
public static void ii(String tag, Throwable throwable, String message) {
internalLog(Log.INFO, tag, throwable, message);
}
public static void w(String format, Object... args) {
w(String.format(format, args));
}
public static void w(String message) {
internalLog(Log.WARN, TAG, message);
}
public static void ww(String tag, String format, Object... args) {
ww(tag, String.format(format, args));
}
public static void ww(String tag, String message) {
internalLog(Log.WARN, tag, message);
}
public static void ww(String tag, Throwable throwable, String format, Object... args) {
ww(tag, throwable, String.format(format, args));
}
public static void ww(String tag, Throwable throwable, String message) {
internalLog(Log.WARN, tag, throwable, message);
}
public static void e(String format, Object... args) {
e(String.format(format, args));
}
public static void e(String message) {
internalLog(Log.ERROR, TAG, message);
}
public static void ee(String tag, String format, Object... args) {
ee(tag, String.format(format, args));
}
public static void ee(String tag, String message) {
internalLog(Log.ERROR, tag, message);
}
public static void ee(String tag, Throwable throwable, String format, Object... args) {
ee(tag, throwable, String.format(format, args));
}
public static void ee(String tag, Throwable throwable, String message) {
internalLog(Log.ERROR, tag, throwable, message);
}
public static void internalLog(int priority, String tag, String message) {
if (msTimeOffset == 0) {
android.util.Log.println(priority, tag, message);
} else {
double offset = msTimeOffset;
long now = (long) (Heartbeat.getMsTimeSyncTime() + offset + 0.5);
GregorianCalendar tNow = new GregorianCalendar();
tNow.setTimeInMillis(now);
android.util.Log.println(priority, tag, String.format("{%5d %2d.%03d} %s", (int) (msTimeOffset + 0.5), tNow.get(GregorianCalendar.SECOND), tNow.get(GregorianCalendar.MILLISECOND), message));
}
}
public static void internalLog(int priority, String tag, Throwable throwable, String message) {
internalLog(priority, tag, message);
logStackTrace(tag, throwable);
}
public static void logExceptionHeader(Exception e, String format, Object... args) {
String message = String.format(format, args);
RobotLog.e("exception %s(%s): %s [%s]", e.getClass().getSimpleName(), e.getMessage(), message, getStackTop(e));
}
public static void logExceptionHeader(String tag, Exception e, String format, Object... args) {
String message = String.format(format, args);
RobotLog.ee(tag, "exception %s(%s): %s [%s]", e.getClass().getSimpleName(), e.getMessage(), message, getStackTop(e));
}
private static StackTraceElement getStackTop(Exception e) {
StackTraceElement[] frames = e.getStackTrace();
return frames.length > 0 ? frames[0] : null;
}
/**
* @deprecated obsolete capitalization
*/
@Deprecated
public static void logStacktrace(Throwable e) {
logStackTrace(e);
}
public static void logStackTrace(Throwable e) {
logStackTrace(TAG, e);
}
public static void logStackTrace(Thread thread, String format, Object... args) {
String message = String.format(format, args);
RobotLog.e("thread id=%d tid=%d name=\"%s\" %s", thread.getId(), ThreadPool.getTID(thread), thread.getName(), message);
logStackFrames(thread.getStackTrace());
}
public static void logStackTrace(Thread thread, StackTraceElement[] stackTrace) {
RobotLog.e("thread id=%d tid=%d name=\"%s\"", thread.getId(), ThreadPool.getTID(thread), thread.getName());
logStackFrames(stackTrace);
}
public static void logStackTrace(String tag, Throwable e) {
e.printStackTrace(LogOutputStream.printStream(tag));
}
private static void logStackFrames(StackTraceElement[] stackTrace) {
for (StackTraceElement frame : stackTrace) {
RobotLog.e(" at %s", frame.toString());
}
}
public static void logAndThrow(String errMsg) throws RobotCoreException {
w(errMsg);
throw new RobotCoreException(errMsg);
}
//------------------------------------------------------------------------------------------------
// Error and Warning Messages
//------------------------------------------------------------------------------------------------
/**
* Set a global error message
* <p>
* This message stays set until clearGlobalErrorMsg is called. Additional
* calls to set the global error message will be silently ignored until the
* current error message is cleared.
* <p>
* This is so that if multiple global error messages are raised, the first
* error message is captured.
* <p>
* Presently, the global error is cleared only when the robot is restarted.
*
* @param message error message
*/
public static boolean setGlobalErrorMsg(String message) {
// don't allow a new error message to overwrite the old error message
if (globalErrorMessage.isEmpty()) {
globalErrorMessage += message; // using += to force a null pointer exception if message is null
return true;
}
return false;
}
public static void setGlobalErrorMsg(String format, Object... args) {
setGlobalErrorMsg(String.format(format, args));
}
/**
* Sets the global warning message.
* <p>
* This stays set until clearGlobalWarningMsg is called.
*
* @param message the warning message to set
*/
public static void setGlobalWarningMessage(String message) {
synchronized (globalWarningLock) {
if (globalWarningMessage.isEmpty()) {
globalWarningMessage += message;
}
}
}
public static void setGlobalWarningMessage(String format, Object... args) {
setGlobalWarningMessage(String.format(format, args));
}
/**
* Adds (if not already present) a new source that can contribute the generation of warnings
* on the robot controller and driver station displays (if the source is already registered,
* the call has no effect). The source will periodically be polled for its contribution to
* the overall warning message; if the source has no warning to contribute, it should return
* an empty string. Note that weak references are used in this registration: the act of adding
* a global warning source will not of its own accord keep that source from being reclaimed by
* the system garbage collector.
*
* @param globalWarningSource the warning source to add
*/
public static void registerGlobalWarningSource(GlobalWarningSource globalWarningSource) {
synchronized (globalWarningLock) {
globalWarningSources.put(globalWarningSource, 1);
}
}
/**
* Removes (if present) a source from the list of warning sources contributing to the
* overall system warning message (if the indicated source is not currently registered, this
* call has no effect). Note that explicit unregistration of a warning source is not required:
* due to the internal use of weak references, warning sources will be automatically
* unregistered if they are reclaimed by the garbage collector. However, explicit unregistration
* may be useful to the source itself so that it will stop being polled for its warning
* contribution.
*
* @param globalWarningSource the source to remove as a global warning source
*/
public static void unregisterGlobalWarningSource(GlobalWarningSource globalWarningSource) {
synchronized (globalWarningLock) {
globalWarningSources.remove(globalWarningSource);
}
}
public static void setGlobalWarningMsg(RobotCoreException e, String message) {
setGlobalWarningMessage(message + ": " + e.getMessage());
}
public static void setGlobalErrorMsg(RobotCoreException e, String message) {
setGlobalErrorMsg(message + ": " + e.getMessage());
}
public static void setGlobalErrorMsgAndThrow(RobotCoreException e, String message) throws RobotCoreException {
setGlobalErrorMsg(e, message);
throw e;
}
public static void setGlobalErrorMsg(RuntimeException e, String message) {
setGlobalErrorMsg(String.format("%s: %s: %s", message, e.getClass().getSimpleName(), e.getMessage()));
}
public static void setGlobalErrorMsgAndThrow(RuntimeException e, String message) throws RobotCoreException {
setGlobalErrorMsg(e, message);
throw e;
}
/**
* Get the current global error message
*
* @return error message
*/
public static String getGlobalErrorMsg() {
return globalErrorMessage;
}
/**
* Returns the current global warning, or "" if there is none
*
* @return the current global warning
*/
public static String getGlobalWarningMessage() {
List<String> warnings = new ArrayList<String>();
synchronized (globalWarningLock) {
warnings.add(globalWarningMessage);
for (GlobalWarningSource source : globalWarningSources.keySet()) {
warnings.add(source.getGlobalWarning());
}
}
return combineGlobalWarnings(warnings);
}
/**
* Combines possibly multiple warnings together using an appropriate delimiter. If
* there is no actual warning in effect, then "" is returned.
*/
public static String combineGlobalWarnings(List<String> warnings) {
StringBuilder result = new StringBuilder();
for (String warning : warnings) {
if (warning != null && !warning.isEmpty()) {
if (result.length() > 0) {
result.append("; ");
}
result.append(warning);
}
}
return result.toString();
}
/**
* Returns true if a global error message is set
*
* @return true if there is an error message
*/
public static boolean hasGlobalErrorMsg() {
return !getGlobalErrorMsg().isEmpty();
}
/**
* Returns whether a global warning currently exists
*
* @return whether a global warning currently exists
*/
public static boolean hasGlobalWarningMsg() {
return !getGlobalWarningMessage().isEmpty();
}
/**
* Clears the current global error message.
*/
public static void clearGlobalErrorMsg() {
globalErrorMessage = "";
}
/**
* Clears the current global warning message.
*/
public static void clearGlobalWarningMsg() {
synchronized (globalWarningLock) {
globalWarningMessage = "";
}
}
//------------------------------------------------------------------------------------------------
// Disk Management
//------------------------------------------------------------------------------------------------
/**
* Write logcat logs to disk. Log data will continue to be written to disk until
* {@link #cancelWriteLogcatToDisk()} is called. {@link #onApplicationStart()} is
* idempotent: additional calls to this method will be a NOOP.
*/
public static void onApplicationStart() {
// Diskify the log in quanta (all but the last of these will get GZIP'd)
writeLogcatToDisk(AppUtil.getDefContext(), kbLogcatQuantum);
}
// Synchronized so we can't start and stop logging at the same time
protected static synchronized void writeLogcatToDisk(final Context context, final int kbFileSize) {
// If we're already logging, then swell: we're done
if (loggingThread != null) {
return;
}
// Make a thread that will hang around so long as logging is active
loggingThread = new Thread("Logging Thread") {
@SuppressLint("DefaultLocale")
@Override
public void run() {
try {
/**
* logcat is documented <a href="https://developer.android.com/studio/command-line/logcat.html">here</a>.
* A brief summary:
*
* logcat [option] ... [filter-spec] ...
*
* -c Clears (flushes) the entire log and exits.
* -f filename Writes log message output to filename
* -r kbytes Rotates the log file every kbytes of output. The default value is 16. Requires the -f option.
* -n count Sets the maximum number of rotated logs to count. The default value is 4. Requires the -r option.
* -v format Sets the output format for log messages. The default is brief format.
*
* output formats are documented <a href="https://developer.android.com/studio/command-line/logcat.html#outputFormat">here</a>.
* brief, process, tag, raw, time, threadtime, long
*/
final File file = getLogFile(context);
final String filename = file.getAbsolutePath();
final String commandLine = String.format("%s -f %s -r%d -n%d -v %s %s", logcatCommand, filename, kbFileSize, logcatRotatedLogsMax, logcatFormat, logcatFilter);
RobotLog.v("saving logcat to " + filename);
RobotLog.v("logging command line: " + commandLine);
final RunShellCommand shell = new RunShellCommand();
// Paranoia: kill any existing logger we spawned previously
RunShellCommand.killSpawnedProcess(logcatCommand, context.getPackageName(), shell);
// (Don't) empty the log: while this would avoid the multi-copies-of-log-entries
// problem, not clearing the log gives us a chance to capture any logcat entries that might
// be still lingering from an immediately preceding crash, entries that might be especially
// valuable to capture.
// shell.run(String.format("%s -c", logcatCommand));
// Dribble to disk until we're cancelled. Note that this call to run()
// doesn't return until such cancellation happens.
shell.run(commandLine);
} catch (RobotCoreException e) {
RobotLog.v("Error while initializing RobotLog to disk: " + e.toString());
} finally {
loggingThread = null;
}
}
};
// Start that thread a-going
loggingThread.start();
}
public static String getLogFilename() {
return getLogFilename(AppUtil.getDefContext());
}
public static String getLogFilename(Context context) {
File directory = AppUtil.LOG_FOLDER;
//noinspection ResultOfMethodCallIgnored
directory.mkdirs(); // paranoia, though we *might* have actually seen this needed, hard to tell
String name;
if (AppUtil.getInstance().isRobotController()) {
name = "robotControllerLog.txt";
} else if (AppUtil.getInstance().isDriverStation()) {
name = "driverStationLog.txt";
} else {
name = context.getPackageName() + "Log.txt";
}
File file = new File(directory, name);
return file.getAbsolutePath();
}
private static File getLogFile(Context context) {
return new File(getLogFilename(context));
}
// Returns the extant log files, which include the rollovers, eg:
// com.qualcomm.ftcrobotcontroller.logcat.1.gz
public static List<File> getExtantLogFiles(Context context) {
List<File> result = new ArrayList<>();
File root = getLogFile(context);
result.add(root);
for (int i = 1; true; i++) {
File compressed = new File(root.getParentFile(), root.getName() + "." + i + ".gz");
if (compressed.exists()) {
result.add(compressed);
} else {
break;
}
}
return result;
}
/**
* Cancels any logcat writing to disk that might currently be going on
*/
public static synchronized void cancelWriteLogcatToDisk() {
// Synchronized so we can't start and top logging at the same time
// If we're not logging, then we've got nothing to do
if (loggingThread == null) {
return;
}
Context context = AppUtil.getDefContext();
final String packageName = context.getPackageName();
final String filename = getLogFile(context).getAbsolutePath();
// let last few log messages out before we stop logging
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// just continue
}
// Kill off the logging process. That will let the shell.run() in the logging thread return
try {
RobotLog.v("closing logcat file " + filename);
RunShellCommand shell = new RunShellCommand();
RunShellCommand.killSpawnedProcess(logcatCommand, packageName, shell);
} catch (RobotCoreException e) {
RobotLog.v("Unable to cancel writing log file to disk: " + e.toString());
return;
}
// wait until the log thread terminates
while (loggingThread != null) {
Thread.yield();
}
}
public static void logBuildConfig(Class buildConfig) {
String moduleName = getStringStatic(buildConfig, "APPLICATION_ID");
int versionCode = getIntStatic(buildConfig, "VERSION_CODE");
String versionName = getStringStatic(buildConfig, "VERSION_NAME");
RobotLog.v("BuildConfig: versionCode=%d versionName=%s module=%s", versionCode, versionName, moduleName);
}
protected static String getStringStatic(Class clazz, String name) {
try {
return (String) (clazz.getField(name).get(null));
} catch (Exception ignored) {
return "";
}
}
protected static int getIntStatic(Class clazz, String name) {
try {
return (clazz.getField(name).getInt(null));
} catch (Exception ignored) {
return 0;
}
}
public static void logBytes(String tag, String caption, byte[] data, int cb) {
logBytes(tag, caption, data, 0, cb);
}
public static void logBytes(String tag, String caption, byte[] data, int ibStart, int cb) {
int cbLine = 16;
char separator = ':';
for (int ibFirst = ibStart; ibFirst < cb; ibFirst += cbLine) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < cbLine; i++) {
int ib = i + ibFirst;
if (ib >= cb) {
break;
}
line.append(String.format("%02x ", data[ib]));
}
vv(tag, "%s%c %s", caption, separator, line.toString());
separator = '|';
}
}
}
|
3e1617bfaa7b9e203c00dd0aedbe53b2911516f7 | 10,945 | java | Java | src/translate/java/org/javarosa/xform/schema/FormTranslationFormatter.java | echisMOH/echisCommCareMOH-core | 30fde2c53a96315195c6d00ef693e63a2f99c6db | [
"Apache-2.0"
] | 10 | 2017-03-24T20:26:54.000Z | 2020-08-28T18:33:34.000Z | src/translate/java/org/javarosa/xform/schema/FormTranslationFormatter.java | echisMOH/echisCommCareMOH-core | 30fde2c53a96315195c6d00ef693e63a2f99c6db | [
"Apache-2.0"
] | 280 | 2016-06-27T14:46:57.000Z | 2022-03-31T14:39:44.000Z | src/translate/java/org/javarosa/xform/schema/FormTranslationFormatter.java | echisMOH/echisCommCareMOH-core | 30fde2c53a96315195c6d00ef693e63a2f99c6db | [
"Apache-2.0"
] | 10 | 2016-07-19T05:53:07.000Z | 2020-10-28T22:02:42.000Z | 38.403509 | 149 | 0.541617 | 9,401 | /**
*
*/
package org.javarosa.xform.schema;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.xpath.XPathConditional;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.xmlpull.mxp1_serializer.MXSerializer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.TreeMap;
import java.util.Vector;
/**
* @author ctsims
*
*/
public class FormTranslationFormatter {
public static StringBuffer dumpTranslationsIntoCSV(FormDef f) {
//absorb errors.
return dumpTranslationsIntoCSV(f, new StringBuffer());
}
public static StringBuffer dumpTranslationsIntoCSV(FormDef f, StringBuffer messages) {
f.getLocalizer().setToDefault();
Hashtable<String, Hashtable<String, String>> localeData = new Hashtable<>();
Hashtable<Integer, String[]> techStrings = new Hashtable<>();
StringWriter writer = new StringWriter();
CsvWriter csv = new CsvWriter(writer, ',');
String[] locales = f.getLocalizer().getAvailableLocales();
String[] header = new String[locales.length + 1];
header[0] = "id";
for(int i = 0 ; i < locales.length ; ++ i) {
header[i+1] = locales[i];
localeData.put(locales[i],f.getLocalizer().getLocaleMap(locales[i]));
}
try {
csv.writeRecord(header);
} catch (IOException e) {
messages.append("Error!").append(e.getMessage());
}
Hashtable<String, String> defaultLocales = localeData.get(f.getLocalizer().getLocale());
//Go through the keys for the default translation, there should be a one-to-one mapping between
//each set of available keys.
for(Enumeration en = defaultLocales.keys(); en.hasMoreElements();) {
String key = (String) en.nextElement();
String[] rowOfTranslations = new String[locales.length + 1];
rowOfTranslations[0] = key;
int index = 1;
//Now dump the translation for each key per-language
for(String locale : locales) {
String translation = localeData.get(locale).get(key);
rowOfTranslations[index] = translation;
Vector<String> arguments = (Vector<String>) Localizer.getArgs(translation);
for (String arg : arguments) {
try {
int nArg = Integer.parseInt(arg);
XPathConditional expr = (XPathConditional) f.getOutputFragments().elementAt((nArg));
//println(sb, indent + 1, expr.xpath);
if(!techStrings.containsKey(Integer.valueOf(nArg))) {
techStrings.put(Integer.valueOf(nArg),new String[locales.length + 1]);
}
techStrings.get(Integer.valueOf(nArg))[index] = expr.xpath;
} catch (NumberFormatException e) {
messages.append("Error!").append(e.getMessage());
e.printStackTrace();
}
}
index++;
}
try {
csv.writeRecord(rowOfTranslations);
} catch (IOException e) {
messages.append("Error!").append(e.getMessage());
}
}
for(Integer nArg : techStrings.keySet()) {
String[] record = techStrings.get(nArg);
record[0] = nArg.toString();
try {
csv.writeRecord(record);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//output.append(writer.getBuffer());
return writer.getBuffer();
}
public static void turnTranslationsCSVtoItext(InputStream stream, OutputStream output, String delimeter, String encoding, String printEncoding) {
InputStreamReader reader;
if(encoding == null) {
reader = new InputStreamReader(stream);
} else {
Charset charset = Charset.forName(encoding);
reader = new InputStreamReader(stream, charset);
}
//Lots of Dictionaries!
//Treemap is important here to keep ordering constraints.
TreeMap<String,Element> itexts = new TreeMap<>();
Hashtable<String,Hashtable<String,Element>> textValues = new Hashtable<>();
Hashtable<String, Hashtable<String,String>> args = new Hashtable<>();
CsvReader csv;
if(delimeter == null) {
csv = new CsvReader(reader);
} else {
if(delimeter.equals("\\t")) {
csv = new CsvReader(reader,'\t');
} else if(delimeter.length() > 1) {
System.err.println("Invalid delimeter: " + delimeter + " Using comma");
csv = new CsvReader(reader);
} else {
csv = new CsvReader(reader,delimeter.charAt(0));
}
}
Document doc = new Document();
try {
csv.readHeaders();
String[] headers = csv.getHeaders();
for(int i = 1 ; i < headers.length; ++i) {
Element translation = doc.createElement(null,"translation");
translation.setAttribute(null, "lang",headers[i]);
itexts.put(headers[i], translation);
textValues.put(headers[i], new Hashtable<String,Element>());
args.put(headers[i], new Hashtable<String,String>());
}
while(csv.readRecord()) {
String[] values = csv.getValues();
String id = values[0];
String form = null;
//If the id is an integer, it's an argument, not a text element
try {
int arg = Integer.parseInt(id);
for(int i = 1; i < values.length ; i++) {
args.get(headers[i]).put(id, "<output value=\"" + values[i] + "\"/>");
}
continue;
}
catch(NumberFormatException e) {
//Java is so stupid, I still can't believe this is how you
//check whether a string is an integer....
//Don't do anything here, it's an expected outcome.
}
//Do this outside of the try catch to get out of the exception handling part of the vm
//We won't get here if the id was an arg, since it gets continued.
if(id.contains((";"))) {
//Sketchy! but it's sketchy in the parser, too...
String[] divided = id.split(";");
id = divided[0];
form = divided[1];
}
int read = Math.min(headers.length,values.length);
for(int i = 1 ; i < read ; i++) {
String valueText = values[i];
Element text;
//Figure out whether this element exists...
if(textValues.get(headers[i]).containsKey(id)) {
text = textValues.get(headers[i]).get(id);
} else {
text = doc.createElement(null,"text");
text.setAttribute(null,"id",id);
textValues.get(headers[i]).put(id,text);
itexts.get(headers[i]).addChild(Element.ELEMENT,text);
}
Element value = doc.createElement(null,"value");
if(form != null) {
value.setAttribute(null,"form",form);
}
value.addChild(Element.TEXT,valueText);
text.addChild(Element.ELEMENT,value);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Now it's time to update all of the arguments!
for(String localeID : textValues.keySet()) {
Hashtable<String,Element> localeValueElements = textValues.get(localeID);
for(Element textElement : localeValueElements.values()) {
for(int i = 0 ; i < textElement.getChildCount(); ++i ){
if(textElement.getChild(i) instanceof Element) {
Element valueElement = (Element)textElement.getChild(i);
if(valueElement.getName().equals("value")) {
//Now we're at a value element, it should have one, and only one, child
//element which contains text that may or may not have an argument string
//that needs to be updated.
String processedString = Localizer.processArguments((String)valueElement.getChild(0), args.get(localeID));
valueElement.removeChild(0);
valueElement.addChild(Element.IGNORABLE_WHITESPACE, processedString);
}
}
}
}
}
Element itext = doc.createElement(null, "itext");
for(Element el : itexts.values()) {
itext.addChild(Document.ELEMENT, el);
}
doc.addChild(Document.ELEMENT, itext);
MXSerializer ser = new MXSerializer();
ser.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " ");
ser.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n");
try {
if(encoding == null) {
StringWriter writer = new StringWriter();
ser.setOutput(writer);
doc.write(ser);
StringBuffer outputBuffer = new StringBuffer();
outputBuffer.append(writer);
PrintStream p = new PrintStream(output);
p.println(outputBuffer);
} else if(printEncoding == null){
ser.setOutput(output, encoding);
doc.write(ser);
} else {
ser.setOutput(output, printEncoding);
doc.write(ser);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void turnTranslationsCSVtoItext(InputStream stream, OutputStream output) {
turnTranslationsCSVtoItext(stream, output, null, null, null);
}
}
|
3e1617c35fd7f58a084f9aca0fcff2e51489ea5d | 787 | java | Java | src/main/java/run/halo/app/service/JournalCommentService.java | SeanGaoTesing/halo-master | 759070caf92e04af2ad4cc4e0dd40c7789f524f5 | [
"MIT"
] | null | null | null | src/main/java/run/halo/app/service/JournalCommentService.java | SeanGaoTesing/halo-master | 759070caf92e04af2ad4cc4e0dd40c7789f524f5 | [
"MIT"
] | 1 | 2021-07-05T20:11:04.000Z | 2021-07-05T20:11:04.000Z | src/main/java/run/halo/app/service/JournalCommentService.java | SeanGaoTesing/halo-master | 759070caf92e04af2ad4cc4e0dd40c7789f524f5 | [
"MIT"
] | 1 | 2021-07-05T20:01:46.000Z | 2021-07-05T20:01:46.000Z | 29.148148 | 83 | 0.791614 | 9,402 | package run.halo.app.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import run.halo.app.model.entity.JournalComment;
import run.halo.app.model.vo.JournalCommentWithJournalVO;
import run.halo.app.service.base.BaseCommentService;
/**
* Journal comment service interface.
*
* @author johnniang
* @date 2019-04-25
*/
public interface JournalCommentService extends BaseCommentService<JournalComment> {
@NonNull
List<JournalCommentWithJournalVO> convertToWithJournalVo(
@Nullable List<JournalComment> journalComments);
@NonNull
Page<JournalCommentWithJournalVO> convertToWithJournalVo(
@NonNull Page<JournalComment> journalCommentPage);
}
|
3e161923d33a87e2bd3c02643f17bf7d5ab67d4f | 4,791 | java | Java | projects/question/src/test/java/org/batfish/question/ospfinterface/OspfInterfaceConfigAnswererTest.java | loftwah/batfish | 4aa3f32a832cd2517668ccffd0ed2a4964085b49 | [
"Apache-2.0"
] | 1 | 2019-05-23T15:50:31.000Z | 2019-05-23T15:50:31.000Z | projects/question/src/test/java/org/batfish/question/ospfinterface/OspfInterfaceConfigAnswererTest.java | gahlberg/batfish | 525e623b3b9e1eb4a5738d15185654bfaa6c3e3c | [
"Apache-2.0"
] | null | null | null | projects/question/src/test/java/org/batfish/question/ospfinterface/OspfInterfaceConfigAnswererTest.java | gahlberg/batfish | 525e623b3b9e1eb4a5738d15185654bfaa6c3e3c | [
"Apache-2.0"
] | null | null | null | 42.026316 | 107 | 0.712795 | 9,403 | package org.batfish.question.ospfinterface;
import static org.batfish.datamodel.matchers.RowMatchers.hasColumn;
import static org.batfish.datamodel.questions.InterfacePropertySpecifier.OSPF_AREA_NAME;
import static org.batfish.datamodel.questions.InterfacePropertySpecifier.OSPF_COST;
import static org.batfish.datamodel.questions.InterfacePropertySpecifier.OSPF_HELLO_MULTIPLIER;
import static org.batfish.datamodel.questions.InterfacePropertySpecifier.OSPF_PASSIVE;
import static org.batfish.datamodel.questions.InterfacePropertySpecifier.OSPF_POINT_TO_POINT;
import static org.batfish.question.ospfinterface.OspfInterfaceConfigurationAnswerer.COLUMNS_FROM_PROP_SPEC;
import static org.batfish.question.ospfinterface.OspfInterfaceConfigurationAnswerer.COL_INTERFACE;
import static org.batfish.question.ospfinterface.OspfInterfaceConfigurationAnswerer.COL_PROCESS_ID;
import static org.batfish.question.ospfinterface.OspfInterfaceConfigurationAnswerer.COL_VRF;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Multiset;
import java.util.List;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.ConfigurationFormat;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.NetworkFactory;
import org.batfish.datamodel.Vrf;
import org.batfish.datamodel.answers.Schema;
import org.batfish.datamodel.collections.NodeInterfacePair;
import org.batfish.datamodel.ospf.OspfArea;
import org.batfish.datamodel.table.ColumnMetadata;
import org.batfish.datamodel.table.Row;
import org.junit.Test;
/** Test for {@link OspfInterfaceConfigurationAnswerer} */
public class OspfInterfaceConfigAnswererTest {
@Test
public void testGetRows() {
NetworkFactory nf = new NetworkFactory();
Configuration configuration =
nf.configurationBuilder()
.setHostname("test_conf")
.setConfigurationFormat(ConfigurationFormat.CISCO_IOS)
.build();
Vrf vrf = nf.vrfBuilder().setName("test_vrf").setOwner(configuration).build();
OspfArea ospfArea =
nf.ospfAreaBuilder().setInterfaces(ImmutableSet.of("int1")).setNumber(1L).build();
Interface iface =
nf.interfaceBuilder()
.setName("int1")
.setOspfArea(ospfArea)
.setOspfPassive(true)
.setOspfCost(2)
.setOspfPointToPoint(true)
.setOwner(configuration)
.setVrf(vrf)
.build();
iface.setOspfHelloMultiplier(2);
nf.ospfProcessBuilder()
.setProcessId("ospf_1")
.setAreas(ImmutableSortedMap.of(1L, ospfArea))
.setRouterId(Ip.parse("1.1.1.1"))
.setVrf(vrf)
.build();
Multiset<Row> rows =
OspfInterfaceConfigurationAnswerer.getRows(
COLUMNS_FROM_PROP_SPEC,
ImmutableMap.of(configuration.getHostname(), configuration),
ImmutableSet.of(configuration.getHostname()),
OspfInterfaceConfigurationAnswerer.createTableMetadata(null, COLUMNS_FROM_PROP_SPEC)
.toColumnMap());
assertThat(
rows.iterator().next(),
allOf(
hasColumn(COL_VRF, equalTo("test_vrf"), Schema.STRING),
hasColumn(COL_PROCESS_ID, equalTo("ospf_1"), Schema.STRING),
hasColumn(
COL_INTERFACE,
equalTo(new NodeInterfacePair("test_conf", "int1")),
Schema.INTERFACE),
hasColumn(OSPF_AREA_NAME, equalTo(1), Schema.INTEGER)));
assertThat(
rows.iterator().next(),
allOf(
hasColumn(OSPF_PASSIVE, equalTo(true), Schema.BOOLEAN),
hasColumn(OSPF_COST, equalTo(2), Schema.INTEGER),
hasColumn(OSPF_POINT_TO_POINT, equalTo(true), Schema.BOOLEAN),
hasColumn(OSPF_HELLO_MULTIPLIER, equalTo(2), Schema.INTEGER)));
}
@Test
public void testMetaData() {
List<ColumnMetadata> metas =
OspfInterfaceConfigurationAnswerer.createColumnMetadata(COLUMNS_FROM_PROP_SPEC);
assertThat(
metas.stream().map(ColumnMetadata::getName).collect(ImmutableList.toImmutableList()),
equalTo(
ImmutableList.builder()
.add(COL_INTERFACE)
.add(COL_VRF)
.add(COL_PROCESS_ID)
.add(OSPF_AREA_NAME)
.add(OSPF_PASSIVE)
.add(OSPF_COST)
.add(OSPF_POINT_TO_POINT)
.add(OSPF_HELLO_MULTIPLIER)
.build()));
}
}
|
3e1619c4563317c90fb70ed563c7fa62b7f550e0 | 6,200 | java | Java | python/experiments/projects/OpenEMS-openems/real_error_dataset/1/49/MeterSocomecCountisE14.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/OpenEMS-openems/real_error_dataset/1/49/MeterSocomecCountisE14.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/OpenEMS-openems/real_error_dataset/1/49/MeterSocomecCountisE14.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | 37.804878 | 135 | 0.774355 | 9,404 | package io.openems.edge.meter.socomec.countise14;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.metatype.annotations.Designate;
import io.openems.common.channel.AccessMode;
import io.openems.edge.bridge.modbus.api.AbstractOpenemsModbusComponent;
import io.openems.edge.bridge.modbus.api.BridgeModbus;
import io.openems.edge.bridge.modbus.api.ElementToChannelConverter;
import io.openems.edge.bridge.modbus.api.ModbusProtocol;
import io.openems.edge.bridge.modbus.api.element.DummyRegisterElement;
import io.openems.edge.bridge.modbus.api.element.SignedDoublewordElement;
import io.openems.edge.bridge.modbus.api.element.UnsignedDoublewordElement;
import io.openems.edge.bridge.modbus.api.element.UnsignedWordElement;
import io.openems.edge.bridge.modbus.api.task.FC3ReadRegistersTask;
import io.openems.edge.common.channel.Doc;
import io.openems.edge.common.component.OpenemsComponent;
import io.openems.edge.common.modbusslave.ModbusSlave;
import io.openems.edge.common.modbusslave.ModbusSlaveTable;
import io.openems.edge.common.taskmanager.Priority;
import io.openems.edge.meter.api.AsymmetricMeter;
import io.openems.edge.meter.api.MeterType;
import io.openems.edge.meter.api.SinglePhase;
import io.openems.edge.meter.api.SinglePhaseMeter;
import io.openems.edge.meter.api.SymmetricMeter;
@Designate(ocd = Config.class, factory = true)
@Component(name = "Meter.SOCOMEC.CountisE24", immediate = true, configurationPolicy = ConfigurationPolicy.REQUIRE)
public class MeterSocomecCountisE14 extends AbstractOpenemsModbusComponent
implements SymmetricMeter, AsymmetricMeter, SinglePhaseMeter, OpenemsComponent, ModbusSlave {
private MeterType meterType = MeterType.PRODUCTION;
private SinglePhase phase = SinglePhase.L1;
/*
* Invert power values
*/
private boolean invert = false;
@Reference
protected ConfigurationAdmin cm;
public MeterSocomecCountisE14() {
super(//
OpenemsComponent.ChannelId.values(), //
SymmetricMeter.ChannelId.values(), //
AsymmetricMeter.ChannelId.values(), //
SinglePhaseMeter.ChannelId.values(), //
ChannelId.values() //
);
}
@Reference(policy = ReferencePolicy.STATIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.MANDATORY)
protected void setModbus(BridgeModbus modbus) {
super.setModbus(modbus);
}
@Activate
void activate(ComponentContext context, Config config) {
this.meterType = config.type();
this.phase = config.phase();
this.invert = config.invert();
super.activate(context, config.id(), config.alias(), config.enabled(), config.modbusUnitId(), this.cm, "Modbus",
config.modbus_id());
SinglePhaseMeter.initializeCopyPhaseChannel(this, this.phase);
}
@Deactivate
protected void deactivate() {
super.deactivate();
}
public enum ChannelId implements io.openems.edge.common.channel.ChannelId {
;
private final Doc doc;
private ChannelId(Doc doc) {
this.doc = doc;
}
public Doc doc() {
return this.doc;
}
}
@Override
public MeterType getMeterType() {
return this.meterType;
}
@Override
protected ModbusProtocol defineModbusProtocol() {
ModbusProtocol protocol = new ModbusProtocol(this, //
// TODO read "Extended Name" from 0xC38A and verify that this is really a
// Countis E24. Implement the same for all the other SOCOMEC meter.
new FC3ReadRegistersTask(0xc558, Priority.HIGH, //
m(new UnsignedDoublewordElement(0xc558)) //
.m(AsymmetricMeter.ChannelId.VOLTAGE_L1, ElementToChannelConverter.SCALE_FACTOR_1) //
.m(SymmetricMeter.ChannelId.VOLTAGE, ElementToChannelConverter.SCALE_FACTOR_1) //
.build(), //
new DummyRegisterElement(0xc55A, 0xc55D), //
m(SymmetricMeter.ChannelId.FREQUENCY, new UnsignedDoublewordElement(0xc55E)), //
m(new UnsignedDoublewordElement(0xc560)) //
.m(AsymmetricMeter.ChannelId.CURRENT_L1,
ElementToChannelConverter.INVERT_IF_TRUE(this.invert)) //
.m(SymmetricMeter.ChannelId.CURRENT,
ElementToChannelConverter.INVERT_IF_TRUE(this.invert)) //
.build(), //
new DummyRegisterElement(0xc562, 0xc567), //
m(SymmetricMeter.ChannelId.ACTIVE_POWER, new SignedDoublewordElement(0xc568),
ElementToChannelConverter.SCALE_FACTOR_1_AND_INVERT_IF_TRUE(this.invert)), //
m(SymmetricMeter.ChannelId.REACTIVE_POWER, new SignedDoublewordElement(0xc56A),
ElementToChannelConverter.SCALE_FACTOR_1_AND_INVERT_IF_TRUE(this.invert)) //
));
if (this.invert) {
protocol.addTask(new FC3ReadRegistersTask(0xC86F, Priority.LOW, //
m(SymmetricMeter.ChannelId.ACTIVE_CONSUMPTION_ENERGY, new UnsignedWordElement(0xC86F)), //
new DummyRegisterElement(0xC870),
m(SymmetricMeter.ChannelId.ACTIVE_PRODUCTION_ENERGY, new UnsignedWordElement(0xC871)) //
));
} else {
protocol.addTask(new FC3ReadRegistersTask(0xC86F, Priority.LOW, //
m(SymmetricMeter.ChannelId.ACTIVE_PRODUCTION_ENERGY, new UnsignedWordElement(0xC86F)), //
new DummyRegisterElement(0xC870),
m(SymmetricMeter.ChannelId.ACTIVE_CONSUMPTION_ENERGY, new UnsignedWordElement(0xC871)) //
));
}
return protocol;
}
@Override
public String debugLog() {
return "L:" + this.getActivePower().value().asString();
}
@Override
public SinglePhase getPhase() {
return this.getPhase();
}
@Override
public ModbusSlaveTable getModbusSlaveTable(AccessMode accessMode) {
return new ModbusSlaveTable( //
OpenemsComponent.getModbusSlaveNatureTable(accessMode), //
SymmetricMeter.getModbusSlaveNatureTable(accessMode), //
AsymmetricMeter.getModbusSlaveNatureTable(accessMode) //
);
}
}
|
3e161a477b05ee8381813582e227c4d5ed49e25a | 7,566 | java | Java | app/src/main/assets/bottomsheetBasicJAVA.java | khangpv202/material | d4a2018b0a347947e46bb3513fc97ae7386b92e7 | [
"Apache-2.0"
] | null | null | null | app/src/main/assets/bottomsheetBasicJAVA.java | khangpv202/material | d4a2018b0a347947e46bb3513fc97ae7386b92e7 | [
"Apache-2.0"
] | null | null | null | app/src/main/assets/bottomsheetBasicJAVA.java | khangpv202/material | d4a2018b0a347947e46bb3513fc97ae7386b92e7 | [
"Apache-2.0"
] | null | null | null | 36.550725 | 111 | 0.658472 | 9,405 | import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.dedsec.materialui.R;
import com.dedsec.materialui.utils.Tools;
public class BottomSheetBasic extends AppCompatActivity {
// Main Context Variable
Context mContext;
// Other Attributes
CoordinatorLayout _clMainLayout;
View bgView;
ListView personLV;
//ArrayAdapter<String> adapterListView;
TextView personNameTxt;
int[] PersonIMAGES = {R.drawable.person1, R.drawable.person2, R.drawable.person3,
R.drawable.person1, R.drawable.person2, R.drawable.person3,
R.drawable.person1, R.drawable.person2, R.drawable.person3,
R.drawable.person1, R.drawable.person2, R.drawable.person3,
R.drawable.person1, R.drawable.person2};
String[] PersonNAME = {"Evans Collins", "Sarah Scott","Betty L", "Garcia Lewis", "Anderson Thomas",
"Kevin John", "Laura Michelle", "Roberts", "Adams Green",
"Roberts Turner", "Mary Jackson", "Miller Wilson", "Betty C",
"Elizabeth"};
// attributes for bottom sheet
private LinearLayout _bottomSheetLayout;
private BottomSheetBehavior _bottomSheetBehavior;
private Button _btnSheetClose, _btnSheetDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_sheet_basic);
mContext = BottomSheetBasic.this;
_clMainLayout = findViewById(R.id.main_layout_t2_l1);
// For Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Basic");
// For Back Button Icon
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ic_menu_white));
// For Bottom Sheet
// Sheet
_bottomSheetLayout = findViewById(R.id.bottom_sheet_l1_sheet);
_bottomSheetBehavior = BottomSheetBehavior.from(_bottomSheetLayout);
// For Make Background Dark
bgView = findViewById(R.id.bgVisible);
_bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED)
bgView.setVisibility(View.GONE);
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
Log.d("TEST", "onSlide: slideOffset" + slideOffset + "");
bgView.setVisibility(View.VISIBLE);
bgView.setAlpha(slideOffset);
}
});
bgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (_bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED)
_bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
// BottomSheet Button
_btnSheetClose = findViewById(R.id.bottom_sheet_close_btn);
_btnSheetDetails = findViewById(R.id.bottom_sheet_details_btn);
_btnSheetClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
_bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
_btnSheetDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("DETAILS", "clicked");
Toast.makeText(mContext, "Details clicked", Toast.LENGTH_SHORT).show();
}
});
// For ListView Person NAme
personLV = findViewById(R.id.listview_person_name);
personNameTxt = findViewById(R.id.txt_person_name);
//final ArrayList<String> arrayPersonName = new ArrayList<>();
//arrayPersonName.addAll(Arrays.asList(getResources().getStringArray(R.array.array_person_name)));
//adapterListView = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, arrayPersonName);
customAdapter customAdapter = new customAdapter();
personLV.setAdapter(customAdapter);
personLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
personNameTxt.setText(PersonNAME[position]);
_bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
Tools.setSystemBarColor(this, R.color.blue_A700);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_default_light, menu);
return true;
}
// Method For Back Button ICON
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
case R.id.default_action_search:
Toast.makeText(mContext, "Search", Toast.LENGTH_SHORT).show();
return true;
case R.id.default_action_setting:
Toast.makeText(mContext, "Setting", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (_bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED)
_bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
else
super.onBackPressed();
}
// Base Class For Custom Listview..
class customAdapter extends BaseAdapter {
@Override
public int getCount() {
return PersonIMAGES.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int pos, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.custom_list_view_1, null);
ImageView personImg = view.findViewById(R.id.imgView_person_img);
TextView personNameTxt = view.findViewById(R.id.txt_person_name);
personImg.setImageResource(PersonIMAGES[pos]);
personNameTxt.setText(PersonNAME[pos]);
return view;
}
}
}
|
3e161a8f295dec9b2549c4a4f469063f0d3f1202 | 17,746 | java | Java | src/Program5.0/src/soars/application/visualshell/object/role/base/edit/tab/legacy/condition/KeywordConditionPropertyPanel.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/visualshell/object/role/base/edit/tab/legacy/condition/KeywordConditionPropertyPanel.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/visualshell/object/role/base/edit/tab/legacy/condition/KeywordConditionPropertyPanel.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | 1 | 2019-03-18T06:22:49.000Z | 2019-03-18T06:22:49.000Z | 31.024476 | 331 | 0.709456 | 9,406 | /*
* 2005/08/25
*/
package soars.application.visualshell.object.role.base.edit.tab.legacy.condition;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import soars.application.visualshell.common.selector.ObjectSelector;
import soars.application.visualshell.common.tool.CommonTool;
import soars.application.visualshell.layer.LayerManager;
import soars.application.visualshell.main.Constant;
import soars.application.visualshell.main.ResourceManager;
import soars.application.visualshell.object.entity.spot.SpotObject;
import soars.application.visualshell.object.role.agent.AgentRole;
import soars.application.visualshell.object.role.base.Role;
import soars.application.visualshell.object.role.base.edit.EditRoleFrame;
import soars.application.visualshell.object.role.base.edit.tab.base.RulePropertyPanelBase;
import soars.application.visualshell.object.role.base.object.base.Rule;
import soars.application.visualshell.object.role.base.object.common.CommonRuleManipulator;
import soars.application.visualshell.object.role.base.object.legacy.condition.KeywordCondition;
import soars.application.visualshell.object.role.spot.SpotRole;
import soars.common.utility.swing.button.CheckBox;
import soars.common.utility.swing.button.RadioButton;
import soars.common.utility.swing.combo.ComboBox;
import soars.common.utility.swing.text.TextExcluder;
import soars.common.utility.swing.text.TextField;
import soars.common.utility.swing.tool.SwingTool;
/**
* @author kurata
*/
public class KeywordConditionPropertyPanel extends RulePropertyPanelBase {
/**
*
*/
private CheckBox _spotCheckBox = null;
/**
*
*/
private ObjectSelector _spotSelector = null;
/**
*
*/
private CheckBox _spotVariableCheckBox = null;
/**
*
*/
private ComboBox _spotVariableComboBox = null;
/**
*
*/
private CheckBox _denyCheckBox = null;
/**
*
*/
private JLabel _keywordLabel = null;
/**
*
*/
private ComboBox[] _keywordComboBoxes = new ComboBox[] {
null, null
};
/**
*
*/
private RadioButton[] _radioButtons1 = new RadioButton[] {
null, null
};
/**
*
*/
private TextField _keywordValueTextField = null;
/**
* @param title
* @param kind
* @param type
* @param color
* @param role
* @param index
* @param owner
* @param parent
*/
public KeywordConditionPropertyPanel(String title, String kind, String type, Color color, Role role, int index, Frame owner, EditRoleFrame parent) {
super(title, kind, type, color, role, index, owner, parent);
}
/* (Non Javadoc)
* @see soars.common.utility.swing.panel.StandardPanel#on_create()
*/
@Override
protected boolean on_create() {
if ( !super.on_create())
return false;
setLayout( new BorderLayout());
JPanel basicPanel = new JPanel();
basicPanel.setLayout( new BorderLayout());
JPanel northPanel = new JPanel();
northPanel.setLayout( new BoxLayout( northPanel, BoxLayout.Y_AXIS));
insert_horizontal_glue( northPanel);
setup_spot_checkBox_and_spot_selector( northPanel);
insert_vertical_strut( northPanel);
setup_spot_variable_checkBox_and_spot_variable_comboBox( northPanel);
insert_vertical_strut( northPanel);
setup_keyword_comboBox0( northPanel);
insert_vertical_strut( northPanel);
ButtonGroup buttonGroup1 = new ButtonGroup();
setup_keyword_comboBox1( buttonGroup1, northPanel);
insert_vertical_strut( northPanel);
setup_keyword_value_textField( buttonGroup1, northPanel);
insert_vertical_strut( northPanel);
basicPanel.add( northPanel, "North");
add( basicPanel);
setup_apply_button();
adjust();
return true;
}
/**
* @param parent
*/
private void setup_spot_checkBox_and_spot_selector(JPanel parent) {
int pad = 5;
JPanel panel = new JPanel();
panel.setLayout( new FlowLayout( FlowLayout.LEFT, pad, 0));
_spotCheckBox = create_checkBox(
ResourceManager.get_instance().get( "edit.rule.dialog.condition.keyword.spot.check.box.name"),
false, true);
_spotCheckBox.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
_spotSelector.setEnabled(
ItemEvent.SELECTED == arg0.getStateChange());
on_update( ItemEvent.SELECTED == arg0.getStateChange(),
_spotSelector,
_spotVariableCheckBox,
_spotVariableComboBox);
}
});
panel.add( _spotCheckBox);
_spotSelector = create_spot_selector( true, true, panel);
parent.add( panel);
}
/**
* @param parent
*/
private void setup_spot_variable_checkBox_and_spot_variable_comboBox( JPanel parent) {
int pad = 5;
JPanel panel = new JPanel();
panel.setLayout( new FlowLayout( FlowLayout.LEFT, pad, 0));
_spotVariableCheckBox = create_checkBox(
ResourceManager.get_instance().get( "edit.rule.dialog.spot.variable.check.box.name"),
true, true);
_spotVariableCheckBox.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
on_update( _spotCheckBox.isSelected(),
_spotSelector,
_spotVariableCheckBox,
_spotVariableComboBox);
}
});
panel.add( _spotVariableCheckBox);
_spotVariableComboBox = create_comboBox( null, _standardControlWidth, false);
panel.add( _spotVariableComboBox);
parent.add( panel);
}
/**
* @param parent
*/
private void setup_keyword_comboBox0(JPanel parent) {
int pad = 5;
JPanel panel = new JPanel();
panel.setLayout( new FlowLayout( FlowLayout.LEFT, pad, 0));
_denyCheckBox = create_checkBox(
ResourceManager.get_instance().get( "edit.rule.dialog.condition.check.box.denial"),
true, false);
panel.add( _denyCheckBox);
_keywordLabel = create_label(
" " + ResourceManager.get_instance().get( "edit.rule.dialog.condition.keyword.label"),
false);
panel.add( _keywordLabel);
_keywordComboBoxes[ 0] = create_comboBox( null, _standardControlWidth, false);
panel.add( _keywordComboBoxes[ 0]);
parent.add( panel);
}
/**
* @param buttonGroup1
* @param parent
*/
private void setup_keyword_comboBox1(ButtonGroup buttonGroup1, JPanel parent) {
int pad = 5;
JPanel panel = new JPanel();
panel.setLayout( new FlowLayout( FlowLayout.LEFT, pad, 0));
_radioButtons1[ 0] = create_radioButton(
ResourceManager.get_instance().get( "edit.rule.dialog.condition.keyword.keyword"),
buttonGroup1, true, false);
_radioButtons1[ 0].addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
_keywordComboBoxes[ 1].setEnabled(
ItemEvent.SELECTED == arg0.getStateChange());
}
});
panel.add( _radioButtons1[ 0]);
_keywordComboBoxes[ 1] = create_comboBox( null, _standardControlWidth, false);
panel.add( _keywordComboBoxes[ 1]);
parent.add( panel);
}
/**
* @param buttonGroup1
* @param parent
*/
private void setup_keyword_value_textField(ButtonGroup buttonGroup1, JPanel parent) {
int pad = 5;
JPanel panel = new JPanel();
panel.setLayout( new FlowLayout( FlowLayout.LEFT, pad, 0));
_radioButtons1[ 1] = create_radioButton(
ResourceManager.get_instance().get( "edit.rule.dialog.condition.keyword.value"),
buttonGroup1, true, false);
_radioButtons1[ 1].addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
_keywordValueTextField.setEnabled(
ItemEvent.SELECTED == arg0.getStateChange());
}
});
panel.add( _radioButtons1[ 1]);
_keywordValueTextField = create_textField( new TextExcluder( Constant._prohibitedCharacters3), false);
panel.add( _keywordValueTextField);
parent.add( panel);
}
/**
*
*/
private void adjust() {
int width1 = ( _denyCheckBox.getPreferredSize().width
+ _keywordLabel.getPreferredSize().width + 5);
int width2 = _spotCheckBox.getPreferredSize().width;
width2 = Math.max( width2, _spotVariableCheckBox.getPreferredSize().width);
for ( int i = 0; i < _radioButtons1.length; ++i)
width2 = Math.max( width2, _radioButtons1[ i].getPreferredSize().width);
int width;
if ( width1 > width2)
width = width1;
else {
width = width2;
_keywordLabel.setPreferredSize( new Dimension(
_keywordLabel.getPreferredSize().width + ( width2 - width1),
_keywordLabel.getPreferredSize().height));
}
_spotCheckBox.setPreferredSize( new Dimension( width,
_spotCheckBox.getPreferredSize().height));
_spotVariableCheckBox.setPreferredSize( new Dimension( width,
_spotVariableCheckBox.getPreferredSize().height));
Dimension dimension = new Dimension( width,
_radioButtons1[ 0].getPreferredSize().height);
for ( int i = 0; i < _radioButtons1.length; ++i)
_radioButtons1[ i].setPreferredSize( dimension);
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#reset(soars.application.visualshell.common.selector.ObjectSelector, soars.common.utility.swing.button.CheckBox, soars.common.utility.swing.combo.ComboBox)
*/
@Override
protected void reset(ObjectSelector objectSelector, CheckBox spotVariableCheckBox, ComboBox spotVariableComboBox) {
if ( !objectSelector.equals( _spotSelector))
return;
CommonTool.update( spotVariableComboBox, !_spotCheckBox.isSelected() ? get_agent_spot_variable_names( false) : get_spot_spot_variable_names( false));
super.reset(objectSelector, spotVariableCheckBox, spotVariableComboBox);
objectSelector.setEnabled( _spotCheckBox.isSelected());
for ( int i = 0; i < _keywordComboBoxes.length; ++i)
CommonTool.update( _keywordComboBoxes[ i], ( !_spotCheckBox.isSelected() && !spotVariableCheckBox.isSelected()) ? get_agent_keyword_names( false) : get_spot_keyword_names( false));
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#update(soars.application.visualshell.common.selector.ObjectSelector, soars.common.utility.swing.button.CheckBox, soars.common.utility.swing.combo.ComboBox)
*/
@Override
protected void update(ObjectSelector objectSelector, CheckBox spotVariableCheckBox, ComboBox spotVariableComboBox) {
if ( !objectSelector.equals( _spotSelector))
return;
super.update(objectSelector, spotVariableCheckBox, spotVariableComboBox);
for ( int i = 0; i < _keywordComboBoxes.length; ++i)
CommonTool.update( _keywordComboBoxes[ i], get_spot_keyword_names( false));
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#update(soars.application.visualshell.object.entiy.spot.SpotObject, java.lang.String, soars.application.visualshell.common.selector.ObjectSelector, soars.common.utility.swing.button.CheckBox, soars.common.utility.swing.combo.ComboBox)
*/
@Override
protected void update(SpotObject spotObject, String number, ObjectSelector objectSelector, CheckBox spotVariableCheckBox, ComboBox spotVariableComboBox) {
if ( !objectSelector.equals( _spotSelector))
return;
super.update(spotObject, number, objectSelector, spotVariableCheckBox, spotVariableComboBox);
for ( int i = 0; i < _keywordComboBoxes.length; ++i)
CommonTool.update( _keywordComboBoxes[ i], !spotVariableCheckBox.isSelected() ? spotObject.get_object_names( "keyword", number, false) : get_spot_keyword_names( false));
}
/* (Non Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#update(soars.application.visualshell.common.selector.ObjectSelector)
*/
@Override
protected void update(ObjectSelector objectSelector) {
update( objectSelector, _spotVariableCheckBox, _spotVariableComboBox);
}
/* (Non Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#update(soars.application.visualshell.object.entiy.spot.SpotObject, java.lang.String, soars.application.visualshell.common.selector.ObjectSelector)
*/
@Override
protected void update(SpotObject spotObject, String number, ObjectSelector objectSelector) {
update( spotObject, number, objectSelector, _spotVariableCheckBox, _spotVariableComboBox);
}
/**
*
*/
private void initialize() {
if ( _role instanceof AgentRole) {
_spotCheckBox.setSelected( false);
_spotSelector.setEnabled( false);
} else {
_spotCheckBox.setSelected( true);
_spotCheckBox.setEnabled( false);
_spotSelector.setEnabled( true);
}
_radioButtons1[ 0].setSelected( true);
update_components( new boolean[] {
true, false
});
}
/**
* @param enables
*/
private void update_components(boolean[] enables) {
_keywordComboBoxes[ 1].setEnabled( enables[ 0]);
_keywordValueTextField.setEnabled( enables[ 1]);
}
/**
*
*/
private void set_handler() {
_spotSelector.set_handler( this);
}
/* (Non Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#on_setup_completed()
*/
@Override
public void on_setup_completed() {
reset( _spotSelector, _spotVariableCheckBox, _spotVariableComboBox);
super.on_setup_completed();
}
/* (Non Javadoc)
* @see soars.common.utility.swing.panel.StandardPanel#on_ok(java.awt.event.ActionEvent)
*/
@Override
protected void on_ok(ActionEvent actionEvent) {
_parent.on_apply( this, actionEvent);
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#set(soars.application.visualshell.object.role.base.rule.base.Rule)
*/
@Override
public boolean set(Rule rule) {
initialize();
if ( null == rule || !_type.equals( rule._type) || rule._value.equals( "")) {
set_handler();
return false;
}
if ( rule._value.equals( "")) {
set_handler();
return false;
}
String[] elements = CommonRuleManipulator.get_elements( rule._value, 1);
if ( null == elements) {
set_handler();
return false;
}
String[] values = CommonRuleManipulator.get_spot_and_object( elements[ 0]);
if ( null == values) {
set_handler();
return false;
}
if ( null == values[ 0] && _role instanceof SpotRole) {
set_handler();
return false;
}
String spot = CommonRuleManipulator.get_semantic_prefix( values);
if ( !set( values[ 0], values[ 1], _spotCheckBox, _spotSelector, _spotVariableCheckBox, _spotVariableComboBox)) {
set_handler();
return false;
}
_keywordComboBoxes[ 0].setSelectedItem( values[ 2]);
if ( 2 > elements.length) {
_keywordValueTextField.setText( "");
_radioButtons1[ 1].setSelected( true);
} else {
if ( 2 <= elements[ 1].length() && elements[ 1].startsWith( "\"") && elements[ 1].endsWith( "\"")) {
_keywordValueTextField.setText( elements[ 1].substring( 1, elements[ 1].length() - 1));
_radioButtons1[ 1].setSelected( true);
} else if ( ( spot.equals( "") && LayerManager.get_instance().is_agent_object_name( "keyword", elements[ 1]))
|| ( spot.equals( "<>") && LayerManager.get_instance().is_spot_object_name( "keyword", elements[ 1]))
|| LayerManager.get_instance().is_spot_object_name( "keyword", spot, elements[ 1])) {
_keywordComboBoxes[ 1].setSelectedItem( elements[ 1]);
_radioButtons1[ 0].setSelected( true);
} else {
_keywordValueTextField.setText( elements[ 1]);
_radioButtons1[ 1].setSelected( true);
}
}
_denyCheckBox.setSelected( rule._value.startsWith( "!"));
set_handler();
return true;
}
/* (non-Javadoc)
* @see soars.application.visualshell.object.role.base.rule.edit.tab.base.RulePropertyPanelBase#get()
*/
@Override
public Rule get() {
String value = null;
int kind = SwingTool.get_enabled_radioButton( _radioButtons1);
switch ( kind) {
case 0:
value = get2( _keywordComboBoxes[ 0], _keywordComboBoxes[ 1]);
break;
case 1:
value = get_keyword();
break;
default:
return null;
}
if ( null == value)
return null;
String spot = get( _spotCheckBox, _spotSelector, _spotVariableCheckBox, _spotVariableComboBox);
return Rule.create( _kind, _type,
( _denyCheckBox.isSelected() ? "!" : "") + ( KeywordCondition._reservedWords[ 0] + spot + value));
}
/**
* @return
*/
private String get_keyword() {
if ( null == _keywordValueTextField.getText()
|| _keywordValueTextField.getText().equals( "$")
|| 0 < _keywordValueTextField.getText().indexOf( '$')
|| _keywordValueTextField.getText().startsWith( " ")
|| _keywordValueTextField.getText().endsWith( " ")
|| _keywordValueTextField.getText().equals( "$Name")
|| _keywordValueTextField.getText().equals( "$Role")
|| _keywordValueTextField.getText().equals( "$Spot")
|| 0 <= _keywordValueTextField.getText().indexOf( Constant._experimentName))
return null;
if ( _keywordValueTextField.getText().startsWith( "$")
&& ( 0 <= _keywordValueTextField.getText().indexOf( " ")
|| 0 < _keywordValueTextField.getText().indexOf( "$", 1)
|| 0 < _keywordValueTextField.getText().indexOf( ")", 1)))
return null;
return get_keyword( _keywordComboBoxes[ 0], _keywordValueTextField);
}
}
|
3e161d05abc1ffce6d612452e48dbb6450abb319 | 5,104 | java | Java | src/main/java/com/hubrick/vertx/elasticsearch/model/GetOptions.java | rluta/vertx-elasticsearch-service | b19bbd51eb692700fd14622d2b8cf6d26819b951 | [
"Apache-2.0"
] | 31 | 2016-11-11T13:56:01.000Z | 2021-04-25T00:02:26.000Z | src/main/java/com/hubrick/vertx/elasticsearch/model/GetOptions.java | rluta/vertx-elasticsearch-service | b19bbd51eb692700fd14622d2b8cf6d26819b951 | [
"Apache-2.0"
] | 12 | 2017-01-17T08:09:07.000Z | 2021-12-10T00:48:42.000Z | src/main/java/com/hubrick/vertx/elasticsearch/model/GetOptions.java | rluta/vertx-elasticsearch-service | b19bbd51eb692700fd14622d2b8cf6d26819b951 | [
"Apache-2.0"
] | 13 | 2017-06-28T11:58:10.000Z | 2020-05-12T02:37:14.000Z | 32.705128 | 128 | 0.678949 | 9,407 | /**
* Copyright (C) 2016 Etaia AS (kenaa@example.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.hubrick.vertx.elasticsearch.model;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* Get operation options
*/
@DataObject
public class GetOptions extends AbstractOptions<GetOptions> {
private String preference;
private List<String> fields = new ArrayList<>();
private Boolean fetchSource;
private List<String> fetchSourceIncludes = new ArrayList<>();
private List<String> fetchSourceExcludes = new ArrayList<>();
private Boolean realtime;
private Boolean refresh;
public static final String FIELD_PREFERENCE = "preference";
public static final String FIELD_FIELDS = "fields";
public static final String FIELD_FETCH_SOURCE = "fetchSource";
public static final String FIELD_FETCH_SOURCE_INCLUDES = "fetchSourceIncludes";
public static final String FIELD_FETCH_SOURCE_EXCLUDES = "fetchSourceExcludes";
public static final String FIELD_REALTIME = "realtime";
public static final String FIELD_REFRESH = "refresh";
public GetOptions() {
}
public GetOptions(GetOptions other) {
super(other);
preference = other.getPreference();
fields.addAll(other.getFields());
fetchSource = other.getFetchSource();
fetchSourceIncludes = other.getFetchSourceIncludes();
fetchSourceExcludes = other.getFetchSourceExcludes();
realtime = other.getRealtime();
refresh = other.getRefresh();
}
public GetOptions(JsonObject json) {
super(json);
preference= json.getString(FIELD_PREFERENCE);
fields = json.getJsonArray(FIELD_FIELDS, new JsonArray()).getList();
fetchSource = json.getBoolean(FIELD_FETCH_SOURCE);
fetchSourceIncludes = json.getJsonArray(FIELD_FETCH_SOURCE_INCLUDES, new JsonArray()).getList();
fetchSourceExcludes = json.getJsonArray(FIELD_FETCH_SOURCE_EXCLUDES, new JsonArray()).getList();
realtime = json.getBoolean(FIELD_REALTIME);
refresh = json.getBoolean(FIELD_REFRESH);
}
public String getPreference() {
return preference;
}
public GetOptions setPreference(String preference) {
this.preference = preference;
return this;
}
public List<String> getFields() {
return fields;
}
public GetOptions addField(String field) {
this.fields.add(field);
return this;
}
public Boolean getFetchSource() {
return fetchSource;
}
public GetOptions setFetchSource(Boolean fetchSource) {
this.fetchSource = fetchSource;
return this;
}
public List<String> getFetchSourceIncludes() {
return fetchSourceIncludes;
}
public List<String> getFetchSourceExcludes() {
return fetchSourceExcludes;
}
public GetOptions setFetchSource(List<String> includes, List<String> excludes) {
if (includes == null || includes.isEmpty()) {
fetchSourceIncludes.clear();
} else {
fetchSourceIncludes.addAll(includes);
}
if (excludes == null || excludes.isEmpty()) {
fetchSourceExcludes.clear();
} else {
fetchSourceExcludes.addAll(excludes);
}
return this;
}
public Boolean getRealtime() {
return realtime;
}
public GetOptions setRealtime(Boolean realtime) {
this.realtime = realtime;
return this;
}
public Boolean getRefresh() {
return refresh;
}
public GetOptions setRefresh(Boolean refresh) {
this.refresh = refresh;
return this;
}
@Override
public JsonObject toJson() {
JsonObject json = super.toJson();
if (getPreference() != null) json.put(FIELD_PREFERENCE, getPreference());
if (!getFields().isEmpty()) json.put(FIELD_FIELDS, new JsonArray(getFields()));
if (getFetchSource() != null) json.put(FIELD_FETCH_SOURCE, getFetchSource());
if (!getFetchSourceIncludes().isEmpty()) json.put(FIELD_FETCH_SOURCE_INCLUDES, new JsonArray(getFetchSourceIncludes()));
if (!getFetchSourceExcludes().isEmpty()) json.put(FIELD_FETCH_SOURCE_EXCLUDES, new JsonArray(getFetchSourceExcludes()));
if (getRealtime() != null) json.put(FIELD_REALTIME, getRealtime());
if (getRefresh() != null) json.put(FIELD_REFRESH, getRefresh());
return json;
}
}
|
3e161d6f626c8aefc0f470453eb492fd6c939984 | 1,327 | java | Java | backend_java_case/JavaFrame/SpringMVCFrame/src/main/java/com/spring/ch_02/study_03/SgtPeppers.java | JUSTLOVELE/MobileDevStudy | ddcfd67d9ad66dd710fcbb355406bab3679ebaf7 | [
"MIT"
] | 1 | 2021-09-26T04:31:52.000Z | 2021-09-26T04:31:52.000Z | backend_java_case/JavaFrame/SpringMVCFrame/src/main/java/com/spring/ch_02/study_03/SgtPeppers.java | JUSTLOVELE/MobileDevStudy | ddcfd67d9ad66dd710fcbb355406bab3679ebaf7 | [
"MIT"
] | null | null | null | backend_java_case/JavaFrame/SpringMVCFrame/src/main/java/com/spring/ch_02/study_03/SgtPeppers.java | JUSTLOVELE/MobileDevStudy | ddcfd67d9ad66dd710fcbb355406bab3679ebaf7 | [
"MIT"
] | 1 | 2020-06-28T01:04:38.000Z | 2020-06-28T01:04:38.000Z | 23.280702 | 78 | 0.55162 | 9,408 | package com.spring.ch_02.study_03;
import com.spring.ch_02.study_02.CompactDisc;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* ���Ҫȡ�Լ�ϲ��������ֵ:@Component("youLikeName")
* ɨ������������@Bean,��ʵ����������ʱ�����@Bean��ע����ȱ�����
* @author Administrator
*
*/
@Component
public class SgtPeppers implements CompactDisc {
private String title = "Sgt. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles";
public void play() {
// TODO Auto-generated method stub
System.out.println("Play " + title + "by " + artist);
}
/**
* ������ʱ���Զ�װ��һ��CompactDisc�����÷�����
* ���ַ�ʽ��������ķ�ʽ������
* @param compactDisc
* @return
*/
@Bean
public CDPlayer cdPlayer(CompactDisc compactDisc){
return new CDPlayer(compactDisc);
}
@Bean
public CDPlayer cdPlayer(){
/**
* ������CompactDisc��ͨ������sgtPeppers()�õ���,�����������ȫ���,
* ��ΪsgtPeppers()�����������@Beanע��,Spring�����������ж����ĵ���,��ȷ��ֱ�ӷ���
* �÷�����������bean,������ÿ�ζ��������ʵ�ʵĵ���
*/
return new CDPlayer(sgtPeppers());
}
/**
* @bean ע������Spring����������᷵��һ������,�ö���Ҫע��ΪSpringӦ���������е�bean
* �������а��������ղ���beanʵ������
* @return
*/
@Bean
public CompactDisc sgtPeppers(){
return new SgtPeppers();
}
}
|
3e161d7d0de29d39170e26d0dd126a3aef2edf8e | 270 | java | Java | android/src/com/msgkatz/ratesapp/presentation/entities/events/PriceEvent.java | msgkatz/chartsnrates | 904e63eb8de0f81b53c59d03cc5863c6f2c62609 | [
"Apache-2.0"
] | 4 | 2019-02-04T11:03:45.000Z | 2021-08-25T10:51:21.000Z | android/src/com/msgkatz/ratesapp/presentation/entities/events/PriceEvent.java | msgkatz/chartsnrates | 904e63eb8de0f81b53c59d03cc5863c6f2c62609 | [
"Apache-2.0"
] | 1 | 2020-07-15T13:43:10.000Z | 2020-07-15T13:43:10.000Z | android/src/com/msgkatz/ratesapp/presentation/entities/events/PriceEvent.java | msgkatz/chartsnrates | 904e63eb8de0f81b53c59d03cc5863c6f2c62609 | [
"Apache-2.0"
] | 2 | 2020-04-29T18:44:24.000Z | 2021-05-03T12:26:42.000Z | 16.875 | 58 | 0.659259 | 9,409 | package com.msgkatz.ratesapp.presentation.entities.events;
public class PriceEvent extends BaseEvent {
private double price;
public PriceEvent(double price)
{
this.price = price;
}
public double getPrice() {
return price;
}
}
|
3e161e552cc277baaac99144aeda82a5a6e69b3d | 2,063 | java | Java | triple-core/src/main/java/com/tjq/triple/transport/netty4/server/NettyServer.java | LoveAlwaysYoung/triple | 68e4d521ec42caf52c13fefc451e1780ce133d91 | [
"Apache-2.0"
] | 3 | 2020-06-15T07:36:01.000Z | 2022-03-25T06:51:16.000Z | triple-core/src/main/java/com/tjq/triple/transport/netty4/server/NettyServer.java | LoveAlwaysYoung/triple | 68e4d521ec42caf52c13fefc451e1780ce133d91 | [
"Apache-2.0"
] | 1 | 2021-02-18T16:28:43.000Z | 2021-02-18T16:28:43.000Z | triple-core/src/main/java/com/tjq/triple/transport/netty4/server/NettyServer.java | KFCFans/triple | 68e4d521ec42caf52c13fefc451e1780ce133d91 | [
"Apache-2.0"
] | null | null | null | 28.260274 | 88 | 0.606398 | 9,410 | package com.tjq.triple.transport.netty4.server;
import com.tjq.triple.transport.netty4.handler.NettyChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
/**
* Netty Server 服务器(监听某个端口的连接请求 & 处理请求数据)
*
* @author tjq
* @since 2020/1/3
*/
@Slf4j
public class NettyServer {
/**
* config info
*/
private final String ip;
private final int port;
public NettyServer(String ip, int port) {
this.ip = ip;
this.port = port;
}
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private volatile boolean started = false;
public boolean start() {
if (started) {
return true;
}
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
ServerBootstrap server = new ServerBootstrap();
server.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new NettyChannelInitializer(false));
started = true;
try {
ChannelFuture future = server.bind(ip, port).sync();
log.info("[TripleServer] netty server startup in address({}:{})", ip, port);
// 阻塞到应用关闭
future.channel().closeFuture().sync();
}catch (Exception e) {
started = false;
stop();
log.error("[TripleServer] netty server startup failed.", e);
}
return started;
}
/**
* 关闭 Netty 服务器
*/
public void stop() {
if (bossGroup != null) {
bossGroup.shutdownGracefully();
}
if (workerGroup != null) {
workerGroup.shutdownGracefully();
}
}
}
|
3e161f43e429d0c3227e86a94961d3dcf99275e7 | 492 | java | Java | cloud-mall-log/cloud-mall-log6201/src/main/java/com/boot/service/TimeCalcService.java | youzhengjie9/cloud-mall | dd3a43d209fd51e9246332122f46fb87f38036d0 | [
"Apache-2.0"
] | 17 | 2021-07-18T01:54:48.000Z | 2021-12-18T07:19:55.000Z | cloud-mall-log/cloud-mall-log6201/src/main/java/com/boot/service/TimeCalcService.java | gopher-king/cloud-mall | 763ce32b7e89f8862ef00cae4c1a9addea7b98ba | [
"Apache-2.0"
] | 1 | 2021-12-18T09:48:49.000Z | 2021-12-18T09:57:59.000Z | cloud-mall-log/cloud-mall-log6201/src/main/java/com/boot/service/TimeCalcService.java | gopher-king/cloud-mall | 763ce32b7e89f8862ef00cae4c1a9addea7b98ba | [
"Apache-2.0"
] | 4 | 2021-11-15T02:16:37.000Z | 2022-03-05T09:24:38.000Z | 18.923077 | 75 | 0.739837 | 9,411 | package com.boot.service;
import com.boot.pojo.TimeCalc;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TimeCalcService {
void insertTimeCalc(TimeCalc timeCalc);
//分页查询
List<TimeCalc> selectTimeCalcBylimit(int page,int size);
//查询接口监控记录总数量
int selectTimeCalcCount();
//根据uri分页查询
List<TimeCalc> selectTimeCalcByUriLimit(String uri,int page, int size);
//根据uri查询数量
int selectTimeCalcCountBylimit(String uri);
}
|
3e1620f70d3aed3b7dfe4dea1879579fbf45b29a | 4,651 | java | Java | Kingdom game/src/Menu.java | whitewolf5432/OOP_Kingdom | 90091ed005b972f1083a6400d70e716e5d054b8e | [
"MIT"
] | null | null | null | Kingdom game/src/Menu.java | whitewolf5432/OOP_Kingdom | 90091ed005b972f1083a6400d70e716e5d054b8e | [
"MIT"
] | null | null | null | Kingdom game/src/Menu.java | whitewolf5432/OOP_Kingdom | 90091ed005b972f1083a6400d70e716e5d054b8e | [
"MIT"
] | null | null | null | 35.234848 | 115 | 0.590196 | 9,412 |
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Menu extends javax.swing.JPanel {
public Menu() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setPreferredSize(new java.awt.Dimension(1280, 800));
setLayout(null);
jButton1.setText("RESUME");
jButton1.setContentAreaFilled(false);
jButton1.setFocusPainted(false);
jButton1.setFocusable(false);
jButton1.setFont(new java.awt.Font("Century", 0, 15));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
add(jButton1);
jButton1.setBounds(490, 180, 250, 100);
jButton2.setText("HOME");
jButton2.setContentAreaFilled(false);
jButton2.setFocusPainted(false);
jButton2.setFocusable(false);
jButton2.setFont(new java.awt.Font("Century", 0, 15));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add(jButton2);
jButton2.setBounds(490, 300, 250, 100);
jButton3.setText("HOW TO PLAY");
jButton3.setContentAreaFilled(false);
jButton3.setFocusPainted(false);
jButton3.setFocusable(false);
jButton3.setFont(new java.awt.Font("Century", 0, 15));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
add(jButton3);
jButton3.setBounds(490, 420, 250, 100);
jButton4.setText("EXIT");
jButton4.setContentAreaFilled(false);
jButton4.setFocusPainted(false);
jButton4.setFocusable(false);
jButton4.setFont(new java.awt.Font("Century", 0, 15));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
add(jButton4);
jButton4.setBounds(490, 540, 250, 100);
ImageIcon bt = new ImageIcon(new javax.swing.ImageIcon("Image/Game/Menubut.png").getImage());
ImageIcon bg = new ImageIcon(new javax.swing.ImageIcon("Image/Game/7055306.png").getImage());
jLabel5.setIcon((Icon) bt);
add(jLabel5);
jLabel5.setBounds(490, 540, 250, 100);
jLabel4.setIcon((Icon) bt);
add(jLabel4);
jLabel4.setBounds(490, 420, 250, 100);
jLabel3.setIcon((Icon) bt);
add(jLabel3);
jLabel3.setBounds(490, 300, 250, 100);
jLabel2.setIcon((Icon) bt);
add(jLabel2);
jLabel2.setBounds(490, 180, 250, 100);
jLabel1.setIcon((Icon) bg);
add(jLabel1);
jLabel1.setBounds(0, 0, 1280, 800);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Game.change("Play");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Game.change("Home");
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Game.HowToPlay(0);
Game.change("How To Play");
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
Game.change("Exit");
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
}
|
3e1623050ecb7e61c20ff0826f1c521abaa99212 | 1,871 | java | Java | tools.hadoop/src/ext/hdfs/org/apache/hadoop/hdfs/security/token/block/BlockTokenSelector.java | aqnotecom/java.tools | 4a60d37f51e141f9cffa0ea89582402991fa89e5 | [
"Apache-2.0"
] | null | null | null | tools.hadoop/src/ext/hdfs/org/apache/hadoop/hdfs/security/token/block/BlockTokenSelector.java | aqnotecom/java.tools | 4a60d37f51e141f9cffa0ea89582402991fa89e5 | [
"Apache-2.0"
] | null | null | null | tools.hadoop/src/ext/hdfs/org/apache/hadoop/hdfs/security/token/block/BlockTokenSelector.java | aqnotecom/java.tools | 4a60d37f51e141f9cffa0ea89582402991fa89e5 | [
"Apache-2.0"
] | null | null | null | 37.34 | 93 | 0.742367 | 9,413 | /**
* 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.
*/
/*
* Copyright (C) 2013-2016 Peng Li<dycjh@example.com>.
* This library is free software; you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation;
*/ org.apache.hadoop.hdfs.security.token.block;
import java.util.Collection;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenSelector;
/**
* A block token selector for HDFS
*/
public class BlockTokenSelector implements TokenSelector<BlockTokenIdentifier> {
@SuppressWarnings("unchecked")
public Token<BlockTokenIdentifier> selectToken(Text service,
Collection<Token<? extends TokenIdentifier>> tokens) {
if (service == null) {
return null;
}
for (Token<? extends TokenIdentifier> token : tokens) {
if (BlockTokenIdentifier.KIND_NAME.equals(token.getKind())) {
return (Token<BlockTokenIdentifier>) token;
}
}
return null;
}
}
|
3e1624660165f1f9d2489c5e67d86cc7e62f1978 | 4,292 | java | Java | sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/logs/models/MetadataApplication.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/logs/models/MetadataApplication.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/logs/models/MetadataApplication.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 30.013986 | 116 | 0.63164 | 9,414 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.monitor.query.implementation.logs.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Application Insights apps that were part of the metadata request and that the user has access to. */
@Fluent
public final class MetadataApplication {
/*
* The ID of the Application Insights app.
*/
@JsonProperty(value = "id", required = true)
private String id;
/*
* The ARM resource ID of the Application Insights app.
*/
@JsonProperty(value = "resourceId", required = true)
private String resourceId;
/*
* The name of the Application Insights app.
*/
@JsonProperty(value = "name", required = true)
private String name;
/*
* The Azure region of the Application Insights app.
*/
@JsonProperty(value = "region", required = true)
private String region;
/*
* The related metadata items for the Application Insights app.
*/
@JsonProperty(value = "related")
private MetadataApplicationRelated related;
/**
* Creates an instance of MetadataApplication class.
*
* @param id the id value to set.
* @param resourceId the resourceId value to set.
* @param name the name value to set.
* @param region the region value to set.
*/
@JsonCreator
public MetadataApplication(
@JsonProperty(value = "id", required = true) String id,
@JsonProperty(value = "resourceId", required = true) String resourceId,
@JsonProperty(value = "name", required = true) String name,
@JsonProperty(value = "region", required = true) String region) {
this.id = id;
this.resourceId = resourceId;
this.name = name;
this.region = region;
}
/**
* Get the id property: The ID of the Application Insights app.
*
* @return the id value.
*/
public String getId() {
return this.id;
}
/**
* Get the resourceId property: The ARM resource ID of the Application Insights app.
*
* @return the resourceId value.
*/
public String getResourceId() {
return this.resourceId;
}
/**
* Get the name property: The name of the Application Insights app.
*
* @return the name value.
*/
public String getName() {
return this.name;
}
/**
* Get the region property: The Azure region of the Application Insights app.
*
* @return the region value.
*/
public String getRegion() {
return this.region;
}
/**
* Get the related property: The related metadata items for the Application Insights app.
*
* @return the related value.
*/
public MetadataApplicationRelated getRelated() {
return this.related;
}
/**
* Set the related property: The related metadata items for the Application Insights app.
*
* @param related the related value to set.
* @return the MetadataApplication object itself.
*/
public MetadataApplication setRelated(MetadataApplicationRelated related) {
this.related = related;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (getId() == null) {
throw new IllegalArgumentException("Missing required property id in model MetadataApplication");
}
if (getResourceId() == null) {
throw new IllegalArgumentException("Missing required property resourceId in model MetadataApplication");
}
if (getName() == null) {
throw new IllegalArgumentException("Missing required property name in model MetadataApplication");
}
if (getRegion() == null) {
throw new IllegalArgumentException("Missing required property region in model MetadataApplication");
}
if (getRelated() != null) {
getRelated().validate();
}
}
}
|
3e16252374238404619f7a5d61f5b7bf419fc7bd | 1,261 | java | Java | src/main/java/sirius/search/suggestion/AutoCompletion.java | scireum/sirius-search | f6dbb2a83481f82dab6e9d110667d7ee1c64d5b7 | [
"Unlicense",
"MIT"
] | 7 | 2015-04-23T23:23:58.000Z | 2017-11-01T16:09:11.000Z | src/main/java/sirius/search/suggestion/AutoCompletion.java | scireum/sirius-search | f6dbb2a83481f82dab6e9d110667d7ee1c64d5b7 | [
"Unlicense",
"MIT"
] | 11 | 2015-09-29T12:29:43.000Z | 2021-12-14T21:06:22.000Z | src/main/java/sirius/search/suggestion/AutoCompletion.java | scireum/sirius-search | f6dbb2a83481f82dab6e9d110667d7ee1c64d5b7 | [
"Unlicense",
"MIT"
] | 6 | 2015-08-14T01:30:46.000Z | 2017-02-19T11:35:20.000Z | 20.306452 | 64 | 0.628276 | 9,415 | /*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - ychag@example.com
*/
package sirius.search.suggestion;
import java.util.List;
import java.util.Map;
/**
* Implements the API for the elasticsearch completion-suggester
*/
public class AutoCompletion {
/**
* All terms for which should be searched/autocompleted
*/
public static final String INPUT = "input";
private List<String> input;
/**
* Used to filter, e.g. a catalog-id
*/
public static final String CONTEXT = "context";
private Map<String, List<String>> contexts;
/**
* Used for ranking
*/
public static final String WEIGHT = "weight";
private String weight;
public List<String> getInput() {
return input;
}
public void setInput(List<String> input) {
this.input = input;
}
public Map<String, List<String>> getContext() {
return contexts;
}
public void setContext(Map<String, List<String>> contexts) {
this.contexts = contexts;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
|
3e16252e4c70a6d090e401f0d95084ed32988ea4 | 530 | java | Java | Java-DB-Spring-Data-Retake-Exam- 03-Apr-2020/src/main/java/softuni/exam/util/ValidationUtilImpl.java | AnnaIvanova73/SpringData | 942cc1f5a5d2297ca758821863e5b777d60e2b96 | [
"MIT"
] | null | null | null | Java-DB-Spring-Data-Retake-Exam- 03-Apr-2020/src/main/java/softuni/exam/util/ValidationUtilImpl.java | AnnaIvanova73/SpringData | 942cc1f5a5d2297ca758821863e5b777d60e2b96 | [
"MIT"
] | 7 | 2021-06-19T16:10:58.000Z | 2021-06-19T16:12:29.000Z | Java-DB-Spring-Data-Retake-Exam- 03-Apr-2020/src/main/java/softuni/exam/util/ValidationUtilImpl.java | AnnaIvanova73/SpringData | 942cc1f5a5d2297ca758821863e5b777d60e2b96 | [
"MIT"
] | 1 | 2022-03-01T10:58:39.000Z | 2022-03-01T10:58:39.000Z | 20.384615 | 62 | 0.737736 | 9,416 | package softuni.exam.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.Validator;
@Component
public class ValidationUtilImpl implements ValidationUtil {
private final Validator validator;
@Autowired
public ValidationUtilImpl(Validator validator) {
this.validator = validator;
}
@Override
public <E> boolean isValid(E entity) {
return this.validator.validate(entity).isEmpty();
}
}
|
3e16257cc672290d2efe6e0a2cfee9213b78b32e | 19,495 | java | Java | java/src/com/google/publicalerts/cap/Polygon.java | TheCycoONE/cap-library | 68568cafad7bc9ebbd07e4dc00448dfdcb1d3e5f | [
"Apache-2.0"
] | 72 | 2015-01-12T08:09:49.000Z | 2022-02-24T04:39:24.000Z | java/src/com/google/publicalerts/cap/Polygon.java | TheCycoONE/cap-library | 68568cafad7bc9ebbd07e4dc00448dfdcb1d3e5f | [
"Apache-2.0"
] | 8 | 2015-03-19T23:12:58.000Z | 2020-03-29T20:10:51.000Z | java/src/com/google/publicalerts/cap/Polygon.java | TheCycoONE/cap-library | 68568cafad7bc9ebbd07e4dc00448dfdcb1d3e5f | [
"Apache-2.0"
] | 28 | 2015-02-12T06:26:24.000Z | 2021-10-16T22:36:55.000Z | 33.324786 | 144 | 0.648884 | 9,417 | // Generated by the protocol buffer compiler. DO NOT EDIT!
package com.google.publicalerts.cap;
public final class Polygon extends
com.google.protobuf.GeneratedMessage
implements PolygonOrBuilder {
// Use Polygon.newBuilder() to construct.
private Polygon(Builder builder) {
super(builder);
}
private Polygon(boolean noInit) {}
private static final Polygon defaultInstance;
public static Polygon getDefaultInstance() {
return defaultInstance;
}
public Polygon getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.publicalerts.cap.Cap.internal_static_publicalerts_cap_Polygon_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.publicalerts.cap.Cap.internal_static_publicalerts_cap_Polygon_fieldAccessorTable;
}
// repeated .publicalerts.cap.Point point = 1;
public static final int POINT_FIELD_NUMBER = 1;
private java.util.List<com.google.publicalerts.cap.Point> point_;
public java.util.List<com.google.publicalerts.cap.Point> getPointList() {
return point_;
}
public java.util.List<? extends com.google.publicalerts.cap.PointOrBuilder>
getPointOrBuilderList() {
return point_;
}
public int getPointCount() {
return point_.size();
}
public com.google.publicalerts.cap.Point getPoint(int index) {
return point_.get(index);
}
public com.google.publicalerts.cap.PointOrBuilder getPointOrBuilder(
int index) {
return point_.get(index);
}
private void initFields() {
point_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
for (int i = 0; i < getPointCount(); i++) {
if (!getPoint(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
for (int i = 0; i < point_.size(); i++) {
output.writeMessage(1, point_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < point_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, point_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.publicalerts.cap.Polygon)) {
return super.equals(obj);
}
com.google.publicalerts.cap.Polygon other = (com.google.publicalerts.cap.Polygon) obj;
boolean result = true;
result = result && getPointList()
.equals(other.getPointList());
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
}
@java.lang.Override
public int hashCode() {
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
if (getPointCount() > 0) {
hash = (37 * hash) + POINT_FIELD_NUMBER;
hash = (53 * hash) + getPointList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
return hash;
}
public static com.google.publicalerts.cap.Polygon parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.google.publicalerts.cap.Polygon parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.google.publicalerts.cap.Polygon parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.google.publicalerts.cap.Polygon parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.google.publicalerts.cap.Polygon prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.google.publicalerts.cap.PolygonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.publicalerts.cap.Cap.internal_static_publicalerts_cap_Polygon_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.publicalerts.cap.Cap.internal_static_publicalerts_cap_Polygon_fieldAccessorTable;
}
// Construct using com.google.publicalerts.cap.Polygon.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getPointFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (pointBuilder_ == null) {
point_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
pointBuilder_.clear();
}
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.publicalerts.cap.Polygon.getDescriptor();
}
public com.google.publicalerts.cap.Polygon getDefaultInstanceForType() {
return com.google.publicalerts.cap.Polygon.getDefaultInstance();
}
public com.google.publicalerts.cap.Polygon build() {
com.google.publicalerts.cap.Polygon result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.google.publicalerts.cap.Polygon buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.google.publicalerts.cap.Polygon result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.google.publicalerts.cap.Polygon buildPartial() {
com.google.publicalerts.cap.Polygon result = new com.google.publicalerts.cap.Polygon(this);
int from_bitField0_ = bitField0_;
if (pointBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
point_ = java.util.Collections.unmodifiableList(point_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.point_ = point_;
} else {
result.point_ = pointBuilder_.build();
}
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.publicalerts.cap.Polygon) {
return mergeFrom((com.google.publicalerts.cap.Polygon)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.publicalerts.cap.Polygon other) {
if (other == com.google.publicalerts.cap.Polygon.getDefaultInstance()) return this;
if (pointBuilder_ == null) {
if (!other.point_.isEmpty()) {
if (point_.isEmpty()) {
point_ = other.point_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePointIsMutable();
point_.addAll(other.point_);
}
onChanged();
}
} else {
if (!other.point_.isEmpty()) {
if (pointBuilder_.isEmpty()) {
pointBuilder_.dispose();
pointBuilder_ = null;
point_ = other.point_;
bitField0_ = (bitField0_ & ~0x00000001);
pointBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getPointFieldBuilder() : null;
} else {
pointBuilder_.addAllMessages(other.point_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
for (int i = 0; i < getPointCount(); i++) {
if (!getPoint(i).isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 10: {
com.google.publicalerts.cap.Point.Builder subBuilder = com.google.publicalerts.cap.Point.newBuilder();
input.readMessage(subBuilder, extensionRegistry);
addPoint(subBuilder.buildPartial());
break;
}
}
}
}
private int bitField0_;
// repeated .publicalerts.cap.Point point = 1;
private java.util.List<com.google.publicalerts.cap.Point> point_ =
java.util.Collections.emptyList();
private void ensurePointIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
point_ = new java.util.ArrayList<com.google.publicalerts.cap.Point>(point_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilder<
com.google.publicalerts.cap.Point, com.google.publicalerts.cap.Point.Builder, com.google.publicalerts.cap.PointOrBuilder> pointBuilder_;
public java.util.List<com.google.publicalerts.cap.Point> getPointList() {
if (pointBuilder_ == null) {
return java.util.Collections.unmodifiableList(point_);
} else {
return pointBuilder_.getMessageList();
}
}
public int getPointCount() {
if (pointBuilder_ == null) {
return point_.size();
} else {
return pointBuilder_.getCount();
}
}
public com.google.publicalerts.cap.Point getPoint(int index) {
if (pointBuilder_ == null) {
return point_.get(index);
} else {
return pointBuilder_.getMessage(index);
}
}
public Builder setPoint(
int index, com.google.publicalerts.cap.Point value) {
if (pointBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointIsMutable();
point_.set(index, value);
onChanged();
} else {
pointBuilder_.setMessage(index, value);
}
return this;
}
public Builder setPoint(
int index, com.google.publicalerts.cap.Point.Builder builderForValue) {
if (pointBuilder_ == null) {
ensurePointIsMutable();
point_.set(index, builderForValue.build());
onChanged();
} else {
pointBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
public Builder addPoint(com.google.publicalerts.cap.Point value) {
if (pointBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointIsMutable();
point_.add(value);
onChanged();
} else {
pointBuilder_.addMessage(value);
}
return this;
}
public Builder addPoint(
int index, com.google.publicalerts.cap.Point value) {
if (pointBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointIsMutable();
point_.add(index, value);
onChanged();
} else {
pointBuilder_.addMessage(index, value);
}
return this;
}
public Builder addPoint(
com.google.publicalerts.cap.Point.Builder builderForValue) {
if (pointBuilder_ == null) {
ensurePointIsMutable();
point_.add(builderForValue.build());
onChanged();
} else {
pointBuilder_.addMessage(builderForValue.build());
}
return this;
}
public Builder addPoint(
int index, com.google.publicalerts.cap.Point.Builder builderForValue) {
if (pointBuilder_ == null) {
ensurePointIsMutable();
point_.add(index, builderForValue.build());
onChanged();
} else {
pointBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
public Builder addAllPoint(
java.lang.Iterable<? extends com.google.publicalerts.cap.Point> values) {
if (pointBuilder_ == null) {
ensurePointIsMutable();
super.addAll(values, point_);
onChanged();
} else {
pointBuilder_.addAllMessages(values);
}
return this;
}
public Builder clearPoint() {
if (pointBuilder_ == null) {
point_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
pointBuilder_.clear();
}
return this;
}
public Builder removePoint(int index) {
if (pointBuilder_ == null) {
ensurePointIsMutable();
point_.remove(index);
onChanged();
} else {
pointBuilder_.remove(index);
}
return this;
}
public com.google.publicalerts.cap.Point.Builder getPointBuilder(
int index) {
return getPointFieldBuilder().getBuilder(index);
}
public com.google.publicalerts.cap.PointOrBuilder getPointOrBuilder(
int index) {
if (pointBuilder_ == null) {
return point_.get(index); } else {
return pointBuilder_.getMessageOrBuilder(index);
}
}
public java.util.List<? extends com.google.publicalerts.cap.PointOrBuilder>
getPointOrBuilderList() {
if (pointBuilder_ != null) {
return pointBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(point_);
}
}
public com.google.publicalerts.cap.Point.Builder addPointBuilder() {
return getPointFieldBuilder().addBuilder(
com.google.publicalerts.cap.Point.getDefaultInstance());
}
public com.google.publicalerts.cap.Point.Builder addPointBuilder(
int index) {
return getPointFieldBuilder().addBuilder(
index, com.google.publicalerts.cap.Point.getDefaultInstance());
}
public java.util.List<com.google.publicalerts.cap.Point.Builder>
getPointBuilderList() {
return getPointFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
com.google.publicalerts.cap.Point, com.google.publicalerts.cap.Point.Builder, com.google.publicalerts.cap.PointOrBuilder>
getPointFieldBuilder() {
if (pointBuilder_ == null) {
pointBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
com.google.publicalerts.cap.Point, com.google.publicalerts.cap.Point.Builder, com.google.publicalerts.cap.PointOrBuilder>(
point_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
point_ = null;
}
return pointBuilder_;
}
// @@protoc_insertion_point(builder_scope:publicalerts.cap.Polygon)
}
static {
defaultInstance = new Polygon(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:publicalerts.cap.Polygon)
}
|
3e1626577866ad384192969789a3604090906050 | 19,198 | java | Java | src/main/java/com/zking/entity/NavLinksExample.java | LjyLab/MoeNav | 2a3452c06180bb1659c3cf07cf5941ad4b6e3821 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zking/entity/NavLinksExample.java | LjyLab/MoeNav | 2a3452c06180bb1659c3cf07cf5941ad4b6e3821 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/zking/entity/NavLinksExample.java | LjyLab/MoeNav | 2a3452c06180bb1659c3cf07cf5941ad4b6e3821 | [
"Apache-2.0"
] | null | null | null | 31.472131 | 102 | 0.582561 | 9,418 | package com.zking.entity;
import java.util.ArrayList;
import java.util.List;
public class NavLinksExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public NavLinksExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andLinkIdIsNull() {
addCriterion("link_id is null");
return (Criteria) this;
}
public Criteria andLinkIdIsNotNull() {
addCriterion("link_id is not null");
return (Criteria) this;
}
public Criteria andLinkIdEqualTo(Integer value) {
addCriterion("link_id =", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdNotEqualTo(Integer value) {
addCriterion("link_id <>", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdGreaterThan(Integer value) {
addCriterion("link_id >", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdGreaterThanOrEqualTo(Integer value) {
addCriterion("link_id >=", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdLessThan(Integer value) {
addCriterion("link_id <", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdLessThanOrEqualTo(Integer value) {
addCriterion("link_id <=", value, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdIn(List<Integer> values) {
addCriterion("link_id in", values, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdNotIn(List<Integer> values) {
addCriterion("link_id not in", values, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdBetween(Integer value1, Integer value2) {
addCriterion("link_id between", value1, value2, "linkId");
return (Criteria) this;
}
public Criteria andLinkIdNotBetween(Integer value1, Integer value2) {
addCriterion("link_id not between", value1, value2, "linkId");
return (Criteria) this;
}
public Criteria andLinkNameIsNull() {
addCriterion("link_name is null");
return (Criteria) this;
}
public Criteria andLinkNameIsNotNull() {
addCriterion("link_name is not null");
return (Criteria) this;
}
public Criteria andLinkNameEqualTo(String value) {
addCriterion("link_name =", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameNotEqualTo(String value) {
addCriterion("link_name <>", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameGreaterThan(String value) {
addCriterion("link_name >", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameGreaterThanOrEqualTo(String value) {
addCriterion("link_name >=", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameLessThan(String value) {
addCriterion("link_name <", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameLessThanOrEqualTo(String value) {
addCriterion("link_name <=", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameLike(String value) {
addCriterion("link_name like", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameNotLike(String value) {
addCriterion("link_name not like", value, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameIn(List<String> values) {
addCriterion("link_name in", values, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameNotIn(List<String> values) {
addCriterion("link_name not in", values, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameBetween(String value1, String value2) {
addCriterion("link_name between", value1, value2, "linkName");
return (Criteria) this;
}
public Criteria andLinkNameNotBetween(String value1, String value2) {
addCriterion("link_name not between", value1, value2, "linkName");
return (Criteria) this;
}
public Criteria andLinkUrlIsNull() {
addCriterion("link_url is null");
return (Criteria) this;
}
public Criteria andLinkUrlIsNotNull() {
addCriterion("link_url is not null");
return (Criteria) this;
}
public Criteria andLinkUrlEqualTo(String value) {
addCriterion("link_url =", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlNotEqualTo(String value) {
addCriterion("link_url <>", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlGreaterThan(String value) {
addCriterion("link_url >", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlGreaterThanOrEqualTo(String value) {
addCriterion("link_url >=", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlLessThan(String value) {
addCriterion("link_url <", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlLessThanOrEqualTo(String value) {
addCriterion("link_url <=", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlLike(String value) {
addCriterion("link_url like", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlNotLike(String value) {
addCriterion("link_url not like", value, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlIn(List<String> values) {
addCriterion("link_url in", values, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlNotIn(List<String> values) {
addCriterion("link_url not in", values, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlBetween(String value1, String value2) {
addCriterion("link_url between", value1, value2, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkUrlNotBetween(String value1, String value2) {
addCriterion("link_url not between", value1, value2, "linkUrl");
return (Criteria) this;
}
public Criteria andLinkSortIsNull() {
addCriterion("link_sort is null");
return (Criteria) this;
}
public Criteria andLinkSortIsNotNull() {
addCriterion("link_sort is not null");
return (Criteria) this;
}
public Criteria andLinkSortEqualTo(String value) {
addCriterion("link_sort =", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortNotEqualTo(String value) {
addCriterion("link_sort <>", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortGreaterThan(String value) {
addCriterion("link_sort >", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortGreaterThanOrEqualTo(String value) {
addCriterion("link_sort >=", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortLessThan(String value) {
addCriterion("link_sort <", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortLessThanOrEqualTo(String value) {
addCriterion("link_sort <=", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortLike(String value) {
addCriterion("link_sort like", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortNotLike(String value) {
addCriterion("link_sort not like", value, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortIn(List<String> values) {
addCriterion("link_sort in", values, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortNotIn(List<String> values) {
addCriterion("link_sort not in", values, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortBetween(String value1, String value2) {
addCriterion("link_sort between", value1, value2, "linkSort");
return (Criteria) this;
}
public Criteria andLinkSortNotBetween(String value1, String value2) {
addCriterion("link_sort not between", value1, value2, "linkSort");
return (Criteria) this;
}
public Criteria andLinkStyleIsNull() {
addCriterion("link_style is null");
return (Criteria) this;
}
public Criteria andLinkStyleIsNotNull() {
addCriterion("link_style is not null");
return (Criteria) this;
}
public Criteria andLinkStyleEqualTo(String value) {
addCriterion("link_style =", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleNotEqualTo(String value) {
addCriterion("link_style <>", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleGreaterThan(String value) {
addCriterion("link_style >", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleGreaterThanOrEqualTo(String value) {
addCriterion("link_style >=", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleLessThan(String value) {
addCriterion("link_style <", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleLessThanOrEqualTo(String value) {
addCriterion("link_style <=", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleLike(String value) {
addCriterion("link_style like", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleNotLike(String value) {
addCriterion("link_style not like", value, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleIn(List<String> values) {
addCriterion("link_style in", values, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleNotIn(List<String> values) {
addCriterion("link_style not in", values, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleBetween(String value1, String value2) {
addCriterion("link_style between", value1, value2, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkStyleNotBetween(String value1, String value2) {
addCriterion("link_style not between", value1, value2, "linkStyle");
return (Criteria) this;
}
public Criteria andLinkTargetIsNull() {
addCriterion("link_target is null");
return (Criteria) this;
}
public Criteria andLinkTargetIsNotNull() {
addCriterion("link_target is not null");
return (Criteria) this;
}
public Criteria andLinkTargetEqualTo(String value) {
addCriterion("link_target =", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetNotEqualTo(String value) {
addCriterion("link_target <>", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetGreaterThan(String value) {
addCriterion("link_target >", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetGreaterThanOrEqualTo(String value) {
addCriterion("link_target >=", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetLessThan(String value) {
addCriterion("link_target <", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetLessThanOrEqualTo(String value) {
addCriterion("link_target <=", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetLike(String value) {
addCriterion("link_target like", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetNotLike(String value) {
addCriterion("link_target not like", value, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetIn(List<String> values) {
addCriterion("link_target in", values, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetNotIn(List<String> values) {
addCriterion("link_target not in", values, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetBetween(String value1, String value2) {
addCriterion("link_target between", value1, value2, "linkTarget");
return (Criteria) this;
}
public Criteria andLinkTargetNotBetween(String value1, String value2) {
addCriterion("link_target not between", value1, value2, "linkTarget");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
3e16271a0b6114a20e54420f9e3db09640efe6d8 | 1,469 | java | Java | Java/Advanced/NationalFlower.java | jerubball/HackerRank | c484532d6e4cd57227d17f049df5dd754611f281 | [
"Unlicense"
] | null | null | null | Java/Advanced/NationalFlower.java | jerubball/HackerRank | c484532d6e4cd57227d17f049df5dd754611f281 | [
"Unlicense"
] | null | null | null | Java/Advanced/NationalFlower.java | jerubball/HackerRank | c484532d6e4cd57227d17f049df5dd754611f281 | [
"Unlicense"
] | null | null | null | 24.081967 | 85 | 0.615385 | 9,419 | package Java.Advanced;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* HackerRank Java Advanced 9
* https://www.hackerrank.com/challenges/java-covariance/problem
* @author Hasol
*/
public class NationalFlower {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine().trim();
Region region = null;
switch (s) {
case "WestBengal":
region = new WestBengal();
break;
case "AndhraPradesh":
region = new AndhraPradesh();
break;
}
Flower flower = region.yourNationalFlower();
System.out.println(flower.whatsYourName());
}
}
class Flower {
String whatsYourName() {
return "I have many names and types.";
}
}
class Jasmine extends Flower {
@Override
String whatsYourName() {
return "Jasmine";
}
}
class Lily extends Flower {
@Override
String whatsYourName() {
return "Lily";
}
}
class Region {
Flower yourNationalFlower() {
return new Flower();
}
}
class WestBengal extends Region {
@Override
Jasmine yourNationalFlower() {
return new Jasmine();
}
}
class AndhraPradesh extends Region {
@Override
Lily yourNationalFlower() {
return new Lily();
}
}
|
3e162744a0d715ac0979d7b8d31dcf87e5b773a6 | 2,819 | java | Java | register-spi/src/main/java/com/uniquid/register/user/UserRegister.java | serenaB87/uniquidPoc | 4eb78998bda1a96ab9ecf06161706b939e98b3e4 | [
"MIT"
] | null | null | null | register-spi/src/main/java/com/uniquid/register/user/UserRegister.java | serenaB87/uniquidPoc | 4eb78998bda1a96ab9ecf06161706b939e98b3e4 | [
"MIT"
] | null | null | null | register-spi/src/main/java/com/uniquid/register/user/UserRegister.java | serenaB87/uniquidPoc | 4eb78998bda1a96ab9ecf06161706b939e98b3e4 | [
"MIT"
] | null | null | null | 41.455882 | 101 | 0.759489 | 9,420 | package com.uniquid.register.user;
import java.util.List;
import com.uniquid.register.exception.RegisterException;
/**
* Data Access Object pattern for User Channel.
*
* Is used to separate low level data accessing API from high level business services.
*/
public interface UserRegister {
/**
* Returns a List containing all the {@code UserChannel} present in the data store.
* In case no {@code UserChannel} is present an empty list is returned.
* @return a List containing all the {@code UserChannel} present in the data store or an empty List.
* @throws RegisterException in case a problem occurs.
*/
public List<UserChannel> getAllUserChannels() throws RegisterException;
/**
* Return an {@code UserChannel} from its provider name or null if no channel is found.
* @param providerName the name of the provider
* @return an {@code UserChannel} from its provider name or null if no channel is found.
* @throws RegisterException in case a problem occurs.
*/
public UserChannel getChannelByName(String providerName) throws RegisterException;
/**
* Return an {@code UserChannel} from its provider address or null if no channel is found.
* @param providerAddress the address of the provider
* @return an {@code UserChannel} from its provider address or null if no channel is found.
* @throws RegisterException in case a problem occurs.
*/
public UserChannel getChannelByProviderAddress(String providerAddress) throws RegisterException;
/**
* Return an {@code UserChannel} from its revoke transaction id or null if no channel is found.
* @param revokeTxId the revoke transaction id
* @return an {@code UserChannel} from its revoke transaction id or null if no channel is found.
* @throws RegisterException in case a problem occurs.
*/
public UserChannel getUserChannelByRevokeTxId(String revokeTxId) throws RegisterException;
/**
* Return an {@code UserChannel} from its revoker address id or null if no channel is found.
* @param revokerAddress the revoker address
* @return an {@code UserChannel} from its revoker address id or null if no channel is found.
* @throws RegisterException in case a problem occurs.
*/
public UserChannel getUserChannelByRevokeAddress(String revokerAddress) throws RegisterException;
/**
* Creates an {@code UserChannel} by persisting its content in the data store.
* @param userChannel the User Channel to persist.
* @throws RegisterException in case a problem occurs.
*/
public void insertChannel(UserChannel userChannel) throws RegisterException;
/**
* Deletes an {@code UserChannel} from the data store.
* @param userChannel the User Channel to delete.
* @throws RegisterException in case a problem occurs.
*/
public void deleteChannel(UserChannel userChannel) throws RegisterException;
} |
3e16278fbdd37540053a2d7cb15f42c3a783cbde | 1,278 | java | Java | spring-cloud-gray-dynamic-logic/src/main/java/cn/springcloud/gray/dynamiclogic/SimpleDynamicLogicManager.java | SoftwareKing/spring-cloud-gray | c60872071d431a702303aa4d759ca0dd35c32029 | [
"Apache-2.0"
] | 861 | 2018-01-11T04:54:04.000Z | 2022-03-30T02:22:52.000Z | spring-cloud-gray-dynamic-logic/src/main/java/cn/springcloud/gray/dynamiclogic/SimpleDynamicLogicManager.java | SoftwareKing/spring-cloud-gray | c60872071d431a702303aa4d759ca0dd35c32029 | [
"Apache-2.0"
] | 25 | 2018-04-26T03:27:12.000Z | 2022-01-21T06:49:42.000Z | spring-cloud-gray-dynamic-logic/src/main/java/cn/springcloud/gray/dynamiclogic/SimpleDynamicLogicManager.java | SoftwareKing/spring-cloud-gray | c60872071d431a702303aa4d759ca0dd35c32029 | [
"Apache-2.0"
] | 307 | 2018-01-11T04:54:04.000Z | 2022-03-03T08:15:46.000Z | 27.191489 | 97 | 0.717527 | 9,421 | package cn.springcloud.gray.dynamiclogic;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author saleson
* @date 2019-12-28 10:23
*/
public class SimpleDynamicLogicManager implements DynamicLogicManager {
protected Map<String, Object> beans = new ConcurrentHashMap<>();
protected DynamicLogicDriver dynamicLogicDriver;
public SimpleDynamicLogicManager(DynamicLogicDriver dynamicLogicDriver) {
this.dynamicLogicDriver = dynamicLogicDriver;
}
@Override
public DynamicLogicDriver getDynamicLogicDriver() {
return dynamicLogicDriver;
}
@Override
public <T> T compleAndRegister(DynamicLogicDefinition dynamicLogicDefinition) {
return compleAndRegister(dynamicLogicDefinition.getName(), dynamicLogicDefinition);
}
@Override
public <T> T compleAndRegister(String alias, DynamicLogicDefinition dynamicLogicDefinition) {
T bean = getDynamicLogicDriver().compleAndInstance(dynamicLogicDefinition);
beans.put(alias, bean);
return bean;
}
@Override
public <T> T getDnamicInstance(String alias) {
return (T) beans.get(alias);
}
@Override
public <T> T remove(String alias) {
return (T) beans.remove(alias);
}
}
|
3e1627b5a679f2bd2ac3f852e5d9d442fe54ffd0 | 2,804 | java | Java | src/main/java/com/direwolf20/buildinggadgets/common/tainted/template/ITemplateProvider.java | ProjectET/BuildingGadgets-Fabric | d1cd911e60c2536828abdae53691040408f64da8 | [
"MIT"
] | 4 | 2021-10-15T11:57:30.000Z | 2021-12-04T09:30:42.000Z | src/main/java/com/direwolf20/buildinggadgets/common/tainted/template/ITemplateProvider.java | ProjectET/BuildingGadgets-Fabric | d1cd911e60c2536828abdae53691040408f64da8 | [
"MIT"
] | 13 | 2021-10-16T02:24:21.000Z | 2021-11-30T22:58:32.000Z | src/main/java/com/direwolf20/buildinggadgets/common/tainted/template/ITemplateProvider.java | ProjectET/BuildingGadgets-Fabric | d1cd911e60c2536828abdae53691040408f64da8 | [
"MIT"
] | 3 | 2021-10-07T10:22:43.000Z | 2021-11-20T15:38:41.000Z | 35.05 | 140 | 0.699001 | 9,422 | package com.direwolf20.buildinggadgets.common.tainted.template;
import com.direwolf20.buildinggadgets.common.network.Target;
import dev.onyxstudios.cca.api.v3.component.Component;
import net.minecraft.world.level.Level;
import java.util.UUID;
public interface ITemplateProvider extends Component {
UUID getId(ITemplateKey key);
Template getTemplateForKey(ITemplateKey key);
/**
* Overrides the TemplateItem for the given key.
* <p>
* Please prefer using TemplateTransactions and only use this if you absolutely have to (f.e. this is used for syncing).
* This is, because if you use this Method and someone else is running a Transaction on the previous value associated with key
* the result will silently not show up!
*
* @param key The key for which the TemplateItem should be set
* @param template The TemplateItem to set
*/
void setTemplate(ITemplateKey key, Template template);
/**
* Requests an update <b>from</b> the other side - aka requests the other side to send an update. Has <b>no effect on Servers</b> as,
* the Client from which to request the update from would be undefined.
*
* @param key The {@link ITemplateKey} for which to request an update
* @return whether or not an update was requested
*/
boolean requestUpdate(ITemplateKey key);
/**
* Requests an update from the specified target.
*
* @param target The target to which to request the update
* @see #requestUpdate(ITemplateKey)
*/
boolean requestUpdate(ITemplateKey key, Target target);
/**
* Requests an update <b>for<b/> the other side - aka sends an update packet to it. On the client this will send the data to the server,
* on the server this will send the data to <b>all logged in Clients</b>.
*
* @param key The key to request a remote update for
* @param level
* @return whether or not a remote update was requested.
*/
boolean requestRemoteUpdate(ITemplateKey key, Level level);
/**
* Requests a remote update for the specified target.
*
* @param target The target for which to request an update
* @see #requestRemoteUpdate(ITemplateKey, Level)
*/
boolean requestRemoteUpdate(ITemplateKey key, Target target);
/**
* Registers an Update Listener - it will only be weakly referenced!
*/
void registerUpdateListener(IUpdateListener listener);
void removeUpdateListener(IUpdateListener listener);
interface IUpdateListener {
default void onTemplateUpdate(ITemplateProvider provider, ITemplateKey key, Template template) {
}
default void onTemplateUpdateSend(ITemplateProvider provider, ITemplateKey key, Template template) {
}
}
}
|
3e162823a17c37a309968d2fe143bb8a92dfd5ed | 8,972 | java | Java | src/main/java/de/dumischbaenger/jetty/JettyFileLogin.java | dumischbaenger/JettyJaasLoginModules | f70d4d9c1979807b82ca91788761704cb3b8faf4 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/dumischbaenger/jetty/JettyFileLogin.java | dumischbaenger/JettyJaasLoginModules | f70d4d9c1979807b82ca91788761704cb3b8faf4 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/dumischbaenger/jetty/JettyFileLogin.java | dumischbaenger/JettyJaasLoginModules | f70d4d9c1979807b82ca91788761704cb3b8faf4 | [
"Apache-2.0"
] | null | null | null | 33.729323 | 163 | 0.674097 | 9,423 | package de.dumischbaenger.jetty;
import java.io.IOException;
// this work is based on https://github.com/eclipse/jetty.project/blob/jetty-9.4.x/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.java
//
//========================================================================
//Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//All rights reserved. This program and the accompanying materials
//are made available under the terms of the Eclipse Public License v1.0
//and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
//You may elect to redistribute this code under either of these licenses.
//========================================================================
//
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.jaas.callback.ObjectCallback;
import org.eclipse.jetty.jaas.callback.ServletRequestCallback;
import org.eclipse.jetty.jaas.spi.AbstractLoginModule;
import org.eclipse.jetty.jaas.spi.UserInfo;
import org.eclipse.jetty.security.PropertyUserStore;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Credential;
/**
* PropertyFileLoginModule
*/
public class JettyFileLogin extends AbstractLoginModule
{
public static final String DEFAULT_FILENAME = "realm.properties";
private static final Logger LOG = Log.getLogger(JettyFileLogin.class);
private static ConcurrentHashMap<String, PropertyUserStore> _propertyUserStores = new ConcurrentHashMap<String, PropertyUserStore>();
private int _refreshInterval = 0;
private String _filename = DEFAULT_FILENAME;
/**
* Read contents of the configured property file.
*
* @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map,
* java.util.Map)
*
* @param subject the subject
* @param callbackHandler the callback handler
* @param sharedState the shared state map
* @param options the options map
*/
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options)
{
super.initialize(subject,callbackHandler,sharedState,options);
setupPropertyUserStore(options);
}
private void setupPropertyUserStore(Map<String, ?> options)
{
parseConfig(options);
if (_propertyUserStores.get(_filename) == null)
{
PropertyUserStore propertyUserStore = new PropertyUserStore();
propertyUserStore.setConfig(_filename);
PropertyUserStore prev = _propertyUserStores.putIfAbsent(_filename, propertyUserStore);
if (prev == null)
{
LOG.debug("setupPropertyUserStore: Starting new PropertyUserStore. PropertiesFile: " + _filename + " refreshInterval: " + _refreshInterval);
try
{
propertyUserStore.start();
}
catch (Exception e)
{
LOG.warn("Exception while starting propertyUserStore: ",e);
}
}
}
}
private void parseConfig(Map<String, ?> options)
{
String tmp = (String)options.get("file");
_filename = (tmp == null? DEFAULT_FILENAME : tmp);
tmp = (String)options.get("refreshInterval");
_refreshInterval = (tmp == null?_refreshInterval:Integer.parseInt(tmp));
}
/**
*
*
* @param userName the user name
* @throws Exception if unable to get the user information
*/
@Override
public UserInfo getUserInfo(String userName) throws Exception
{
PropertyUserStore propertyUserStore = _propertyUserStores.get(_filename);
if (propertyUserStore == null)
throw new IllegalStateException("PropertyUserStore should never be null here!");
LOG.debug("Checking PropertyUserStore "+_filename+" for "+userName);
UserIdentity userIdentity = propertyUserStore.getUserIdentity(userName);
if (userIdentity==null)
return null;
//TODO in future versions change the impl of PropertyUserStore so its not
//storing Subjects etc, just UserInfo
Set<Principal> principals = userIdentity.getSubject().getPrincipals();
List<String> roles = new ArrayList<String>();
for ( Principal principal : principals )
{
roles.add( principal.getName() );
}
Credential credential = (Credential)userIdentity.getSubject().getPrivateCredentials().iterator().next();
LOG.debug("Found: " + userName + " in PropertyUserStore "+_filename);
return new UserInfo(userName, credential, roles);
}
@Override
public Callback[] configureCallbacks() {
Callback[] callbacks = new Callback[4];
callbacks[0] = new NameCallback("Enter user name");
callbacks[1] = new ObjectCallback();
callbacks[2] = new PasswordCallback("Enter password", false); //only used if framework does not support the ObjectCallback
callbacks[3] = new ServletRequestCallback();
return callbacks;
}
/**
* @see javax.security.auth.spi.LoginModule#login()
* @return true if is authenticated, false otherwise
* @throws LoginException if unable to login
*/
@Override
public boolean login() throws LoginException
{
try
{
if (isIgnored())
return false;
if (getCallbackHandler() == null)
throw new LoginException ("No callback handler");
Callback[] callbacks = configureCallbacks();
getCallbackHandler().handle(callbacks);
String webUserName = ((NameCallback) callbacks[0]).getName();
Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
ServletRequest servletRequest=((ServletRequestCallback)callbacks[3]).getRequest();
String pwShort = "unknown";
if (webCredential!=null && webCredential instanceof String) {
String pw = (String) webCredential;
if(pw.length()>1) {
pwShort = pw.charAt(0) + "..." + pw.charAt(pw.length() - 1);
}
}
LOG.info("using username: " + webUserName + ", password (shortened): " + pwShort);
if(servletRequest!=null && servletRequest instanceof HttpServletRequest) {
HttpSession httpSession=((HttpServletRequest)servletRequest).getSession(true);
if(httpSession!=null) {
httpSession.setAttribute("de.dumischbaenger.jetty.username", webUserName);
httpSession.setAttribute("de.dumischbaenger.jetty.password", webCredential);
LOG.info("session catched: " + httpSession.getId());
}
servletRequest.setAttribute("de.dumischbaenger.jetty.username", webUserName);
servletRequest.setAttribute("de.dumischbaenger.jetty.password", webCredential);
LOG.info("servlet request catched");
}
if (webCredential == null)
webCredential = ((PasswordCallback)callbacks[2]).getPassword(); //use standard PasswordCallback
if ((webUserName == null) || (webCredential == null))
{
setAuthenticated(false);
throw new FailedLoginException();
}
UserInfo userInfo = getUserInfo(webUserName);
if (userInfo == null)
{
setAuthenticated(false);
throw new FailedLoginException();
}
JAASUserInfo currentUser = new JAASUserInfo(userInfo);
setCurrentUser(currentUser);
setAuthenticated(currentUser.checkCredential(webCredential));
if (isAuthenticated())
{
currentUser.fetchRoles();
return true;
}
else
throw new FailedLoginException();
}
catch (IOException e)
{
throw new LoginException (e.toString());
}
catch (UnsupportedCallbackException e)
{
throw new LoginException (e.toString());
}
catch (Exception e)
{
if (e instanceof LoginException)
throw (LoginException)e;
throw new LoginException (e.toString());
}
}
}
|
3e1628404731e1905fd63bfad751869fdd934838 | 521 | java | Java | src/tankrotationexample/GameConstants.java | swu465/TankGame | d05c07a318cfa252cad520e6e89a21c89b00e6e4 | [
"MIT"
] | null | null | null | src/tankrotationexample/GameConstants.java | swu465/TankGame | d05c07a318cfa252cad520e6e89a21c89b00e6e4 | [
"MIT"
] | null | null | null | src/tankrotationexample/GameConstants.java | swu465/TankGame | d05c07a318cfa252cad520e6e89a21c89b00e6e4 | [
"MIT"
] | null | null | null | 34.733333 | 63 | 0.760077 | 9,424 | package tankrotationexample;
public class GameConstants {
public static final int GAME_SCREEN_WIDTH = 1290; //43 col
public static final int GAME_SCREEN_HEIGHT = 960; //32 rows
public static final int WORLD_HEIGHT = 2010;
public static final int WORLD_WIDTH = 2010;
public static final int START_MENU_SCREEN_WIDTH = 500;
public static final int START_MENU_SCREEN_HEIGHT = 550;
public static final int END_MENU_SCREEN_WIDTH = 500;
public static final int END_MENU_SCREEN_HEIGHT = 500;
}
|
3e16284f8be020db6cd4eda8b4049ea7bb69cf9e | 793 | java | Java | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadAllDocsAction.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadAllDocsAction.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/DownloadAllDocsAction.java | dunno99/intellij-community | aa656a5d874b947271b896b2105e4370827b9149 | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 36.045455 | 76 | 0.754098 | 9,425 | /*
* Copyright 2000-2010 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 org.jetbrains.idea.maven.project.actions;
public class DownloadAllDocsAction extends DownloadAllSourcesAndDocsAction {
public DownloadAllDocsAction() {
super(false, true);
}
} |
3e1628c4e0a73536f8de88ffd846c1b7c3b70e67 | 332 | java | Java | src/main/java/de/SweetCode/SteamAPI/interfaces/ISteamCommunity.java | waterfl0w/SteamAPI | dae0326de8c87a329a8ac666f19dc5c8798259b8 | [
"MIT"
] | 5 | 2019-09-08T15:18:14.000Z | 2020-11-01T11:25:28.000Z | src/main/java/de/SweetCode/SteamAPI/interfaces/ISteamCommunity.java | waterfl0w/SteamAPI | dae0326de8c87a329a8ac666f19dc5c8798259b8 | [
"MIT"
] | 1 | 2017-12-25T03:44:04.000Z | 2017-12-27T01:28:40.000Z | src/main/java/de/SweetCode/SteamAPI/interfaces/ISteamCommunity.java | waterfl0w/SteamAPI | dae0326de8c87a329a8ac666f19dc5c8798259b8 | [
"MIT"
] | 2 | 2017-02-28T11:44:36.000Z | 2017-03-16T19:22:53.000Z | 22.133333 | 56 | 0.75 | 9,426 | package de.SweetCode.SteamAPI.interfaces;
import de.SweetCode.SteamAPI.SteamAPI;
import de.SweetCode.SteamAPI.method.methods.ReportAbuse;
public class ISteamCommunity extends SteamInterface {
public ISteamCommunity(SteamAPI steam) {
super(steam, "ISteamCommunity");
this.add(new ReportAbuse(this));
}
}
|
3e1629f5bcb7d60aff81573088fe409f9bd7a444 | 6,372 | java | Java | tools/gatt-config/android/BeaconConfig/app/src/main/java/com/github/google/beaconfig/dialogs/UnlockDialog.java | sammys/eddystone | f00c15cac7c605a9cd26d687b91ca6999a6f3968 | [
"Apache-2.0"
] | 3,352 | 2015-07-14T15:15:34.000Z | 2022-03-31T03:21:27.000Z | tools/gatt-config/android/BeaconConfig/app/src/main/java/com/github/google/beaconfig/dialogs/UnlockDialog.java | sammys/eddystone | f00c15cac7c605a9cd26d687b91ca6999a6f3968 | [
"Apache-2.0"
] | 233 | 2015-07-14T16:22:24.000Z | 2022-03-14T09:22:22.000Z | tools/gatt-config/android/BeaconConfig/app/src/main/java/com/github/google/beaconfig/dialogs/UnlockDialog.java | sammys/eddystone | f00c15cac7c605a9cd26d687b91ca6999a6f3968 | [
"Apache-2.0"
] | 954 | 2015-07-14T16:06:58.000Z | 2022-03-25T12:04:12.000Z | 42.48 | 99 | 0.516478 | 9,427 | // Copyright 2016 Google 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.github.google.beaconfig.dialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import com.github.google.beaconfig.R;
import com.github.google.beaconfig.utils.Utils;
/**
* This Dialog pops up when a password is required by the user to unlock the beacon manually.
*/
public class UnlockDialog {
public static void show(final Activity ctx, final UnlockListener unlockListener) {
ctx.runOnUiThread(new Runnable() {
@Override
public void run() {
final AlertDialog unlockDialog = new AlertDialog.Builder(ctx).show();
unlockDialog.setContentView(R.layout.dialog_unlock);
unlockDialog.setCanceledOnTouchOutside(false);
// This is needed because there are some flags being set which prevent the keyboard
// from popping up when an EditText is clicked
unlockDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
final EditText unlockCodeView
= (EditText) unlockDialog.findViewById(R.id.enter_lock_code);
final TextView newPasswordLengthTracker
= (TextView) unlockDialog.findViewById(R.id.lock_code_tracker);
unlockCodeView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence,
int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
newPasswordLengthTracker.setText("("
+ unlockCodeView.getText().length() + "/32)");
}
});
unlockCodeView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
if (unlockCodeView.getText().toString().length() < 32) {
unlockCodeView.setError("Lock code must be 32 hex characters.");
return true;
} else {
return false;
}
}
return false;
}
});
unlockCodeView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
String input = unlockCodeView.getText().toString();
if (input.length() < 32 && input.length() > 0) {
unlockCodeView.setError("Lock code too short!");
}
}
}
});
unlockDialog.findViewById(R.id.confirm_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
final String newPassword = unlockCodeView.getText().toString();
if (newPassword.length() < 32) {
unlockCodeView.setError(
"Please enter a 32 character lock code");
return;
}
unlockListener.unlock(Utils.toByteArray
(unlockCodeView.getText().toString()));
unlockDialog.dismiss();
}
});
unlockDialog.findViewById(R.id.exit).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
unlockListener.unlockingDismissed();
unlockDialog.dismiss();
}
});
unlockDialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
unlockListener.unlockingDismissed();
unlockDialog.dismiss();
}
return true;
}
});
}
});
}
/**
* Listener interface to be called when password has been types in.
*/
public interface UnlockListener {
void unlockingDismissed();
void unlock(byte[] unlockCode);
}
} |
3e1629fdf63f81c8fc118a4b1c2b55d6e8f2ef93 | 1,455 | java | Java | core/src/main/java/org/codegist/crest/annotate/ConnectionTimeout.java | codegist/crest | e99ba7728b27d2ddb2c247261350f1b6fa7a6698 | [
"Apache-2.0"
] | 2 | 2015-05-10T13:11:23.000Z | 2015-10-26T18:57:29.000Z | core/src/main/java/org/codegist/crest/annotate/ConnectionTimeout.java | codegist/crest | e99ba7728b27d2ddb2c247261350f1b6fa7a6698 | [
"Apache-2.0"
] | 3 | 2015-02-04T15:05:58.000Z | 2021-06-04T01:32:52.000Z | core/src/main/java/org/codegist/crest/annotate/ConnectionTimeout.java | codegist/crest | e99ba7728b27d2ddb2c247261350f1b6fa7a6698 | [
"Apache-2.0"
] | 3 | 2015-02-04T14:49:02.000Z | 2017-04-26T03:00:43.000Z | 34.069767 | 104 | 0.666212 | 9,428 | /*
* Copyright 2011 CodeGist.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ===================================================================
*
* More information at http://www.codegist.org.
*/
package org.codegist.crest.annotate;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>Indicates the connection timeout of the annotated method</p>
* <p>When set at interface level, it will applies to all methods where it is not already specified</p>
* @author Laurent Gilles (anpch@example.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface ConnectionTimeout {
/**
* connection timeout in milliseconds to apply. Default is 20000.
*/
int value();
}
|
3e162a56b742030804dd7d0f41bf39e277d34c2e | 4,601 | java | Java | BraintreeApi/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureWebViewActivity.java | cardinalblue/braintree_android | dcc73fd1bfb7fc497b059262be7d386949b6f780 | [
"MIT"
] | null | null | null | BraintreeApi/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureWebViewActivity.java | cardinalblue/braintree_android | dcc73fd1bfb7fc497b059262be7d386949b6f780 | [
"MIT"
] | null | null | null | BraintreeApi/src/main/java/com/braintreepayments/api/threedsecure/ThreeDSecureWebViewActivity.java | cardinalblue/braintree_android | dcc73fd1bfb7fc497b059262be7d386949b6f780 | [
"MIT"
] | null | null | null | 35.392308 | 117 | 0.699196 | 9,429 | package com.braintreepayments.api.threedsecure;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
import android.widget.FrameLayout;
import com.braintreepayments.api.annotations.Beta;
import com.braintreepayments.api.models.ThreeDSecureAuthenticationResponse;
import com.braintreepayments.api.models.ThreeDSecureLookup;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
@Beta
public class ThreeDSecureWebViewActivity extends Activity {
public static final String EXTRA_THREE_D_SECURE_LOOKUP = "com.braintreepayments.api.EXTRA_THREE_D_SECURE_LOOKUP";
public static final String EXTRA_THREE_D_SECURE_RESULT = "com.braintreepayments.api.EXTRA_THREE_D_SECURE_RESULT";
private ActionBar mActionBar;
private FrameLayout mRootView;
private Stack<ThreeDSecureWebView> mThreeDSecureWebViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
ThreeDSecureLookup threeDSecureLookup =
getIntent().getParcelableExtra(EXTRA_THREE_D_SECURE_LOOKUP);
if (threeDSecureLookup == null) {
throw new IllegalArgumentException("A ThreeDSecureLookup must be specified with " +
ThreeDSecureLookup.class.getSimpleName() + ".EXTRA_THREE_D_SECURE_LOOKUP extra");
}
setupActionBar();
mThreeDSecureWebViews = new Stack<ThreeDSecureWebView>();
mRootView = ((FrameLayout) findViewById(android.R.id.content));
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("PaReq", threeDSecureLookup.getPareq()));
params.add(new BasicNameValuePair("MD", threeDSecureLookup.getMd()));
params.add(new BasicNameValuePair("TermUrl", threeDSecureLookup.getTermUrl()));
ByteArrayOutputStream encodedParams = new ByteArrayOutputStream();
try {
new UrlEncodedFormEntity(params, HTTP.UTF_8).writeTo(encodedParams);
} catch (IOException e) {
finish();
}
ThreeDSecureWebView webView = new ThreeDSecureWebView(this);
webView.init(this);
webView.postUrl(threeDSecureLookup.getAcsUrl(), encodedParams.toByteArray());
pushNewWebView(webView);
}
protected void pushNewWebView(ThreeDSecureWebView webView) {
mThreeDSecureWebViews.push(webView);
mRootView.removeAllViews();
mRootView.addView(webView);
}
protected void popCurrentWebView() {
mThreeDSecureWebViews.pop();
pushNewWebView(mThreeDSecureWebViews.pop());
}
protected void finishWithResult(ThreeDSecureAuthenticationResponse threeDSecureAuthenticationResponse) {
setResult(Activity.RESULT_OK, new Intent()
.putExtra(ThreeDSecureWebViewActivity.EXTRA_THREE_D_SECURE_RESULT,
threeDSecureAuthenticationResponse));
finish();
}
@Override
public void onBackPressed() {
if (mThreeDSecureWebViews.peek().canGoBack()) {
mThreeDSecureWebViews.peek().goBack();
} else if (mThreeDSecureWebViews.size() > 1) {
popCurrentWebView();
} else {
super.onBackPressed();
}
}
@TargetApi(VERSION_CODES.HONEYCOMB)
protected void setActionBarTitle(String title) {
if (mActionBar != null) {
mActionBar.setTitle(title);
}
}
@TargetApi(VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
mActionBar = getActionBar();
if (mActionBar != null) {
setActionBarTitle("");
mActionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
setResult(Activity.RESULT_CANCELED);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
3e162aa0f778a8c26874db92edd960ce20a0250e | 3,078 | java | Java | java/java/src/org/opengroup/openvds/JniPointer.java | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | java/java/src/org/opengroup/openvds/JniPointer.java | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | java/java/src/org/opengroup/openvds/JniPointer.java | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | 26.765217 | 86 | 0.604613 | 9,430 | /*
* Copyright 2019 The Open Group
* Copyright 2019 INT, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opengroup.openvds;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* JNI wrapper for pointer to C++ object in OpenVdsJni library.
*
* Deletion of C++ object - metod deleteHandle() - must be implemented in
* derived classes of JniPointer to properly call C++ class destructor.
*/
public abstract class JniPointer {
static final String JNI_LIB_NAME = "openvds-javacpp";
private static final Logger LOGGER = Logger.getLogger(JniPointer.class.getName());
private static final String ERR_LIBRARY = "JNI library load failed";
private static long _librarySize;
private static native String cpLibraryDescription();
protected abstract void deleteHandle();
protected long _handle;
protected boolean _ownHandle;
static {
try {
if (JNI_LIB_NAME.indexOf('/') < 0 && JNI_LIB_NAME.indexOf('\\') < 0) {
System.loadLibrary(JNI_LIB_NAME);
} else {
_librarySize = new File(JNI_LIB_NAME).length();
System.load(JNI_LIB_NAME);
}
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, ERR_LIBRARY, e);
}
}
public static String libraryDescription() {
String str = JNI_LIB_NAME;
if (_librarySize > 0) {
str += " Size=" + _librarySize;
}
String nativeDescr = null;
try {
nativeDescr = cpLibraryDescription();
if (nativeDescr != null) {
str += " " + nativeDescr;
}
} catch (Throwable t) {
str += " Error: " + t.toString();
}
return str;
}
public JniPointer(long handle, boolean ownHandle) {
_handle = handle;
_ownHandle = ownHandle;
}
@Override
public void finalize() {
release();
}
public synchronized void release() {
// Deletion of C++ object
if (_handle != 0) {
if (_ownHandle) {
deleteHandle();
}
_handle = 0;
}
}
public void setHandle(long handle) {
_handle = handle;
}
public long handle() {
return _handle;
}
public boolean isNull() {
return _handle == 0;
}
public void setOwnHandle(boolean ownHandle) {
_ownHandle = ownHandle;
}
public boolean ownHandle() {
return _ownHandle;
}
}
|
3e162af12f0cab701be45cde43429a1166747f90 | 2,787 | java | Java | SDK/examples/java/com/extremenetworks/exos/api/examples/ExecCLIExample.java | mhelmEXTR/ExtremeScripting | fd8554748dfb4b408965d9a3e1a977c6a86842e2 | [
"BSD-2-Clause"
] | null | null | null | SDK/examples/java/com/extremenetworks/exos/api/examples/ExecCLIExample.java | mhelmEXTR/ExtremeScripting | fd8554748dfb4b408965d9a3e1a977c6a86842e2 | [
"BSD-2-Clause"
] | null | null | null | SDK/examples/java/com/extremenetworks/exos/api/examples/ExecCLIExample.java | mhelmEXTR/ExtremeScripting | fd8554748dfb4b408965d9a3e1a977c6a86842e2 | [
"BSD-2-Clause"
] | null | null | null | 30.966667 | 105 | 0.708647 | 9,431 | /**
* THE INFORMATION AND SPECIFICATIONS IN THIS DEVELOPER KIT ARE SUBJECT TO CHANGE WITHOUT NOTICE.
* ALL INFORMATION AND SPECIFICATIONS IN THIS DEVELOPER KIT ARE PRESENTED WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED. YOU TAKE FULL RESPONSIBILITY FOR YOUR USE OF THE DEVELOPER KIT.
* THE DEVELOPER KIT IS LICENSED TO YOU UNDER THE THEN-CURRENT LICENSE TERMS FOR THE DEVELOPER
* KIT IN EFFECT AT THE TIME THE DEVELOPER KIT IS PROVIDED TO YOU BY EXTREME NETWORKS.
* PLEASE CONTACT EXTREME NETWORKS IF YOU DO NOT HAVE A COPY OF THE LICENSE TERMS. USE OF THE
* DEVELOPER KIT CONSTITUTES YOUR ACCEPTANCE OF THE DEVELOPER KIT LICENSE TERMS.
*
* Copyright (c) Extreme Networks Inc. 2007,2008
*/
package com.extremenetworks.exos.api.examples;
import java.util.Map;
import xapi.XosPortType;
/**
* This is an example of a request to execute a CLI command.
* The example is based on the operations defined in xos.wsdl
*
* The "show switch" command is executed using execCLI and the output is printed.
*
* NOTE: This example code is for illustration purposes only.
* The choice of attributes, values and error handling is simplified to emphasis the API functionality.
*
*/
public class ExecCLIExample {
/**
* Execute CLI command. This sends a execCLI request to execute the command.
*
* The result is the command ouptut as seen from a CLI session.
*
* @param stub handle to the webservices on the switch
* @param cliCommand CLI command to execute
*
*/
public void execCLI(XosPortType stub, String cliCommand) {
Utilities.log("execCLI: CLI command= "+cliCommand);
try {
String result=stub.execCli(cliCommand);
Utilities.log(result);
} catch(Exception ex) {
Utilities.log("ERROR : "+ex.getMessage());
}
Utilities.log("execCLI: DONE");
}
/**
* Main execution method
* Usage: ExecCLIExample switch=<switch> username=<username> password=<password>
*
* @param args command line arguments
*/
public static void main(String[] args) {
Map arguments=Utilities.parseCommandLineArgs(args);
String device=(String)arguments.get("switch");
String username=(String)arguments.get("username");
String password=(String)arguments.get("password");
if(device==null || username==null) {
System.out.println("Usage: ExecCLIExample switch=<switch> username=<username> password=<password>");
System.exit(1);
}
try {
//Get handle to switch web service
XosPortType stub=Utilities.getXosPort(device,username,password);
//Execute command
ExecCLIExample execCLIExample=new ExecCLIExample();
execCLIExample.execCLI(stub,"show switch");
} catch(Exception ex) {
Utilities.log("ERROR : "+ex.getMessage());
}
}
}
|
3e162b2360c1795b33b7f5b9f6bf3075490d648c | 3,949 | java | Java | choco-solver/src/main/java/org/chocosolver/solver/constraints/unary/PropMemberBound.java | PhilAndrew/choco3gwt | b5d1bfe274c5cd3da5823888249b736de5e1d84c | [
"BSD-3-Clause"
] | null | null | null | choco-solver/src/main/java/org/chocosolver/solver/constraints/unary/PropMemberBound.java | PhilAndrew/choco3gwt | b5d1bfe274c5cd3da5823888249b736de5e1d84c | [
"BSD-3-Clause"
] | null | null | null | choco-solver/src/main/java/org/chocosolver/solver/constraints/unary/PropMemberBound.java | PhilAndrew/choco3gwt | b5d1bfe274c5cd3da5823888249b736de5e1d84c | [
"BSD-3-Clause"
] | null | null | null | 38.339806 | 98 | 0.696126 | 9,432 | /**
* Copyright (c) 2014,
* Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241),
* Jean-Guillaume Fages (COSLING S.A.S.).
* 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 the <organization> 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 <COPYRIGHT HOLDER> 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.chocosolver.solver.constraints.unary;
import gnu.trove.map.hash.THashMap;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.explanations.Deduction;
import org.chocosolver.solver.explanations.Explanation;
import org.chocosolver.solver.explanations.ExplanationEngine;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.events.IntEventType;
import org.chocosolver.util.ESat;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 26 nov. 2010
*/
public class PropMemberBound extends Propagator<IntVar> {
final int lb, ub;
public PropMemberBound(IntVar var, int lb, int ub) {
super(new IntVar[]{var}, PropagatorPriority.UNARY, false);
this.lb = lb;
this.ub = ub;
}
@Override
public void propagate(int evtmask) throws ContradictionException {
// with views such as abs(...), the prop can be not entailed after initial propagation
vars[0].updateLowerBound(lb, aCause);
vars[0].updateUpperBound(ub, aCause);
if (lb <= vars[0].getLB() && ub >= vars[0].getUB()) {
this.setPassive();
}
}
@Override
public int getPropagationConditions(int vIdx) {
return IntEventType.boundAndInst();
}
@Override
public ESat isEntailed() {
if (vars[0].getLB() >= lb && vars[0].getUB() <= ub) {
return ESat.TRUE;
} else if (vars[0].getUB() < lb || vars[0].getLB() > ub) {
return ESat.FALSE;
}
return ESat.UNDEFINED;
}
@Override
public String toString() {
return vars[0].getName() + " in [" + lb + "," + ub + "]";
}
@Override
public void explain(ExplanationEngine xengine, Deduction d, Explanation e) {
e.add(xengine.getPropagatorActivation(this));
}
@Override
public void duplicate(Solver solver, THashMap<Object, Object> identitymap) {
if (!identitymap.containsKey(this)) {
identitymap.put(this, new PropMemberBound((IntVar) identitymap.get(vars[0]), lb, ub));
}
}
}
|
3e162b4527dfca4c898533afc0158ebb5acb7818 | 1,411 | java | Java | ExtractedJars/Shopkick_com.shopkick.app/javafiles/io/radar/sdk/model/RadarPolygonGeometry.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 3 | 2019-05-01T09:22:08.000Z | 2019-07-06T22:21:59.000Z | ExtractedJars/Shopkick_com.shopkick.app/javafiles/io/radar/sdk/model/RadarPolygonGeometry.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | null | null | null | ExtractedJars/Shopkick_com.shopkick.app/javafiles/io/radar/sdk/model/RadarPolygonGeometry.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 1 | 2020-11-26T12:22:02.000Z | 2020-11-26T12:22:02.000Z | 33.595238 | 116 | 0.650602 | 9,433 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package io.radar.sdk.model;
import kotlin.jvm.internal.Intrinsics;
// Referenced classes of package io.radar.sdk.model:
// RadarGeofenceGeometry, Coordinate
public final class RadarPolygonGeometry extends RadarGeofenceGeometry
{
public RadarPolygonGeometry(Coordinate acoordinate[])
{
Intrinsics.checkParameterIsNotNull(((Object) (acoordinate)), "coordinates");
// 0 0:aload_1
// 1 1:ldc1 #28 <String "coordinates">
// 2 3:invokestatic #34 <Method void Intrinsics.checkParameterIsNotNull(Object, String)>
super(((kotlin.jvm.internal.DefaultConstructorMarker) (null)));
// 3 6:aload_0
// 4 7:aconst_null
// 5 8:invokespecial #37 <Method void RadarGeofenceGeometry(kotlin.jvm.internal.DefaultConstructorMarker)>
coordinates = acoordinate;
// 6 11:aload_0
// 7 12:aload_1
// 8 13:putfield #39 <Field Coordinate[] coordinates>
// 9 16:return
}
public final Coordinate[] getCoordinates()
{
return coordinates;
// 0 0:aload_0
// 1 1:getfield #39 <Field Coordinate[] coordinates>
// 2 4:areturn
}
private final Coordinate coordinates[];
}
|
3e162c0817891adceb558eca225971a13215b001 | 52,224 | java | Java | oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndex.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 288 | 2015-01-11T04:09:03.000Z | 2022-03-28T22:20:09.000Z | oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndex.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 154 | 2016-10-30T11:31:04.000Z | 2022-03-31T14:20:52.000Z | oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndex.java | mrozati/jackrabbit-oak | eefe51315926cc2cc1736bfdd03f1a0f4abf725a | [
"Apache-2.0"
] | 405 | 2015-01-15T16:15:56.000Z | 2022-03-24T08:27:08.000Z | 41.846154 | 153 | 0.550169 | 9,434 | /*
* 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.jackrabbit.oak.plugins.index.lucene;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterables;
import com.google.common.collect.Queues;
import com.google.common.collect.Sets;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.api.Result.SizePrecision;
import org.apache.jackrabbit.oak.plugins.index.Cursors;
import org.apache.jackrabbit.oak.plugins.index.Cursors.PathCursor;
import org.apache.jackrabbit.oak.plugins.index.lucene.util.MoreLikeThisHelper;
import org.apache.jackrabbit.oak.plugins.index.lucene.util.PathStoredFieldVisitor;
import org.apache.jackrabbit.oak.plugins.index.lucene.util.SpellcheckHelper;
import org.apache.jackrabbit.oak.plugins.index.lucene.util.SuggestHelper;
import org.apache.jackrabbit.oak.plugins.index.search.FieldNames;
import org.apache.jackrabbit.oak.plugins.index.search.IndexDefinition;
import org.apache.jackrabbit.oak.plugins.index.search.IndexDefinition.IndexingRule;
import org.apache.jackrabbit.oak.plugins.index.search.PropertyDefinition;
import org.apache.jackrabbit.oak.plugins.index.search.SizeEstimator;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.spi.query.Cursor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.Filter.PropertyRestriction;
import org.apache.jackrabbit.oak.spi.query.IndexRow;
import org.apache.jackrabbit.oak.spi.query.QueryConstants;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.AdvanceFulltextQueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryLimits;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextAnd;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextContains;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextExpression;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextOr;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextTerm;
import org.apache.jackrabbit.oak.spi.query.fulltext.FullTextVisitor;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TotalHitCountCollector;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLEncoder;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.spell.SuggestWord;
import org.apache.lucene.search.suggest.Lookup;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkState;
import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.commons.PathUtils.denotesRoot;
import static org.apache.jackrabbit.oak.commons.PathUtils.getAncestorPath;
import static org.apache.jackrabbit.oak.commons.PathUtils.getDepth;
import static org.apache.jackrabbit.oak.commons.PathUtils.getName;
import static org.apache.jackrabbit.oak.commons.PathUtils.getParentPath;
import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.VERSION;
import static org.apache.jackrabbit.oak.plugins.index.lucene.TermFactory.newFulltextTerm;
import static org.apache.jackrabbit.oak.plugins.index.lucene.TermFactory.newPathTerm;
import static org.apache.jackrabbit.oak.plugins.index.search.util.IndexHelper.skipTokenization;
import static org.apache.jackrabbit.oak.spi.query.QueryConstants.JCR_PATH;
import static org.apache.lucene.search.BooleanClause.Occur.MUST;
import static org.apache.lucene.search.BooleanClause.Occur.MUST_NOT;
import static org.apache.lucene.search.BooleanClause.Occur.SHOULD;
/**
* Used to query old (compatVersion 1) Lucene indexes.
*
* Provides a QueryIndex that does lookups against a Lucene-based index
*
* <p>
* To define a lucene index on a subtree you have to add an
* <code>oak:index</code> node.
*
* Under it follows the index definition node that:
* <ul>
* <li>must be of type <code>oak:QueryIndexDefinition</code></li>
* <li>must have the <code>type</code> property set to <b><code>lucene</code></b></li>
* <li>must have the <code>async</code> property set to <b><code>async</code></b></li>
* </ul>
* <p>
* Optionally you can add
* <ul>
* <li>what subset of property types to be included in the index via the <code>includePropertyTypes</code> property</li>
* <li>a blacklist of property names: what property to be excluded from the index via the <code>excludePropertyNames</code> property</li>
* <li>the <code>reindex</code> flag which when set to <code>true</code>, triggers a full content re-index.</li>
* </ul>
* <pre>{@code
* {
* NodeBuilder index = root.child("oak:index");
* index.child("lucene")
* .setProperty("jcr:primaryType", "oak:QueryIndexDefinition", Type.NAME)
* .setProperty("type", "lucene")
* .setProperty("async", "async")
* .setProperty("reindex", "true");
* }
* }</pre>
* @see QueryIndex
*
*/
public class LuceneIndex implements AdvanceFulltextQueryIndex {
private static final Logger LOG = LoggerFactory
.getLogger(LuceneIndex.class);
public static final String NATIVE_QUERY_FUNCTION = "native*lucene";
private static double MIN_COST = 2.2;
/**
* IndexPaln Attribute name which refers to the path of Lucene index to be used
* to perform query
*/
static final String ATTR_INDEX_PATH = "oak.lucene.indexPath";
/**
* Batch size for fetching results from Lucene queries.
*/
static final int LUCENE_QUERY_BATCH_SIZE = 50;
static final boolean USE_PATH_RESTRICTION = Boolean.getBoolean("oak.luceneUsePath");
static final int MAX_RELOAD_COUNT = Integer.getInteger("oak.luceneMaxReloadCount", 16);
protected final IndexTracker tracker;
private final NodeAggregator aggregator;
private final Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<strong>", "</strong>"),
new SimpleHTMLEncoder(), null);
public LuceneIndex(IndexTracker tracker, NodeAggregator aggregator) {
this.tracker = tracker;
this.aggregator = aggregator;
}
@Override
public double getMinimumCost() {
return MIN_COST;
}
@Override
public String getIndexName() {
return "lucene";
}
@Override
public List<IndexPlan> getPlans(Filter filter, List<OrderEntry> sortOrder, NodeState rootState) {
FullTextExpression ft = filter.getFullTextConstraint();
if (ft == null) {
// no full-text condition: don't use this index,
// as there might be a better one
return Collections.emptyList();
}
String indexPath = LuceneIndexLookupUtil.getOldFullTextIndexPath(rootState, filter, tracker);
if (indexPath == null) { // unusable index
return Collections.emptyList();
}
Set<String> relPaths = getRelativePaths(ft);
if (relPaths.size() > 1) {
LOG.warn("More than one relative parent for query " + filter.getQueryStatement());
// there are multiple "parents", as in
// "contains(a/x, 'hello') and contains(b/x, 'world')"
return Collections.emptyList();
}
LuceneIndexNode node = tracker.acquireIndexNode(indexPath);
try{
if (node != null){
IndexDefinition defn = node.getDefinition();
LuceneIndexStatistics stats = node.getIndexStatistics();
if (stats != null) {
return Collections.singletonList(planBuilder(filter)
.setEstimatedEntryCount(defn.getFulltextEntryCount(stats.numDocs()))
.setCostPerExecution(defn.getCostPerExecution())
.setCostPerEntry(defn.getCostPerEntry())
.setDeprecated(defn.isDeprecated())
.setAttribute(ATTR_INDEX_PATH, indexPath)
.setDeprecated(defn.isDeprecated())
.build());
}
}
//No index node then no plan possible
return Collections.emptyList();
} finally {
if (node != null){
node.release();
}
}
}
@Override
public double getCost(Filter filter, NodeState root) {
throw new UnsupportedOperationException("Not supported as implementing AdvancedQueryIndex");
}
@Override
public String getPlan(Filter filter, NodeState root) {
throw new UnsupportedOperationException("Not supported as implementing AdvancedQueryIndex");
}
@Override
public String getPlanDescription(IndexPlan plan, NodeState root) {
Filter filter = plan.getFilter();
LuceneIndexNode index = tracker.acquireIndexNode((String) plan.getAttribute(ATTR_INDEX_PATH));
checkState(index != null, "The Lucene index is not available");
try {
FullTextExpression ft = filter.getFullTextConstraint();
Set<String> relPaths = getRelativePaths(ft);
if (relPaths.size() > 1) {
return new MultiLuceneIndex(filter, root, relPaths).getPlan();
}
String parent = relPaths.size() == 0 ? "" : relPaths.iterator().next();
// we only restrict non-full-text conditions if there is
// no relative property in the full-text constraint
boolean nonFullTextConstraints = parent.isEmpty();
String planDesc = getLuceneRequest(filter, null, nonFullTextConstraints, index.getDefinition()) + " ft:(" + ft + ")";
if (!parent.isEmpty()) {
planDesc += " parent:" + parent;
}
return planDesc;
} finally {
index.release();
}
}
@Override
public Cursor query(final Filter filter, final NodeState root) {
throw new UnsupportedOperationException("Not supported as implementing AdvancedQueryIndex");
}
@Override
public Cursor query(final IndexPlan plan, NodeState rootState) {
if (plan.isDeprecated()) {
LOG.warn("This index is deprecated: {}; it is used for query {}. " +
"Please change the query or the index definitions.", plan.getPlanName(), plan.getFilter());
}
final Filter filter = plan.getFilter();
FullTextExpression ft = filter.getFullTextConstraint();
final Set<String> relPaths = getRelativePaths(ft);
if (relPaths.size() > 1) {
return new MultiLuceneIndex(filter, rootState, relPaths).query();
}
final String parent = relPaths.size() == 0 ? "" : relPaths.iterator().next();
// we only restrict non-full-text conditions if there is
// no relative property in the full-text constraint
final boolean nonFullTextConstraints = parent.isEmpty();
final int parentDepth = getDepth(parent);
QueryLimits settings = filter.getQueryLimits();
LuceneResultRowIterator itr = new LuceneResultRowIterator() {
private final Deque<LuceneResultRow> queue = Queues.newArrayDeque();
private final Set<String> seenPaths = Sets.newHashSet();
private ScoreDoc lastDoc;
private int nextBatchSize = LUCENE_QUERY_BATCH_SIZE;
private boolean noDocs = false;
private long lastSearchIndexerVersion;
private int reloadCount;
@Override
protected LuceneResultRow computeNext() {
while (!queue.isEmpty() || loadDocs()) {
return queue.remove();
}
return endOfData();
}
@Override
public int rewoundCount() {
return reloadCount;
}
private LuceneResultRow convertToRow(ScoreDoc doc, IndexSearcher searcher, String excerpt) throws IOException {
IndexReader reader = searcher.getIndexReader();
PathStoredFieldVisitor visitor = new PathStoredFieldVisitor();
reader.document(doc.doc, visitor);
String path = visitor.getPath();
if (path != null) {
if ("".equals(path)) {
path = "/";
}
if (!parent.isEmpty()) {
// TODO OAK-828 this breaks node aggregation
// get the base path
// ensure the path ends with the given
// relative path
// if (!path.endsWith("/" + parent)) {
// continue;
// }
path = getAncestorPath(path, parentDepth);
// avoid duplicate entries
if (seenPaths.contains(path)) {
return null;
}
seenPaths.add(path);
}
return new LuceneResultRow(path, doc.score, excerpt);
}
return null;
}
/**
* Loads the lucene documents in batches
* @return true if any document is loaded
*/
private boolean loadDocs() {
if (noDocs) {
return false;
}
ScoreDoc lastDocToRecord = null;
LuceneIndexNode indexNode = tracker.acquireIndexNode((String) plan.getAttribute(ATTR_INDEX_PATH));
checkState(indexNode != null);
try {
IndexSearcher searcher = indexNode.getSearcher();
LuceneRequestFacade luceneRequestFacade = getLuceneRequest(filter, searcher.getIndexReader(),
nonFullTextConstraints, indexNode.getDefinition());
if (luceneRequestFacade.getLuceneRequest() instanceof Query) {
Query query = (Query) luceneRequestFacade.getLuceneRequest();
TopDocs docs;
long time = System.currentTimeMillis();
checkForIndexVersionChange(searcher);
while (true) {
if (lastDoc != null) {
LOG.debug("loading the next {} entries for query {}", nextBatchSize, query);
docs = searcher.searchAfter(lastDoc, query, nextBatchSize);
} else {
LOG.debug("loading the first {} entries for query {}", nextBatchSize, query);
docs = searcher.search(query, nextBatchSize);
}
time = System.currentTimeMillis() - time;
LOG.debug("... took {} ms", time);
nextBatchSize = (int) Math.min(nextBatchSize * 2L, 100000);
PropertyRestriction restriction = filter.getPropertyRestriction(QueryConstants.REP_EXCERPT);
boolean addExcerpt = restriction != null && restriction.isNotNullRestriction();
Analyzer analyzer = indexNode.getDefinition().getAnalyzer();
if (addExcerpt) {
// setup highlighter
QueryScorer scorer = new QueryScorer(query);
scorer.setExpandMultiTermQuery(true);
highlighter.setFragmentScorer(scorer);
}
for (ScoreDoc doc : docs.scoreDocs) {
String excerpt = null;
if (addExcerpt) {
excerpt = getExcerpt(analyzer, searcher, doc);
}
LuceneResultRow row = convertToRow(doc, searcher, excerpt);
if (row != null) {
queue.add(row);
}
lastDocToRecord = doc;
}
if (queue.isEmpty() && docs.scoreDocs.length > 0) {
lastDoc = lastDocToRecord;
} else {
break;
}
}
} else if (luceneRequestFacade.getLuceneRequest() instanceof SpellcheckHelper.SpellcheckQuery) {
SpellcheckHelper.SpellcheckQuery spellcheckQuery = (SpellcheckHelper.SpellcheckQuery) luceneRequestFacade.getLuceneRequest();
noDocs = true;
SuggestWord[] suggestWords = SpellcheckHelper.getSpellcheck(spellcheckQuery);
// ACL filter spellchecks
Collection<String> suggestedWords = new ArrayList<String>(suggestWords.length);
QueryParser qp = new QueryParser(Version.LUCENE_47, FieldNames.SUGGEST, indexNode.getDefinition().getAnalyzer());
for (SuggestWord suggestion : suggestWords) {
Query query = qp.createPhraseQuery(FieldNames.SUGGEST, suggestion.string);
TopDocs topDocs = searcher.search(query, 100);
if (topDocs.totalHits > 0) {
for (ScoreDoc doc : topDocs.scoreDocs) {
Document retrievedDoc = searcher.doc(doc.doc);
if (filter.isAccessible(retrievedDoc.get(FieldNames.PATH))) {
suggestedWords.add(suggestion.string);
break;
}
}
}
}
queue.add(new LuceneResultRow(suggestedWords));
} else if (luceneRequestFacade.getLuceneRequest() instanceof SuggestHelper.SuggestQuery) {
SuggestHelper.SuggestQuery suggestQuery = (SuggestHelper.SuggestQuery) luceneRequestFacade.getLuceneRequest();
noDocs = true;
List<Lookup.LookupResult> lookupResults = SuggestHelper.getSuggestions(indexNode.getLookup(), suggestQuery);
// ACL filter suggestions
Collection<String> suggestedWords = new ArrayList<String>(lookupResults.size());
QueryParser qp = new QueryParser(Version.LUCENE_47, FieldNames.FULLTEXT, indexNode.getDefinition().getAnalyzer());
for (Lookup.LookupResult suggestion : lookupResults) {
Query query = qp.createPhraseQuery(FieldNames.FULLTEXT, suggestion.key.toString());
TopDocs topDocs = searcher.search(query, 100);
if (topDocs.totalHits > 0) {
for (ScoreDoc doc : topDocs.scoreDocs) {
Document retrievedDoc = searcher.doc(doc.doc);
if (filter.isAccessible(retrievedDoc.get(FieldNames.PATH))) {
suggestedWords.add("{term=" + suggestion.key + ",weight=" + suggestion.value + "}");
break;
}
}
}
}
queue.add(new LuceneResultRow(suggestedWords));
}
} catch (IOException e) {
LOG.warn("query via {} failed.", LuceneIndex.this, e);
} finally {
indexNode.release();
}
if (lastDocToRecord != null) {
this.lastDoc = lastDocToRecord;
}
return !queue.isEmpty();
}
private void checkForIndexVersionChange(IndexSearcher searcher) {
long currentVersion = LucenePropertyIndex.getVersion(searcher);
if (currentVersion != lastSearchIndexerVersion && lastDoc != null){
reloadCount++;
if (reloadCount > MAX_RELOAD_COUNT) {
LOG.error("More than {} index version changes detected for query {}",
MAX_RELOAD_COUNT,
plan);
throw new IllegalStateException("Too many version changes");
}
lastDoc = null;
LOG.info("Change in index version detected {} => {}. Query would be performed without " +
"offset; reload {}", currentVersion, lastSearchIndexerVersion, reloadCount);
}
this.lastSearchIndexerVersion = currentVersion;
}
};
SizeEstimator sizeEstimator = new SizeEstimator() {
@Override
public long getSize() {
LuceneIndexNode indexNode = tracker.acquireIndexNode((String) plan.getAttribute(ATTR_INDEX_PATH));
checkState(indexNode != null);
try {
IndexSearcher searcher = indexNode.getSearcher();
LuceneRequestFacade luceneRequestFacade = getLuceneRequest(filter, searcher.getIndexReader(),
nonFullTextConstraints, indexNode.getDefinition());
if (luceneRequestFacade.getLuceneRequest() instanceof Query) {
Query query = (Query) luceneRequestFacade.getLuceneRequest();
TotalHitCountCollector collector = new TotalHitCountCollector();
searcher.search(query, collector);
int totalHits = collector.getTotalHits();
LOG.debug("Estimated size for query {} is {}", query, totalHits);
return totalHits;
}
LOG.debug("Estimated size: not a Query: {}", luceneRequestFacade.getLuceneRequest());
} catch (IOException e) {
LOG.warn("query via {} failed.", LuceneIndex.this, e);
} finally {
indexNode.release();
}
return -1;
}
};
return new LucenePathCursor(itr, settings, sizeEstimator, filter);
}
private String getExcerpt(Analyzer analyzer, IndexSearcher searcher, ScoreDoc doc) throws IOException {
StringBuilder excerpt = new StringBuilder();
for (IndexableField field : searcher.getIndexReader().document(doc.doc).getFields()) {
String name = field.name();
// only full text or analyzed fields
if (name.startsWith(FieldNames.FULLTEXT) || name.startsWith(FieldNames.ANALYZED_FIELD_PREFIX)) {
String text = field.stringValue();
TokenStream tokenStream = analyzer.tokenStream(name, text);
try {
TextFragment[] textFragments = highlighter.getBestTextFragments(tokenStream, text, true, 2);
if (textFragments != null && textFragments.length > 0) {
for (TextFragment fragment : textFragments) {
if (excerpt.length() > 0) {
excerpt.append("...");
}
excerpt.append(fragment.toString());
}
break;
}
} catch (InvalidTokenOffsetsException e) {
LOG.error("higlighting failed", e);
}
}
}
return excerpt.toString();
}
protected static IndexPlan.Builder planBuilder(Filter filter){
return new IndexPlan.Builder()
.setCostPerExecution(0) // we're local. Low-cost
.setCostPerEntry(1)
.setFilter(filter)
.setFulltextIndex(true)
.setEstimatedEntryCount(0) //TODO Fake it to provide constant cost for now
.setIncludesNodeData(false) // we should not include node data
.setDelayed(true); //Lucene is always async
}
/**
* Get the set of relative paths of a full-text condition. For example, for
* the condition "contains(a/b, 'hello') and contains(c/d, 'world'), the set
* { "a", "c" } is returned. If there are no relative properties, then one
* entry is returned (the empty string). If there is no expression, then an
* empty set is returned.
*
* @param ft the full-text expression
* @return the set of relative paths (possibly empty)
*/
private static Set<String> getRelativePaths(FullTextExpression ft) {
if (ft == null) {
// there might be no full-text constraint when using the
// LowCostLuceneIndexProvider which is used for testing
// TODO if the LowCostLuceneIndexProvider is removed, we should do
// the following instead:
// throw new
// IllegalStateException("Lucene index is used even when no full-text conditions are used for filter "
// + filter);
return Collections.emptySet();
}
final HashSet<String> relPaths = new HashSet<String>();
ft.accept(new FullTextVisitor.FullTextVisitorBase() {
@Override
public boolean visit(FullTextTerm term) {
String p = term.getPropertyName();
if (p == null) {
relPaths.add("");
} else if (p.startsWith("../") || p.startsWith("./")) {
throw new IllegalArgumentException("Relative parent is not supported:" + p);
} else if (getDepth(p) > 1) {
String parent = getParentPath(p);
relPaths.add(parent);
} else {
relPaths.add("");
}
return true;
}
});
return relPaths;
}
/**
* Get the Lucene query for the given filter.
*
* @param filter the filter, including full-text constraint
* @param reader the Lucene reader
* @param nonFullTextConstraints whether non-full-text constraints (such a
* path, node type, and so on) should be added to the Lucene
* query
* @param indexDefinition nodestate that contains the index definition
* @return the Lucene query
*/
private static LuceneRequestFacade getLuceneRequest(Filter filter, IndexReader reader, boolean nonFullTextConstraints,
LuceneIndexDefinition indexDefinition) {
List<Query> qs = new ArrayList<Query>();
Analyzer analyzer = indexDefinition.getAnalyzer();
FullTextExpression ft = filter.getFullTextConstraint();
if (ft == null) {
// there might be no full-text constraint
// when using the LowCostLuceneIndexProvider
// which is used for testing
} else {
qs.add(getFullTextQuery(ft, analyzer, reader));
}
PropertyRestriction pr = filter.getPropertyRestriction(NATIVE_QUERY_FUNCTION);
if (pr != null) {
String query = String.valueOf(pr.first.getValue(pr.first.getType()));
QueryParser queryParser = new QueryParser(VERSION, "", indexDefinition.getAnalyzer());
if (query.startsWith("mlt?")) {
String mltQueryString = query.replace("mlt?", "");
if (reader != null) {
Query moreLikeThis = MoreLikeThisHelper.getMoreLikeThis(reader, analyzer, mltQueryString);
if (moreLikeThis != null) {
qs.add(moreLikeThis);
}
}
}
if (query.startsWith("spellcheck?")) {
String spellcheckQueryString = query.replace("spellcheck?", "");
if (reader != null) {
return new LuceneRequestFacade<SpellcheckHelper.SpellcheckQuery>(SpellcheckHelper.getSpellcheckQuery(spellcheckQueryString, reader));
}
} else if (query.startsWith("suggest?")) {
String suggestQueryString = query.replace("suggest?", "");
if (reader != null) {
return new LuceneRequestFacade<SuggestHelper.SuggestQuery>(SuggestHelper.getSuggestQuery(suggestQueryString));
}
} else {
try {
qs.add(queryParser.parse(query));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
} else if (nonFullTextConstraints) {
addNonFullTextConstraints(qs, filter, reader, analyzer,
indexDefinition);
}
if (qs.size() == 0) {
return new LuceneRequestFacade<Query>(new MatchAllDocsQuery());
}
return LucenePropertyIndex.performAdditionalWraps(qs);
}
private static void addNonFullTextConstraints(List<Query> qs,
Filter filter, IndexReader reader, Analyzer analyzer, IndexDefinition indexDefinition) {
if (!filter.matchesAllTypes()) {
addNodeTypeConstraints(qs, filter);
}
String path = filter.getPath();
switch (filter.getPathRestriction()) {
case ALL_CHILDREN:
if (USE_PATH_RESTRICTION) {
if ("/".equals(path)) {
break;
}
if (!path.endsWith("/")) {
path += "/";
}
qs.add(new PrefixQuery(newPathTerm(path)));
}
break;
case DIRECT_CHILDREN:
if (USE_PATH_RESTRICTION) {
if (!path.endsWith("/")) {
path += "/";
}
qs.add(new PrefixQuery(newPathTerm(path)));
}
break;
case EXACT:
qs.add(new TermQuery(newPathTerm(path)));
break;
case PARENT:
if (denotesRoot(path)) {
// there's no parent of the root node
// we add a path that can not possibly occur because there
// is no way to say "match no documents" in Lucene
qs.add(new TermQuery(new Term(FieldNames.PATH, "///")));
} else {
qs.add(new TermQuery(newPathTerm(getParentPath(path))));
}
break;
case NO_RESTRICTION:
break;
}
//Fulltext index definition used by LuceneIndex only works with old format
//which is not nodeType based. So just use the nt:base index
IndexingRule rule = indexDefinition.getApplicableIndexingRule(JcrConstants.NT_BASE);
for (PropertyRestriction pr : filter.getPropertyRestrictions()) {
if (pr.first == null && pr.last == null) {
// we only support equality or range queries,
// but not "in", "is null", "is not null"
// queries (OAK-1208)
continue;
}
// check excluded properties and types
if (isExcludedProperty(pr, rule)) {
continue;
}
String name = pr.propertyName;
if (QueryConstants.REP_EXCERPT.equals(name) || QueryConstants.OAK_SCORE_EXPLANATION.equals(name) || QueryConstants.REP_FACET.equals(name)) {
continue;
}
if (JCR_PRIMARYTYPE.equals(name)) {
continue;
}
if (QueryConstants.RESTRICTION_LOCAL_NAME.equals(name)) {
continue;
}
if (skipTokenization(name)) {
qs.add(new TermQuery(new Term(name, pr.first
.getValue(STRING))));
continue;
}
String first = null;
String last = null;
boolean isLike = pr.isLike;
// TODO what to do with escaped tokens?
if (pr.first != null) {
first = pr.first.getValue(STRING);
first = first.replace("\\", "");
}
if (pr.last != null) {
last = pr.last.getValue(STRING);
last = last.replace("\\", "");
}
if (isLike) {
first = first.replace('%', WildcardQuery.WILDCARD_STRING);
first = first.replace('_', WildcardQuery.WILDCARD_CHAR);
int indexOfWS = first.indexOf(WildcardQuery.WILDCARD_STRING);
int indexOfWC = first.indexOf(WildcardQuery.WILDCARD_CHAR);
int len = first.length();
if (indexOfWS == len || indexOfWC == len) {
// remove trailing "*" for prefixquery
first = first.substring(0, first.length() - 1);
if (JCR_PATH.equals(name)) {
qs.add(new PrefixQuery(newPathTerm(first)));
} else {
qs.add(new PrefixQuery(new Term(name, first)));
}
} else {
if (JCR_PATH.equals(name)) {
qs.add(new WildcardQuery(newPathTerm(first)));
} else {
qs.add(new WildcardQuery(new Term(name, first)));
}
}
continue;
}
if (first != null && first.equals(last) && pr.firstIncluding
&& pr.lastIncluding) {
if (JCR_PATH.equals(name)) {
qs.add(new TermQuery(newPathTerm(first)));
} else {
if ("*".equals(name)) {
addReferenceConstraint(first, qs, reader);
} else {
for (String t : tokenize(first, analyzer)) {
qs.add(new TermQuery(new Term(name, t)));
}
}
}
continue;
}
first = tokenizeAndPoll(first, analyzer);
last = tokenizeAndPoll(last, analyzer);
qs.add(TermRangeQuery.newStringRange(name, first, last,
pr.firstIncluding, pr.lastIncluding));
}
}
private static String tokenizeAndPoll(String token, Analyzer analyzer){
if (token != null) {
List<String> tokens = tokenize(token, analyzer);
if (!tokens.isEmpty()) {
token = tokens.get(0);
}
}
return token;
}
private static boolean isExcludedProperty(PropertyRestriction pr,
IndexingRule rule) {
String name = pr.propertyName;
if (name.contains("/")) {
// lucene cannot handle child-level property restrictions
return true;
}
PropertyDefinition pd = rule.getConfig(name);
// check name
if(pd == null || !pd.index){
return true;
}
// check type
Integer type = null;
if (pr.first != null) {
type = pr.first.getType().tag();
} else if (pr.last != null) {
type = pr.last.getType().tag();
} else if (pr.list != null && !pr.list.isEmpty()) {
type = pr.list.get(0).getType().tag();
}
if (type != null) {
if (!includePropertyType(type, rule)) {
return true;
}
}
return false;
}
private static boolean includePropertyType(int type, IndexingRule rule){
if(rule.propertyTypes < 0){
return false;
}
return (rule.propertyTypes & (1 << type)) != 0;
}
private static void addReferenceConstraint(String uuid, List<Query> qs,
IndexReader reader) {
if (reader == null) {
// getPlan call
qs.add(new TermQuery(new Term("*", uuid)));
return;
}
// reference query
BooleanQuery bq = new BooleanQuery();
Collection<String> fields = MultiFields.getIndexedFields(reader);
for (String f : fields) {
bq.add(new TermQuery(new Term(f, uuid)), SHOULD);
}
qs.add(bq);
}
private static void addNodeTypeConstraints(List<Query> qs, Filter filter) {
BooleanQuery bq = new BooleanQuery();
for (String type : filter.getPrimaryTypes()) {
bq.add(new TermQuery(new Term(JCR_PRIMARYTYPE, type)), SHOULD);
}
for (String type : filter.getMixinTypes()) {
bq.add(new TermQuery(new Term(JCR_MIXINTYPES, type)), SHOULD);
}
qs.add(bq);
}
static Query getFullTextQuery(FullTextExpression ft, final Analyzer analyzer, final IndexReader reader) {
// a reference to the query, so it can be set in the visitor
// (a "non-local return")
final AtomicReference<Query> result = new AtomicReference<Query>();
ft.accept(new FullTextVisitor() {
@Override
public boolean visit(FullTextContains contains) {
return contains.getBase().accept(this);
}
@Override
public boolean visit(FullTextOr or) {
BooleanQuery q = new BooleanQuery();
for (FullTextExpression e : or.list) {
Query x = getFullTextQuery(e, analyzer, reader);
q.add(x, SHOULD);
}
result.set(q);
return true;
}
@Override
public boolean visit(FullTextAnd and) {
BooleanQuery q = new BooleanQuery();
for (FullTextExpression e : and.list) {
Query x = getFullTextQuery(e, analyzer, reader);
/* Only unwrap the clause if MUST_NOT(x) */
boolean hasMustNot = false;
if (x instanceof BooleanQuery) {
BooleanQuery bq = (BooleanQuery) x;
if ((bq.getClauses().length == 1) &&
(bq.getClauses()[0].getOccur() == Occur.MUST_NOT)) {
hasMustNot = true;
q.add(bq.getClauses()[0]);
}
}
if (!hasMustNot) {
q.add(x, MUST);
}
}
result.set(q);
return true;
}
@Override
public boolean visit(FullTextTerm term) {
return visitTerm(term.getPropertyName(), term.getText(), term.getBoost(), term.isNot());
}
private boolean visitTerm(String propertyName, String text, String boost, boolean not) {
String p = propertyName;
if (p != null && p.indexOf('/') >= 0) {
p = getName(p);
}
Query q = tokenToQuery(text, p, analyzer, reader);
if (q == null) {
return false;
}
if (boost != null) {
q.setBoost(Float.parseFloat(boost));
}
if (not) {
BooleanQuery bq = new BooleanQuery();
bq.add(q, MUST_NOT);
result.set(bq);
} else {
result.set(q);
}
return true;
}
});
return result.get();
}
static Query tokenToQuery(String text, String fieldName, Analyzer analyzer, IndexReader reader) {
if (analyzer == null) {
return null;
}
List<String> tokens = tokenize(text, analyzer);
if (tokens.isEmpty()) {
// TODO what should be returned in the case there are no tokens?
return new BooleanQuery();
}
if (tokens.size() == 1) {
String token = tokens.iterator().next();
if (hasFulltextToken(token)) {
return new WildcardQuery(newFulltextTerm(token, fieldName));
} else {
return new TermQuery(newFulltextTerm(token, fieldName));
}
} else {
if (hasFulltextToken(tokens)) {
BooleanQuery bq = new BooleanQuery();
for(String token: tokens){
if (hasFulltextToken(token)) {
bq.add(new WildcardQuery(newFulltextTerm(token, fieldName)), Occur.MUST);
} else {
bq.add(new TermQuery(newFulltextTerm(token, fieldName)), Occur.MUST);
}
}
return bq;
} else {
PhraseQuery pq = new PhraseQuery();
for (String t : tokens) {
pq.add(newFulltextTerm(t, fieldName));
}
return pq;
}
}
}
private static boolean hasFulltextToken(List<String> tokens) {
for (String token : tokens) {
if (hasFulltextToken(token)) {
return true;
}
}
return false;
}
private static boolean hasFulltextToken(String token) {
for (char c : fulltextTokens) {
if (token.indexOf(c) != -1) {
return true;
}
}
return false;
}
private static char[] fulltextTokens = new char[] { '*', '?' };
/**
* Tries to merge back tokens that are split on relevant fulltext query
* wildcards ('*' or '?')
*
*
* @param text
* @param analyzer
* @return
*/
static List<String> tokenize(String text, Analyzer analyzer) {
List<String> tokens = new ArrayList<String>();
TokenStream stream = null;
try {
stream = analyzer.tokenStream(FieldNames.FULLTEXT,
new StringReader(text));
CharTermAttribute termAtt = stream
.addAttribute(CharTermAttribute.class);
OffsetAttribute offsetAtt = stream
.addAttribute(OffsetAttribute.class);
// TypeAttribute type = stream.addAttribute(TypeAttribute.class);
stream.reset();
int poz = 0;
boolean hasFulltextToken = false;
StringBuilder token = new StringBuilder();
while (stream.incrementToken()) {
String term = termAtt.toString();
int start = offsetAtt.startOffset();
int end = offsetAtt.endOffset();
if (start > poz) {
for (int i = poz; i < start; i++) {
for (char c : fulltextTokens) {
if (c == text.charAt(i)) {
token.append(c);
hasFulltextToken = true;
}
}
}
}
poz = end;
if (hasFulltextToken) {
token.append(term);
hasFulltextToken = false;
} else {
if (token.length() > 0) {
tokens.add(token.toString());
}
token = new StringBuilder();
token.append(term);
}
}
// consume to the end of the string
if (poz < text.length()) {
for (int i = poz; i < text.length(); i++) {
for (char c : fulltextTokens) {
if (c == text.charAt(i)) {
token.append(c);
}
}
}
}
if (token.length() > 0) {
tokens.add(token.toString());
}
stream.end();
} catch (IOException e) {
LOG.error("Building fulltext query failed", e.getMessage());
return null;
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ignore
}
}
return tokens;
}
@Override
public NodeAggregator getNodeAggregator() {
return aggregator;
}
static class LuceneResultRow {
final String path;
final double score;
final Iterable<String> suggestWords;
final boolean isVirtual;
final String excerpt;
LuceneResultRow(String path, double score, String excerpt) {
this.isVirtual = false;
this.path = path;
this.score = score;
this.excerpt = excerpt;
this.suggestWords = Collections.emptySet();
}
LuceneResultRow(Iterable<String> suggestWords) {
this.isVirtual = true;
this.path = "/";
this.score = 1.0d;
this.suggestWords = suggestWords;
this.excerpt = null;
}
@Override
public String toString() {
return String.format("%s (%1.2f)", path, score);
}
}
/**
* A cursor over Lucene results. The result includes the path,
* and the jcr:score pseudo-property as returned by Lucene.
*/
static class LucenePathCursor implements Cursor {
private final int TRAVERSING_WARNING = Integer.getInteger("oak.traversing.warning", 10000);
private final Cursor pathCursor;
LuceneResultRow currentRow;
private final SizeEstimator sizeEstimator;
private long estimatedSize;
LucenePathCursor(final LuceneResultRowIterator it, QueryLimits settings, SizeEstimator sizeEstimator, Filter filter) {
this.sizeEstimator = sizeEstimator;
Iterator<String> pathIterator = new Iterator<String>() {
private int readCount;
private int rewoundCount;
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public String next() {
if (it.rewoundCount() > rewoundCount) {
readCount = 0;
rewoundCount = it.rewoundCount();
}
currentRow = it.next();
readCount++;
if (readCount % TRAVERSING_WARNING == 0) {
Cursors.checkReadLimit(readCount, settings);
LOG.warn("Index-Traversed {} nodes with filter {}", readCount, filter);
}
return currentRow.path;
}
@Override
public void remove() {
it.remove();
}
};
pathCursor = new PathCursor(pathIterator, true, settings);
}
@Override
public boolean hasNext() {
return pathCursor.hasNext();
}
@Override
public void remove() {
pathCursor.remove();
}
@Override
public IndexRow next() {
final IndexRow pathRow = pathCursor.next();
return new IndexRow() {
@Override
public boolean isVirtualRow() {
return currentRow.isVirtual;
}
@Override
public String getPath() {
return pathRow.getPath();
}
@Override
public PropertyValue getValue(String columnName) {
// overlay the score
if (QueryConstants.JCR_SCORE.equals(columnName)) {
return PropertyValues.newDouble(currentRow.score);
}
if (QueryConstants.REP_SPELLCHECK.equals(columnName) || QueryConstants.REP_SUGGEST.equals(columnName)) {
return PropertyValues.newString(Iterables.toString(currentRow.suggestWords));
}
if (QueryConstants.REP_EXCERPT.equals(columnName)) {
return PropertyValues.newString(currentRow.excerpt);
}
return pathRow.getValue(columnName);
}
};
}
@Override
public long getSize(SizePrecision precision, long max) {
if (estimatedSize != 0) {
return estimatedSize;
}
return estimatedSize = sizeEstimator.getSize();
}
}
static abstract class LuceneResultRowIterator extends AbstractIterator<LuceneResultRow> {
abstract int rewoundCount();
}
}
|
3e162cc9e123c0061bd49ced369d71b7feab3bb2 | 870 | java | Java | src/test/java/me/djin/weixin/api/SnsTest.java | djin-cn/weixin | 50f85cc2b586e58d83c2ce3e5c2a05c2d1fd4ca3 | [
"MIT"
] | null | null | null | src/test/java/me/djin/weixin/api/SnsTest.java | djin-cn/weixin | 50f85cc2b586e58d83c2ce3e5c2a05c2d1fd4ca3 | [
"MIT"
] | null | null | null | src/test/java/me/djin/weixin/api/SnsTest.java | djin-cn/weixin | 50f85cc2b586e58d83c2ce3e5c2a05c2d1fd4ca3 | [
"MIT"
] | null | null | null | 27.1875 | 94 | 0.734483 | 9,435 | package me.djin.weixin.api;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.slf4j.Logger;
import me.djin.weixin.ApiInstance;
import me.djin.weixin.Constant;
import me.djin.weixin.pojo.sns.AccessToken;
public class SnsTest {
private Logger logger = me.djin.weixin.util.Constant.LOGGER;
private Sns svcBaseSns = ApiInstance.createBaseSns();
@Test
public void testGetUserAccessToken() throws Exception {
String code = null;
if (code == null) {
logger.info("没有设置code, 跳过测试!!!");
return;
}
AccessToken response = svcBaseSns.accessToken(Constant.APPID, Constant.APPSECRET, code);
assertNotNull(response);
assertNotNull(response.getErrcode());
if (0 != response.getErrcode()) {
throw new Exception("code:" + response.getErrcode() + ", message:" + response.getErrmsg());
}
logger.info("accessToken获取成功");
}
}
|
3e162ccd15da8eb3b027b63b6137b50eea63410b | 2,653 | java | Java | API/src/main/java/org/sikuli/natives/Vision.java | martianworm17/SikuliX1 | 25d8a380871ceb07ab4f99e2cc56813606f91dbb | [
"MIT"
] | 1 | 2018-03-10T11:10:20.000Z | 2018-03-10T11:10:20.000Z | API/src/main/java/org/sikuli/natives/Vision.java | martianworm17/SikuliX1 | 25d8a380871ceb07ab4f99e2cc56813606f91dbb | [
"MIT"
] | null | null | null | API/src/main/java/org/sikuli/natives/Vision.java | martianworm17/SikuliX1 | 25d8a380871ceb07ab4f99e2cc56813606f91dbb | [
"MIT"
] | null | null | null | 27.926316 | 100 | 0.669431 | 9,436 | /*
* Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.sikuli.natives;
public class Vision {
private long swigCPtr;
protected boolean swigCMemOwn;
protected Vision(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(Vision obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
VisionProxyJNI.delete_Vision(swigCPtr);
}
swigCPtr = 0;
}
}
public static FindResults find(FindInput q) {
return new FindResults(VisionProxyJNI.Vision_find(FindInput.getCPtr(q), q), true);
}
public static FindResults findChanges(FindInput q) {
return new FindResults(VisionProxyJNI.Vision_findChanges(FindInput.getCPtr(q), q), true);
}
public static double compare(Mat m1, Mat m2) {
return VisionProxyJNI.Vision_compare(Mat.getCPtr(m1), m1, Mat.getCPtr(m2), m2);
}
public static void initOCR(String ocrDataPath) {
VisionProxyJNI.Vision_initOCR(ocrDataPath);
}
public static OCRText recognize_as_ocrtext(Mat image) {
return new OCRText(VisionProxyJNI.Vision_recognize_as_ocrtext(Mat.getCPtr(image), image), true);
}
public static String recognize(Mat image) {
return VisionProxyJNI.Vision_recognize(Mat.getCPtr(image), image);
}
public static String recognizeWord(Mat image) {
return VisionProxyJNI.Vision_recognizeWord(Mat.getCPtr(image), image);
}
public static Mat createMat(int _rows, int _cols, byte[] _data) {
return new Mat(VisionProxyJNI.Vision_createMat(_rows, _cols, _data), true);
}
public static void setParameter(String param, float val) {
VisionProxyJNI.Vision_setParameter(param, val);
}
public static float getParameter(String param) {
return VisionProxyJNI.Vision_getParameter(param);
}
public static void setSParameter(String param, String val) {
VisionProxyJNI.Vision_setSParameter(param, val);
}
public static String getSParameter(String param) {
return VisionProxyJNI.Vision_getSParameter(param);
}
public Vision() {
this(VisionProxyJNI.new_Vision(), true);
}
}
|
3e162debaf8230e1e6d2b14f20a145e92fb2df04 | 1,666 | java | Java | src/main/java/org/omg/hw/subnetworkConnection/TPDataList_THelper.java | dong706/CorbaDemo | bcf0826ae8934f91b5e68085605127c2a671ffe3 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/omg/hw/subnetworkConnection/TPDataList_THelper.java | dong706/CorbaDemo | bcf0826ae8934f91b5e68085605127c2a671ffe3 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/omg/hw/subnetworkConnection/TPDataList_THelper.java | dong706/CorbaDemo | bcf0826ae8934f91b5e68085605127c2a671ffe3 | [
"Apache-2.0"
] | null | null | null | 27.766667 | 227 | 0.731092 | 9,437 | package org.omg.hw.subnetworkConnection;
/**
* Generated from IDL definition of alias "TPDataList_T"
* @author JacORB IDL compiler
*/
public final class TPDataList_THelper
{
private static org.omg.CORBA.TypeCode _type = null;
public static void insert (org.omg.CORBA.Any any, org.omg.hw.subnetworkConnection.TPData_T[] s)
{
any.type (type ());
write (any.create_output_stream (), s);
}
public static org.omg.hw.subnetworkConnection.TPData_T[] extract (final org.omg.CORBA.Any any)
{
return read (any.create_input_stream ());
}
public static org.omg.CORBA.TypeCode type ()
{
if (_type == null)
{
_type = org.omg.CORBA.ORB.init().create_alias_tc(org.omg.hw.subnetworkConnection.TPDataList_THelper.id(), "TPDataList_T",org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.hw.subnetworkConnection.TPData_THelper.type()));
}
return _type;
}
public static String id()
{
return "IDL:mtnm.tmforum.org/subnetworkConnection/TPDataList_T:1.0";
}
public static org.omg.hw.subnetworkConnection.TPData_T[] read (final org.omg.CORBA.portable.InputStream _in)
{
org.omg.hw.subnetworkConnection.TPData_T[] _result;
int _l_result7 = _in.read_long();
_result = new org.omg.hw.subnetworkConnection.TPData_T[_l_result7];
for (int i=0;i<_result.length;i++)
{
_result[i]=org.omg.hw.subnetworkConnection.TPData_THelper.read(_in);
}
return _result;
}
public static void write (final org.omg.CORBA.portable.OutputStream _out, org.omg.hw.subnetworkConnection.TPData_T[] _s)
{
_out.write_long(_s.length);
for (int i=0; i<_s.length;i++)
{
org.omg.hw.subnetworkConnection.TPData_THelper.write(_out,_s[i]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.