answer
stringlengths 17
10.2M
|
|---|
package com.gmail.zahusek.packets;
import org.bukkit.entity.Player;
import com.gmail.zahusek.protocols.TinyProtocol;
public abstract class AbstractPacket {
protected Object packet;
protected TinyProtocol tinyprotocol;
protected AbstractPacket(TinyProtocol tinyprotocol) {
this.tinyprotocol = tinyprotocol;
}
public void setPacket(Object p) {
this.packet = p;
}
public void sendPacket(Player receiver) { tinyprotocol.sendPacket(receiver, this.packet); }
public void recievePacket(Player sender) { tinyprotocol.receivePacket(sender, this.packet); }
}
|
package com.icecondor.nest.service;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.icecondor.nest.Condor;
import com.icecondor.nest.Constants;
import com.icecondor.nest.db.activity.HeartBeat;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// can we always assume context is Condor?
Condor condor = (Condor)context;
String action = intent.getAction();
if (action.equals(Constants.ACTION_WAKE_ALARM)) {
Log.i(Constants.APP_TAG, "AlarmReceiver onReceive "+
context.getClass().getSimpleName()+" now "+new Date());
HeartBeat heartBeat = new HeartBeat("");
if(condor.isBatteryValid()){
heartBeat.setBatteryPercentage(condor.getBattPercent());
heartBeat.setPower(condor.getBattAc());
} else {
Log.i(Constants.APP_TAG, "AlarmReceiver onReceive Warning Batt not valid");
}
condor.getDb().append(heartBeat);
condor.binder.onNewActivity();
}
}
}
|
package com.jetbrains.edu.utils;
import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix;
import com.intellij.execution.junit.JUnitExternalLibraryDescriptor;
import com.intellij.ide.IdeView;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.ide.projectView.actions.MarkRootActionBase;
import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard;
import com.intellij.ide.util.newProjectWizard.StepSequence;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.ui.configuration.actions.NewModuleAction;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.util.PathUtil;
import com.intellij.util.io.ZipUtil;
import com.jetbrains.edu.coursecreator.settings.CCSettings;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.learning.core.EduNames;
import com.jetbrains.edu.learning.courseFormat.Course;
import com.jetbrains.edu.learning.courseFormat.tasks.Task;
import com.jetbrains.edu.utils.generation.EduTaskModuleBuilder;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class EduIntellijUtils {
private static final Logger LOG = Logger.getInstance(EduIntellijUtils.class);
private EduIntellijUtils() {
}
public static File getBundledCourseRoot(final String courseName, Class clazz) {
@NonNls String jarPath = PathUtil.getJarPathForClass(clazz);
if (jarPath.endsWith(".jar")) {
final File jarFile = new File(jarPath);
File pluginBaseDir = jarFile.getParentFile();
File coursesDir = new File(pluginBaseDir, "courses");
if (!coursesDir.exists()) {
if (!coursesDir.mkdir()) {
LOG.info("Failed to create courses dir");
} else {
try {
ZipUtil.extract(jarFile, pluginBaseDir, new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(courseName);
}
});
} catch (IOException e) {
LOG.info("Failed to extract default course", e);
}
}
}
return coursesDir;
}
return new File(jarPath, "courses");
}
private static void commitAndSaveModel(final ModifiableRootModel model) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
model.commit();
model.getProject().save();
}
});
}
@Nullable
private static ModifiableRootModel getModel(@NotNull VirtualFile dir, @NotNull Project project) {
final Module module = ModuleUtilCore.findModuleForFile(dir, project);
if (module == null) {
LOG.info("Module for " + dir.getPath() + " was not found");
return null;
}
return ModuleRootManager.getInstance(module).getModifiableModel();
}
static void markDirAsSourceRoot(@NotNull final VirtualFile dir, @NotNull final Project project) {
final ModifiableRootModel model = getModel(dir, project);
if (model == null) {
return;
}
final ContentEntry entry = MarkRootActionBase.findContentEntry(model, dir);
if (entry == null) {
LOG.info("Content entry for " + dir.getPath() + " was not found");
return;
}
entry.addSourceFolder(dir, false);
commitAndSaveModel(model);
}
public static void addTemplate(@NotNull final Project project, @NotNull VirtualFile baseDir, @NotNull @NonNls final String templateName) {
final FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate(templateName);
final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir);
if (projectDir == null) return;
try {
// PsiDirectory utilDir = projectDir.findSubdirectory("util");
// if (utilDir == null) {
// utilDir = projectDir.createSubdirectory("util");
FileTemplateUtil.createFromTemplate(template, templateName, null, projectDir);
} catch (Exception exception) {
LOG.error("Failed to create from file template ", exception);
}
}
public static PsiDirectory createTask(@NotNull Project project, @NotNull Task task, @Nullable IdeView view, @NotNull PsiDirectory parentDirectory,
@Nullable String taskFileName, @Nullable String testFileName) {
String lessonDirName = parentDirectory.getName();
NewModuleAction newModuleAction = new NewModuleAction();
Module lessonModule = ModuleManager.getInstance(project).findModuleByName(lessonDirName);
Module utilModule = ModuleManager.getInstance(project).findModuleByName(EduIntelliJNames.UTIL);
if (lessonModule == null || utilModule == null) {
return null;
}
newModuleAction.createModuleFromWizard(project, null, new AbstractProjectWizard("", project, "") {
@Override
public StepSequence getSequence() {
return null;
}
@Override
public ProjectBuilder getProjectBuilder() {
return new EduTaskModuleBuilder(parentDirectory.getVirtualFile().getPath(), lessonDirName, task, utilModule) {
@Override
protected void createTask(Project project, Course course, VirtualFile src) throws IOException {
PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(src);
if (psiDirectory == null) {
return;
}
createIfNotNull(project, psiDirectory, taskFileName, view);
createIfNotNull(project, psiDirectory, testFileName, view);
}
};
}
});
return parentDirectory.findSubdirectory(EduNames.LESSON + task.getLesson().getIndex() + "-" + EduNames.TASK + task.getIndex());
}
private static void createIfNotNull(@NotNull Project project, @NotNull PsiDirectory psiDirectory, @Nullable String fileName, @Nullable IdeView view) {
if (fileName != null) {
StudyUtils.createFromTemplate(project, psiDirectory, fileName, view, false);
}
}
public static void addJUnit(Module baseModule) {
ExternalLibraryDescriptor descriptor = JUnitExternalLibraryDescriptor.JUNIT4;
List<String> defaultRoots = descriptor.getLibraryClassesRoots();
final List<String> urls = OrderEntryFix.refreshAndConvertToUrls(defaultRoots);
ModuleRootModificationUtil.addModuleLibrary(baseModule, descriptor.getPresentableName(), urls, Collections.emptyList());
}
}
|
package Listeners;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import jrtr.RenderPanel;
import SceneGraph.GraphSceneManager;
public class ShooterMouseMotionListener implements MouseMotionListener{
private int width, height;
private Vector3f v1,v2;
private float theta;
private GraphSceneManager sceneManager;
private RenderPanel renderPanel;
private float deltaX, deltaY;
private float oldXPos, oldYPos;
public ShooterMouseMotionListener(GraphSceneManager sceneManager, RenderPanel renderPanel, int width, int height){
this.sceneManager = sceneManager;
this.renderPanel = renderPanel;
this.width = width;
this.height = height;
}
@Override
public void mouseDragged(MouseEvent e) {}
@Override
public void mouseMoved(MouseEvent e) {
float newXPos = e.getXOnScreen();
this.deltaX = newXPos-oldXPos;
this.oldXPos = newXPos;
float newYPos = e.getYOnScreen();
this.deltaY = newYPos-oldYPos;
this.oldYPos = newYPos;
System.out.println(" shiftX " + (deltaX) + " shiftY " + (deltaY));
Matrix4f camera = sceneManager.getCamera().getCameraMatrix();
Matrix4f rotY = new Matrix4f();
Matrix4f rotZ = new Matrix4f();
rotY.rotY((deltaX)/80);
rotZ.rotZ((deltaY)/1000);
camera.mul(rotY);
camera.mul(rotZ);
sceneManager.getCamera().setCameraMatrix(camera);
// Trigger redrawing of the render window
renderPanel.getCanvas().repaint();
}
}
|
package com.kovaciny.linemonitorbot;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
MenuItem mJobPicker;
MenuItem mLinePicker;
MenuItem mDebugDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mJobPicker = (MenuItem) menu.findItem(R.id.action_pick_job);
mLinePicker = (MenuItem) menu.findItem(R.id.action_pick_line);
mDebugDisplay = (MenuItem) menu.findItem(R.id.debug_display);
mDebugDisplay.setVisible(false);
//populate the line picker with lines
new PopulateMenusTask().execute();
Menu pickLineSubMenu = mLinePicker.getSubMenu();
pickLineSubMenu.clear();
String lineList[] = getResources().getStringArray(R.array.line_list);
for (int i=0; i<lineList.length; i++) {
pickLineSubMenu.add(lineList[i]);
}
//populate the job picker with jobs
Menu pickJobSubMenu = mJobPicker.getSubMenu();
pickJobSubMenu.clear();
String jobList[]= {"Wo #1", "Wo #2"};
int jobListGroup = 0;
for (int i=0; i<jobList.length; i++) {
int menuId = i;
pickJobSubMenu.add(jobListGroup, menuId, Menu.FLAG_APPEND_TO_GROUP, jobList[i]);
}
int jobOptionsGroup = 1;
pickJobSubMenu.add(jobOptionsGroup, R.id.new_wo, Menu.FLAG_APPEND_TO_GROUP, "+ New");
pickJobSubMenu.add(jobOptionsGroup, R.id.clear_wos, Menu.FLAG_APPEND_TO_GROUP, "Clear");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_wo:
item.setTitle("new wo");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a SectionFragment with the page number as its lone argument.
Fragment fragment;
switch(position){
case 0:
fragment = new SkidTimesFragment();
break;
case 1:
fragment = new RatesFragment();
break;
case 2:
fragment = new DrainingFragment();
break;
default:
fragment = new SectionFragment();
}
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class PopulateMenusTask extends AsyncTask<Void,Void,Void> {
//Context mContext;
public PopulateMenusTask() {
super();
//this.mContext = getApplicationContext();
}
@Override
protected Void doInBackground(Void... arg0) {
// using mContext
SystemClock.sleep(5000);
return null;
}
@Override
protected void onPostExecute(Void result) {
mLinePicker.setTitle("Async complete");
super.onPostExecute(result);
}
}
}
|
package com.lonkal.convexhullapp.main;
import java.awt.Point;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Graham Scan algorithm 1. Sorts the points based on angle 2. Push point if
* Left turn 3. Pop point if Right turn
*
* @author Kal
*
*/
public class GrahamScan extends ConvexHullAlgo {
private LinkedList<Point> stepPointList;
private int i = 2; // starts at the "3rd" array element
private boolean isDone;
private Point lowestRightestPt;
private Point p, q, r;
public GrahamScan(LinkedList<Point> list) {
super(list);
stepPointList = new LinkedList<Point>();
init();
}
private class AngleComparator implements Comparator<Point> {
private Point comparisonPoint; // assume it is lowest
public AngleComparator(Point cp) {
comparisonPoint = cp;
}
@Override
public int compare(Point p1, Point p2) {
// comparisonPoint is default bigger then anything, to be at the end
if (p1 == comparisonPoint) {
return 1;
} else if (p2 == comparisonPoint) {
return -1;
}
// Basically, the angle of the points are calculated from the the
// comparisonPoint
// But if the point lies further left of the point, we look at the
// right side angle instead
// by doing pi - the left side angle
Double angleOfP1 = Math.atan(Math.abs(p1.getY()
- comparisonPoint.getY())
/ Math.abs(p1.getX() - comparisonPoint.getX()));
if (p1.getX() < comparisonPoint.getX()) {
angleOfP1 = Math.PI - angleOfP1;
}
Double angleOfP2 = Math.atan(Math.abs(p2.getY()
- comparisonPoint.getY())
/ Math.abs(p2.getX() - comparisonPoint.getX()));
if (p2.getX() < comparisonPoint.getX()) {
angleOfP2 = Math.PI - angleOfP2;
}
// We are forced to do this since the values are doubles
// and the difference could be below 1 which means it gets
// casted to 0 :(
if (angleOfP1 > angleOfP2) {
return 1;
} else if (angleOfP2 > angleOfP1) {
return -1;
} else {
// The point with lesser X is considered "bigger" in the
// sorting of angles
if (p1.getX() < p2.getX()) {
return 1;
} else if (p2.getX() > p1.getX()) {
return -1;
} else {
return 0;
}
}
}
}
@Override
protected void init() {
// Find lowest and bottommost point
Iterator<Point> it = pointList.iterator();
lowestRightestPt = pointList.getFirst();
while (it.hasNext()) {
Point p = it.next();
if (p.y > lowestRightestPt.y) {
lowestRightestPt = p;
} else if (p.y == lowestRightestPt.y) {
lowestRightestPt = (lowestRightestPt.x > p.x) ? lowestRightestPt
: p;
}
}
// Sort all points based on angle
Collections.sort(pointList, new AngleComparator(lowestRightestPt));
convexHullList.add(lowestRightestPt);
convexHullList.add(pointList.getFirst());
convexHullList.add(pointList.get(1));
}
@Override
public void step() {
if (isDone) {
return;
}
stepNum++;
if (i >= pointList.size()) {
isDone = true;
convexHullList.add(lowestRightestPt);
pointList.add(lowestRightestPt); // Add it back so it is rendered
return;
}
p = convexHullList.get(convexHullList.size() - 2);
q = convexHullList.get(convexHullList.size() - 1);
r = pointList.get(i);
if (Primitives.orientation(p, q, r) <= 1 || i == pointList.size() - 1) {
convexHullList.add(r); // Push because it's a left turn
i++;
} else if (Primitives.orientation(p, q, r) == 2) {
convexHullList.remove(q); // Pop off the chain
}
}
@Override
public boolean isDone() {
return isDone;
}
@Override
public Line getCurrentStepLine() {
return null;
}
@Override
public LinkedList<Point> getCurrentStepPoints() {
if (p == null || q == null || r == null) {
return null;
}
stepPointList.clear();
stepPointList.add(p);
stepPointList.add(q);
stepPointList.add(r);
return stepPointList;
}
}
|
package com.maddyhome.idea.vim.group;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actionSystem.ActionPlan;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.editor.actionSystem.TypedActionHandlerEx;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.impl.TextRangeInterval;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.maddyhome.idea.vim.EventFacade;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.*;
import com.maddyhome.idea.vim.common.Register;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.ex.LineRange;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.option.BoundListOption;
import com.maddyhome.idea.vim.option.Options;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Provides all the insert/replace related functionality
* TODO - change cursor for the different modes
*/
public class ChangeGroup {
public static final int MAX_REPEAT_CHARS_COUNT = 10000;
private static final String VIM_MOTION_BIG_WORD_RIGHT = "VimMotionBigWordRight";
private static final String VIM_MOTION_WORD_RIGHT = "VimMotionWordRight";
private static final String VIM_MOTION_CAMEL_RIGHT = "VimMotionCamelRight";
private static final String VIM_MOTION_WORD_END_RIGHT = "VimMotionWordEndRight";
private static final String VIM_MOTION_BIG_WORD_END_RIGHT = "VimMotionBigWordEndRight";
private static final String VIM_MOTION_CAMEL_END_RIGHT = "VimMotionCamelEndRight";
/**
* Creates the group
*/
public ChangeGroup() {
// We want to know when a user clicks the mouse somewhere in the editor so we can clear any
// saved text for the current insert mode.
final EventFacade eventFacade = EventFacade.getInstance();
eventFacade.addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
eventFacade.addEditorMouseListener(editor, listener);
EditorData.setChangeGroup(editor, true);
}
public void editorReleased(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
if (EditorData.getChangeGroup(editor)) {
eventFacade.removeEditorMouseListener(editor, listener);
EditorData.setChangeGroup(editor, false);
}
}
@NotNull
private final EditorMouseAdapter listener = new EditorMouseAdapter() {
public void mouseClicked(@NotNull EditorMouseEvent event) {
Editor editor = event.getEditor();
if (!VimPlugin.isEnabled()) {
return;
}
if (CommandState.inInsertMode(editor)) {
clearStrokes(editor);
}
}
};
}, ApplicationManager.getApplication());
}
public void setInsertRepeat(int lines, int column, boolean append) {
repeatLines = lines;
repeatColumn = column;
repeatAppend = append;
}
/**
* Begin insert before the cursor position
*
* @param editor The editor to insert into
* @param context The data context
*/
public void insertBeforeCursor(@NotNull Editor editor, @NotNull DataContext context) {
initInsert(editor, context, CommandState.Mode.INSERT);
}
/**
* Begin insert before the first non-blank on the current line
*
* @param editor The editor to insert into
*/
public void insertBeforeFirstNonBlank(@NotNull Editor editor, @NotNull DataContext context) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret));
}
initInsert(editor, context, CommandState.Mode.INSERT);
}
/**
* Begin insert before the start of the current line
*
* @param editor The editor to insert into
* @param context The data context
*/
public void insertLineStart(@NotNull Editor editor, @NotNull DataContext context) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStart(editor, caret));
}
initInsert(editor, context, CommandState.Mode.INSERT);
}
/**
* Begin insert after the cursor position
*
* @param editor The editor to insert into
* @param context The data context
*/
public void insertAfterCursor(@NotNull Editor editor, @NotNull DataContext context) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretHorizontal(editor, caret, 1, true));
}
initInsert(editor, context, CommandState.Mode.INSERT);
}
public void insertAfterLineEnd(@NotNull Editor editor, @NotNull DataContext context) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
}
initInsert(editor, context, CommandState.Mode.INSERT);
}
/**
* Begin insert before the current line by creating a new blank line above the current line
* for all carets
*
* @param editor The editor to insert into
*/
public void insertNewLineAbove(@NotNull final Editor editor, @NotNull DataContext context) {
if (editor.isOneLineMode()) return;
for (Caret caret : editor.getCaretModel().getAllCarets()) {
if (caret.getVisualPosition().line == 0) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStart(editor, caret));
CaretData.setWasInFirstLine(caret, true);
}
else {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretVertical(editor, caret, -1));
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
}
}
initInsert(editor, context, CommandState.Mode.INSERT);
runEnterAction(editor, context);
for (Caret caret : editor.getCaretModel().getAllCarets()) {
if (CaretData.wasInFirstLine(caret)) {
CaretData.setWasInFirstLine(caret, false);
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretVertical(editor, caret, -1));
}
}
}
/**
* Inserts a new line above the caret position
*
* @param editor The editor to insert into
* @param caret The caret to insert above
* @param col The column to indent to
*/
private void insertNewLineAbove(@NotNull Editor editor, @NotNull Caret caret, int col) {
if (editor.isOneLineMode()) return;
if (caret.getVisualPosition().line == 0) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStart(editor, caret));
CaretData.setWasInFirstLine(caret, true);
}
else {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretVertical(editor, caret, -1));
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
}
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
insertText(editor, caret, "\n" + StringUtil.repeat(" ", col));
if (CaretData.wasInFirstLine(caret)) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretVertical(editor, caret, -1));
CaretData.setWasInFirstLine(caret, false);
}
}
/**
* Begin insert after the current line by creating a new blank line below the current line
* for all carets
*
* @param editor The editor to insert into
* @param context The data context
*/
public void insertNewLineBelow(@NotNull final Editor editor, @NotNull final DataContext context) {
if (editor.isOneLineMode()) return;
for (Caret caret : editor.getCaretModel().getAllCarets()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
}
initInsert(editor, context, CommandState.Mode.INSERT);
runEnterAction(editor, context);
}
/**
* Inserts a new line below the caret position
*
* @param editor The editor to insert into
* @param caret The caret to insert after
* @param col The column to indent to
*/
private void insertNewLineBelow(@NotNull Editor editor, @NotNull Caret caret, int col) {
if (editor.isOneLineMode()) return;
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
insertText(editor, caret, "\n" + StringUtil.repeat(" ", col));
}
private void runEnterAction(Editor editor, @NotNull DataContext context) {
CommandState state = CommandState.getInstance(editor);
if (state.getMode() != CommandState.Mode.REPEAT) {
final ActionManager actionManager = ActionManager.getInstance();
final AnAction action = actionManager.getAction("EditorEnter");
if (action != null) {
strokes.add(action);
KeyHandler.executeAction(action, context);
}
}
}
/**
* Begin insert at the location of the previous insert
*
* @param editor The editor to insert into
*/
public void insertAtPreviousInsert(@NotNull Editor editor, @NotNull DataContext context) {
editor.getCaretModel().removeSecondaryCarets();
final Caret caret = editor.getCaretModel().getPrimaryCaret();
final int offset = VimPlugin.getMotion().moveCaretToMark(editor, caret, '^');
if (offset != -1) {
MotionGroup.moveCaret(editor, caret, offset);
}
insertAfterCursor(editor, context);
}
/**
* Inserts previously inserted text
*
* @param editor The editor to insert into
* @param context The data context
* @param exit true if insert mode should be exited after the insert, false should stay in insert mode
*/
public void insertPreviousInsert(@NotNull Editor editor, @NotNull DataContext context, boolean exit) {
repeatInsertText(editor, context, 1);
if (exit) {
processEscape(editor, context);
}
}
/**
* Inserts the contents of the specified register
*
* @param editor The editor to insert the text into
* @param context The data context
* @param key The register name
* @return true if able to insert the register contents, false if not
*/
public boolean insertRegister(@NotNull Editor editor, @NotNull DataContext context, char key) {
final Register register = VimPlugin.getRegister().getRegister(key);
if (register != null) {
final String text = register.getText();
if (text != null) {
final int length = text.length();
for (int i = 0; i < length; i++) {
processKey(editor, context, KeyStroke.getKeyStroke(text.charAt(i)));
}
return true;
}
}
return false;
}
/**
* Inserts the character above/below the cursor at the cursor location
*
* @param editor The editor to insert into
* @param caret The caret to insert after
* @param context The data context
* @param dir 1 for getting from line below cursor, -1 for getting from line above cursor
* @return true if able to get the character and insert it, false if not
*/
public boolean insertCharacterAroundCursor(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
int dir) {
boolean res = false;
VisualPosition vp = caret.getVisualPosition();
vp = new VisualPosition(vp.line + dir, vp.column);
int len = EditorHelper.getLineLength(editor, EditorHelper.visualLineToLogicalLine(editor, vp.line));
if (vp.column < len) {
int offset = EditorHelper.visualPositionToOffset(editor, vp);
char ch = editor.getDocument().getCharsSequence().charAt(offset);
editor.getDocument().insertString(caret.getOffset(), Character.toString(ch));
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretHorizontal(editor, caret, 1, true));
res = true;
}
return res;
}
/**
* If the cursor is currently after the start of the current insert this deletes all the newly inserted text.
* Otherwise it deletes all text from the cursor back to the first non-blank in the line.
*
* @param editor The editor to delete the text from
* @param caret The caret on which the action is performed
* @return true if able to delete the text, false if not
*/
public boolean insertDeleteInsertedText(@NotNull Editor editor, @NotNull Caret caret) {
int deleteTo = CaretData.getInsertStart(caret);
int offset = caret.getOffset();
if (offset == deleteTo) {
deleteTo = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret);
}
if (deleteTo != -1) {
deleteRange(editor, caret, new TextRange(deleteTo, offset), SelectionType.CHARACTER_WISE, false);
return true;
}
return false;
}
/**
* Deletes the text from the cursor to the start of the previous word
*
* @param editor The editor to delete the text from
* @return true if able to delete text, false if not
*/
public boolean insertDeletePreviousWord(@NotNull Editor editor, @NotNull Caret caret) {
final int deleteTo = VimPlugin.getMotion().moveCaretToNextWord(editor, caret, -1, false);
if (deleteTo == -1) {
return false;
}
final TextRange range = new TextRange(deleteTo, caret.getOffset());
deleteRange(editor, caret, range, SelectionType.CHARACTER_WISE, true);
return true;
}
/**
* Begin insert/replace mode
*
* @param editor The editor to insert into
* @param context The data context
* @param mode The mode - indicate insert or replace
*/
private void initInsert(@NotNull Editor editor, @NotNull DataContext context, @NotNull CommandState.Mode mode) {
final CommandState state = CommandState.getInstance(editor);
for (Caret caret : editor.getCaretModel().getAllCarets()) {
CaretData.setInsertStart(caret, caret.getOffset());
}
final Command cmd = state.getCommand();
if (cmd != null && state.getMode() == CommandState.Mode.REPEAT) {
if (mode == CommandState.Mode.REPLACE) {
processInsert(editor, context);
}
if ((cmd.getFlags() & Command.FLAG_NO_REPEAT) != 0) {
repeatInsert(editor, context, 1, false);
}
else {
repeatInsert(editor, context, cmd.getCount(), false);
}
if (mode == CommandState.Mode.REPLACE) {
processInsert(editor, context);
}
}
else {
lastInsert = cmd;
strokes.clear();
repeatCharsCount = 0;
final EventFacade eventFacade = EventFacade.getInstance();
if (document != null && documentListener != null) {
eventFacade.removeDocumentListener(document, documentListener);
}
document = editor.getDocument();
documentListener = new InsertActionsDocumentListener();
eventFacade.addDocumentListener(document, documentListener);
oldOffset = -1;
inInsert = true;
if (mode == CommandState.Mode.REPLACE) {
processInsert(editor, context);
}
state.pushState(mode, CommandState.SubMode.NONE, MappingMode.INSERT);
resetCursor(editor, true);
}
}
/**
* Performs a mode switch after change action
*
* @param editor The editor to switch mode in
* @param context The data context
* @param toSwitch The mode to switch to
*/
public void processPostChangeModeSwitch(@NotNull Editor editor, @NotNull DataContext context,
@NotNull CommandState.Mode toSwitch) {
if (toSwitch == CommandState.Mode.INSERT) {
initInsert(editor, context, toSwitch);
}
}
private class InsertActionsDocumentListener extends DocumentAdapter {
@Override
public void documentChanged(@NotNull DocumentEvent e) {
final String newFragment = e.getNewFragment().toString();
final String oldFragment = e.getOldFragment().toString();
final int newFragmentLength = newFragment.length();
final int oldFragmentLength = oldFragment.length();
// Repeat buffer limits
if (repeatCharsCount > MAX_REPEAT_CHARS_COUNT) {
return;
}
// <Enter> is added to strokes as an action during processing in order to indent code properly in the repeat
// command
if (newFragment.startsWith("\n") && newFragment.trim().isEmpty()) {
strokes.addAll(getAdjustCaretActions(e));
oldOffset = -1;
return;
}
// Ignore multi-character indents as they should be inserted automatically while repeating <Enter> actions
if (newFragmentLength > 1 && newFragment.trim().isEmpty()) {
return;
}
strokes.addAll(getAdjustCaretActions(e));
if (oldFragmentLength > 0) {
final AnAction editorDelete = ActionManager.getInstance().getAction("EditorDelete");
for (int i = 0; i < oldFragmentLength; i++) {
strokes.add(editorDelete);
}
}
if (newFragmentLength > 0) {
strokes.add(newFragment.toCharArray());
}
repeatCharsCount += newFragmentLength;
oldOffset = e.getOffset() + newFragmentLength;
}
@NotNull
private List<AnAction> getAdjustCaretActions(@NotNull DocumentEvent e) {
final int delta = e.getOffset() - oldOffset;
if (oldOffset >= 0 && delta != 0) {
final List<AnAction> positionCaretActions = new ArrayList<AnAction>();
final String motionName = delta < 0 ? "VimMotionLeft" : "VimMotionRight";
final AnAction action = ActionManager.getInstance().getAction(motionName);
final int count = Math.abs(delta);
for (int i = 0; i < count; i++) {
positionCaretActions.add(action);
}
return positionCaretActions;
}
return Collections.emptyList();
}
}
/**
* This repeats the previous insert count times
*
* @param editor The editor to insert into
* @param context The data context
* @param count The number of times to repeat the previous insert
*/
private void repeatInsert(@NotNull Editor editor, @NotNull DataContext context, int count, boolean started) {
for (Caret caret : editor.getCaretModel().getAllCarets()) {
if (repeatLines > 0) {
final int visualLine = caret.getVisualPosition().line;
final int logicalLine = caret.getLogicalPosition().line;
final int position = editor.logicalPositionToOffset(new LogicalPosition(logicalLine, repeatColumn));
for (int i = 0; i < repeatLines; i++) {
if (repeatAppend && repeatColumn < MotionGroup.LAST_COLUMN &&
EditorHelper.getVisualLineLength(editor, visualLine + i) < repeatColumn) {
final String pad = EditorHelper.pad(editor, context, logicalLine + i, repeatColumn);
if (pad.length() > 0) {
final int offset = editor.getDocument().getLineEndOffset(logicalLine + i);
caret.moveToOffset(offset);
insertText(editor, caret, pad);
}
}
if (repeatColumn > MotionGroup.LAST_COLUMN) {
caret.moveToOffset(VimPlugin.getMotion().moveCaretToLineEnd(editor, logicalLine + i, true));
repeatInsertText(editor, context, started ? (i == 0 ? count : count + 1) : count);
}
else if (EditorHelper.getVisualLineLength(editor, visualLine + i) >= repeatColumn) {
caret.moveToVisualPosition(new VisualPosition(visualLine + i, repeatColumn));
repeatInsertText(editor, context, started ? (i == 0 ? count : count + 1) : count);
}
}
MotionGroup.moveCaret(editor, caret, position);
}
else {
repeatInsertText(editor, context, count);
final int position = VimPlugin.getMotion().moveCaretHorizontal(editor, caret, -1, false);
MotionGroup.moveCaret(editor, caret, position);
}
}
repeatLines = 0;
repeatColumn = 0;
repeatAppend = false;
}
/**
* This repeats the previous insert count times
*
* @param editor The editor to insert into
* @param context The data context
* @param count The number of times to repeat the previous insert
*/
private void repeatInsertText(@NotNull Editor editor, @NotNull DataContext context, int count) {
if (lastStrokes == null) {
return;
}
for (Caret caret : editor.getCaretModel().getAllCarets()) {
for (int i = 0; i < count; i++) {
for (Object lastStroke : lastStrokes) {
if (lastStroke instanceof AnAction) {
KeyHandler.executeAction((AnAction)lastStroke, context);
strokes.add(lastStroke);
}
else if (lastStroke instanceof char[]) {
final char[] chars = (char[])lastStroke;
insertText(editor, caret, new String(chars));
}
}
}
}
}
/**
* Terminate insert/replace mode after the user presses Escape or Ctrl-C
*
* @param editor The editor that was being edited
* @param context The data context
*/
public void processEscape(@NotNull Editor editor, @NotNull DataContext context) {
int cnt = lastInsert != null ? lastInsert.getCount() : 0;
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) {
KeyHandler.executeAction("VimInsertReplaceToggle", context);
}
if (lastInsert != null && (lastInsert.getFlags() & Command.FLAG_NO_REPEAT) != 0) {
cnt = 1;
}
if (document != null && documentListener != null) {
EventFacade.getInstance().removeDocumentListener(document, documentListener);
documentListener = null;
}
lastStrokes = new ArrayList<>(strokes);
repeatInsert(editor, context, cnt == 0 ? 0 : cnt - 1, true);
final MarkGroup markGroup = VimPlugin.getMark();
final int offset = editor.getCaretModel().getPrimaryCaret().getOffset();
markGroup.setMark(editor, '^', offset);
markGroup.setMark(editor, MarkGroup.MARK_CHANGE_END, offset);
markGroup.setMark(editor, MarkGroup.MARK_CHANGE_POS, offset);
CommandState.getInstance(editor).popState();
if (!CommandState.inInsertMode(editor)) {
resetCursor(editor, false);
}
}
/**
* Processes the Enter key by running the first successful action registered for "ENTER" keystroke.
* <p>
* If this is REPLACE mode we need to turn off OVERWRITE before and then turn OVERWRITE back on after sending the
* "ENTER" key.
*
* @param editor The editor to press "Enter" in
* @param context The data context
*/
public void processEnter(@NotNull Editor editor, @NotNull DataContext context) {
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) {
KeyHandler.executeAction("EditorToggleInsertState", context);
}
final KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
final List<AnAction> actions = VimPlugin.getKey().getActions(editor.getComponent(), enterKeyStroke);
for (AnAction action : actions) {
if (KeyHandler.executeAction(action, context)) {
break;
}
}
if (CommandState.getInstance(editor).getMode() == CommandState.Mode.REPLACE) {
KeyHandler.executeAction("EditorToggleInsertState", context);
}
}
/**
* Processes the user pressing the Insert key while in INSERT or REPLACE mode. This simply toggles the
* Insert/Overwrite state which updates the status bar.
*
* @param editor The editor to toggle the state in
* @param context The data context
*/
public void processInsert(Editor editor, @NotNull DataContext context) {
KeyHandler.executeAction("EditorToggleInsertState", context);
CommandState.getInstance(editor).toggleInsertOverwrite();
inInsert = !inInsert;
}
/**
* While in INSERT or REPLACE mode the user can enter a single NORMAL mode command and then automatically
* return to INSERT or REPLACE mode.
*
* @param editor The editor to put into NORMAL mode for one command
*/
public void processSingleCommand(@NotNull Editor editor) {
CommandState.getInstance(editor).pushState(CommandState.Mode.COMMAND, CommandState.SubMode.SINGLE_COMMAND,
MappingMode.NORMAL);
clearStrokes(editor);
}
/**
* Drafts an {@link ActionPlan} for preemptive rendering before "regular" keystroke processing in insert/replace mode.
* <p>
* Like {@link #processKey(Editor, DataContext, KeyStroke)}, delegates the task to the original handler.
*
* @param editor The editor the character was typed into
* @param context The data context
* @param key The user entered keystroke
* @param plan the current action plan draft
*/
public void beforeProcessKey(@NotNull final Editor editor, @NotNull final DataContext context,
@NotNull final KeyStroke key, @NotNull ActionPlan plan) {
final TypedActionHandler originalHandler = KeyHandler.getInstance().getOriginalHandler();
if (originalHandler instanceof TypedActionHandlerEx) {
((TypedActionHandlerEx)originalHandler).beforeExecute(editor, key.getKeyChar(), context, plan);
}
}
/**
* This processes all "regular" keystrokes entered while in insert/replace mode
*
* @param editor The editor the character was typed into
* @param context The data context
* @param key The user entered keystroke
* @return true if this was a regular character, false if not
*/
public boolean processKey(@NotNull final Editor editor, @NotNull final DataContext context,
@NotNull final KeyStroke key) {
if (logger.isDebugEnabled()) {
logger.debug("processKey(" + key + ")");
}
if (key.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
final Document doc = editor.getDocument();
CommandProcessor.getInstance().executeCommand(editor.getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
KeyHandler.getInstance().getOriginalHandler().execute(editor, key.getKeyChar(), context);
}
});
}
}, "", doc, UndoConfirmationPolicy.DEFAULT, doc);
return true;
}
return false;
}
/**
* This processes all keystrokes in Insert/Replace mode that were converted into Commands. Some of these
* commands need to be saved off so the inserted/replaced text can be repeated properly later if needed.
*
* @param editor The editor the command was executed in
* @param cmd The command that was executed
* @return true if the command was stored for later repeat, false if not
*/
public boolean processCommand(@NotNull Editor editor, @NotNull Command cmd) {
if ((cmd.getFlags() & Command.FLAG_SAVE_STROKE) != 0) {
strokes.add(cmd.getAction());
return true;
}
else if ((cmd.getFlags() & Command.FLAG_CLEAR_STROKES) != 0) {
clearStrokes(editor);
return false;
}
else {
return false;
}
}
/**
* Clears all the keystrokes from the current insert command
*
* @param editor The editor to clear strokes from.
*/
private void clearStrokes(@NotNull Editor editor) {
strokes.clear();
repeatCharsCount = 0;
for (Caret caret : editor.getCaretModel().getAllCarets()) {
CaretData.setInsertStart(caret, caret.getOffset());
}
}
/**
* Deletes count character after the caret from the editor
*
* @param editor The editor to remove characters from
* @param caret The caret on which the operation is performed
* @param count The numbers of characters to delete.
* @return true if able to delete, false if not
*/
public boolean deleteCharacter(@NotNull Editor editor, @NotNull Caret caret, int count, boolean isChange) {
int offset = VimPlugin.getMotion().moveCaretHorizontal(editor, caret, count, true);
if (offset != -1) {
boolean res = deleteText(editor, new TextRange(caret.getOffset(), offset), SelectionType.CHARACTER_WISE);
int pos = caret.getOffset();
int norm = EditorHelper.normalizeOffset(editor, caret.getLogicalPosition().line, pos, isChange);
if (norm != pos) {
MotionGroup.moveCaret(editor, caret, norm);
}
return res;
}
return false;
}
/**
* Deletes count lines including the current line
*
* @param editor The editor to remove the lines from
* @param count The number of lines to delete
* @return true if able to delete the lines, false if not
*/
public boolean deleteLine(@NotNull Editor editor, @NotNull Caret caret, int count) {
int start = VimPlugin.getMotion().moveCaretToLineStart(editor, caret);
int offset = Math.min(VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, count - 1, true) + 1,
EditorHelper.getFileSize(editor, true));
if (logger.isDebugEnabled()) {
logger.debug("start=" + start);
logger.debug("offset=" + offset);
}
if (offset != -1) {
boolean res = deleteText(editor, new TextRange(start, offset), SelectionType.LINE_WISE);
if (res && caret.getOffset() >= EditorHelper.getFileSize(editor) && caret.getOffset() != 0) {
MotionGroup.moveCaret(editor, caret,
VimPlugin.getMotion().moveCaretToLineStartSkipLeadingOffset(editor, caret, -1));
}
return res;
}
return false;
}
/**
* Delete from the cursor to the end of count - 1 lines down
*
* @param editor The editor to delete from
* @param caret Caret on the position to start
* @param count The number of lines affected
* @return true if able to delete the text, false if not
*/
public boolean deleteEndOfLine(@NotNull Editor editor, @NotNull Caret caret, int count) {
int offset = VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, count - 1, true);
if (offset != -1) {
boolean res = deleteText(editor, new TextRange(caret.getOffset(), offset), SelectionType.CHARACTER_WISE);
int pos = VimPlugin.getMotion().moveCaretHorizontal(editor, caret, -1, false);
if (pos != -1) {
MotionGroup.moveCaret(editor, caret, pos);
}
return res;
}
return false;
}
/**
* Joins count lines together starting at the cursor. No count or a count of one still joins two lines.
*
* @param editor The editor to join the lines in
* @param caret The caret in the first line to be joined.
* @param count The number of lines to join
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
public boolean deleteJoinLines(@NotNull Editor editor, @NotNull Caret caret, int count, boolean spaces) {
if (count < 2) count = 2;
int lline = caret.getLogicalPosition().line;
int total = EditorHelper.getLineCount(editor);
//noinspection SimplifiableIfStatement
if (lline + count > total) {
return false;
}
return deleteJoinNLines(editor, caret, lline, count, spaces);
}
/**
* Joins all the lines selected by the current visual selection.
*
* @param editor The editor to join the lines in
* @param caret The caret to be moved after joining
* @param range The range of the visual selection
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
public boolean deleteJoinRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull TextRange range,
boolean spaces) {
int startLine = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int endLine = editor.offsetToLogicalPosition(range.getEndOffset()).line;
int count = endLine - startLine + 1;
if (count < 2) count = 2;
return deleteJoinNLines(editor, caret, startLine, count, spaces);
}
/**
* This does the actual joining of the lines
*
* @param editor The editor to join the lines in
* @param caret The caret on the starting line (to be moved)
* @param startLine The starting logical line
* @param count The number of lines to join including startLine
* @param spaces If true the joined lines will have one space between them and any leading space on the second line
* will be removed. If false, only the newline is removed to join the lines.
* @return true if able to join the lines, false if not
*/
private boolean deleteJoinNLines(@NotNull Editor editor, @NotNull Caret caret, int startLine, int count,
boolean spaces) {
// start my moving the cursor to the very end of the first line
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, startLine, true), true);
for (int i = 1; i < count; i++) {
int start = VimPlugin.getMotion().moveCaretToLineEnd(editor, caret);
int trailingWhitespaceStart = VimPlugin.getMotion().moveCaretToLineEndSkipLeadingOffset(editor, caret, 0);
boolean hasTrailingWhitespace = start != trailingWhitespaceStart + 1;
MotionGroup.moveCaret(editor, caret, start, true);
int offset;
if (spaces) {
offset = VimPlugin.getMotion().moveCaretToLineStartSkipLeadingOffset(editor, caret, 1);
}
else {
offset = VimPlugin.getMotion().moveCaretToLineStart(editor, caret.getLogicalPosition().line + 1);
}
deleteText(editor, new TextRange(caret.getOffset(), offset), null);
if (spaces && !hasTrailingWhitespace) {
insertText(editor, caret, " ");
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretHorizontal(editor, caret, -1, true), true);
}
}
return true;
}
/**
* Delete all text moved over by the supplied motion command argument.
*
* @param editor The editor to delete the text from
* @param caret The caret on which the motion appears to be performed
* @param context The data context
* @param count The number of times to repeat the deletion
* @param rawCount The actual count entered by the user
* @param argument The motion command
* @param isChange if from a change
* @return true if able to delete the text, false if not
*/
public boolean deleteMotion(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count,
int rawCount, @NotNull final Argument argument, boolean isChange) {
final TextRange range = getDeleteMotionRange(editor, caret, context, count, rawCount, argument);
if (range == null) {
return (EditorHelper.getFileSize(editor) == 0);
}
// Delete motion commands that are not linewise become linewise if all the following are true:
// 1) The range is across multiple lines
// 2) There is only whitespace before the start of the range
// 3) There is only whitespace after the end of the range
final Command motion = argument.getMotion();
if (motion == null) {
return false;
}
if (!isChange && (motion.getFlags() & Command.FLAG_MOT_LINEWISE) == 0) {
LogicalPosition start = editor.offsetToLogicalPosition(range.getStartOffset());
LogicalPosition end = editor.offsetToLogicalPosition(range.getEndOffset());
if (start.line != end.line) {
if (!SearchHelper.anyNonWhitespace(editor, range.getStartOffset(), -1) &&
!SearchHelper.anyNonWhitespace(editor, range.getEndOffset(), 1)) {
int flags = motion.getFlags();
flags &= ~Command.FLAG_MOT_EXCLUSIVE;
flags &= ~Command.FLAG_MOT_INCLUSIVE;
flags |= Command.FLAG_MOT_LINEWISE;
motion.setFlags(flags);
}
}
}
return deleteRange(editor, caret, range, SelectionType.fromCommandFlags(motion.getFlags()), isChange);
}
@Nullable
private static TextRange getDeleteMotionRange(@NotNull Editor editor, @NotNull Caret caret,
@NotNull DataContext context, int count, int rawCount,
@NotNull Argument argument) {
TextRange range = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, true);
// This is a kludge for dw, dW, and d[w. Without this kludge, an extra newline is deleted when it shouldn't be.
if (range != null) {
String text = editor.getDocument().getCharsSequence().subSequence(range.getStartOffset(),
range.getEndOffset()).toString();
final int lastNewLine = text.lastIndexOf('\n');
if (lastNewLine > 0) {
final Command motion = argument.getMotion();
if (motion != null) {
final String id = ActionManager.getInstance().getId(motion.getAction());
if (id.equals(VIM_MOTION_WORD_RIGHT) ||
id.equals(VIM_MOTION_BIG_WORD_RIGHT) ||
id.equals(VIM_MOTION_CAMEL_RIGHT)) {
if (!SearchHelper.anyNonWhitespace(editor, range.getEndOffset(), -1)) {
final int start = range.getStartOffset();
range = new TextRange(start, start + lastNewLine);
}
}
}
}
}
return range;
}
/**
* Delete the range of text.
*
* @param editor The editor to delete the text from
* @param range The range to delete
* @param type The type of deletion
* @param isChange is from a change action
* @return true if able to delete the text, false if not
* @deprecated Use {@link #deleteRange(Editor, Caret, TextRange, SelectionType, boolean)}
*/
public boolean deleteRange(@NotNull Editor editor, @NotNull TextRange range, @Nullable SelectionType type,
boolean isChange) {
return deleteRange(editor, editor.getCaretModel().getPrimaryCaret(), range, type, isChange);
}
/**
* Delete the range of text.
*
* @param editor The editor to delete the text from
* @param caret The caret to be moved after deletion
* @param range The range to delete
* @param type The type of deletion
* @param isChange Is from a change action
* @return true if able to delete the text, false if not
*/
public boolean deleteRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull TextRange range,
@Nullable SelectionType type, boolean isChange) {
final boolean res = deleteText(editor, range, type);
final int size = EditorHelper.getFileSize(editor);
if (res) {
final int pos;
if (caret.getOffset() > size) {
pos = size - 1;
}
else {
pos = EditorHelper.normalizeOffset(editor, range.getStartOffset(), isChange);
}
MotionGroup.moveCaret(editor, caret, pos, true);
}
return res;
}
/**
* Begin Replace mode
*
* @param editor The editor to replace in
* @param context The data context
*/
public void changeReplace(@NotNull Editor editor, @NotNull DataContext context) {
initInsert(editor, context, CommandState.Mode.REPLACE);
}
/**
* Replace each of the next count characters with the character ch
*
* @param editor The editor to change
* @param caret The caret to perform action on
* @param count The number of characters to change
* @param ch The character to change to
* @return true if able to change count characters, false if not
*/
public boolean changeCharacter(@NotNull Editor editor, @NotNull Caret caret, int count, char ch) {
int col = caret.getLogicalPosition().column;
int len = EditorHelper.getLineLength(editor);
int offset = caret.getOffset();
if (len - col < count) {
return false;
}
// Special case - if char is newline, only add one despite count
int num = count;
String space = null;
if (ch == '\n') {
num = 1;
space = EditorHelper.getLeadingWhitespace(editor, editor.offsetToLogicalPosition(offset).line);
if (logger.isDebugEnabled()) {
logger.debug("space='" + space + "'");
}
}
StringBuilder repl = new StringBuilder(count);
for (int i = 0; i < num; i++) {
repl.append(ch);
}
replaceText(editor, offset, offset + count, repl.toString());
// Indent new line if we replaced with a newline
if (ch == '\n') {
caret.moveToOffset(offset + 1);
insertText(editor, caret, space);
int slen = space.length();
if (slen == 0) {
slen++;
}
caret.moveToOffset(offset + slen);
}
return true;
}
/**
* Each character in the supplied range gets replaced with the character ch
*
* @param editor The editor to change
* @param range The range to change
* @param ch The replacing character
* @return true if able to change the range, false if not
*/
public boolean changeCharacterRange(@NotNull Editor editor, @NotNull TextRange range, char ch) {
if (logger.isDebugEnabled()) {
logger.debug("change range: " + range + " to " + ch);
}
CharSequence chars = editor.getDocument().getCharsSequence();
int[] starts = range.getStartOffsets();
int[] ends = range.getEndOffsets();
for (int j = ends.length - 1; j >= 0; j
for (int i = starts[j]; i < ends[j]; i++) {
if (i < chars.length() && '\n' != chars.charAt(i)) {
replaceText(editor, i, i + 1, Character.toString(ch));
}
}
}
return true;
}
/**
* Delete count characters and then enter insert mode
*
* @param editor The editor to change
* @param caret The caret to be moved
* @param context The data context
* @param count The number of characters to change
* @return true if able to delete count characters, false if not
*/
public boolean changeCharacters(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
int count) {
int len = EditorHelper.getLineLength(editor);
int col = caret.getLogicalPosition().column;
if (col + count >= len) {
return changeEndOfLine(editor, caret, context, 1);
}
boolean res = deleteCharacter(editor, caret, count, true);
if (res) {
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
}
return res;
}
/**
* Delete count lines and then enter insert mode
*
* @param editor The editor to change
* @param caret The caret on the line to be changed
* @param count The number of lines to change
* @return true if able to delete count lines, false if not
*/
public boolean changeLine(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count) {
final LogicalPosition pos = editor.offsetToLogicalPosition(caret.getOffset());
final boolean insertBelow = pos.line + count >= EditorHelper.getLineCount(editor);
final LogicalPosition lp = editor.offsetToLogicalPosition(
VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret));
boolean res = deleteLine(editor, caret, count);
if (res) {
if (insertBelow) {
insertNewLineBelow(editor, caret, lp.column);
}
else {
insertNewLineAbove(editor, caret, lp.column);
}
}
return res;
}
/**
* Delete from the cursor to the end of count - 1 lines down and enter insert mode
*
* @param editor The editor to change
* @param caret The caret to perform action on
* @param context The data context
* @param count The number of lines to change
* @return true if able to delete count lines, false if not
*/
public boolean changeEndOfLine(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
int count) {
boolean res = deleteEndOfLine(editor, caret, count);
if (res) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineEnd(editor, caret));
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
}
return res;
}
/**
* Delete the text covered by the motion command argument and enter insert mode
*
* @param editor The editor to change
* @param caret The caret on which the motion is supposed to be performed
* @param context The data context
* @param count The number of time to repeat the change
* @param rawCount The actual count entered by the user
* @param argument The motion command
* @return true if able to delete the text, false if not
*/
public boolean changeMotion(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count,
int rawCount, @NotNull Argument argument) {
// Vim treats cw as ce and cW as cE if cursor is on a non-blank character
final Command motion = argument.getMotion();
if (motion == null) {
return false;
}
String id = ActionManager.getInstance().getId(motion.getAction());
boolean kludge = false;
boolean bigWord = id.equals(VIM_MOTION_BIG_WORD_RIGHT);
final CharSequence chars = editor.getDocument().getCharsSequence();
final int offset = caret.getOffset();
final CharacterHelper.CharacterType charType = CharacterHelper.charType(chars.charAt(offset), bigWord);
if (EditorHelper.getFileSize(editor) > 0 && charType != CharacterHelper.CharacterType.WHITESPACE) {
final boolean lastWordChar = offset > EditorHelper.getFileSize(editor) ||
CharacterHelper.charType(chars.charAt(offset + 1), bigWord) != charType;
final ImmutableSet<String> wordMotions =
ImmutableSet.of(VIM_MOTION_WORD_RIGHT, VIM_MOTION_BIG_WORD_RIGHT, VIM_MOTION_CAMEL_RIGHT);
if (wordMotions.contains(id) && lastWordChar && motion.getCount() == 1) {
final boolean res = deleteCharacter(editor, caret, 1, true);
if (res) {
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
}
return res;
}
if (id.equals(VIM_MOTION_WORD_RIGHT)) {
kludge = true;
motion.setAction(ActionManager.getInstance().getAction(VIM_MOTION_WORD_END_RIGHT));
motion.setFlags(Command.FLAG_MOT_INCLUSIVE);
}
else if (id.equals(VIM_MOTION_BIG_WORD_RIGHT)) {
kludge = true;
motion.setAction(ActionManager.getInstance().getAction(VIM_MOTION_BIG_WORD_END_RIGHT));
motion.setFlags(Command.FLAG_MOT_INCLUSIVE);
}
else if (id.equals(VIM_MOTION_CAMEL_RIGHT)) {
kludge = true;
motion.setAction(ActionManager.getInstance().getAction(VIM_MOTION_CAMEL_END_RIGHT));
motion.setFlags(Command.FLAG_MOT_INCLUSIVE);
}
}
if (kludge) {
int size = EditorHelper.getFileSize(editor);
int cnt = count * motion.getCount();
int pos1 = SearchHelper.findNextWordEnd(chars, offset, size, cnt, bigWord, false);
int pos2 = SearchHelper.findNextWordEnd(chars, pos1, size, -cnt, bigWord, false);
if (logger.isDebugEnabled()) {
logger.debug("pos=" + offset);
logger.debug("pos1=" + pos1);
logger.debug("pos2=" + pos2);
logger.debug("count=" + count);
logger.debug("arg.count=" + motion.getCount());
}
if (pos2 == offset) {
if (count > 1) {
count
rawCount
}
else if (motion.getCount() > 1) {
motion.setCount(motion.getCount() - 1);
}
else {
motion.setFlags(Command.FLAG_MOT_EXCLUSIVE);
}
}
}
boolean res = deleteMotion(editor, caret, context, count, rawCount, argument, true);
if (res) {
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
}
return res;
}
public boolean blockInsert(@NotNull Editor editor, @NotNull DataContext context, @NotNull TextRange range,
boolean append) {
final int lines = getLinesCountInVisualBlock(editor, range);
final LogicalPosition startPosition = editor.offsetToLogicalPosition(range.getStartOffset());
for (Caret caret : editor.getCaretModel().getAllCarets()) {
final int line = startPosition.line;
int column = startPosition.column;
if (!range.isMultiple()) {
column = 0;
}
else if (append) {
column += range.getMaxLength();
if (CaretData.getLastColumn(caret) == MotionGroup.LAST_COLUMN) {
column = MotionGroup.LAST_COLUMN;
}
}
final int lineLength = EditorHelper.getLineLength(editor, line);
if (column < MotionGroup.LAST_COLUMN && lineLength < column) {
final String pad = EditorHelper.pad(editor, context, line, column);
final int offset = editor.getDocument().getLineEndOffset(line);
caret.moveToOffset(offset);
insertText(editor, caret, pad);
}
if (range.isMultiple() || !append) {
caret.moveToOffset(editor.logicalPositionToOffset(new LogicalPosition(line, column)));
}
if (range.isMultiple()) {
setInsertRepeat(lines, column, append);
}
}
if (range.isMultiple() || !append) {
insertBeforeCursor(editor, context);
}
else {
insertAfterCursor(editor, context);
}
return true;
}
/**
* Deletes the range of text and enters insert mode
*
* @param editor The editor to change
* @param caret The caret to be moved after range deletion
* @param range The range to change
* @param type The type of the range
* @return true if able to delete the range, false if not
*/
public boolean changeRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
@NotNull TextRange range, @NotNull SelectionType type) {
int col = 0;
int lines = 0;
if (type == SelectionType.BLOCK_WISE) {
lines = getLinesCountInVisualBlock(editor, range);
col = editor.offsetToLogicalPosition(range.getStartOffset()).column;
if (CaretData.getLastColumn(caret) == MotionGroup.LAST_COLUMN) {
col = MotionGroup.LAST_COLUMN;
}
}
boolean after = range.getEndOffset() >= EditorHelper.getFileSize(editor);
final LogicalPosition lp = editor.offsetToLogicalPosition(
VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, caret));
boolean res = deleteRange(editor, caret, range, type, true);
if (res) {
if (type == SelectionType.LINE_WISE) {
if (after) {
insertNewLineBelow(editor, caret, lp.column);
}
else {
insertNewLineAbove(editor, caret, lp.column);
}
}
else {
if (type == SelectionType.BLOCK_WISE) {
setInsertRepeat(lines, col, false);
}
EditorData.setChangeSwitchMode(editor, CommandState.Mode.INSERT);
}
}
return res;
}
/**
* Counts number of lines in the visual block.
* <p>
* The result includes empty and short lines which does not have explicit start position (caret).
*
* @param editor The editor the block was selected in
* @param range The range corresponding to the selected block
* @return total number of lines
*/
private static int getLinesCountInVisualBlock(@NotNull Editor editor, @NotNull TextRange range) {
final int[] startOffsets = range.getStartOffsets();
if (startOffsets.length == 0) return 0;
final LogicalPosition firstStart = editor.offsetToLogicalPosition(startOffsets[0]);
final LogicalPosition lastStart = editor.offsetToLogicalPosition(startOffsets[range.size() - 1]);
return lastStart.line - firstStart.line + 1;
}
/**
* Toggles the case of count characters
*
* @param editor The editor to change
* @param caret The caret on which the operation is performed
* @param count The number of characters to change
* @return true if able to change count characters
*/
public boolean changeCaseToggleCharacter(@NotNull Editor editor, @NotNull Caret caret, int count) {
final int offset = VimPlugin.getMotion().moveCaretHorizontal(editor, caret, count, true);
if (offset == -1) {
return false;
}
changeCase(editor, caret.getOffset(), offset, CharacterHelper.CASE_TOGGLE);
MotionGroup.moveCaret(editor, caret, EditorHelper.normalizeOffset(editor, offset, false));
return true;
}
/**
* Changes the case of all the character moved over by the motion argument.
*
* @param editor The editor to change
* @param caret The caret on which motion pretends to be performed
* @param context The data context
* @param count The number of times to repeat the change
* @param rawCount The actual count entered by the user
* @param type The case change type (TOGGLE, UPPER, LOWER)
* @param argument The motion command
* @return true if able to delete the text, false if not
*/
public boolean changeCaseMotion(@NotNull Editor editor, @NotNull Caret caret, DataContext context, int count,
int rawCount, char type, @NotNull Argument argument) {
final TextRange range = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, true);
return range != null && changeCaseRange(editor, caret, range, type);
}
/**
* Changes the case of all the characters in the range
*
* @param editor The editor to change
* @param caret The caret to be moved
* @param range The range to change
* @param type The case change type (TOGGLE, UPPER, LOWER)
* @return true if able to delete the text, false if not
*/
public boolean changeCaseRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull TextRange range, char type) {
int[] starts = range.getStartOffsets();
int[] ends = range.getEndOffsets();
for (int i = ends.length - 1; i >= 0; i
changeCase(editor, starts[i], ends[i], type);
}
MotionGroup.moveCaret(editor, caret, range.getStartOffset());
return true;
}
/**
* This performs the actual case change.
*
* @param editor The editor to change
* @param start The start offset to change
* @param end The end offset to change
* @param type The type of change (TOGGLE, UPPER, LOWER)
*/
private void changeCase(@NotNull Editor editor, int start, int end, char type) {
if (start > end) {
int t = end;
end = start;
start = t;
}
end = EditorHelper.normalizeOffset(editor, end);
CharSequence chars = editor.getDocument().getCharsSequence();
StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++) {
sb.append(CharacterHelper.changeCase(chars.charAt(i), type));
}
replaceText(editor, start, end, sb.toString());
}
public void autoIndentLines(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count) {
final int startLine = caret.getLogicalPosition().line;
final int endLine = startLine + count - 1;
if (endLine <= EditorHelper.getLineCount(editor)) {
final TextRange range = new TextRange(caret.getOffset(), editor.getDocument().getLineEndOffset(endLine));
autoIndentRange(editor, caret, context, range);
}
}
public void autoIndentMotion(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count,
int rawCount, @NotNull Argument argument) {
final TextRange range = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, false);
if (range != null) {
autoIndentRange(editor, caret, context, range);
}
}
private void restoreCursor(@NotNull Editor editor, @NotNull Caret caret, int startLine) {
if (caret != editor.getCaretModel().getPrimaryCaret()) {
editor.getCaretModel().addCaret(
editor.offsetToVisualPosition(VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, startLine)), false);
}
}
public void autoIndentRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
@NotNull TextRange range) {
final int startOffset = EditorHelper.getLineStartForOffset(editor, range.getStartOffset());
final int endOffset = EditorHelper.getLineEndForOffset(editor, range.getEndOffset());
editor.getSelectionModel().setSelection(startOffset, endOffset);
KeyHandler.executeAction("AutoIndentLines", context);
final int firstLine = editor.offsetToLogicalPosition(Math.min(startOffset, endOffset)).line;
final int newOffset = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, firstLine);
MotionGroup.moveCaret(editor, caret, newOffset);
restoreCursor(editor, caret, caret.getLogicalPosition().line);
}
public void reformatCode(@NotNull DataContext context) {
KeyHandler.executeAction("ReformatCode", context);
}
public void indentLines(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int lines,
int dir) {
int start = caret.getOffset();
int end = VimPlugin.getMotion().moveCaretToLineEndOffset(editor, caret, lines - 1, false);
indentRange(editor, caret, context, new TextRange(start, end), 1, dir);
}
public void indentMotion(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context, int count,
int rawCount, @NotNull Argument argument, int dir) {
final TextRange range = MotionGroup.getMotionRange(editor, caret, context, count, rawCount, argument, false);
if (range != null) {
indentRange(editor, caret, context, range, 1, dir);
}
}
public void indentRange(@NotNull Editor editor, @NotNull Caret caret, @NotNull DataContext context,
@NotNull TextRange range, int count, int dir) {
if (logger.isDebugEnabled()) {
logger.debug("count=" + count);
}
Project proj = PlatformDataKeys.PROJECT.getData(context); // API change - don't merge
int tabSize = 8;
int indentSize = 8;
boolean useTabs = true;
VirtualFile file = EditorData.getVirtualFile(editor);
if (file != null) {
FileType type = FileTypeManager.getInstance().getFileTypeByFile(file);
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(proj);
tabSize = settings.getTabSize(type);
indentSize = settings.getIndentSize(type);
useTabs = settings.useTabCharacter(type);
}
int sline = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int eline = editor.offsetToLogicalPosition(range.getEndOffset()).line;
if (range.isMultiple()) {
int col = editor.offsetToLogicalPosition(range.getStartOffset()).column;
int size = indentSize * count;
if (dir == 1) {
// Right shift blockwise selection
StringBuilder space = new StringBuilder();
int tabCnt = 0;
int spcCnt;
if (useTabs) {
tabCnt = size / tabSize;
spcCnt = size % tabSize;
}
else {
spcCnt = size;
}
for (int i = 0; i < tabCnt; i++) {
space.append('\t');
}
for (int i = 0; i < spcCnt; i++) {
space.append(' ');
}
for (int l = sline; l <= eline; l++) {
int len = EditorHelper.getLineLength(editor, l);
if (len > col) {
LogicalPosition spos = new LogicalPosition(l, col);
caret.moveToOffset(editor.logicalPositionToOffset(spos));
insertText(editor, caret, space.toString());
}
}
}
else {
// Left shift blockwise selection
CharSequence chars = editor.getDocument().getCharsSequence();
for (int l = sline; l <= eline; l++) {
int len = EditorHelper.getLineLength(editor, l);
if (len > col) {
LogicalPosition spos = new LogicalPosition(l, col);
LogicalPosition epos = new LogicalPosition(l, col + size - 1);
int wsoff = editor.logicalPositionToOffset(spos);
int weoff = editor.logicalPositionToOffset(epos);
int pos;
for (pos = wsoff; pos <= weoff; pos++) {
if (CharacterHelper.charType(chars.charAt(pos), false) != CharacterHelper.CharacterType.WHITESPACE) {
break;
}
}
if (pos > wsoff) {
deleteText(editor, new TextRange(wsoff, pos), null);
}
}
}
}
}
else {
// Shift non-blockwise selection
for (int l = sline; l <= eline; l++) {
int soff = EditorHelper.getLineStartOffset(editor, l);
int eoff = EditorHelper.getLineEndOffset(editor, l, true);
int woff = VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, l);
int col = editor.offsetToVisualPosition(woff).column;
int newCol = Math.max(0, col + dir * indentSize * count);
if (col > 0 || soff != eoff) {
StringBuilder space = new StringBuilder();
int tabCnt = 0;
int spcCnt;
if (useTabs) {
tabCnt = newCol / tabSize;
spcCnt = newCol % tabSize;
}
else {
spcCnt = newCol;
}
for (int i = 0; i < tabCnt; i++) {
space.append('\t');
}
for (int i = 0; i < spcCnt; i++) {
space.append(' ');
}
replaceText(editor, soff, woff, space.toString());
}
}
}
if (!CommandState.inInsertMode(editor)) {
if (!range.isMultiple()) {
MotionGroup.moveCaret(editor, caret, VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, sline));
}
else {
MotionGroup.moveCaret(editor, caret, range.getStartOffset());
}
}
CaretData.setLastColumn(editor, caret, caret.getVisualPosition().column);
}
/**
* Inserts text into the document
*
* @param editor The editor to insert into
* @param caret The caret to start insertion in
* @param str The text to insert
*/
public void insertText(@NotNull Editor editor, @NotNull Caret caret, @NotNull String str) {
int start = caret.getOffset();
editor.getDocument().insertString(start, str);
caret.moveToOffset(start + str.length());
VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, start);
}
/**
* Delete text from the document. This will fail if being asked to store the deleted text into a read-only
* register.
*
* @param editor The editor to delete from
* @param range The range to delete
* @param type The type of deletion
* @return true if able to delete the text, false if not
*/
private boolean deleteText(@NotNull final Editor editor, @NotNull final TextRange range,
@Nullable SelectionType type) {
if (!range.normalize(EditorHelper.getFileSize(editor, true))) {
return false;
}
if (type == null || VimPlugin.getRegister().storeText(editor, range, type, true)) {
final Document document = editor.getDocument();
final int[] startOffsets = range.getStartOffsets();
final int[] endOffsets = range.getEndOffsets();
for (int i = range.size() - 1; i >= 0; i
document.deleteString(startOffsets[i], endOffsets[i]);
}
if (type != null) {
int start = range.getStartOffset();
VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, start);
VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, start));
}
return true;
}
return false;
}
/**
* Replace text in the editor
*
* @param editor The editor to replace text in
* @param start The start offset to change
* @param end The end offset to change
* @param str The new text
*/
private void replaceText(@NotNull Editor editor, int start, int end, @NotNull String str) {
editor.getDocument().replaceString(start, end, str);
final int newEnd = start + str.length();
VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, newEnd));
VimPlugin.getMark().setMark(editor, MarkGroup.MARK_CHANGE_POS, newEnd);
}
/**
* Sort range of text with a given comparator
*
* @param editor The editor to replace text in
* @param range The range to sort
* @param lineComparator The comparator to use to sort
* @return true if able to sort the text, false if not
*/
public boolean sortRange(@NotNull Editor editor, @NotNull LineRange range,
@NotNull Comparator<String> lineComparator) {
final int startLine = range.getStartLine();
final int endLine = range.getEndLine();
final int count = endLine - startLine + 1;
if (count < 2) {
return false;
}
final int startOffset = editor.getDocument().getLineStartOffset(startLine);
final int endOffset = editor.getDocument().getLineEndOffset(endLine);
return sortTextRange(editor, startOffset, endOffset, lineComparator);
}
/**
* Sorts a text range with a comparator. Returns true if a replace was performed, false otherwise.
*
* @param editor The editor to replace text in
* @param start The starting position for the sort
* @param end The ending position for the sort
* @param lineComparator The comparator to use to sort
* @return true if able to sort the text, false if not
*/
private boolean sortTextRange(@NotNull Editor editor, int start, int end,
@NotNull Comparator<String> lineComparator) {
final String selectedText = editor.getDocument().getText(new TextRangeInterval(start, end));
final List<String> lines = Lists.newArrayList(Splitter.on("\n").split(selectedText));
if (lines.size() < 1) {
return false;
}
Collections.sort(lines, lineComparator);
replaceText(editor, start, end, StringUtil.join(lines, "\n"));
return true;
}
public static void resetCursor(@NotNull Editor editor, boolean insert) {
Document doc = editor.getDocument();
VirtualFile vf = FileDocumentManager.getInstance().getFile(doc);
if (vf != null) {
resetCursor(vf, editor.getProject(), insert);
}
else {
editor.getSettings().setBlockCursor(!insert);
}
}
private static void resetCursor(@NotNull VirtualFile virtualFile, Project proj, boolean insert) {
logger.debug("resetCursor");
Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
if (doc == null) return; // Must be no text editor (such as image)
Editor[] editors = EditorFactory.getInstance().getEditors(doc, proj);
if (logger.isDebugEnabled()) {
logger.debug("There are " + editors.length + " editors for virtual file " + virtualFile.getName());
}
for (Editor editor : editors) {
editor.getSettings().setBlockCursor(!insert);
}
}
public boolean changeNumber(@NotNull final Editor editor, @NotNull Caret caret, final int count) {
final BoundListOption nf = (BoundListOption)Options.getInstance().getOption("nrformats");
final boolean alpha = nf.contains("alpha");
final boolean hex = nf.contains("hex");
final boolean octal = nf.contains("octal");
final TextRange range = SearchHelper.findNumberUnderCursor(editor, caret, alpha, hex, octal);
if (range == null) {
logger.debug("no number on line");
return false;
}
else {
String text = EditorHelper.getText(editor, range);
if (logger.isDebugEnabled()) {
logger.debug("found range " + range);
logger.debug("text=" + text);
}
String number = text;
if (text.length() == 0) {
return false;
}
char ch = text.charAt(0);
if (hex && text.toLowerCase().startsWith("0x")) {
for (int i = text.length() - 1; i >= 2; i
int index = "abcdefABCDEF".indexOf(text.charAt(i));
if (index >= 0) {
lastLower = index < 6;
break;
}
}
int num = (int)Long.parseLong(text.substring(2), 16);
num += count;
number = Integer.toHexString(num);
number = StringHelper.rightJustify(number, text.length() - 2, '0');
if (!lastLower) {
number = number.toUpperCase();
}
number = text.substring(0, 2) + number;
}
else if (octal && text.startsWith("0") && text.length() > 1) {
int num = (int)Long.parseLong(text, 8);
num += count;
number = Integer.toOctalString(num);
number = "0" + StringHelper.rightJustify(number, text.length() - 1, '0');
}
else if (alpha && Character.isLetter(ch)) {
ch += count;
if (Character.isLetter(ch)) {
number = "" + ch;
}
}
else if (ch == '-' || Character.isDigit(ch)) {
boolean pad = ch == '0';
int len = text.length();
if (ch == '-' && text.charAt(1) == '0') {
pad = true;
len
}
int num = Integer.parseInt(text);
num += count;
number = Integer.toString(num);
if (!octal && pad) {
boolean neg = false;
if (number.charAt(0) == '-') {
neg = true;
number = number.substring(1);
}
number = StringHelper.rightJustify(number, len, '0');
if (neg) {
number = "-" + number;
}
}
}
if (!text.equals(number)) {
replaceText(editor, range.getStartOffset(), range.getEndOffset(), number);
caret.moveToOffset(range.getStartOffset() + number.length() - 1);
}
return true;
}
}
private final List<Object> strokes = new ArrayList<Object>();
private int repeatCharsCount;
private List<Object> lastStrokes;
@Nullable
private Command lastInsert;
private boolean inInsert;
private int repeatLines;
private int repeatColumn;
private boolean repeatAppend;
private boolean lastLower = true;
private Document document;
@Nullable
private DocumentAdapter documentListener;
private int oldOffset = -1;
private static final Logger logger = Logger.getInstance(ChangeGroup.class.getName());
}
|
package com.mebigfatguy.fbcontrib.utils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* an automatic toString() builder using reflection
*/
public class ToString {
private static class VisitedInfo {
Set<Integer> visited = new HashSet<Integer>();
int count = 0;
}
private static final ThreadLocal<VisitedInfo> visited = new ThreadLocal<VisitedInfo>() {
@Override
protected VisitedInfo initialValue() {
return new VisitedInfo();
}
};
private ToString() {
}
public static String build(Object o) {
VisitedInfo vi = visited.get();
try {
vi.count++;
return generate(o, vi.visited);
} finally {
if (--vi.count == 0) {
vi.visited.clear();
}
}
}
private static String generate(Object o, Set<Integer> visitedObjects) {
StringBuilder sb = new StringBuilder(100);
Class<?> cls = o.getClass();
int identityHC = System.identityHashCode(o);
sb.append(cls.getSimpleName()).append('[').append(identityHC).append("]{");
if (!visitedObjects.contains(identityHC)) {
try {
visitedObjects.add(identityHC);
String sep = "";
for (Field f : cls.getDeclaredFields()) {
sb.append(sep);
sep = ", ";
sb.append(f.getName()).append('=');
try {
f.setAccessible(true);
Object value = f.get(o);
if (value == null) {
sb.append((String) null);
} else if (value.getClass().isArray()) {
sb.append(Arrays.toString((Object[]) value));
} else {
sb.append(value);
}
} catch (SecurityException e) {
sb.append("*SECURITY_EXCEPTION*");
}
}
} catch (Exception e) {
}
}
sb.append('}');
return sb.toString();
}
}
|
package com.microsoft.adal;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
/*
*TODO: error messages define
*TODO: serialization to restore the context onresume inside the client's app so that user does not need to authenticate again
*TODO: Browser flow add
*TODO:
*/
/**
* ADAL context to get access token, refresh token
*
* @author omercan
*/
public class AuthenticationContext {
/**
* TAG to check messages
*/
private final static String TAG = "AuthenticationContext";
private final static String BROKER_APP_PACKAGE = "com.microsoft.broker";
private final static String BROKER_APP_TOKEN_ACTION = "com.microsoft.broker.token";
static final int GET_AUTHORIZATION = 1;
private String mAuthority;
private String mClientId;
private String mRedirectUri;
private String mLoginHint;
private String mBroadRefreshToken;
private Context mContext;
private transient ActivityDelegate mActivityDelegate;
private transient AuthenticationCallback mExternalCallback;
/**
* Delegate to use for starting browser flow from activity's context
*/
public interface ActivityDelegate {
public void startActivityForResult(Intent intent, int requestCode);
public void startActivity(Intent intent);
public Activity getActivityContext();
}
/**
* Response listener for web requests
*/
public interface OnResponseListener {
/**
* Called when response is received
*
* @param values on success, contains the values returned by the dialog
* @param error on an error, contains an exception describing the error
*/
void onComplete(HashMap<String, String> response);
}
/**
* Constructs context to use with known authority to get the token
*
* @param authority
* @param clientId
* @param redirectUri
* @param loginHint
*/
public AuthenticationContext(Context contextFromMainThread, String authority, String clientId, String redirectUri,
String loginHint)
{
mContext = contextFromMainThread;
mAuthority = authority;
mClientId = clientId;
mRedirectUri = redirectUri;
mLoginHint = loginHint;
}
public AuthenticationContext(Context contextFromMainThread, AuthenticationRequest previousRequest)
{
mContext = contextFromMainThread;
mAuthority = previousRequest.getAuthority();
mClientId = previousRequest.getClientId();
mRedirectUri = previousRequest.getRedirectUri();
mLoginHint = previousRequest.getLoginHint();
Log.d(TAG, "Make context from request");
}
/**
* Get token for this resource if cached
* @param resource
*/
public AuthenticationResult getToken(String resource) {
final AuthenticationRequest request = new AuthenticationRequest(this, resource);
// Check cached authorization object
final AuthenticationResult cachedResult = getCachedResult(request.getCacheKey());
if (cachedResult != null) {
if (!cachedResult.isExpired()) {
return cachedResult;
}
}
return null;
}
/**
* acquire Token will start interactive flow if needed.
* It checks the cache to return existing result if not expired.
* It tries to use refresh token if available. If it fails to get token with refresh token, it will remove
* this refresh token from cache and return error without trying interactive flow.
* @param activity
* @param resource
* @param correlationID
* @param callback
*/
public void acquireToken(Context activity, String resource, UUID correlationID,
AuthenticationCallback callback) {
verifyParams(activity, callback);
mContext = activity;
boolean hasbroker = appInstalledOrNot(BROKER_APP_PACKAGE);
boolean askforinstall = getSettings().getEnableInstallRedirect();
setTokenActivityDelegate(activity);
if (hasbroker)
{
final AuthenticationRequest request = new AuthenticationRequest(this, resource);
mExternalCallback = callback;
// Broker app needs to expose token activity to call from other apps
Log.d(TAG, "start token activity");
startTokenActivity(request);
}
else if (askforinstall)
{
askUserToInstallBroker();
}
else
{
// local flow
acquireTokenLocal(activity, resource, correlationID, callback);
}
}
private void startTokenActivity(AuthenticationRequest request) {
// TODO Auto-generated method stub
Intent intent = getTokenActivityIntent(request);
if (!resolveIntent(intent)) {
mExternalCallback.onError(new AuthException(request, "intent resolve failure",
"failed to resolve intent"));
}
try {
// Start activity from callers context so that caller can intercept
// when it is done
getTokenActivityDelegate().startActivityForResult(intent,
AuthenticationConstants.UIRequest.TOKEN_FLOW);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "Activity login not found");
mExternalCallback.onError(e);
}
}
private void askUserToInstallBroker() {
// implement prompt dialog asking user to download the package
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(mContext);
downloadDialog.setTitle("Download that bro");
downloadDialog.setMessage("Really get that now!");
downloadDialog.setPositiveButton("yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
Uri uri = Uri
.parse("market://search?q=pname:com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
getTokenActivityDelegate().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Log.d(TAG, "ERROR Google Play Market not found!");
mExternalCallback.onError(e);
}
}
});
downloadDialog.setNegativeButton("no",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int i)
{
dialog.dismiss();
}
});
downloadDialog.show();
}
public void invalidateToken(String authority, String clientid, String redirect,
String resource, String scope, String loginHint)
{
final AuthenticationRequest request = new AuthenticationRequest(authority, clientid,
resource, scope, redirect, loginHint);
// Check cached authorization object
final AuthenticationResult cachedResult = getCachedResult(request.getCacheKey());
if (cachedResult != null) {
if (getSettings().getEnableTokenCaching())
{
getSettings().getCache().removeResult(request.getCacheKey());
}
}
}
public void resetTokens()
{
ITokenCache cache = getCache();
if (cache != null)
{
cache.removeAll();
}
}
public void acquireTokenLocal(Context activity, String resource, UUID correlationID,
AuthenticationCallback callback) {
verifyParams(activity, callback);
final AuthenticationRequest request = new AuthenticationRequest(this, resource);
// Check cached authorization object
final AuthenticationResult cachedResult = getCachedResult(request.getCacheKey());
if (cachedResult != null) {
if (!cachedResult.isExpired()) {
callback.onCompleted(cachedResult);
} else if (cachedResult.isRefreshable()) {
// refreshToken will try to refresh. If it fails, it removes
// authorization object and returns error
refreshToken(cachedResult, resource, callback);
}
} else {
mExternalCallback = callback;
setTokenActivityDelegate(activity);
mContext = activity.getApplicationContext();
startLoginActivity(request);
}
}
private void verifyParams(Context context, AuthenticationCallback callback) {
if (callback == null)
throw new IllegalArgumentException("listener is null");
if (context == null)
throw new IllegalArgumentException("context is null");
// Check authority url
ExtractUrl();
// If user has enabled validation, it will call the discovery service to
// verify the instance
ValidateAuthority();
}
private void setTokenActivityDelegate(Context context)
{
final Context callingActivity = context;
mActivityDelegate = new ActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
Log.d(TAG, "Delegate calling startActivityForResult");
((Activity) callingActivity).startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return (Activity) callingActivity;
}
@Override
public void startActivity(Intent intent) {
Log.d(TAG, "Delegate calling startActivity");
callingActivity.startActivity(intent);
}
};
}
ActivityDelegate getTokenActivityDelegate() {
return mActivityDelegate;
}
private boolean startLoginActivity(AuthenticationRequest request) {
Intent intent = getLoginActivityIntent(request);
if (!resolveIntent(intent)) {
return false;
}
try {
// Start activity from callers context so that caller can intercept
// when it is done
getTokenActivityDelegate().startActivityForResult(intent,
AuthenticationConstants.UIRequest.BROWSER_FLOW);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "Activity login not found");
return false;
}
return true;
}
/**
* Resolve activity from the package
*
* @param intent
* @return
*/
private boolean resolveIntent(Intent intent) {
ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, 0);
if (resolveInfo == null) {
return false;
}
return true;
}
private Intent getLoginActivityIntent(AuthenticationRequest request) {
Intent intent = new Intent();
intent.setClass(mContext, LoginActivity.class);
intent.putExtra(AuthenticationConstants.BROWSER_REQUEST_MESSAGE, request);
return intent;
}
/*
* It targets broker app's Token Activity. If it is not exposed in the broker app, it will fail.
*/
private Intent getTokenActivityIntent(AuthenticationRequest request) {
Intent intent = new Intent(BROKER_APP_TOKEN_ACTION);
intent.putExtra(AuthenticationConstants.BROWSER_REQUEST_MESSAGE, request);
return intent;
}
/**
* Check if app installed on this device
*
* @param uri
* @return
*/
private boolean appInstalledOrNot(String name)
{
PackageManager pm = mContext.getPackageManager();
boolean app_installed = false;
try
{
pm.getPackageInfo(name, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e)
{
app_installed = false;
}
return app_installed;
}
/**
* Call from your onActivityResult method inside your activity that started
* token request
*
* @param requestCode
* @param resultCode
* @param data
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AuthenticationConstants.UIRequest.BROWSER_FLOW)
{
Bundle extras = data.getExtras();
if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL)
{
mExternalCallback.onCancelled();
} else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR)
{
AuthenticationRequest errRequest = (AuthenticationRequest) extras
.getSerializable(AuthenticationConstants.BROWSER_RESPONSE_ERROR_REQUEST);
String errCode = extras
.getString(AuthenticationConstants.BROWSER_RESPONSE_ERROR_CODE);
String errMessage = extras
.getString(AuthenticationConstants.BROWSER_RESPONSE_ERROR_MESSAGE);
mExternalCallback.onError(new AuthException(errRequest, errCode, errMessage));
} else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE)
{
String endingUrl = extras
.getString(AuthenticationConstants.BROWSER_RESPONSE_FINAL_URL);
if (endingUrl.isEmpty())
{
Log.d(TAG, "ending url is empty");
mExternalCallback.onError(new IllegalArgumentException("Final url is empty"));
}
Log.d(TAG, "Process this url");
processUIResponse(endingUrl);
}
}
else if (requestCode == AuthenticationConstants.UIRequest.TOKEN_FLOW)
{
Bundle extras = data.getExtras();
if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL)
{
mExternalCallback.onCancelled();
} else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR)
{
AuthenticationRequest errRequest = (AuthenticationRequest) extras
.getSerializable(AuthenticationConstants.BROWSER_RESPONSE_ERROR_REQUEST);
String errCode = extras
.getString(AuthenticationConstants.BROWSER_RESPONSE_ERROR_CODE);
String errMessage = extras
.getString(AuthenticationConstants.BROWSER_RESPONSE_ERROR_MESSAGE);
mExternalCallback.onError(new AuthException(errRequest, errCode, errMessage));
} else
{
AuthenticationResult resultback = (AuthenticationResult) data
.getSerializableExtra(AuthenticationConstants.BROKER_RESPONSE);
if (resultback != null)
{
mExternalCallback.onCompleted(resultback);
}
else
{
mExternalCallback.onError(new Exception("hello damn..broker did not work"));
}
}
}
}
/**
* TODO: cleanup
*
* @param endUrl
*/
private void processUIResponse(String endUrl) {
// Success
Uri response = Uri.parse(endUrl);
HashMap<String, String> parameters = UriExtensions
.getFragmentParameters(response);
if (parameters == null || parameters.isEmpty())
parameters = UriExtensions.getQueryParameters(response);
// TODO: No encoded state
String encodedState = parameters.get("state");
String state = AuthenticationRequest.decodeProtocolState(encodedState);
if (null != state && !state.isEmpty()) {
// We have encoded state, crack it open
Uri stateUri = Uri.parse("http://state/path?" + state);
String authorizationUri = stateUri.getQueryParameter("a");
String resource = stateUri.getQueryParameter("r");
String scope = stateUri.getQueryParameter("s");
//TODO add more verification for the state if needed
if (null != authorizationUri && !authorizationUri.isEmpty()
&& null != resource && !resource.isEmpty()
) {
// ToDo: if token, ask to token endpoint and post the message
// Same authority
final AuthenticationRequest request = new AuthenticationRequest(this, resource);
AuthenticationResult result = processUIResponseParams(
parameters, request);
if (result.getStatus() == com.microsoft.adal.AuthenticationResult.AuthenticationStatus.Succeeded) {
if (!result.getCode().isEmpty()) {
// Need to get exchange code to get token
HashMap<String, String> tokenRequestMessage = buildTokenRequestMessage(
result);
sendRequest(request.getTokenEndpoint(),
tokenRequestMessage, new OnResponseListener() {
@Override
public void onComplete(
HashMap<String, String> response) {
AuthenticationResult result = processUIResponseParams(
response, request);
if (result.getStatus() == com.microsoft.adal.AuthenticationResult.AuthenticationStatus.Succeeded) {
setCachedResult(request
.getCacheKey(), result);
mExternalCallback.onCompleted(result);
} else {
// did not get token
mExternalCallback
.onError(new AuthException(request, result
.getErrorCode(), result
.getErrorDescription()));
}
}
});
}
else
{
// We have token directly with implicit flow
}
}
} else {
mExternalCallback.onError(new AzureException(
AuthenticationConstants.AUTH_FAILED_BAD_STATE));
}
} else {
// The response from the server had no state
// information
mExternalCallback.onError(new AzureException(
AuthenticationConstants.AUTH_FAILED_NO_STATE));
}
}
/**
* TODO: abstract sendrequest to set headers,
* method type, data
* Sends a request with the specified parameters to the given endpoint TODO:
* add correlationid headers
*/
private static void sendRequest(final String endpoint,
HashMap<String, String> requestData,
final OnResponseListener callback) {
HashMap<String, String> response = null;
try {
String body = HashMapExtensions.URLFormEncode(requestData);
HttpWebRequest webRequest = new HttpWebRequest(new URL(endpoint));
webRequest.getRequestHeaders().put("Accept", "application/json");
webRequest.sendAsyncPost(
body.getBytes(AuthenticationConstants.ENCODING_UTF8),
"application/x-www-form-urlencoded",
new HttpWebRequestCallback() {
@Override
public void onComplete(Exception exception,
HttpWebResponse webResponse) {
HashMap<String, String> response = new HashMap<String, String>();
// Response should have Oauth2 token
if (exception != null) {
Log.e(TAG, ExceptionExtensions
.getExceptionMessage(exception));
response.put(
AuthenticationConstants.OAuth2.ERROR,
AuthenticationConstants.AUTH_FAILED);
response.put(
AuthenticationConstants.OAuth2.ERROR_DESCRIPTION,
ExceptionExtensions
.getExceptionMessage(exception));
} else if (webResponse.getStatusCode() <= 400) {
try {
JSONObject jsonObject = new JSONObject(
new String(webResponse.getBody()));
@SuppressWarnings("unchecked")
Iterator<String> i = jsonObject.keys();
while (i.hasNext()) {
String key = i.next();
response.put(key,
jsonObject.getString(key));
}
} catch (Exception ex) {
// There is no recovery possible here, so
// catch the generic Exception
Log.e(TAG, ExceptionExtensions
.getExceptionMessage(ex));
response.put(
AuthenticationConstants.OAuth2.ERROR,
AuthenticationConstants.AUTH_FAILED);
response.put(
AuthenticationConstants.OAuth2.ERROR_DESCRIPTION,
ExceptionExtensions
.getExceptionMessage(ex));
}
} else {
response.put(
AuthenticationConstants.OAuth2.ERROR,
AuthenticationConstants.AUTH_FAILED);
response.put(
AuthenticationConstants.OAuth2.ERROR_DESCRIPTION,
new String(webResponse.getBody()));
}
// Run the callback
Log.d(TAG, "Callback complete call");
callback.onComplete(response);
}
});
} catch (Exception ex) {
// There is no recovery possible here, so catch the generic
// Exception
Log.e(TAG, ExceptionExtensions.getExceptionMessage(ex));
response = new HashMap<String, String>();
response.put(AuthenticationConstants.OAuth2.ERROR,
AuthenticationConstants.AUTH_FAILED);
response.put(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION,
ExceptionExtensions.getExceptionMessage(ex));
}
Log.d(TAG, "sendRequest at the end");
if (response != null) {
callback.onComplete(response);
}
}
private static AuthenticationResult processUIResponseParams(
HashMap<String, String> response, AuthenticationRequest request) {
AuthenticationResult result = new AuthenticationResult(request);
if (response.containsKey(AuthenticationConstants.OAuth2.ERROR)) {
// Error response from the server
// TODO: Should we kill the authorization object?
result = new AuthenticationResult(
response.get(AuthenticationConstants.OAuth2.ERROR),
response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION));
} else if (response.containsKey(AuthenticationConstants.OAuth2.CODE)) {
// Code response
Calendar expires = new GregorianCalendar();
expires.add(Calendar.SECOND, 300); //TODO check .net ADAL for skew time
result.setAccessTokenType(null);
result.setAccessTokenType(null);
result.setCode(response
.get(AuthenticationConstants.OAuth2.CODE));
result.setExpires(expires.getTime());
result.setRefreshToken(null);
} else if (response
.containsKey(AuthenticationConstants.OAuth2.ACCESS_TOKEN)) {
// Token response
String expires_in = response.get("expires_in");
Calendar expires = new GregorianCalendar();
// Compute token expiration
expires.add(
Calendar.SECOND,
expires_in == null || expires_in.isEmpty() ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC
: Integer.parseInt(expires_in));
result.setAccessToken(response
.get(AuthenticationConstants.OAuth2.ACCESS_TOKEN));
result.setAccessTokenType(response
.get(AuthenticationConstants.OAuth2.TOKEN_TYPE));
result.setCode(null);
result.setExpires(expires.getTime());
if (response
.containsKey(AuthenticationConstants.OAuth2.REFRESH_TOKEN)) {
result.setRefreshToken(response
.get(AuthenticationConstants.OAuth2.REFRESH_TOKEN));
//TODO test broad refresh token
//TODO how to use this broad token
if (response.containsKey(AuthenticationConstants.AAD.RESOURCE))
{
result.setBroadRefreshToken(true);
}
}
} else {
result = new AuthenticationResult(
AuthenticationConstants.AUTH_FAILED,
AuthenticationConstants.AUTH_FAILED_SERVER_ERROR);
}
return result;
}
/**
* TODO move token request message to outside
* Build token request message which uses code to get token
*
* @param result Authentication result which has code
* @return Hashmap request params
*/
private HashMap<String, String> buildTokenRequestMessage(
AuthenticationResult result) {
HashMap<String, String> reqParameters = new HashMap<String, String>();
reqParameters.put(AuthenticationConstants.OAuth2.GRANT_TYPE,
AuthenticationConstants.OAuth2.AUTHORIZATION_CODE);
reqParameters.put(AuthenticationConstants.OAuth2.CODE, result
.getCode());
reqParameters.put(AuthenticationConstants.OAuth2.CLIENT_ID,
result.getClientId());
reqParameters.put(AuthenticationConstants.OAuth2.REDIRECT_URI,
result.getRedirectUri());
return reqParameters;
}
/*
* If refresh token is broad refresh token, this request will include
* resource in the message.
*/
private HashMap<String, String> buildRefreshTokenRequestMessage(
AuthenticationResult cachedResult, String targetResource) {
HashMap<String, String> reqParameters = new HashMap<String, String>();
if (TextUtils.isEmpty(cachedResult.getRefreshToken()))
{
throw new IllegalArgumentException("Refresh token is required");
}
if (TextUtils.isEmpty(cachedResult.getRedirectUri()))
{
throw new IllegalArgumentException("RedirectUri is required");
}
if (TextUtils.isEmpty(cachedResult.getClientId()))
{
throw new IllegalArgumentException("ClientId is required");
}
reqParameters.put(AuthenticationConstants.OAuth2.GRANT_TYPE,
AuthenticationConstants.OAuth2.REFRESH_TOKEN);
reqParameters.put(AuthenticationConstants.OAuth2.REFRESH_TOKEN, cachedResult
.getRefreshToken());
reqParameters.put(AuthenticationConstants.OAuth2.REDIRECT_URI,
cachedResult.getRedirectUri());
reqParameters.put(AuthenticationConstants.OAuth2.CLIENT_ID,
cachedResult.getClientId());
if (cachedResult.IsBroadRefreshToken())
{
reqParameters.put(AuthenticationConstants.AAD.RESOURCE,
targetResource);
}
return reqParameters;
}
/**
* Callback to use for web ui login completed
*/
interface WebLoginCallback {
/**
* Method to call if the operation finishes successfully
*
* @param url The final login URL
* @param e An exception
*/
void onCompleted(String url, Exception exception);
/*
* User or UI cancelled login
*/
void onCancelled();
}
/**
* Refresh token based on cached result and targetresource.
*
* @param cachedResult ClientId, Refreshtoken, RedirectUri are used from
* this result obj
* @param targetResource Resource to ask for refresh token
* @param callback Callback to be called for results
*/
private void refreshToken(AuthenticationResult cachedResult, String targetResource,
AuthenticationCallback callback) {
// Same authority
final AuthenticationRequest request = new AuthenticationRequest(this, targetResource);
HashMap<String, String> tokenRequestMessage = buildRefreshTokenRequestMessage(cachedResult,
targetResource);
final AuthenticationCallback externalCallback = callback;
Log.d(TAG, "Calling sendrequest for refreshtoken");
sendRequest(request.getTokenEndpoint(),
tokenRequestMessage, new OnResponseListener() {
@Override
public void onComplete(HashMap<String, String> response) {
Log.d(TAG, "sendRequest onComplete");
AuthenticationResult result = processUIResponseParams(response, request);
if (result.getStatus() == com.microsoft.adal.AuthenticationResult.AuthenticationStatus.Succeeded) {
setCachedResult(request.getCacheKey(), result);
externalCallback.onCompleted(result);
} else {
// did not get token
externalCallback
.onError(new AuthException(request, result
.getErrorCode(), result
.getErrorDescription()));
}
}
});
}
/*
* Return cache from settings if it was set.
* Otherwise, return default impl.
*/
private ITokenCache getCache()
{
// Default cache uses shared preferences and needs to be connected to
// the context
// Shared pref. handles synchronization
ITokenCache cache = null;
if (getSettings().getEnableTokenCaching())
{
cache = getSettings().getCache();
if (cache == null)
{
// Context should be passed in
if (mContext == null)
throw new IllegalArgumentException("Context");
cache = new TokenCache(mContext);
}
}
return cache;
}
private AuthenticationResult getCachedResult(String cacheKey) {
if (getSettings().getEnableTokenCaching())
{
if(getCache() != null)
{
return getCache().getResult(cacheKey);
}
}
return null;
}
private void setCachedResult(String cacheKey, AuthenticationResult result) {
if (getSettings().getEnableTokenCaching())
{
if (getCache() != null)
{
getCache().putResult(cacheKey, result);
}
}
}
private void removeCachedResult(String cacheKey) {
if (getSettings().getEnableTokenCaching())
{
if(!getCache().removeResult(cacheKey))
{
if(!getCache().removeResult(cacheKey))
{
Log.e(TAG, "Cache remove failed!");
}
}
}
}
private void ValidateAuthority()
{
if (getSettings().getValidateAuthority())
{
if (!getSettings().getDiscovery().IsValidAuthority(mAuthority))
{
throw new IllegalArgumentException("Authority is not valid");
}
}
}
private void ExtractUrl()
{
// Authorization server URL is like
// - must not be empty
// - must be absolute
// - must not have query or fragment
// - must be https
if (mAuthority == null || mAuthority.isEmpty())
throw new IllegalArgumentException("authorizationServer");
Uri uri = Uri.parse(mAuthority);
if (!uri.isAbsolute()) {
throw new IllegalArgumentException("authorizationServer");
}
if (!uri.getScheme().equalsIgnoreCase("https")) {
throw new IllegalArgumentException("authorizationServer");
}
if (uri.getFragment() != null || uri.getQuery() != null) {
throw new IllegalArgumentException("authorizationServer has query or fragments");
}
// Normalize authority url to remove extra url parts
int thirdSlash = mAuthority.indexOf("/", 8); // exclude starting
if (thirdSlash >= 0)
{
if (thirdSlash != (mAuthority.length() - 1))
{
// Extract url
int fourthSlash = mAuthority.indexOf("/", thirdSlash + 1);
if (fourthSlash > thirdSlash + 1)
{
mAuthority.substring(0, fourthSlash);
}
}
}
else
{
throw new IllegalArgumentException("Authority url");
}
}
public static AuthenticationSettings getSettings() {
return AuthenticationSettings.getInstance();
}
public String getAuthority() {
return mAuthority;
}
public String getClientId() {
return mClientId;
}
public String getRedirectUri() {
return mRedirectUri;
}
}
|
package com.uwflow.flow_android;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.uwflow.flow_android.adapters.NavDrawerAdapter;
import com.uwflow.flow_android.entities.NavDrawerItem;
import com.uwflow.flow_android.fragment.AboutFragment;
import com.uwflow.flow_android.fragment.ExploreFragment;
import com.uwflow.flow_android.fragment.ProfileFragment;
import com.uwflow.flow_android.fragment.ShortlistFragment;
import java.util.ArrayList;
public class MainFlowActivity extends FlowActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavDrawerAdapter mNavDrawerAdapter;
private ArrayList<NavDrawerItem> mDrawerItems;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flow_main);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerItems = new ArrayList<NavDrawerItem>();
mDrawerItems.add(new NavDrawerItem("Profile", R.drawable.drawer_profile_icon));
mDrawerItems.add(new NavDrawerItem("Explore", R.drawable.drawer_explore_icon));
mDrawerItems.add(new NavDrawerItem("Shortlist", R.drawable.drawer_shortlist_icon));
mDrawerItems.add(new NavDrawerItem("About", R.drawable.drawer_about_icon));
mNavDrawerAdapter = new NavDrawerAdapter(mDrawerItems, this);
mDrawerList.setAdapter(mNavDrawerAdapter);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer_am,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
Fragment profileFrag = new ProfileFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.content_frame, profileFrag)
.commit();
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerList.setItemChecked(0, true);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
@Override
public void setTitle(CharSequence title) {
getActionBar().setTitle(title);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment = null;
switch (position){
case(0) : fragment = new ProfileFragment();break;
case(1) : fragment = new ExploreFragment();break;
case(2) : fragment = new ShortlistFragment();break;
case(3) : fragment = new AboutFragment();break;
}
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
|
package com.winterwell.es.client.agg;
import java.util.Map;
import com.winterwell.utils.Utils;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.web.IHasJson;
/**
* Made via Aggregations
* @author daniel
*
*/
public class Aggregation implements IHasJson {
@Override
public String toString() {
return "Aggregation[name=" + name + ", field=" + getField()+ ", type=" + type + ", props=" + props
+(aggs==null?"": ", aggs="+aggs)
+"]";
}
/**
* @return Can be null
*/
public String getField() {
return (String) props.get("field");
}
public final String name;
private String type;
/**
* the type props
*/
private final ArrayMap props = new ArrayMap();
public Aggregation setMissing(Object missing) {
props.put("missing", missing);
// safety check on type: string in stats is an error
if (missing != null) {
if ("stats".equals(getField())) assert missing instanceof Number;
}
return this;
}
/**
* See {@link Aggregations}
* @param aggResultName
* @param aggType
* @param field
*/
Aggregation(String aggResultName, String aggType, String field) {
Utils.check4null(aggResultName);
this.name = aggResultName;
this.type = aggType;
if (field != null) props.put("field", field);
}
/**
* child sub-aggregations, can be null
*/
Map<String,Aggregation> aggs;
/**
* a weak defence against lifecycle-breaking edits -- but this does not protect against sub-aggs being edited!
*/
private transient boolean toJsond;
/**
* {@inheritDoc}
*
* This does NOT include the name, which is used by the parent search
*/
@Override
public Map toJson2() {
if (type!=null) map.put(type, props);
// convert sub-aggregations
if (aggs!=null) {
Map<String, Object> jsonaggs = Containers.applyToValues(IHasJson.RECURSE_TOJSON2, aggs);
map.put("aggs", jsonaggs);
}
toJsond = true;
return map;
}
/**
* The base map. We'll poke things into this in toJson2()
*/
ArrayMap map = new ArrayMap();
public Aggregation put(String k, Object v) {
assert ! toJsond : "Cannot modify with "+k+"="+v+". This has already been converted into json :(";
props.put(k, v);
return this;
}
public Aggregation subAggregation(Aggregation dh) {
assert ! toJsond : "Cannot modify with sub-agg "+dh+". This has already been converted into json :(";
if (aggs==null) {
aggs = new ArrayMap();
}
aggs.put(dh.name, dh); //.toJson2());
return this;
}
public void setSize(int numTerms) {
if ( ! "terms".equals(type)) throw new IllegalStateException("Wrong type of agg: "+this);
put("size", numTerms);
}
/**
* Can be null
* @return e.g. "terms"
*/
public String getType() {
return type;
}
}
|
package de.kasoki.jfeedly.helper;
import de.kasoki.jfeedly.JFeedly;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPConnections {
private JFeedly jfeedlyHandler;
private static enum RequestType {
POST,
GET,
DELETE
};
public HTTPConnections(JFeedly feedly) {
this.jfeedlyHandler = feedly;
}
public String sendPostRequestToFeedly(String apiUrl, String urlParameters) {
return this.sendPostRequestToFeedly(apiUrl, urlParameters, false);
}
public String sendPostRequestToFeedly(String apiUrl, String urlParameters, boolean isAuthenticated) {
return this.sendRequest(apiUrl, urlParameters, isAuthenticated, RequestType.POST);
}
public String sendGetRequestToFeedly(String apiUrl) {
return this.sendRequest(apiUrl, "", true, RequestType.GET);
}
public String sendDeleteRequestToFeedly(String apiUrl) {
return this.sendRequest(apiUrl, "", true, RequestType.DELETE);
}
private String sendRequest(String apiUrl, String parameters, boolean isAuthenticated, RequestType type) {
try {
String url = this.jfeedlyHandler.getBaseUrl() + apiUrl;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("User-Agent", "jfeedly");
con.setRequestProperty("Content-Type", "application/json");
if(isAuthenticated) {
con.setRequestProperty("Authorization", "OAuth " + this.jfeedlyHandler.getConnection().getAccessToken());
}
// Send request header
if(type == RequestType.POST) {
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
} else if(type == RequestType.GET) {
con.setRequestMethod("GET");
} else if(type == RequestType.DELETE) {
con.setRequestMethod("DELETE");
} else {
System.err.println("jfeedly: Unkown RequestType " + type);
}
int responseCode = con.getResponseCode();
if(jfeedlyHandler.getVerbose()) {
System.out.println("\n" + type + " to: " + url);
System.out.println("parameters : " + parameters);
System.out.println("\nResponse Code : " + responseCode);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String serverResponse = response.toString();
if(jfeedlyHandler.getVerbose()) {
//print response
System.out.println(serverResponse);
}
return serverResponse;
} catch(IOException ex) {
ex.printStackTrace();
}
return null;
}
}
|
package de.lmu.ifi.dbs.logging;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* Additionally to the functionality of a LogRecord,
* a ProgressLogRecord provides information concerning
* the progress as the name of the progressing task
* and the percentage of the progress.
*
* @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public class ProgressLogRecord extends LogRecord
{
/**
* Generated serial version UID.
*/
private static final long serialVersionUID = 8776951182872391225L;
/**
* The name of the progressing task.
*/
private String task;
/**
* The percentage of progress.
*/
private int percentage;
/**
* Provides a ProgressLogRecord.
*
* @param level logging level
* @param msg log message
* @param task the name of the progressing task
* @param percentage the percentage of progress
* @see LogRecord#LogRecord(Level, String)
*/
public ProgressLogRecord(Level level, String msg, String task, int percentage)
{
super(level, msg);
this.task = task;
this.percentage = percentage;
}
/**
* Returns the percentage of the progress as set in the constructor.
*
*
* @return the percentage of the progress as set in the constructor
*/
public int getPercentage()
{
return this.percentage;
}
/**
* Returns the name of the progressing task.
*
*
* @return the name of the progressing task
*/
public String getTask()
{
return this.task;
}
}
|
package de.mrapp.android.preference.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
/**
* A custom view, which is extended from the view {@link android.widget.SeekBar}
* in order to provide a getter method, which allows to retrieve the seek bar's
* thumb on API versions less than 16.
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public class SeekBar extends android.widget.SeekBar {
/**
* The drawable, which is used to visualize the seek bar's thumb.
*/
private Drawable thumb;
/**
* Creates a new seek bar.
*
* @param context
* The context, which should be used by the seek bar, as an
* instance of the class {@link Context}
*/
public SeekBar(final Context context) {
super(context);
}
/**
* Creates a new seek bar.
*
* @param context
* The context, which should be used by the seek bar, as an
* instance of the class {@link Context}
* @param attributeSet
* The attributes of the XML tag that is inflating the view, as
* an instance of the type {@link AttributeSet}
*/
public SeekBar(final Context context, final AttributeSet attributeSet) {
super(context, attributeSet);
}
/**
* Creates a new seek bar.
*
* @param context
* The context, which should be used by the seek bar, as an
* instance of the class {@link Context}
* @param attributeSet
* The attributes of the XML tag that is inflating the view, as
* an instance of the type {@link AttributeSet}
* @param defaultStyle
* The default style to apply to this preference. If 0, no style
* will be applied (beyond what is included in the theme). This
* may either be an attribute resource, whose value will be
* retrieved from the current theme, or an explicit style
* resource
*/
public SeekBar(final Context context, final AttributeSet attributeSet,
final int defaultStyle) {
super(context, attributeSet, defaultStyle);
}
/**
* Creates a new seek bar.
*
* @param context
* The context, which should be used by the seek bar, as an
* instance of the class {@link Context}
* @param attributeSet
* The attributes of the XML tag that is inflating the view, as
* an instance of the type {@link AttributeSet}
* @param defaultStyle
* The default style to apply to this preference. If 0, no style
* will be applied (beyond what is included in the theme). This
* may either be an attribute resource, whose value will be
* retrieved from the current theme, or an explicit style
* resource
* @param defaultStyleResource
* A resource identifier of a style resource that supplies
* default values for the view, used only if defStyleAttr is 0 or
* can not be found in the theme. Can be 0 to not look for
* defaults
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SeekBar(final Context context, final AttributeSet attributeSet,
final int defaultStyle, final int defaultStyleResource) {
super(context, attributeSet, defaultStyle, defaultStyleResource);
}
/**
* Returns the drawable, which is used to visualize the seek bar's thumb.
*
* @return The drawable, which is used to visualize the seek bar's thumb, as
* an instance of the class {@link Drawable}
*/
public final Drawable getThumbDrawable() {
return thumb;
}
@Override
public final void setThumb(final Drawable thumb) {
super.setThumb(thumb);
this.thumb = thumb;
}
}
|
package dr.app.tracer.analysis;
import dr.inference.trace.MarginalLikelihoodAnalysis;
import jam.framework.AuxilaryFrame;
import jam.framework.DocumentFrame;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class BayesFactorsFrame extends AuxilaryFrame {
private List<MarginalLikelihoodAnalysis> marginalLikelihoods = new ArrayList<MarginalLikelihoodAnalysis>();
private JPanel contentPanel;
private JComboBox transformCombo;
private BayesFactorsModel bayesFactorsModel;
private JTable bayesFactorsTable;
enum Transform {
LOG10_BF("log10 Bayes Factors"),
LN_BF("ln Bayes Factors"),
BF("Bayes Factors");
Transform(String name) {
this.name = name;
}
public String toString() {
return name;
}
private String name;
}
public BayesFactorsFrame(DocumentFrame frame, String title, String info, boolean hasErrors) {
super(frame);
setTitle(title);
bayesFactorsModel = new BayesFactorsModel(hasErrors);
bayesFactorsTable = new JTable(bayesFactorsModel);
bayesFactorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane1 = new JScrollPane(bayesFactorsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPanel = new JPanel(new BorderLayout(0, 0));
contentPanel.setOpaque(false);
contentPanel.setBorder(new BorderUIResource.EmptyBorderUIResource(
new java.awt.Insets(0, 0, 6, 0)));
JToolBar toolBar = new JToolBar();
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
toolBar.setFloatable(false);
transformCombo = new JComboBox(Transform.values());
transformCombo.setFont(UIManager.getFont("SmallSystemFont"));
JLabel label = new JLabel("Show:");
label.setFont(UIManager.getFont("SmallSystemFont"));
label.setLabelFor(transformCombo);
toolBar.add(label);
toolBar.add(transformCombo);
toolBar.add(new JToolBar.Separator(new Dimension(8, 8)));
contentPanel.add(toolBar, BorderLayout.NORTH);
transformCombo.addItemListener(
new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent ev) {
bayesFactorsModel.fireTableDataChanged();
}
}
);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
label = new JLabel(info);
label.setFont(UIManager.getFont("SmallSystemFont"));
panel1.add(label, BorderLayout.NORTH);
panel1.add(scrollPane1, BorderLayout.CENTER);
contentPanel.add(panel1, BorderLayout.CENTER);
label = new JLabel("<html>Marginal likelihood estimated using the method Newton & Raftery <br>" +
"(Newton M, Raftery A: Approximate Bayesian inference with the weighted likelihood bootstrap.<br>" +
"Journal of the Royal Statistical Society, Series B 1994, 56:3-48)<br>" +
"with the modifications proprosed by Suchard et al (2001, <i>MBE</i> <b>18</b>: 1001-1013)</html>");
label.setFont(UIManager.getFont("SmallSystemFont"));
contentPanel.add(label, BorderLayout.SOUTH);
setContentsPanel(contentPanel);
getSaveAction().setEnabled(false);
getSaveAsAction().setEnabled(false);
getCutAction().setEnabled(false);
getCopyAction().setEnabled(true);
getPasteAction().setEnabled(false);
getDeleteAction().setEnabled(false);
getSelectAllAction().setEnabled(false);
getFindAction().setEnabled(false);
getZoomWindowAction().setEnabled(false);
}
public void addMarginalLikelihood(MarginalLikelihoodAnalysis marginalLikelihood) {
this.marginalLikelihoods.add(marginalLikelihood);
bayesFactorsModel.fireTableStructureChanged();
bayesFactorsTable.repaint();
}
public void initializeComponents() {
setSize(new Dimension(640, 480));
}
public boolean useExportAction() {
return true;
}
public JComponent getExportableComponent() {
return contentPanel;
}
public void doCopy() {
java.awt.datatransfer.Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
java.awt.datatransfer.StringSelection selection =
new java.awt.datatransfer.StringSelection(bayesFactorsModel.toString());
clipboard.setContents(selection, selection);
}
class BayesFactorsModel extends AbstractTableModel {
String[] columnNames = {"Trace", "ln P(data | model)", "S.E."};
private DecimalFormat formatter2 = new DecimalFormat("
private int columnCount;
public BayesFactorsModel(boolean hasErrors) {
this.columnCount = (hasErrors ? 3 : 2);
}
public int getColumnCount() {
return columnCount + marginalLikelihoods.size();
}
public int getRowCount() {
return marginalLikelihoods.size();
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return marginalLikelihoods.get(row).getTraceName();
}
if (col == 1) {
return formatter2.format(marginalLikelihoods.get(row).getLogMarginalLikelihood());
} else if (columnCount > 2 && col == 2) {
return " +/- " + formatter2.format(marginalLikelihoods.get(row).getBootstrappedSE());
} else {
if (col - columnCount != row) {
double lnML1 = marginalLikelihoods.get(row).getLogMarginalLikelihood();
double lnML2 = marginalLikelihoods.get(col - columnCount).getLogMarginalLikelihood();
double lnRatio = lnML1 - lnML2;
double value;
switch ((Transform) transformCombo.getSelectedItem()) {
case BF:
value = Math.exp(lnRatio);
break;
case LN_BF:
value = lnRatio;
break;
case LOG10_BF:
value = lnRatio / Math.log(10.0);
break;
default:
throw new IllegalArgumentException("Unknown transform type");
}
return formatter2.format(value);
} else {
return "-";
}
}
}
public String getColumnName(int column) {
if (column < columnCount) {
return columnNames[column];
}
return marginalLikelihoods.get(column - columnCount).getTraceName();
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
}
|
package dr.evolution.tree;
import dr.evolution.io.Importer;
import dr.evolution.io.NewickImporter;
import java.io.IOException;
import java.util.ArrayList;
/**
* @author Guy Baele
* Path difference metric according to Kendall & Colijn (2015)
*/
public class KCPathDifferenceMetric {
private Tree focalTree;
private int dim, externalNodeCount;
private double[] focalSmallM, focalLargeM;
public KCPathDifferenceMetric() {
}
public KCPathDifferenceMetric(Tree focalTree) {
this.focalTree = focalTree;
this.externalNodeCount = focalTree.getExternalNodeCount();
this.dim = (externalNodeCount-2)*(externalNodeCount-1)+externalNodeCount;
this.focalSmallM = new double[dim];
this.focalLargeM = new double[dim];
int index = 0;
for (int i = 0; i < externalNodeCount; i++) {
for (int j = i+1; j < externalNodeCount; j++) {
//get two leaf nodes
NodeRef nodeOne = focalTree.getExternalNode(i);
NodeRef nodeTwo = focalTree.getExternalNode(j);
//get common ancestor of 2 leaf nodes
NodeRef MRCA = Tree.Utils.getCommonAncestor(focalTree, nodeOne, nodeTwo);
int edges = 0;
double branchLengths = 0.0;
while (MRCA != focalTree.getRoot()) {
edges++;
branchLengths += focalTree.getNodeHeight(focalTree.getParent(MRCA)) - focalTree.getNodeHeight(MRCA);
MRCA = focalTree.getParent(MRCA);
}
focalSmallM[index] = edges;
focalLargeM[index] = branchLengths;
index++;
}
}
//fill out arrays further
index = 0;
for (int i = (externalNodeCount-1)*(externalNodeCount-2); i < dim; i++) {
focalSmallM[i] = 1.0;
focalLargeM[i] = focalTree.getNodeHeight(focalTree.getParent(focalTree.getExternalNode(index))) - focalTree.getNodeHeight(focalTree.getExternalNode(index));
index++;
}
}
public ArrayList<Double> getMetric(Tree tree, ArrayList<Double> lambda) {
//check if taxon lists are in the same order!!
if (focalTree.getExternalNodeCount() != tree.getExternalNodeCount()) {
throw new RuntimeException("Different number of taxa in both trees.");
} else {
for (int i = 0; i < focalTree.getExternalNodeCount(); i++) {
if (!focalTree.getNodeTaxon(focalTree.getExternalNode(i)).getId().equals(tree.getNodeTaxon(tree.getExternalNode(i)).getId())) {
throw new RuntimeException("Mismatch between taxa in both trees: " + focalTree.getNodeTaxon(focalTree.getExternalNode(i)).getId() + " vs. " + tree.getNodeTaxon(tree.getExternalNode(i)).getId());
}
}
}
double[] smallMTwo = new double[dim];
double[] largeMTwo = new double[dim];
int index = 0;
for (int i = 0; i < tree.getExternalNodeCount(); i++) {
for (int j = i+1; j < tree.getExternalNodeCount(); j++) {
//get two leaf nodes
NodeRef nodeOne = tree.getExternalNode(i);
NodeRef nodeTwo = tree.getExternalNode(j);
//get common ancestor of 2 leaf nodes
NodeRef MRCA = Tree.Utils.getCommonAncestor(tree, nodeOne, nodeTwo);
int edges = 0;
double branchLengths = 0.0;
while (MRCA != tree.getRoot()) {
edges++;
branchLengths += tree.getNodeHeight(tree.getParent(MRCA)) - tree.getNodeHeight(MRCA);
MRCA = tree.getParent(MRCA);
}
smallMTwo[index] = edges;
largeMTwo[index] = branchLengths;
index++;
}
}
//fill out arrays further
index = 0;
for (int i = (tree.getExternalNodeCount()-1)*(tree.getExternalNodeCount()-2); i < dim; i++) {
smallMTwo[i] = 1.0;
largeMTwo[i] = tree.getNodeHeight(tree.getParent(tree.getExternalNode(index))) - tree.getNodeHeight(tree.getExternalNode(index));
index++;
}
double[] vArrayOne = new double[dim];
double[] vArrayTwo = new double[dim];
ArrayList<Double> results = new ArrayList<Double>();
for (Double l : lambda) {
double distance = 0.0;
//calculate Euclidean distance for this lambda value
for (int i = 0; i < dim; i++) {
vArrayOne[i] = (1.0 - l)*focalSmallM[i] + l*focalLargeM[i];
vArrayTwo[i] = (1.0 - l)*smallMTwo[i] + l*largeMTwo[i];
distance += Math.pow(vArrayOne[i] - vArrayTwo[i],2);
}
distance = Math.sqrt(distance);
results.add(distance);
}
return results;
}
/**
* This method bypasses the constructor entirely, computing the metric on the two provided trees
* and ignoring the internally stored tree.
* @param tree1 Focal tree that will be used for computing the metric
* @param tree2 Provided tree that will be compared to the focal tree
* @param lambda Collection of lambda values for which to compute the metric
* @return
*/
public ArrayList<Double> getMetric(Tree tree1, Tree tree2, ArrayList<Double> lambda) {
int dim = (tree1.getExternalNodeCount()-2)*(tree1.getExternalNodeCount()-1)+tree1.getExternalNodeCount();
double[] smallMOne = new double[dim];
double[] largeMOne = new double[dim];
double[] smallMTwo = new double[dim];
double[] largeMTwo = new double[dim];
//check if taxon lists are in the same order!!
if (tree1.getExternalNodeCount() != tree2.getExternalNodeCount()) {
throw new RuntimeException("Different number of taxa in both trees.");
} else {
for (int i = 0; i < tree1.getExternalNodeCount(); i++) {
if (!tree1.getNodeTaxon(tree1.getExternalNode(i)).getId().equals(tree2.getNodeTaxon(tree2.getExternalNode(i)).getId())) {
throw new RuntimeException("Mismatch between taxa in both trees: " + tree1.getNodeTaxon(tree1.getExternalNode(i)).getId() + " vs. " + tree2.getNodeTaxon(tree2.getExternalNode(i)).getId());
}
}
}
int index = 0;
for (int i = 0; i < tree1.getExternalNodeCount(); i++) {
for (int j = i+1; j < tree1.getExternalNodeCount(); j++) {
//get two leaf nodes
NodeRef nodeOne = tree1.getExternalNode(i);
NodeRef nodeTwo = tree1.getExternalNode(j);
//get common ancestor of 2 leaf nodes
NodeRef MRCA = Tree.Utils.getCommonAncestor(tree1, nodeOne, nodeTwo);
int edges = 0;
double branchLengths = 0.0;
while (MRCA != tree1.getRoot()) {
edges++;
branchLengths += tree1.getNodeHeight(tree1.getParent(MRCA)) - tree1.getNodeHeight(MRCA);
MRCA = tree1.getParent(MRCA);
}
smallMOne[index] = edges;
largeMOne[index] = branchLengths;
index++;
}
}
//fill out arrays further
index = 0;
for (int i = (tree1.getExternalNodeCount()-1)*(tree1.getExternalNodeCount()-2); i < dim; i++) {
smallMOne[i] = 1.0;
largeMOne[i] = tree1.getNodeHeight(tree1.getParent(tree1.getExternalNode(index))) - tree1.getNodeHeight(tree1.getExternalNode(index));
index++;
}
/*for (int i = 0; i < smallMOne.length; i++) {
System.out.print(smallMOne[i] + " ");
}
System.out.println();
for (int i = 0; i < largeMOne.length; i++) {
System.out.print(largeMOne[i] + " ");
}
System.out.println("\n");*/
index = 0;
for (int i = 0; i < tree2.getExternalNodeCount(); i++) {
for (int j = i+1; j < tree2.getExternalNodeCount(); j++) {
//get two leaf nodes
NodeRef nodeOne = tree2.getExternalNode(i);
NodeRef nodeTwo = tree2.getExternalNode(j);
//get common ancestor of 2 leaf nodes
NodeRef MRCA = Tree.Utils.getCommonAncestor(tree2, nodeOne, nodeTwo);
int edges = 0;
double branchLengths = 0.0;
while (MRCA != tree2.getRoot()) {
edges++;
branchLengths += tree2.getNodeHeight(tree2.getParent(MRCA)) - tree2.getNodeHeight(MRCA);
MRCA = tree2.getParent(MRCA);
}
smallMTwo[index] = edges;
largeMTwo[index] = branchLengths;
index++;
}
}
//fill out arrays further
index = 0;
for (int i = (tree2.getExternalNodeCount()-1)*(tree2.getExternalNodeCount()-2); i < dim; i++) {
smallMTwo[i] = 1.0;
largeMTwo[i] = tree2.getNodeHeight(tree2.getParent(tree2.getExternalNode(index))) - tree2.getNodeHeight(tree2.getExternalNode(index));
index++;
}
/*for (int i = 0; i < smallMTwo.length; i++) {
System.out.print(smallMTwo[i] + " ");
}
System.out.println();
for (int i = 0; i < largeMTwo.length; i++) {
System.out.print(largeMTwo[i] + " ");
}
System.out.println("\n");*/
double[] vArrayOne = new double[dim];
double[] vArrayTwo = new double[dim];
ArrayList<Double> results = new ArrayList<Double>();
for (Double l : lambda) {
double distance = 0.0;
//calculate Euclidean distance for this lambda value
for (int i = 0; i < dim; i++) {
vArrayOne[i] = (1.0 - l)*smallMOne[i] + l*largeMOne[i];
vArrayTwo[i] = (1.0 - l)*smallMTwo[i] + l*largeMTwo[i];
distance += Math.pow(vArrayOne[i] - vArrayTwo[i],2);
}
distance = Math.sqrt(distance);
results.add(distance);
}
return results;
}
public static void main(String[] args) {
try {
NewickImporter importer = new NewickImporter("(('A':1.2,'B':0.8):0.5,('C':0.8,'D':1.0):1.1)");
Tree treeOne = importer.importNextTree();
System.out.println("tree 1: " + treeOne);
importer = new NewickImporter("((('A':0.8,'B':1.4):0.3,'C':0.7):0.9,'D':1.0)");
Tree treeTwo = importer.importNextTree();
System.out.println("tree 2: " + treeTwo + "\n");
ArrayList<Double> lambdaValues = new ArrayList<Double>();
lambdaValues.add(0.0);
lambdaValues.add(0.5);
lambdaValues.add(1.0);
ArrayList<Double> metric = (new KCPathDifferenceMetric().getMetric(treeOne, treeTwo, lambdaValues));
System.out.println("lambda (0.0) = " + metric.get(0));
System.out.println("lambda (0.5) = " + metric.get(1));
System.out.println("lambda (1.0) = " + metric.get(2));
//Additional test for comparing a collection of trees against a (fixed) focal tree
KCPathDifferenceMetric focalMetric = new KCPathDifferenceMetric(treeOne);
metric = focalMetric.getMetric(treeTwo, lambdaValues);
System.out.println("lambda (0.0) = " + metric.get(0));
System.out.println("lambda (0.5) = " + metric.get(1));
System.out.println("lambda (1.0) = " + metric.get(2));
} catch(Importer.ImportException ie) {
System.err.println(ie);
} catch(IOException ioe) {
System.err.println(ioe);
}
}
}
|
package dr.evomodel.continuous;
import dr.inference.model.*;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.Matrix;
import dr.util.Citable;
import dr.util.Citation;
import java.util.List;
/**
* @author Max Tolkoff
* @author Marc Suchard
*/
public class LatentFactorModel extends AbstractModelLikelihood implements Citable {
// private Matrix data;
// private Matrix factors;
// private Matrix loadings;
private Matrix residual;
private final MatrixParameter data;
private final MatrixParameter factors;
private final MatrixParameter loadings;
private Matrix tData;
private final DiagonalMatrix rowPrecision;
private final DiagonalMatrix colPrecision;
private final int dimFactors;
private final int dimData;
private final int nTaxa;
private boolean likelihoodKnown = false;
private boolean isDataScaled=false;
private boolean storedLikelihoodKnown;
private double logLikelihood;
private double storedLogLikelihood;
public LatentFactorModel(MatrixParameter data, MatrixParameter factors, MatrixParameter loadings,
DiagonalMatrix rowPrecision, DiagonalMatrix colPrecision
) {
super("");
// data = new Matrix(dataIn.getParameterAsMatrix());
// factors = new Matrix(factorsIn.getParameterAsMatrix());
// loadings = new Matrix(loadingsIn.getParameterAsMatrix());
this.data = data;
this.factors = factors;
// Put default bounds on factors
for (int i = 0; i < factors.getParameterCount(); ++i) {
Parameter p = factors.getParameter(i);
System.err.println(p.getId() + " " + p.getDimension());
p.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, p.getDimension()));
}
this.loadings = loadings;
// Put default bounds on loadings
// loadings.addBounds();
this.rowPrecision = rowPrecision;
this.colPrecision = colPrecision;
addVariable(data);
addVariable(factors);
addVariable(loadings);
addVariable(rowPrecision);
addVariable(colPrecision);
dimFactors = factors.getRowDimension();
dimData = loadings.getColumnDimension();
// nTaxa = factors.getParameterCount();
// nTaxa = factors.getParameter(0).getDimension();
nTaxa = factors.getColumnDimension();
// System.out.print(nTaxa);
// System.out.print("\n");
// System.out.print(dimData);
// System.out.print("\n");
// System.out.println(dimFactors);
// System.out.println(data.getDimension());
// System.out.println(data.getRowDimension());
// System.out.println(data.getColumnDimension());
// System.out.println(new Matrix(data.getParameterAsMatrix()));
// System.out.println(new Matrix(factors.getParameterAsMatrix()));
if (nTaxa * dimData != data.getDimension()) {
throw new RuntimeException("LOADINGS MATRIX AND FACTOR MATRIX MUST HAVE EXTERNAL DIMENSIONS WHOSE PRODUCT IS EQUAL TO THE NUMBER OF DATA POINTS\n");
// System.exit(10);
}
if (dimData < dimFactors) {
throw new RuntimeException("MUST HAVE FEWER FACTORS THAN DATA POINTS\n");
}
// computeResiduals();
// System.out.print(new Matrix(residual.toComponents()));
// System.out.print(calculateLogLikelihood());
}
// public Matrix getData(){
// Matrix ans=data;
// return ans;
// public Matrix getFactors(){
// Matrix ans=factors;
// return ans;
// public Matrix getLoadings(){
// Matrix ans=loadings;
// return ans;
// public Matrix getResidual(){
// Matrix ans=residual;
// return ans;
private Matrix getScaledData(){
// Matrix answer=new Matrix(data.getRowDimension(), data.getColumnDimension());
double[][] aData=data.getParameterAsMatrix();
double[] meanList=new double[data.getRowDimension()];
double[] varList=new double[data.getRowDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for (int j=0; j<data.getRowDimension(); j++){
meanList[j]+=data.getParameterValue(j,i);
}
}
for(int i=0; i<data.getRowDimension(); i++){
meanList[i]=meanList[i]/data.getColumnDimension();
}
double[][] answerTemp=new double[data.getRowDimension()][data.getColumnDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
answerTemp[j][i]=aData[j][i]-meanList[j];
}
}
// System.out.println(new Matrix(answerTemp));
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
varList[j]+=answerTemp[j][i]*answerTemp[j][i];
}
}
for(int i=0; i<data.getRowDimension(); i++){
varList[i]=varList[i]/(data.getColumnDimension()-1);
varList[i]=StrictMath.sqrt(varList[i]);
}
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
answerTemp[j][i]=answerTemp[j][i]/varList[j];
}
}
// System.out.println(new Matrix(answerTemp));
return new Matrix(answerTemp);
}
private Matrix copy(CompoundParameter parameter, int dimMajor, int dimMinor) {
return new Matrix(parameter.getParameterValues(), dimMajor, dimMinor);
}
private Matrix computeResiduals() {
// Parameter[] dataTemp=new Parameter[nTaxa];
// for(int i=0; i<nTaxa; i++)
// dataTemp[i] = new Parameter.Default(dimData);
// for(int j=0; j<dimData; j++)
// dataTemp[i].setParameterValue(j, data.getParameterValue(i*dimData+j));
// MatrixParameter dataMatrix=new MatrixParameter(null, dataTemp);
Matrix residual = null;
Matrix tLoadings = new Matrix(loadings.getParameterAsMatrix());
if(!isDataScaled){
tData = getScaledData();
isDataScaled=true;
}
Matrix tFactors = new Matrix(factors.getParameterAsMatrix());
try {
residual = tData.subtract(tLoadings.transpose().product(tFactors));
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return residual;
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
// Do nothing
}
/**
* Additional state information, outside of the sub-model is stored by this call.
*/
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
storedLikelihoodKnown = likelihoodKnown;
}
/**
* After this call the model is guaranteed to have returned its extra state information to
* the values coinciding with the last storeState call.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood; // TODO Possible error in store/restore -- when changed to 42, no error arises
likelihoodKnown = storedLikelihoodKnown;
}
/**
* This call specifies that the current state is accept. Most models will not need to do anything.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void acceptState() {
// Do nothing
}
/**
* This method is called whenever a parameter is changed.
* <p/>
* It is strongly recommended that the model component sets a "dirty" flag and does no
* further calculations. Recalculation is typically done when the model component is asked for
* some information that requires them. This mechanism is 'lazy' so that this method
* can be safely called multiple times with minimal computational cost.
*/
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
likelihoodKnown = false;
isDataScaled=false;
}
/**
* @return a list of citations associated with this object
*/
@Override
public List<Citation> getCitations() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Get the model.
*
* @return the model.
*/
@Override
public Model getModel() {
return this;
}
/**
* Get the log likelihood.
*
* @return the log likelihood.
*/
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
/**
* Forces a complete recalculation of the likelihood next time getLikelihood is called
*/
@Override
public void makeDirty() {
likelihoodKnown = false;
}
private double calculateLogLikelihood() {
for(int i=0; i<StrictMath.min(loadings.getRowDimension(),loadings.getColumnDimension()); i++)
{
if(loadings.getParameter(i).getParameterValue(i)<0)
{
return Double.NEGATIVE_INFINITY;
}
}
Matrix tRowPrecision= new Matrix(rowPrecision.getParameterAsMatrix());
Matrix tColPrecision= new Matrix(colPrecision.getParameterAsMatrix());
Matrix residual = computeResiduals();
// computeResiduals();
Matrix expPart=null;
double logDetRow=0;
double logDetCol=0;
try{
expPart = residual.product(tRowPrecision.product(residual.transpose())).product(tColPrecision);
logDetRow=tRowPrecision.logDeterminant();
logDetCol=tColPrecision.logDeterminant();
// System.out.println(logDetCol);
// System.out.println(logDetRow);
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
double trace=0;
if(!expPart.isSquare())
{
System.err.print("Matrices are not conformable");
System.exit(0);
}
else{
for(int i=0; i<expPart.rows(); i++){
trace+=expPart.component(i,i);
}
}
// System.out.println(expPart);
return -.5*trace + .5*tRowPrecision.rows()*logDetCol
+ .5*tColPrecision.rows()*logDetRow
-.5*tRowPrecision.rows()*tColPrecision.rows()*Math.log(2.0 * StrictMath.PI);
}
}
|
package edu.mit.commensalejml.impl;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import edu.mit.streamjit.util.bytecode.Argument;
import edu.mit.streamjit.util.bytecode.Field;
import edu.mit.streamjit.util.bytecode.Method;
import edu.mit.streamjit.util.bytecode.Value;
import edu.mit.streamjit.util.bytecode.methodhandles.Combinators;
import static edu.mit.streamjit.util.bytecode.methodhandles.LookupUtils.findVirtual;
import static edu.mit.streamjit.util.bytecode.methodhandles.LookupUtils.params;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toList;
import org.ejml.data.D1Matrix64F;
import org.ejml.data.DenseMatrix64F;
/**
*
* @author Jeffrey Bosboom <jbosboom@csail.mit.edu>
* @since 10/3/2014
*/
public final class GreedyCodegen {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private final Object stateHolder;
private final Map<Value, Field> fieldMap;
private final Method method;
private final ExpressionDAG result;
private final Map<Expr, MethodHandle> ready = new LinkedHashMap<>();
private final Set<Expr> worklist = new LinkedHashSet<>();
//the number of "leases" on temporary matrices
private final Multiset<MethodHandle> allocatedTemps = HashMultiset.create();
private final Map<MatrixDimension, Deque<MethodHandle>> tempFreelist;
private final SetMultimap<Expr, Expr> remainingUses = HashMultimap.create();
private final Map<Input, MethodHandle> deferredFieldSets = new LinkedHashMap<>();
private MethodHandle deferredRet = null;
public GreedyCodegen(Object stateHolder, Map<Value, Field> fieldMap, Method method, ExpressionDAG result, Map<MatrixDimension, Deque<MethodHandle>> tempFreelist) {
this.stateHolder = stateHolder;
this.fieldMap = fieldMap;
this.method = method;
this.result = result;
this.tempFreelist = tempFreelist;
}
public MethodHandle codegen() {
result.roots().forEachOrdered(this::prepare);
List<MethodHandle> ops = new ArrayList<>();
while (!worklist.isEmpty()) {
Expr next = popNext();
List<MethodHandle> sources = next.deps().stream().map(this::source).collect(toList());
//inplace sources are now free
next.inplacePlaces().stream().forEachOrdered((d) -> remainingUses.get(d).remove(next));
next.inplacePlaces().stream().distinct().forEachOrdered(this::tryFree);
MethodHandle sink = sink(next);
ops.add(next.operate(sources, sink));
ready.put(next, sink);
//If this expression sets a field and we didn't allocate it as a
//sink, we have to set it later. (We'll process deferred sets
//after each expr, so we might do it immediately.)
Field destField = result.sets.inverse().get(next);
if (destField != null && sink != makeFieldGetter(destField)) {
Input destInput = result.inputs.get(destField);
deferredFieldSets.put(destInput, sink);
//take another temp lease
if (allocatedTemps.contains(sink))
allocatedTemps.add(sink);
//Field sets aren't considered uses, so we can free it now.
tryFree(next);
}
//If this is the return value, it's live until method end.
if (result.ret == next) {
deferredRet = sink;
//take another temp lease
if (allocatedTemps.contains(sink))
allocatedTemps.add(sink);
//Returns aren't considered uses, so we can free it now.
tryFree(next);
}
//non-inplace sources are now free
next.deps().stream().filter((d) -> !next.inplacePlaces().contains(d)).forEachOrdered((d) -> remainingUses.get(d).remove(next));
next.deps().stream().filter((d) -> !next.inplacePlaces().contains(d)).distinct().forEachOrdered(this::tryFree);
ops.addAll(undeferSets());
}
assert deferredFieldSets.isEmpty() : deferredFieldSets;
MethodHandle opsHandle = Combinators.semicolon(ops);
MethodHandle withArgs = opsHandle;
for (Argument a : FluentIterable.from(method.arguments()).skip(1)) {
Field f = fieldMap.get(a);
withArgs = MethodHandles.collectArguments(withArgs, withArgs.type().parameterCount(), makeFieldSetter(f));
}
if (deferredRet != null) {
withArgs = MethodHandles.filterReturnValue(withArgs, deferredRet);
tryExpireTemp(deferredRet);
}
assert allocatedTemps.isEmpty() : allocatedTemps;
return withArgs;
}
private void prepare(Expr e) {
if (e instanceof Input) {
if (!ready.containsKey(e))
ready.put(e, makeFieldGetter(((Input)e).getField()));
} else
worklist.add(e);
e.deps().forEach(d -> remainingUses.put(d, e));
e.deps().forEach(this::prepare);
}
private Expr popNext() {
// List<Expr> possibleNext = new ArrayList<>();
for (Expr e : worklist)
if (ready.keySet().containsAll(e.deps())) {
worklist.remove(e);
return e;
}
throw new AssertionError("nothing with all deps ready");
// possibleNext.add(e);
// Collections.sort(possibleNext, new Comparator<Expr>() {
// @Override
// public int compare(Expr left, Expr right) {
// List<Integer> leftDepsRank = new ArrayList<>(),
// rightDepsRank = new ArrayList<>();
// for (Expr e : left.deps())
// leftDepsRank.add(ready.indexOf(e));
// for (Expr e : right.deps())
// rightDepsRank.add(ready.indexOf(e));
// Collections.sort(leftDepsRank);
// Collections.sort(rightDepsRank);
// return Ordering.<Integer>natural().lexicographical().compare(leftDepsRank, rightDepsRank);
// return possibleNext.get(0);
}
private MethodHandle source(Expr e) {
return ready.computeIfAbsent(e, (Expr x) -> {
throw new AssertionError(e + " is not ready");
});
}
/**
* Finds a sink for the result of the given expression. If inplace is
* possible, inplace will be done; else a temporary will be allocated.
* Despite intuition, sinks are getter handles, not setters.
*/
private MethodHandle sink(Expr e) {
// //Field outputs should go direct if we don't still need the
// //corresponding input.
// //TODO: I guess we'd want some lookahead to see if going direct is
// //possible early, to set up an inplace operation targeting the output.
Field output = result.sets.inverse().get(e);
Input input = result.inputs.get(output);
if (output != null && remainingUses.get(input).isEmpty())
return makeFieldGetter(input.getField());
assert e.rows() != -1 && e.cols() != -1;
Deque<MethodHandle> freelist = tempFreelist.computeIfAbsent(new MatrixDimension(e.rows(), e.cols()), (MatrixDimension d) -> new ArrayDeque<>());
if (freelist.isEmpty())
freelist.push(MethodHandles.constant(DenseMatrix64F.class, new DenseMatrix64F(e.rows(), e.cols())));
MethodHandle temp = freelist.pop();
assert !allocatedTemps.contains(temp) : "free list contained temp already allocated";
allocatedTemps.add(temp);
return temp;
}
private void tryFree(Expr e) {
MethodHandle loc = ready.get(e);
//We took another lease on deferred field sets or ret so we don't
//need to check that here; we can still unready it.
if (remainingUses.get(e).isEmpty()) {
ready.remove(e);
tryExpireTemp(loc);
}
}
private void tryExpireTemp(MethodHandle loc) {
//if loc is a temp and we expired its last lease
if (allocatedTemps.remove(loc) && !allocatedTemps.contains(loc))
try {
tempFreelist.get(new MatrixDimension((DenseMatrix64F)loc.invokeExact())).push(loc);
} catch (Throwable ex) {
throw Throwables.propagate(ex);
}
}
private List<MethodHandle> undeferSets() {
List<MethodHandle> setOps = new ArrayList<>();
for (Iterator<Map.Entry<Input, MethodHandle>> i = deferredFieldSets.entrySet().iterator(); i.hasNext();) {
Map.Entry<Input, MethodHandle> entry = i.next();
Input input = entry.getKey();
MethodHandle temp = entry.getValue();
if (remainingUses.get(input).isEmpty()) {
setOps.add(setField(input.getField(), temp));
tryExpireTemp(temp);
i.remove();
}
}
return setOps;
}
private final MethodHandle SET_ = findVirtual(D1Matrix64F.class, "set", params(1));
private final MethodHandle SET = SET_.asType(MethodType.methodType(void.class, DenseMatrix64F.class, DenseMatrix64F.class));
private MethodHandle setField(Field field, MethodHandle source) {
MethodHandle sink = makeFieldGetter(field);
MethodHandle set = MethodHandles.collectArguments(SET, 0, sink);
return MethodHandles.collectArguments(set, 0, source);
}
private final Map<Field, MethodHandle> fieldGetterCache = new IdentityHashMap<>();
private MethodHandle makeFieldGetter(Field f) {
//TODO: if we know the Input's matrix (i.e., not an arg), should we
//make a constant handle instead?
return fieldGetterCache.computeIfAbsent(f, (Field f_) -> {
try {
return LOOKUP.findGetter(stateHolder.getClass(), f_.getName(), DenseMatrix64F.class).bindTo(stateHolder);
} catch (NoSuchFieldException | IllegalAccessException ex) {
throw new AssertionError(ex);
}
});
}
private MethodHandle makeFieldSetter(Field f) {
try {
return LOOKUP.findSetter(stateHolder.getClass(), f.getName(), DenseMatrix64F.class).bindTo(stateHolder);
} catch (NoSuchFieldException | IllegalAccessException ex) {
throw new AssertionError(ex);
}
}
}
|
package edu.mit.streamjit.apps.test;
import com.google.common.collect.ImmutableList;
import edu.mit.streamjit.api.CompiledStream;
import edu.mit.streamjit.api.Filter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.OneToOneElement;
import edu.mit.streamjit.api.Pipeline;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.StreamCompiler;
import edu.mit.streamjit.api.StreamElement;
import edu.mit.streamjit.impl.common.BlobHostStreamCompiler;
import edu.mit.streamjit.impl.common.PrintStreamVisitor;
import edu.mit.streamjit.impl.compiler.CompilerBlobFactory;
import edu.mit.streamjit.impl.interp.DebugStreamCompiler;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
/**
* Generates random streams.
*
* TODO: This (and all of test/) really doesn't belong under apps/; we should
* have a separate package for sanity/regression tests (basically anything that
* isn't real-world).
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 7/26/2013
*/
public final class StreamFuzzer {
public interface FuzzElement {
public OneToOneElement<Integer, Integer> instantiate();
public String toJava();
@Override
public boolean equals(Object other);
@Override
public int hashCode();
}
private static final int MAX_DEPTH = 5;
public static FuzzElement generate() {
return makeStream(MAX_DEPTH);
}
private static final Random rng = new Random();
private static final int FILTER_PROB = 50, PIPELINE_PROB = 25, SPLITJOIN_PROB = 25;
private static FuzzElement makeStream(int depthLimit) {
int r = rng.nextInt(FILTER_PROB + PIPELINE_PROB + SPLITJOIN_PROB);
if (depthLimit == 0 || r < FILTER_PROB) {
return makeFilter();
} else if (r < FILTER_PROB + PIPELINE_PROB) {
return makePipeline(depthLimit);
} else if (r < FILTER_PROB + PIPELINE_PROB + SPLITJOIN_PROB) {
return makeSplitjoin(depthLimit);
} else
throw new AssertionError(r);
}
private static FuzzFilter makeFilter() {
return new FuzzFilter(Identity.class, ImmutableList.of());
}
private static final int MAX_PIPELINE_LENGTH = 5;
private static FuzzPipeline makePipeline(int depthLimit) {
int length = rng.nextInt(MAX_PIPELINE_LENGTH) + 1;
ImmutableList.Builder<FuzzElement> elements = ImmutableList.builder();
for (int i = 0; i < length; ++i)
elements.add(makeStream(depthLimit - 1));
return new FuzzPipeline(elements.build());
}
private static final int MAX_SPLITJOIN_BRANCHES = 5;
private static FuzzSplitjoin makeSplitjoin(int depthLimit) {
int numBranches = rng.nextInt(MAX_SPLITJOIN_BRANCHES) + 1;
ImmutableList.Builder<FuzzElement> branches = ImmutableList.builder();
for (int i = 0; i < numBranches; ++i)
branches.add(makeStream(depthLimit - 1));
return new FuzzSplitjoin(makeSplitter(), makeJoiner(), branches.build());
}
private static FuzzSplitter makeSplitter() {
return new FuzzSplitter(RoundrobinSplitter.class, ImmutableList.of());
}
private static FuzzJoiner makeJoiner() {
return new FuzzJoiner(RoundrobinJoiner.class, ImmutableList.of());
}
private static final com.google.common.base.Joiner ARG_JOINER = com.google.common.base.Joiner.on(", ");
private static class FuzzStreamElement<T extends StreamElement<Integer, Integer>> {
private final Class<? extends T> filterClass;
private final ImmutableList<Object> arguments;
private transient Constructor<? extends T> constructor;
protected FuzzStreamElement(Class<? extends T> filterClass, ImmutableList<Object> arguments) {
this.filterClass = filterClass;
this.arguments = arguments;
}
public T instantiate() {
if (constructor == null)
constructor = findConstructor();
try {
return constructor.newInstance(arguments.toArray());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
throw new AssertionError("Failed to instantiate "+constructor+" with "+arguments, ex);
}
}
private Constructor<? extends T> findConstructor() {
@SuppressWarnings("unchecked")
Constructor<? extends T>[] constructors = (Constructor<T>[])filterClass.getConstructors();
List<Constructor<? extends T>> retvals = new ArrayList<>();
Map<Constructor<? extends T>, Throwable> exceptions = new HashMap<>();
for (Constructor<? extends T> ctor : constructors)
try {
ctor.newInstance(arguments.toArray());
retvals.add(ctor);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
exceptions.put(ctor, ex);
}
if (retvals.isEmpty())
throw new AssertionError("Couldn't create a "+filterClass+" from "+arguments+": exceptions "+exceptions);
if (retvals.size() > 1)
throw new AssertionError("Creating a "+filterClass+" from "+arguments+" was ambiguous: "+retvals);
return retvals.get(0);
}
public String toJava() {
//This will generate unchecked code if the filter is generic.
return "new " + filterClass.getCanonicalName() + "(" + ARG_JOINER.join(arguments)+")";
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzStreamElement<T> other = (FuzzStreamElement<T>)obj;
if (!Objects.equals(this.filterClass, other.filterClass))
return false;
if (!Objects.equals(this.arguments, other.arguments))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.filterClass);
hash = 41 * hash + Objects.hashCode(this.arguments);
return hash;
}
}
private static final class FuzzFilter extends FuzzStreamElement<Filter<Integer, Integer>> implements FuzzElement {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzFilter(Class<? extends Filter> filterClass, ImmutableList<Object> arguments) {
super((Class<Filter<Integer, Integer>>)filterClass, arguments);
}
@Override
public Filter<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
private static final class FuzzPipeline implements FuzzElement {
private final ImmutableList<FuzzElement> elements;
private FuzzPipeline(ImmutableList<FuzzElement> elements) {
this.elements = elements;
}
@Override
public Pipeline<Integer, Integer> instantiate() {
Pipeline<Integer, Integer> pipeline = new Pipeline<>();
for (FuzzElement e : elements)
pipeline.add(e.instantiate());
return pipeline;
}
@Override
public String toJava() {
List<String> args = new ArrayList<>(elements.size());
for (FuzzElement e : elements)
args.add(e.toJava());
return "new Pipeline(" + ARG_JOINER.join(args) + ")";
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzPipeline other = (FuzzPipeline)obj;
if (!Objects.equals(this.elements, other.elements))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 59 * hash + Objects.hashCode(this.elements);
return hash;
}
}
/**
* Can't implement FuzzElement because Splitter isn't a OneToOneElement, but
* can still share the instantiation code.
*/
private static final class FuzzSplitter extends FuzzStreamElement<Splitter<Integer, Integer>> {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzSplitter(Class<? extends Splitter> filterClass, ImmutableList<Object> arguments) {
super((Class<Splitter<Integer, Integer>>)filterClass, arguments);
}
@Override
public Splitter<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
/**
* See comments on FuzzSplitter.
*/
private static final class FuzzJoiner extends FuzzStreamElement<Joiner<Integer, Integer>> {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzJoiner(Class<? extends Joiner> filterClass, ImmutableList<Object> arguments) {
super((Class<Joiner<Integer, Integer>>)filterClass, arguments);
}
@Override
public Joiner<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
private static final class FuzzSplitjoin implements FuzzElement {
private final FuzzSplitter splitter;
private final FuzzJoiner joiner;
private final ImmutableList<FuzzElement> branches;
private FuzzSplitjoin(FuzzSplitter splitter, FuzzJoiner joiner, ImmutableList<FuzzElement> branches) {
this.splitter = splitter;
this.joiner = joiner;
this.branches = branches;
}
@Override
public OneToOneElement<Integer, Integer> instantiate() {
Splitjoin<Integer, Integer> splitjoin = new Splitjoin<>(splitter.instantiate(), joiner.instantiate());
for (FuzzElement e : branches)
splitjoin.add(e.instantiate());
return splitjoin;
}
@Override
public String toJava() {
List<String> args = new ArrayList<>(branches.size()+2);
args.add(splitter.toJava());
args.add(joiner.toJava());
for (FuzzElement e : branches)
args.add(e.toJava());
return "new Splitjoin(" + ARG_JOINER.join(args) + ")";
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzSplitjoin other = (FuzzSplitjoin)obj;
if (!Objects.equals(this.splitter, other.splitter))
return false;
if (!Objects.equals(this.joiner, other.joiner))
return false;
if (!Objects.equals(this.branches, other.branches))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.splitter);
hash = 71 * hash + Objects.hashCode(this.joiner);
hash = 71 * hash + Objects.hashCode(this.branches);
return hash;
}
}
private static final int INPUT_LENGTH = 1000;
private static List<Integer> run(FuzzElement element, StreamCompiler compiler) {
OneToOneElement<Integer, Integer> graph = element.instantiate();
CompiledStream<Integer, Integer> stream = compiler.compile(graph);
ImmutableList.Builder<Integer> retval = ImmutableList.builder();
Integer o;
for (int i = 0; i < INPUT_LENGTH;) {
if (stream.offer(i))
++i;
while ((o = stream.poll()) != null)
retval.add(o);
}
stream.drain();
while (!stream.isDrained())
while ((o = stream.poll()) != null)
retval.add(o);
while ((o = stream.poll()) != null)
retval.add(o);
return retval.build();
}
public static void main(String[] args) {
StreamCompiler debugSC = new DebugStreamCompiler();
StreamCompiler compilerSC = new BlobHostStreamCompiler(new CompilerBlobFactory(), 1);
while (true) {
FuzzElement fuzz = StreamFuzzer.generate();
List<Integer> debugOutput = run(fuzz, debugSC);
List<Integer> compilerOutput = null;
try {
compilerOutput = run(fuzz, compilerSC);
} catch (Throwable ex) {
System.out.println("Compiler failed");
ex.printStackTrace(System.out);
//fall into the if below
}
if (!debugOutput.equals(compilerOutput)) {
fuzz.instantiate().visit(new PrintStreamVisitor(System.out));
System.out.println(fuzz.toJava());
//TODO: show only elements where they differ
System.out.println("Debug output: "+debugOutput);
System.out.println("Compiler output: "+compilerOutput);
break;
}
System.out.println(fuzz.hashCode()+" matched");
}
}
}
|
package edu.wheaton.simulator.gui;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.simulation.GUIToAgentFacade;
public class SpawnCondition {
public final Prototype prototype;
public final int x;
public final int y;
public final String pattern;
public final int number;
public SpawnCondition(Prototype prototype, int x, int y, int number, String pattern) {
this.pattern = pattern;
this.prototype = prototype;
this.x = x;
this.y = y;
this.number = number;
}
public void addToGrid(GUIToAgentFacade facade) {
if (pattern.equals("Clustered")) {
for (int i = 0; i < number; i++) {
facade.getGrid().spawnAgent(prototype.createAgent(), x, y);
}
}
else if (pattern.equals("Random")) {
for (int i = 0; i < number; i++) {
facade.getGrid().spawnAgent(prototype.createAgent());
}
}
else if (pattern.equals("Horizontal")) {
for (int i = 0; i < number; i++) {
//Horizontal line spawn
}
}
else if (pattern.equals("Vertical")) {
for (int i = 0; i < number; i++) {
//vertical line spawn
}
}
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.DriverStationLCD.Line;
import edu.wpi.first.wpilibj.templates.*;
//import edu.wpi.first.wpilibj.RobotDrive;
//import edu.wpi.first.wpilibj.SimpleRobot;
//import edu.wpi.first.wpilibj.templates.Shooter;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Team3373 extends SimpleRobot{
/**
* This function is called once each time the robot enters autonomous mode.
*/
int StageOneMotorPWM = 1; //Declares channel of StageOne PWM
int StageTwoMotorPWM = 2; //Declares channel of StageTwo PWM
Servo frontCameraServo = new Servo(6);
DigitalInput armLimit = new DigitalInput(3); //returns true if clicked
Talon StageOneTalon = new Talon(1, 1); //Creates instance of StageOne PWM
Talon StageTwoTalon = new Talon(1, 2); //Creates instance of StageTwo PWM
DriverStationLCD LCD = DriverStationLCD.getInstance();
//SmartDashboard smartDashboard;
Joystick shootStick = new Joystick(2);
Shooter objShooter = new Shooter(this);
//Deadband objDeadband = new Deadband();
Timer robotTimer = new Timer();
PickArm Arm = new PickArm(this);
boolean shootA;
boolean shootB;
boolean shootX;
boolean shootY;
boolean shootRB;
boolean shootLB;
boolean shootBack;
boolean shootStart;
boolean test;
double shootLX = shootStick.getRawAxis(1);
double shootLY = shootStick.getRawAxis(2);
double shootTriggers = shootStick.getRawAxis(3);
double shootRX = shootStick.getRawAxis(4);
double shootRY = shootStick.getRawAxis(5);
double shootDP = shootStick.getRawAxis(6);
double ShooterSpeedStage2 = 0;//was StageTwoTalon.get()
double percentageScaler = 0.75;
double ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler;//was StageOneTalon.get()
double ShooterSpeedMax = 5300.0;
double ShooterSpeedAccel = 250;
double stageOneScaler = .5; //What stage one is multiplied by in order to make it a pecentage of stage 2
double PWMMax = 1; //maximum voltage sent to motor
double MaxScaler = PWMMax/5300;
double ShooterSpeedScale = MaxScaler * ShooterSpeedMax; //Scaler for voltage to RPM. Highly experimental!!
double currentRPMT2 = StageTwoTalon.get()*ShooterSpeedScale;
double currentRPMT1 = currentRPMT2*stageOneScaler;
double target;
double RPMModifier = 250;
double idle = 1 * ShooterSpeedScale;
double off = 0;
double Scaler = 5936;
double change;
double startTime = 9000000;
double backTime = 90000000;
double aTime = 900000000;
double bTime = 900000000;
boolean flagA;
boolean flagB;
boolean flagX;
boolean flagY;
boolean flagStart;
boolean flagBack;
boolean flagBack2;
public Team3373(){
}
public void autonomous() {
for (int i = 0; i < 4; i++) {
}
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
robotTimer.start();
while (isOperatorControl() & isDisabled()){
}
flagA = true;
flagB = true;
flagX = true;
flagY = true;
flagStart = true;
flagBack = true;
while (isOperatorControl() & isEnabled()){
shootA = shootStick.getRawButton(1);
shootB = shootStick.getRawButton(2);
shootX = shootStick.getRawButton(3);
shootY = shootStick.getRawButton(4);
shootRB = shootStick.getRawButton(5);
shootLB = shootStick.getRawButton(6);
shootBack = shootStick.getRawButton(7);
shootStart = shootStick.getRawButton(8);
shootLX = shootStick.getRawAxis(1);
shootLY = shootStick.getRawAxis(2);
shootTriggers = shootStick.getRawAxis(3);
shootRX = shootStick.getRawAxis(4);
shootRY = shootStick.getRawAxis(5);
shootDP = shootStick.getRawAxis(6);
/*
ShooterSpeedStage1 = ShooterSpeedStage2 * percentageScaler;
StageOneTalon.set(ShooterSpeedStage1);
StageTwoTalon.set(ShooterSpeedStage2);
if (shootStart && flagStart) {
ShooterSpeedStage2 = objShooter.start();
flagStart = false;
} else if (shootA && flagA){//increases stage 2
ShooterSpeedStage2 = objShooter.increaseSpeed(ShooterSpeedStage2);
flagA = false;
} else if (shootB && flagB){//decrease stage 2
ShooterSpeedStage2 = objShooter.decreaseSpeed(ShooterSpeedStage2);
flagB = false;
} else if (shootX && flagX){//increases percentage between Stage1 and Stage2
percentageScaler = objShooter.decreasePercentage(percentageScaler);
flagX = false;
} else if (shootY && flagY){//decreases percentage between Stage1 and Stage2
percentageScaler = objShooter.decreasePercentage(percentageScaler);
flagY = false;
} else if (shootBack && flagBack){//turns off
ShooterSpeedStage2 = objShooter.stop();
percentageScaler = 0.75;
}
*/
Arm.extend();
//try {Thread.sleep(1000);} catch(Exception e){}
//String percentage = Double.toString();
double speedOne = StageOneTalon.get();
String speed1 = Double.toString(speedOne);
double speedTwo = StageTwoTalon.get();
String speed2 = Double.toString(speedTwo);
LCD.println(Line.kUser3, 1, ((StageOneTalon.get()/StageTwoTalon.get()) *100) + " %");
LCD.println(Line.kUser4, 1,"S1:" + speed1);
LCD.println(Line.kUser2, 1,"S2:" + speed2);
//LCD.println(Line.kUser1, 1, "RPM1: " + (speedOne * Scaler));
//LCD.println(Line.kUser2, 1, "RPM2: " + (speedTwo * Scaler));
LCD.updateLCD();
if (!shootA && !flagA) { //toggles
flagA = true;
} else if (!shootB && !flagB){
flagB = true;
}else if (!shootX && !flagX){
flagX = true;
}else if (!shootY && !flagY){
flagY = true;
} else if (!shootStart && !flagStart){
flagStart = true;
}else if (!shootBack && !flagBack){
flagBack = true;
}
/*Servo Test Code*/
if (shootTriggers<= 0.8){
shootTriggers = 0.8;
} else if (shootTriggers >= 0.25){
shootTriggers = 0.25;
}
frontCameraServo.set(shootTriggers);
/*frontCameraServo.set(0.5);
double servoPosition = frontCameraServo.get();
String tilt = Double.toString(servoPosition);
LCD.println(Line.kUser6, 1, "Servo: " + tilt);
LCD.updateLCD();
try{
//Thread.sleep(1000);
}
catch(Exception e){
}
frontCameraServo.set(0.75);
servoPosition = frontCameraServo.get();
tilt = Double.toString(servoPosition);
LCD.println(Line.kUser6, 1, "Servo: " + tilt);
LCD.updateLCD();
*/
/*if (shootA & !flagA) { //increases speed
objShooter.speedChange();
LCD.println(Line.kUser2, 1, "Pressing A");
LCD.updateLCD();
flagA = true;
}
if (!shootA & flagA) { //if a is not pressed and it has been pressed set it to false
flagA = false;
}
if (shootB & !flagB) { //decreases speed
objShooter.speedChange();
LCD.println(Line.kUser2, 1, "Pressing B");
LCD.updateLCD();
flagB = true;
}
if (!shootB & flagB) { //if b is not pressed and it has been pressed set it to false
flagB = false;
}
if (shootX & stageOneScaler <= 100 & !flagX){
stageOneScaler += 0.05;
//changes stage1 percentage of stage2 adds 5%
LCD.println(Line.kUser6, 1, "Adding 5% to Stage One Percentile");
LCD.updateLCD();
flagX = true;
}
if (!shootX & flagX) { //if x is not pressed and it has been pressed set it to false
flagX = false;
}
if (shootY & !flagY){
objShooter.percentageSubtract();
LCD.println(Line.kUser2, 1, "Pressing Y");
LCD.updateLCD();
}*/
String currentTime = Double.toString(robotTimer.get());
LCD.println(Line.kUser6, 1, currentTime);
}
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.DriverStationLCD.Line;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
//import edu.wpi.first.wpilibj.RobotDrive;
//import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.templates.*;
//import edu.wpi.first.wpilibj.templates.Shooter;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Team3373 extends SimpleRobot{
/**
* This function is called once each time the robot enters autonomous mode.
*/
int StageOneMotorPWM = 1; //Declares channel of StageOne PWM
int StageTwoMotorPWM = 2; //Declares channel of StageTwo PWM
Talon StageOneTalon = new Talon(1, 1); //Creates instance of StageOne PWM
Talon StageTwoTalon = new Talon(1, 2); //Creates instance of StageTwo PWM
DriverStationLCD LCD = DriverStationLCD.getInstance();
SmartDashboard smartDashboard;
Joystick shootStick = new Joystick(2);
Shooter objShooter = new Shooter(this);
Deadband objDeadband = new Deadband();
Timer robotTimer = new Timer();
boolean shootA = shootStick.getRawButton(1);
boolean shootB = shootStick.getRawButton(2);
boolean shootX = shootStick.getRawButton(3);
boolean shootY = shootStick.getRawButton(4);
boolean shootRB = shootStick.getRawButton(5);
boolean shootLB = shootStick.getRawButton(6);
boolean shootBack = shootStick.getRawButton(7);
boolean shootStart = shootStick.getRawButton(8);
boolean test;
double shootLX = shootStick.getRawAxis(1);
double shootLY = shootStick.getRawAxis(2);
double shootTriggers = shootStick.getRawAxis(3);
double shootRX = shootStick.getRawAxis(4);
double shootRY = shootStick.getRawAxis(5);
double shootDP = shootStick.getRawAxis(6);
double ShooterSpeedStage1 = StageOneTalon.get();
double ShooterSpeedStage2 = StageTwoTalon.get();
double ShooterSpeedMax = 5300.0;
double ShooterSpeedAccel = 250;
double stageOneScaler = .5; //What stage one is multiplied by in order to make it a pecentage of stage 2
double PWMMax = 1; //maximum voltage sent to motor
double MaxScaler = PWMMax/5300;
double ShooterSpeedScale = MaxScaler * ShooterSpeedMax; //Scaler for voltage to RPM. Highly experimental!!
double currentRPMT2 = StageTwoTalon.get()*ShooterSpeedScale;
double currentRPMT1 = currentRPMT2*stageOneScaler;
double target;
double RPMModifier = 250;
double idle = 1 * ShooterSpeedScale;
double off = 0;
double change;
public Team3373(){
}
public void autonomous() {
for (int i = 0; i < 4; i++) {
}
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
robotTimer.start();
while (isOperatorControl() & isDisabled()){
objShooter.shootInit();
}
while (isOperatorControl() & isEnabled()){
boolean shootA = shootStick.getRawButton(1);
boolean shootB = shootStick.getRawButton(2);
boolean shootX = shootStick.getRawButton(3);
boolean shootY = shootStick.getRawButton(4);
boolean shootRB = shootStick.getRawButton(5);
boolean shootLB = shootStick.getRawButton(6);
boolean shootBack = shootStick.getRawButton(7);
boolean shootStart = shootStick.getRawButton(8);
boolean test;
double shootLX = shootStick.getRawAxis(1);
double shootLY = shootStick.getRawAxis(2);
double shootTriggers = shootStick.getRawAxis(3);
double shootRX = shootStick.getRawAxis(4);
double shootRY = shootStick.getRawAxis(5);
double shootDP = shootStick.getRawAxis(6);
boolean flagA = false;
boolean flagB = false;
boolean flagX = false;
boolean flagY = false;
//Shooter objShooter = new Shooter();
objShooter.shooterPrint();
objShooter.Start();
LCD.println(Line.kUser2, 1, "Not Inside");
if (true) return;
if (shootA & !flagA) { //increases speed
objShooter.speedChange();
LCD.println(Line.kUser2, 1, "Pressing A");
LCD.updateLCD();
flagA = true;
}
if (!shootA & flagA) {
flagA = false;
}
if (shootB & !flagB) { //decreases speed
objShooter.speedChange();
LCD.println(Line.kUser2, 1, "Pressing B");
LCD.updateLCD();
flagB = true;
}
if (!shootB & flagB) {
flagB = true;
}
if (shootX & stageOneScaler <= 100 & !flagX){
stageOneScaler += 0.05;
//changes stage1 percentage of stage2 adds 5%
LCD.println(Line.kUser6, 1, "Adding 5% to Stage One Percentile");
LCD.updateLCD();
flagX = true;
}
if (!shootX & flagX) {
flagX = true;
}
if (shootY & !flagY){
objShooter.percentageSubtract();
LCD.println(Line.kUser2, 1, "Pressing Y");
LCD.updateLCD();
}
String currentTime = Double.toString(robotTimer.get());
LCD.println(Line.kUser6, 1, currentTime);
}
}
}
|
package edu.wustl.xipHost.dicom;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.nema.dicom.wg23.Modality;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.Uid;
import org.nema.dicom.wg23.Uuid;
import com.pixelmed.database.DatabaseInformationModel;
import com.pixelmed.database.PatientStudySeriesConcatenationInstanceModel;
import com.pixelmed.dicom.Attribute;
import com.pixelmed.dicom.AttributeList;
import com.pixelmed.dicom.AttributeTag;
import com.pixelmed.dicom.DicomDictionary;
import com.pixelmed.dicom.DicomException;
import com.pixelmed.dicom.TagFromName;
import com.pixelmed.network.DicomNetworkException;
import com.pixelmed.network.VerificationSOPClassSCU;
import com.pixelmed.query.QueryInformationModel;
import com.pixelmed.query.QueryTreeModel;
import com.pixelmed.query.QueryTreeRecord;
import com.pixelmed.query.StudyRootQueryInformationModel;
import com.pixelmed.server.DicomAndWebStorageServer;
import edu.wustl.xipHost.dataModel.ImageItem;
import edu.wustl.xipHost.dataModel.Item;
import edu.wustl.xipHost.dataModel.Patient;
import edu.wustl.xipHost.dataModel.SearchResult;
import edu.wustl.xipHost.dataModel.Series;
import edu.wustl.xipHost.dataModel.Study;
import edu.wustl.xipHost.hostControl.HostConfigurator;
import edu.wustl.xipHost.iterator.Criteria;
public class DicomManagerImpl implements DicomManager{
final static Logger logger = Logger.getLogger(DicomManagerImpl.class);
Document documentPacs;
Element rootPacs;
SAXBuilder builder = new SAXBuilder();
List<PacsLocation> pacsLocations = new ArrayList<PacsLocation>();
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#loadPacsLocations(java.io.File)
*/
public boolean loadPacsLocations(File file) throws IOException, JDOMException {
documentPacs = builder.build(file);
rootPacs = documentPacs.getRootElement();
List<?> children = rootPacs.getChildren("pacs_location");
for (int i = 0; i < children.size(); i++){
String address = (((Element)children.get(i)).getChildText("hostAddress"));
int port = Integer.valueOf((((Element)children.get(i)).getChildText("hostPort")));
String aeTitle = (((Element)children.get(i)).getChildText("hostAETitle"));
String shortName = (((Element)children.get(i)).getChildText("hostShortName"));
/*System.out.println(address);
System.out.println(port);
System.out.println(aeTitle);*/
try {
PacsLocation loc = new PacsLocation(address, port, aeTitle, shortName);
pacsLocations.add(loc);
} catch (IllegalArgumentException e) {
//Prints invalid location and proceeds to load next one
System.out.println("Unable to load: " + address + " " + port + " " + aeTitle + " " + shortName + " - invalid location.");
}
}
return true;
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#storePacsLocations(java.util.List, java.io.File)
*/
public boolean storePacsLocations(List<PacsLocation> locations, File file) throws FileNotFoundException {
Element rootSave = new Element("locations");
Document document = new Document();
document.setRootElement(rootSave);
if(locations == null){return false;}
for(int i = 0; i < locations.size(); i++){
Element pacsElem = new Element("pacs_location");
Element addressElem = new Element("hostAddress");
Element portElem = new Element("hostPort");
Element aeTitleElem = new Element("hostAETitle");
Element shortNameElem = new Element("hostShortName");
pacsElem.addContent(addressElem);
pacsElem.addContent(portElem);
pacsElem.addContent(aeTitleElem);
pacsElem.addContent(shortNameElem);
rootSave.addContent(pacsElem);
addressElem.addContent(locations.get(i).getAddress());
portElem.addContent(String.valueOf(locations.get(i).getPort()));
aeTitleElem.addContent(locations.get(i).getAETitle());
shortNameElem.addContent(locations.get(i).getShortName());
}
try {
FileOutputStream outStream = new FileOutputStream(file);
XMLOutputter outToXMLFile = new XMLOutputter();
outToXMLFile.setFormat(Format.getPrettyFormat());
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#addPacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean addPacsLocation(PacsLocation pacsLocation){
try {
if(!pacsLocations.contains(pacsLocation)){
return pacsLocations.add(pacsLocation);
} else {
return false;
}
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#modifyPacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation, edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean modifyPacsLocation(PacsLocation oldPacsLocation, PacsLocation newPacsLocation) {
//validate method is used to check if parameters are valid, are notmissing,
//do not contain empty strings or do not start from white spaces
try {
int i = pacsLocations.indexOf(oldPacsLocation);
if (i != -1){
pacsLocations.set(i, newPacsLocation);
return true;
} else{
return false;
}
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#removePacsLocation(edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public boolean removePacsLocation(PacsLocation pacsLocation){
//System.out.println(pacsLocations.indexOf(pacsLocation));
try {
return pacsLocations.remove(pacsLocation);
} catch (IllegalArgumentException e){
return false;
}
}
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#getPacsLocations()
*/
public List<PacsLocation> getPacsLocations(){
return pacsLocations;
}
QueryTreeModel mTree = null;
QueryInformationModel mModel = null;
String calledAETitle;
/* (non-Javadoc)
* @see edu.wustl.xipHost.globalSearch.DicomManager#query(com.pixelmed.dicom.AttributeList, edu.wustl.xipHost.globalSearch.PacsLocation)
*/
public SearchResult query(AttributeList criteria, PacsLocation location) {
if(criteria == null || location == null){
return null;
}
//Connecting to the server
logger.debug("Queried source: " + location.toString());
String hostName = location.getAddress();
int port = location.getPort();
calledAETitle = location.getAETitle();
//ensure callingAETitle is not empty (not all stations allow empty value).
String callingAETitle = "";
if(HostConfigurator.getHostConfigurator() != null){
callingAETitle = HostConfigurator.getHostConfigurator().getAETitle();
}
if (callingAETitle == "") {
callingAETitle = "WS_XIP";
}
mModel = new StudyRootQueryInformationModel(hostName, port, calledAETitle, callingAETitle, 0);
try {
new VerificationSOPClassSCU(hostName, port, calledAETitle, callingAETitle, false, 0);
}catch (Exception e) {
return null;
}
SearchResult returnResult = null;
try {
//mTree hangs when supplied callingAETitle is an empty string
mTree = mModel.performHierarchicalQuery(criteria);
result = new SearchResult(location.hostShortName);
Map<Integer, Object> dicomCriteria = DicomUtil.convertToADDicomCriteria(criteria);
Map<String, Object> aimCriteria = new HashMap<String, Object>();
Criteria originalCriteria = new Criteria(dicomCriteria, aimCriteria);
result.setOriginalCriteria(originalCriteria);
Object root = mTree.getRoot();
returnResult = (SearchResult) resolveToSearchResult(root);
if(logger.isDebugEnabled()){
Iterator<Patient> patients = result.getPatients().iterator();
while(patients.hasNext()){
Patient patient = patients.next();
Timestamp patientLastUpdated = patient.getLastUpdated();
String strPatientLastUpdated = null;
if(patientLastUpdated != null){
strPatientLastUpdated = patientLastUpdated.toString();
}
logger.debug(patient.toString() + " Last updated: " + strPatientLastUpdated);
Iterator<Study> studies = patient.getStudies().iterator();
while(studies.hasNext()){
Study study = studies.next();
Timestamp studyLastUpdated = study.getLastUpdated();
String strStudyLastUpdated = null;
if(studyLastUpdated != null){
strStudyLastUpdated = studyLastUpdated.toString();
}
logger.debug(" " + study.toString() + " Last updated: " + strStudyLastUpdated);
Iterator<Series> series = study.getSeries().iterator();
while(series.hasNext()){
Series oneSeries = series.next();
Timestamp seriesLastUpdated = oneSeries.getLastUpdated();
String strSeriesLastUpdated = null;
if(seriesLastUpdated != null){
strSeriesLastUpdated = seriesLastUpdated.toString();
}
logger.debug(" " + oneSeries.toString() + " Last updated: " + strSeriesLastUpdated);
Iterator<Item> images = oneSeries.getItems().iterator();
while(images.hasNext()){
logger.debug(" " + images.next().toString());
}
}
}
}
}
} catch (IOException e) {
return null;
} catch (DicomException e) {
return null;
} catch (DicomNetworkException e) {
return null;
}
return returnResult;
}
Patient patient = null;
Study study = null;
Series series = null;
SearchResult result;
SearchResult resolveToSearchResult(Object node) {
int numChildren = mTree.getChildCount(node);
for(int i = 0; i < numChildren; i++){
Object child = mTree.getChild(node, i);
//find if child is Study, Series or Image
//Case approach
String level = getRetrieveLevel(child);
Timestamp lastUpdated = new Timestamp(Calendar.getInstance().getTime().getTime());
if(level.equalsIgnoreCase("Study")){
String patientName = attValues.get("(0x0010,0x0010)");
if(patientName == null){patientName = "";}
String patientID = attValues.get("(0x0010,0x0020)");
if(patientID == null){patientID = "";}
String patientBirthDate = attValues.get("(0x0010,0x0030)");
if(patientBirthDate == null){patientBirthDate = "";}
patient = new Patient(patientName, patientID, patientBirthDate);
//patient.setLastUpdated(lastUpdated);
if(!result.contains(patientID)){
result.addPatient(patient);
} else {
patient = result.getPatient(patientID);
}
String studyDate = attValues.get("(0x0008,0x0020)");
if(studyDate == null){studyDate = "";}
String studyID = attValues.get("(0x0020,0x0010)");
if(studyID == null){studyID = "";}
String studyDesc = attValues.get("(0x0008,0x1030)");
if(studyDesc == null){studyDesc = "";}
String studyInstanceUID = attValues.get("(0x0020,0x000D)");
if(studyInstanceUID == null){studyInstanceUID = "";}
study = new Study(studyDate, studyID, studyDesc, studyInstanceUID);
if(!patient.contains(studyInstanceUID)){
patient.addStudy(study);
} else {
study = patient.getStudy(studyInstanceUID);
}
patient.setLastUpdated(lastUpdated);
resolveToSearchResult(child);
}else if(level.equalsIgnoreCase("Series")){
String seriesNumber = attValues.get("(0x0020,0x0011)");
if(seriesNumber == null){seriesNumber = "";}
String modality = attValues.get("(0x0008,0x0060)");
if(modality == null){modality = "";}
String seriesDesc = attValues.get("(0x0008,0x103E)");
if(seriesDesc == null){seriesDesc = "";}
String seriesInstanceUID = attValues.get("(0x0020,0x000E)");
if(seriesInstanceUID == null){seriesInstanceUID = "";}
series = new Series(seriesNumber, modality, seriesDesc, seriesInstanceUID);
if(!study.contains(seriesInstanceUID)){
study.addSeries(series);
} else {
series = study.getSeries(seriesInstanceUID);
}
study.setLastUpdated(lastUpdated);
resolveToSearchResult(child);
}else if(level.equalsIgnoreCase("Image")){
String imageNumber = attValues.get("(0x0008,0x0018)"); //SOPIntanceUID
String sopClassUID = attValues.get("(0x0008,0x0016)"); //SOPClassUID
String modCode = attValues.get("(0x0008,0x0060)"); //Modality
if(imageNumber == null){imageNumber = "";}
Item image = new ImageItem(imageNumber);
if(!series.contains(imageNumber)){
series.addItem(image);
ObjectDescriptor objDesc = new ObjectDescriptor();
Uuid objDescUUID = new Uuid();
objDescUUID.setUuid(UUID.randomUUID().toString());
objDesc.setUuid(objDescUUID);
objDesc.setMimeType("application/dicom");
Uid uid = new Uid();
String classUID = sopClassUID;
uid.setUid(classUID);
objDesc.setClassUID(uid);
Modality modality = new Modality();
modality.setModality(modCode);
objDesc.setModality(modality);
image.setObjectDescriptor(objDesc);
}
series.setLastUpdated(lastUpdated);
}else{
return null;
}
}
return result;
}
Map<String, String> attValues;
/**
*
* @param node
* @return
*/
String getRetrieveLevel(Object node){
attValues = new HashMap<String, String>();
if (node instanceof QueryTreeRecord) {
QueryTreeRecord r = (QueryTreeRecord)node;
AttributeList keys = r.getUniqueKeys();
String seriesInstanceUID = Attribute.getSingleStringValueOrNull(keys, TagFromName.SeriesInstanceUID);
String studyInstanceUID = Attribute.getSingleStringValueOrNull(keys, TagFromName.StudyInstanceUID);
attValues.put("(0x0020,0x000D)", studyInstanceUID);
attValues.put("(0x0020,0x000E)", seriesInstanceUID);
AttributeList identifier = r.getAllAttributesReturnedInIdentifier();
DicomDictionary dictionary = AttributeList.getDictionary();
Iterator<?> iter = dictionary.getTagIterator();
String strAtt = null;
String attValue = null;
while(iter.hasNext()){
AttributeTag attTag = (AttributeTag)iter.next();
strAtt = attTag.toString();
attValue = Attribute.getSingleStringValueOrEmptyString(identifier, attTag);
//put only those attributes non empty and non null
if(!attValue.isEmpty()){
//System.out.println(strAtt + " " + attValue);
attValues.put(strAtt, attValue);
}
}
}
String level = attValues.get("(0x0008,0x0052)");
return level;
}
BasicDicomParser2 parser = new BasicDicomParser2();
public boolean submit(File[] dicomFiles, PacsLocation location) {
for(int i = 0; i < dicomFiles.length; i++){
AttributeList attList = parser.parse(dicomFiles[i]);
try {
dbModel.insertObject(attList, dicomFiles[i].getAbsolutePath(), "R");
} catch (DicomException e) {
logger.error(e, e);
return false;
}
}
return true;
}
File xmlPacsLocFile = new File("./config/pacs_locations.xml");
String dbFileName;
public boolean runDicomStartupSequence(String hsqldbServerConfigFilePath, Properties pixelmedProp) {
if(xmlPacsLocFile == null ){return false;}
startHSQLDB(hsqldbServerConfigFilePath);
startPixelmedServer(pixelmedProp);
dbFileName = prop.getProperty("Application.DatabaseFileName");
setDBModel(dbFileName);
try {
loadPacsLocations(xmlPacsLocFile);
} catch (IOException e) {
logger.error("DICOM module startup sequence error. System could not find: pacs_locations.xml", e);
return false;
} catch (JDOMException e) {
logger.error(e, e);
return false;
}
return true;
}
public boolean runDicomShutDownSequence(String connectionPath, String user, String password){
logger.debug("Running DICOM shutdown sequence.");
closeDicomServer(connectionPath, user, password);
return true;
}
Connection conn;
public void closeDicomServer(String connectionPath, String user, String password){
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException e1) {
logger.error(e1, e1);
}
try {
conn = DriverManager.getConnection(connectionPath, user, password);
if(conn.isClosed() == false){
Statement st = conn.createStatement();
boolean bln = st.execute("SHUTDOWN");
if(bln){
conn.close();
}
}
} catch (SQLException e) {
logger.error("ERROR detected when shuting down DICOM Pixelmed and HSQLDB servers");
logger.error(e, e);
}
}
Server hsqldbServer;
public void startHSQLDB(String hsqldbServerConfigFilePath ) {
hsqldbServer = new Server();
hsqldbServer.putPropertiesFromFile(hsqldbServerConfigFilePath);
hsqldbServer.start();
}
DicomAndWebStorageServer server;
Properties prop = new Properties();
public boolean startPixelmedServer(Properties prop){
try {
this.prop = prop;
server = new DicomAndWebStorageServer(this.prop);
} catch (FileNotFoundException e) {
logger.error(e, e);
return false;
} catch (IOException e) {
logger.error(e, e);
return false;
} catch (DicomException e) {
logger.error(e, e);
return false;
} catch (DicomNetworkException e) {
logger.error(e, e);
return false;
}
return true;
}
DatabaseInformationModel dbModel = null;
public DatabaseInformationModel getDBModel(){
return dbModel;
}
public void setDBModel(String dbModel){
try {
this.dbModel = new PatientStudySeriesConcatenationInstanceModel(dbModel);
} catch (DicomException e) {
logger.error(e, e);
}
}
public String getDBFileName(){
return dbFileName;
}
public void closeHSQLDB(){
hsqldbServer.shutdown();
}
@Override
public PacsLocation getDefaultCallingPacsLocation() {
return callingPacsLocation;
}
PacsLocation callingPacsLocation;
public void setDefaultCallingPacsLOcation(PacsLocation callingPacsLocation){
this.callingPacsLocation = callingPacsLocation;
}
}
|
package edu.ycp.cs.netcoder.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class NetCoder_GWT2 implements EntryPoint, AceEditorCallback {
private HorizontalPanel appPanel;
private HorizontalPanel editorAndWidgetPanel;
private AceEditor editor;
private VerticalPanel widgetPanel;
private HorizontalPanel buttonPanel;
private Label statusLabel;
private LogCodeChangeServiceAsync logCodeChangeService;
private CompileServiceAsync compileService;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// The app panel can be for logout button, menus, etc.
appPanel = new HorizontalPanel();
appPanel.add(new Label("Menus and logout button should go here"));
// The editor (left) and widget panel (right) occupy most of the vertical space
// TODO: make it expand vertically when window resizes
editorAndWidgetPanel = new HorizontalPanel();
editorAndWidgetPanel.setWidth("100%");
// Code editor
editor = new AceEditor();
editor.setStylePrimaryName("NetCoderEditor");
// Widget panel: for things like hints, affect data collection, etc.
widgetPanel = new VerticalPanel();
widgetPanel.add(new Label("Hints should go here!")); // TODO
widgetPanel.add(new Label("Affect data collection!")); // TODO
// Add the editor and widget panel so that it is a 70/30 split
editorAndWidgetPanel.add(editor);
editorAndWidgetPanel.setCellWidth(editor, "70%");
editorAndWidgetPanel.add(widgetPanel);
editorAndWidgetPanel.setCellWidth(widgetPanel, "30%");
// Button panel is for buttons
buttonPanel = new HorizontalPanel();
Button compileButton = new Button("Compile");
compileButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
compileCode();
}
});
buttonPanel.add(compileButton);
// Status label - need to think more about what feedback to provide and how
FlowPanel statusPanel = new FlowPanel();
statusLabel = new Label();
statusPanel.add(statusLabel);
statusPanel.setWidth("100%");
// Build the UI
RootPanel rootPanel = RootPanel.get();
rootPanel.add(appPanel);
rootPanel.add(editorAndWidgetPanel);
rootPanel.add(buttonPanel);
rootPanel.add(statusPanel);
// fire up the ACE editor
editor.startEditor();
editor.setTheme("eclipse");
editor.setFontSize("14px");
editor.setMode(AceEditorMode.JAVA);
editor.addOnChangeHandler(this);
// Create async service objects for communication with server
logCodeChangeService = (LogCodeChangeServiceAsync) GWT.create(LogCodeChangeService.class);
compileService = (CompileServiceAsync) GWT.create(CompileService.class);
}
/**
* Handles onChange events from the editor.
*/
@Override
public void invokeAceCallback(JavaScriptObject obj) {
sendChangeToServer(obj);
}
/**
* Send an ACE onChange event to the server.
*
* @param obj an ACE onChange event object
*/
private native void sendChangeToServer(JavaScriptObject obj) /*-{
var jsonText = JSON.stringify(obj);
this.@edu.ycp.cs.netcoder.client.NetCoder_GWT2::sendStringifiedChangeToServer(Ljava/lang/String;)(jsonText);
}-*/;
/**
* Send a code change to the server.
*
* @param changeEvent a JSON-stringified ACE onChange event object
*/
private void sendStringifiedChangeToServer(String changeEvent) {
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
GWT.log("send code change failed", caught);
}
@Override
public void onSuccess(Boolean result) {
// TODO: clear queue of change events
}
};
logCodeChangeService.logChange(changeEvent, callback);
}
/**
* Send the current text in the editor to the server to be compiled.
*/
protected void compileCode() {
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
statusLabel.setText("Compile failed");
GWT.log("compile failed", caught);
}
@Override
public void onSuccess(Boolean result) {
statusLabel.setText("Compile succeeded");
}
};
compileService.compile(editor.getText(), callback);
}
}
|
package eu.amidst.models.staticmodels;
import eu.amidst.core.Potential.ConstantPotential;
import eu.amidst.core.Potential.Potential;
import eu.amidst.core.Potential.PotentialTable;
import eu.amidst.core.StaticBayesianNetwork.BNFactory;
import eu.amidst.core.StaticBayesianNetwork.BayesianNetwork;
import eu.amidst.core.StaticDataBase.DataInstance;
import eu.amidst.core.headers.StaticDataHeader;
import eu.amidst.core.headers.StaticModelHeader;
import eu.amidst.core.utils.Utils;
import eu.amidst.learning.staticLearning.MaximumLikelihood;
public class NaiveBayes extends LearnableModel implements Classifier {
int classID = 0;
public NaiveBayes() {
this.setLearningAlgorithm(new MaximumLikelihood());
}
@Override
public double[] predict(DataInstance data) {
double currentClass = data.getValue(this.getClassVarID());
if (!Utils.isMissing(currentClass)) {
data.setValue(this.getClassVarID(), Utils.getMissingValue());
}
PotentialTable potResult = (PotentialTable) this.getBayesianNetwork().getEstimator(this.classID).getRestrictedPotential(data);
for (int i = 0; i < this.getBayesianNetwork().getNumberOfNodes(); i++) {
if (Utils.isMissing(data.getValue(i)) || i==this.getClassVarID())
continue;
Potential pot = this.getBayesianNetwork().getEstimator(i).getRestrictedPotential(data);
potResult.combine(pot);
}
potResult.normalize();
if (!Utils.isMissing(currentClass)) {
data.setValue(this.getClassVarID(), currentClass);
}
return potResult.getValues();
}
@Override
public int getClassVarID() {
return classID;
}
@Override
public void setClassVarID(int varID) {
this.classID = varID;
}
@Override
public Potential inferenceForLearning(DataInstance data, int varID) {
return null;
}
@Override
public void buildStructure(StaticDataHeader dataHeader) {
StaticModelHeader modelHeader = new StaticModelHeader(dataHeader);
BayesianNetwork net = BNFactory.createBN(modelHeader);
for (int i = 0; i < net.getNumberOfNodes(); i++) {
if (i == this.getClassVarID())
continue;
net.getParentSet(i).addParent(this.getClassVarID());
}
net.initEstimators();
this.bnet = net;
}
}
|
package org.voltdb.types;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* The Java class used to represent data with the SQL type GEOGRAPHY.
* For now, this means polygons, but may include other kinds of geospatial
* types in the future.
*/
public class GeographyValue {
// Note that Google S2 refers to each ring of a polygon as a "loop"
// whereas VoltDB uses the term "ring" or "linear ring" in documentation
// and comments on public APIs. In other places in the code, the terms
// "loop" and "ring" are used interchangeably.
/**
* The default length (in bytes) for a column with type GEOGRAPHY, if no
* length is specified.
*/
public static final int DEFAULT_LENGTH = 32768;
/**
* The minimum-allowed length (in bytes) for a column with type GEOGRAPHY.
* This is the length of a polygon with just three vertices.
*/
public static final int MIN_SERIALIZED_LENGTH = 155; // number of bytes need to store a triangle
// This is a list of loops. Each loop must be in
// S2Loop format. That is to say, it must have type XYZPoint
// type, it must be in counter-clockwise order and it must not
// be closed. All loops, even holes, are CCW.
private List<List<XYZPoint>> m_loops;
/**
* Create a polygon from a list of rings. Each ring is a list of points:
* <ol>
* <li>The first ring in the list is the outer ring, also known as the
* shell.</li>
* <li>Subsequent rings should be inside of the outer ring and represent
* "holes" in the polygon.</li>
* <li>The shell should have its vertices listed in counter-clockwise order,
* so that the area inside the ring is on the left side of the line segments
* formed by adjacent vertices.</li>
* <li>Each hole, or inner ring, should have its vertices listed in clockwise
* order, so that the area inside the ring (the "hole") is on the right side
* of the line segments formed by adjacent vertices.</li>
* </ol>
* Note that this is the same as the order expected by the OGC standard's
* Well-Known Text format.
*
* Note also that the rings here are lists of GeographyPointValues, and that they
* are closed. That is to say, the first vertex and the last
* vertex must be equal.
*
* @param rings A list of lists of points that will form a polygon.
*/
public GeographyValue(List<List<GeographyPointValue>> rings) {
if (rings == null || rings.size() < 1) {
throw new IllegalArgumentException("GeographyValue must be instantiated with at least one ring");
}
// Note that we need to reverse all but the
// first loop, since the EE wants them all in CCW order,
// and the OGC order for holes is CW.
m_loops = new ArrayList<List<XYZPoint>>();
boolean firstLoop = true;
for (List<GeographyPointValue> loop : rings) {
diagnoseLoop(loop, "Invalid loop for GeographyValue: ");
List<XYZPoint> oneLoop = new ArrayList<XYZPoint>();
int startIdx;
int endIdx;
int delta;
if (firstLoop) {
startIdx = 1;
// Don't copy the last vertex.
endIdx = loop.size() - 1;
delta = 1;
} else {
// Don't copy the last vertex.
startIdx = loop.size() - 2;
endIdx = 0;
delta = -1;
}
oneLoop.add(XYZPoint.fromGeographyPointValue(loop.get(0)));
for (int i = startIdx; i != endIdx; i += delta) {
oneLoop.add(XYZPoint.fromGeographyPointValue(loop.get(i)));
}
m_loops.add(oneLoop);
firstLoop = false;
}
}
/**
* Create a GeographyValue object from an OGC well-known text-formatted string.
* Currently only polygons can be created via this method.
*
* Well-known text format for polygons is composed of the "POLYGON" keyword
* followed by a list of rings enclosed in parenthesis. For example:
* <p><tt>
* POLYGON((0 0, 20 0, 20 20, 0 20, 0 0),(5 5, 5 15, 15 15, 15 5, 5 5))
* </tt></p>
* Each point in a ring is composed of a coordinate of longitude and a coordinate
* of latitude separated by a space. Note that longitude comes first in this notation.
*
* Additional notes about rings:
* <ol>
* <li>The first ring in the list is the outer ring, also known as the
* shell.</li>
* <li>Subsequent rings should be inside of the outer ring and represent
* "holes" in the polygon.</li>
* <li>The shell should have its vertices listed in counter-clockwise order,
* so that the area inside the ring is on the left side of the line segments
* formed by adjacent vertices.</li>
* <li>Each hole, or inner ring, should have its vertices listed in clockwise
* order, so that the area inside the ring (the "hole") is on the right side
* of the line segments formed by adjacent vertices.</li>
* <li>Each ring must be closed; that is, the last point in the ring must be
* equal to this first.</li>
* </ol>
*
* @param wkt A well-known text-formatted string for a polygon.
*/
public GeographyValue(String wkt) {
if (wkt == null) {
throw new IllegalArgumentException("Argument to GeographyValue WKT constructor was null");
}
m_loops = loopsFromWkt(wkt);
if (m_loops == null || m_loops.isEmpty()) {
throw new IllegalArgumentException("Argument to GeographyValue WKT constructor was invalid");
}
}
/**
* Create a GeographyValue object from a well-known text string.
* This format is described in {@link #GeographyValue(String) the WKT constructor}
* for this class.
*
* @param text A well-known text string
* @return A new instance of GeographyValue
*/
public static GeographyValue fromWKT(String text) {
return new GeographyValue(text);
}
/**
* Return the list of rings of a polygon. The list has the same
* values as the list of rings used to construct the polygon, or
* the sequence of WKT rings used to construct the polygon.
*
* @return A list of rings.
*/
public List<List<GeographyPointValue>> getRings() {
/*
* Gets the loops that make up the polygon, with the outer loop first.
* Note that we need to convert from XYZPoint to GeographyPointValue.
*
* Include the loop back to the first vertex. Also, since WKT wants
* holes oriented Clockwise and S2 wants everything oriented CounterClockWise,
* reverse the order of holes. We take care to leave the first vertex
* the same.
*/
List<List<GeographyPointValue>> llLoops = new ArrayList<List<GeographyPointValue>>();
boolean isShell = true;
for (List<XYZPoint> xyzLoop : m_loops) {
List<GeographyPointValue> llLoop = new ArrayList<GeographyPointValue>();
// Add the first of xyzLoop first.
llLoop.add(xyzLoop.get(0).toGeographyPointValue());
// Add shells left to right, and holes right to left. Make sure
// not to add the first element we just added.
int startIdx = (isShell ? 1 : xyzLoop.size()-1);
int endIdx = (isShell ? xyzLoop.size() : 0);
int delta = (isShell ? 1 : -1);
for (int idx = startIdx; idx != endIdx; idx += delta) {
XYZPoint xyz = xyzLoop.get(idx);
llLoop.add(xyz.toGeographyPointValue());
}
// Close the loop.
llLoop.add(xyzLoop.get(0).toGeographyPointValue());
llLoops.add(llLoop);
isShell = false;
}
return llLoops;
}
/**
* Return a representation of this object as well-known text.
* @return A well-known text string for this object.
*/
@Override
public String toString() {
return toWKT();
}
/**
* Return a representation of this object as well-known text.
* @return A well-known text string for this object.
*/
public String toWKT() {
StringBuffer sb = new StringBuffer();
sb.append("POLYGON (");
boolean isFirstLoop = true;
for (List<XYZPoint> loop : m_loops) {
if (!isFirstLoop) {
sb.append(", ");
}
sb.append("(");
int startIdx = (isFirstLoop ? 1 : loop.size()-1);
int endIdx = (isFirstLoop ? loop.size() : 0);
int increment = (isFirstLoop ? 1 : -1);
sb.append(loop.get(0).toGeographyPointValue().formatLngLat()).append(", ");
for (int idx = startIdx; idx != endIdx; idx += increment) {
XYZPoint xyz = loop.get(idx);
sb.append(xyz.toGeographyPointValue().formatLngLat());
sb.append(", ");
}
// Repeat the start vertex to close the loop as WKT requires.
sb.append(loop.get(0).toGeographyPointValue().formatLngLat());
sb.append(")");
isFirstLoop = false;
}
sb.append(")");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof GeographyValue)) {
return false;
}
GeographyValue that = (GeographyValue)o;
if (this == that) {
return true;
}
List<List<GeographyPointValue>> expectedRings = that.getRings();
List<List<GeographyPointValue>> actualRings = getRings();
// check number of rings/loops
if (expectedRings.size() != actualRings.size()) {
return false;
}
Iterator<List<GeographyPointValue>> expectedRingIt = expectedRings.iterator();
for (List<GeographyPointValue> actualRing : actualRings) {
List<GeographyPointValue> expectedRing = expectedRingIt.next();
// check if number of the vertices in loops are equal
if (expectedRing.size() != actualRing.size()) {
return false;
};
Iterator<GeographyPointValue> expectedVertexIt = expectedRing.iterator();
for (GeographyPointValue actualPt : actualRing) {
GeographyPointValue expectedPt = expectedVertexIt.next();
if (!expectedPt.equals(actualPt)) {
return false;
}
}
}
return true;
}
/* Serialization format for polygons.
*
* This is the format used by S2 in the EE. Most of the
* metadata (especially lat/lng rect bounding boxes) are
* ignored here in Java.
*
* 1 byte encoding version
* 1 byte boolean owns_loops
* 1 byte boolean has_holes
* 4 bytes number of loops
* And then for each loop:
* 1 byte encoding version
* 4 bytes number of vertices
* ((number of vertices) * sizeof(double) * 3) bytes vertices as XYZPoints
* 1 byte boolean origin_inside
* 4 bytes depth (nesting level of loop)
* 33 bytes bounding box
* 33 bytes bounding box
*
* We use S2 in the EE for all geometric computation, so polygons sent to
* the EE will be missing bounding box and other info. We indicate this
* by passing INCOMPLETE_ENCODING_FROM_JAVA in the version field. This
* tells the EE to compute bounding boxes and other metadata before storing
* the polygon to memory.
*/
private static final byte INCOMPLETE_ENCODING_FROM_JAVA = 0;
private static final byte COMPLETE_ENCODING = 1;
/**
* Return the number of bytes in the serialization for this polygon.
* Returned value does not include the 4-byte length prefix that precedes variable-length types.
* @return The number of bytes in the serialization for this polygon.
*/
public int getLengthInBytes() {
long length = 7;
for (List<XYZPoint> loop : m_loops) {
length += loopLengthInBytes(loop.size());
}
length += boundLengthInBytes();
return (int)length;
}
/**
* Serialize this object to a ByteBuffer.
* (Assumes that the 4-byte length prefix for variable-length data
* has already been serialized.)
*
* @param buf The ByteBuffer into which the serialization will be placed.
*/
public void flattenToBuffer(ByteBuffer buf) {
buf.put(INCOMPLETE_ENCODING_FROM_JAVA); // encoding version
buf.put((byte)1); // owns_loops_
buf.put((byte)(m_loops.size() > 1 ? 1 : 0)); // has_holes_
buf.putInt(m_loops.size());
for (List<XYZPoint> loop : m_loops) {
flattenLoopToBuffer(loop, buf);
}
flattenEmptyBoundToBuffer(buf);
}
/**
* Deserialize a GeographyValue from a ByteBuffer from an absolute offset.
* (Assumes that the 4-byte length prefix has already been deserialized, and that
* offset points to the start of data just after the prefix.)
* @param inBuffer The ByteBuffer from which to read a GeographyValue
* @param offset The absolute offset in the ByteBuffer from which to read data
* @return A new GeographyValue instance.
*/
public static GeographyValue unflattenFromBuffer(ByteBuffer inBuffer, int offset) {
int origPos = inBuffer.position();
inBuffer.position(offset);
GeographyValue gv = unflattenFromBuffer(inBuffer);
inBuffer.position(origPos);
return gv;
}
/**
* Deserialize a GeographyValue from a ByteBuffer at the ByteBuffer's
* current position.
* (Assumes that the 4-byte length prefix has already been deserialized.)
* @param inBuffer The ByteBuffer from which to read a GeographyValue
* @return A new GeographyValue instance.
*/
public static GeographyValue unflattenFromBuffer(ByteBuffer inBuffer) {
byte version = inBuffer.get(); // encoding version
inBuffer.get(); // owns loops
inBuffer.get(); // has holes
int numLoops = inBuffer.getInt();
List<List<XYZPoint>> loops = new ArrayList<List<XYZPoint>>();
int indexOfOuterRing = 0;
for (int i = 0; i < numLoops; ++i) {
List<XYZPoint> loop = new ArrayList<XYZPoint>();
int depth = unflattenLoopFromBuffer(inBuffer, loop);
if (depth == 0) {
indexOfOuterRing = i;
}
loops.add(loop);
}
// S2 will order loops in depth-first order, which will leave the outer ring last.
// Make it first so it looks right when converted back to WKT.
if (version == COMPLETE_ENCODING && indexOfOuterRing != 0) {
List<XYZPoint> outerRing = loops.get(indexOfOuterRing);
loops.set(indexOfOuterRing, loops.get(0));
loops.set(0, outerRing);
}
unflattenBoundFromBuffer(inBuffer);
return polygonFromXyzPoints(loops);
}
/**
* Google's S2 geometry library uses (x, y, z) representation of polygon vertices,
* But the interface we expose to users is (lat, lng). This class is the
* internal representation for vertices.
*/
static class XYZPoint {
private final double m_x;
private final double m_y;
private final double m_z;
public static XYZPoint fromGeographyPointValue(GeographyPointValue pt) {
double latRadians = pt.getLatitude() * (Math.PI / 180); // AKA phi
double lngRadians = pt.getLongitude() * (Math.PI / 180); // AKA theta
double cosPhi = Math.cos(latRadians);
double x = Math.cos(lngRadians) * cosPhi;
double y = Math.sin(lngRadians) * cosPhi;
double z = Math.sin(latRadians);
return new XYZPoint(x, y, z);
}
public XYZPoint(double x, double y, double z) {
m_x = x;
m_y = y;
m_z = z;
}
public double x() {
return m_x;
}
public double y() {
return m_y;
}
public double z() {
return m_z;
}
public GeographyPointValue toGeographyPointValue() {
double latRadians = Math.atan2(m_z, Math.sqrt(m_x * m_x + m_y * m_y));
double lngRadians = Math.atan2(m_y, m_x);
double latDegrees = latRadians * (180 / Math.PI);
double lngDegrees = lngRadians * (180 / Math.PI);
return new GeographyPointValue(lngDegrees, latDegrees);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof XYZPoint)) {
return false;
}
XYZPoint compareTo = (XYZPoint) other;
if(m_x == compareTo.x() && m_y == compareTo.y() && m_z == compareTo.z()) {
return true;
}
return false;
}
@Override
public String toString() {
return toGeographyPointValue().toString();
}
}
private GeographyValue() {
m_loops = null;
}
static private GeographyValue polygonFromXyzPoints(List<List<XYZPoint>> loops) {
if (loops == null || loops.size() < 1) {
throw new IllegalArgumentException("GeographyValue must be instantiated with at least one loop");
}
GeographyValue geog = new GeographyValue();
geog.m_loops = loops;
return geog;
}
private static long boundLengthInBytes() {
// 1 byte for encoding version
// 32 bytes for lat min, lat max, lng min, lng max as doubles
return 33;
}
private static long loopLengthInBytes(long numberOfVertices) {
// 1 byte for encoding version
// 4 bytes for number of vertices
// number of vertices * 8 * 3 bytes for vertices as XYZPoints
// 1 byte for origin_inside_
// 4 bytes for depth_
// length of bound
return 5 + (numberOfVertices * 24) + 5 + boundLengthInBytes();
}
private static void flattenEmptyBoundToBuffer(ByteBuffer buf) {
buf.put(INCOMPLETE_ENCODING_FROM_JAVA); // for encoding version
buf.putDouble(GeographyPointValue.NULL_COORD);
buf.putDouble(GeographyPointValue.NULL_COORD);
buf.putDouble(GeographyPointValue.NULL_COORD);
buf.putDouble(GeographyPointValue.NULL_COORD);
}
private static void flattenLoopToBuffer(List<XYZPoint> loop, ByteBuffer buf) {
// 1 byte for encoding version
// 4 bytes for number of vertices
// number of vertices * 8 * 3 bytes for vertices as XYZPoints
// 1 byte for origin_inside_
// 4 bytes for depth_
// length of bound
buf.put(INCOMPLETE_ENCODING_FROM_JAVA);
buf.putInt(loop.size());
for (XYZPoint xyz : loop) {
buf.putDouble(xyz.x());
buf.putDouble(xyz.y());
buf.putDouble(xyz.z());
}
buf.put((byte)0); // origin_inside_
buf.putInt(0); // depth_
flattenEmptyBoundToBuffer(buf);
}
private static void unflattenBoundFromBuffer(ByteBuffer inBuffer) {
inBuffer.get(); // for encoding version
inBuffer.getDouble();
inBuffer.getDouble();
inBuffer.getDouble();
inBuffer.getDouble();
}
private static int unflattenLoopFromBuffer(ByteBuffer inBuffer, List<XYZPoint> loop) {
// 1 byte for encoding version
// 4 bytes for number of vertices
// number of vertices * 8 * 3 bytes for vertices as XYZPoints
// 1 byte for origin_inside_
// 4 bytes for depth_
// length of bound
inBuffer.get(); // encoding version
int numVertices = inBuffer.getInt();
for (int i = 0; i < numVertices; ++i) {
double x = inBuffer.getDouble();
double y = inBuffer.getDouble();
double z = inBuffer.getDouble();
loop.add(new XYZPoint(x, y, z));
}
inBuffer.get(); // origin_inside_
int depth = inBuffer.getInt(); // depth
unflattenBoundFromBuffer(inBuffer);
return depth;
}
private static <T> void diagnoseLoop(List<T> loop, String excpMsgPrf) throws IllegalArgumentException {
if (loop == null) {
throw new IllegalArgumentException(excpMsgPrf + "a polygon must contain at least one ring " +
"(with each ring at least 4 points, including repeated closing vertex)");
}
// 4 vertices = 3 unique vertices for polygon + 1 end point which is same as start point
if (loop.size() < 4) {
throw new IllegalArgumentException(excpMsgPrf + "a polygon ring must contain at least 4 points " +
"(including repeated closing vertex)");
}
// check if the end points of the loop are equal
if (loop.get(0).equals(loop.get(loop.size() - 1)) == false) {
throw new IllegalArgumentException(excpMsgPrf
+ "closing points of ring are not equal: \""
+ loop.get(0).toString()
+ "\" != \""
+ loop.get(loop.size()-1).toString()
+ "\"");
}
}
/**
* A helper method to parse WKT and produce a list of polygon loops.
* Anything more complicated than this and we probably want a dedicated parser.
*
* Note that we assume that the vertices of the first loop are in counter-clockwise
* order, and that subsequent loops are in clockwise order. This is the OGC format's
* definition. When we send these to the EE we need to put them all into counter-clockwise
* order. So, we need to reverse the order of all but the first loop.
*/
private static List<List<XYZPoint>> loopsFromWkt(String wkt) throws IllegalArgumentException {
final String msgPrefix = "Improperly formatted WKT for polygon: ";
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(wkt));
tokenizer.lowerCaseMode(true);
tokenizer.eolIsSignificant(false);
List<XYZPoint> currentLoop = null;
List<List<XYZPoint>> loops = new ArrayList<List<XYZPoint>>();
boolean is_shell = true;
try {
int token = tokenizer.nextToken();
if (token != StreamTokenizer.TT_WORD
|| ! tokenizer.sval.equals("polygon")) {
throw new IllegalArgumentException(msgPrefix + "expected WKT to start with POLYGON");
}
token = tokenizer.nextToken();
if (token != '(') {
throw new IllegalArgumentException(msgPrefix + "expected left parenthesis after POLYGON");
}
boolean polygonOpen = true;
while (polygonOpen) {
token = tokenizer.nextToken();
switch (token) {
case '(':
if (currentLoop != null) {
throw new IllegalArgumentException(msgPrefix + "missing closing parenthesis");
}
currentLoop = new ArrayList<XYZPoint>();
break;
case StreamTokenizer.TT_NUMBER:
if (currentLoop == null) {
throw new IllegalArgumentException(msgPrefix + "missing opening parenthesis");
}
double lng = tokenizer.nval;
token = tokenizer.nextToken();
if (token != StreamTokenizer.TT_NUMBER) {
throw new IllegalArgumentException(msgPrefix + "missing latitude in long lat pair");
}
double lat = tokenizer.nval;
currentLoop.add(XYZPoint.fromGeographyPointValue(new GeographyPointValue(lng, lat)));
token = tokenizer.nextToken();
if (token != ',') {
if (token != ')') {
throw new IllegalArgumentException(msgPrefix + "missing comma between long lat pairs");
}
tokenizer.pushBack();
}
break;
case ')':
// perform basic validation of loop
diagnoseLoop(currentLoop, msgPrefix);
// Following the OGC standard, the first loop should be CCW, and subsequent loops
// should be CW. But we will be building the S2 polygon here,
// and S2 wants everything to be CCW. So, we need to
// reverse all but the first loop.
// Note also that we don't want to touch the vertex at index 0, and we want
// to remove the vertex at index currentLoop.size() - 1. We want to hold the first
// vertex invariant. The vertex at currentLoop.size() - 1 should be a duplicate
// of the vertex at index 0, and should be removed before pushing it into the
// list of loops.
// We are also allowed to swap these out, because they have been
// created and are owned by us.
currentLoop.remove(currentLoop.size() - 1);
if (!is_shell) {
for (int fidx = 1, lidx = currentLoop.size() - 1; fidx < lidx; ++fidx, --lidx) {
Collections.swap(currentLoop, fidx, lidx);
}
}
is_shell = false;
loops.add(currentLoop);
currentLoop = null;
token = tokenizer.nextToken();
if (token == ')') {
polygonOpen = false;
}
else if (token != ',') {
throw new IllegalArgumentException(msgPrefix + "unrecognized token in WKT: " + Character.toString((char)token));
}
break;
case StreamTokenizer.TT_EOF:
throw new IllegalArgumentException(msgPrefix + "premature end of input");
default:
throw new IllegalArgumentException(msgPrefix + "unrecognized token in WKT: " + Character.toString((char)token));
}
}
token = tokenizer.nextToken();
if (token != StreamTokenizer.TT_EOF) {
throw new IllegalArgumentException(msgPrefix + "unrecognized input after WKT");
}
} catch (IOException e) {
throw new IllegalArgumentException(msgPrefix + "error tokenizing string");
}
return loops;
}
/**
* Create a new GeographyValue which is offset from this one
* by the given point. The latitude and longitude values
* stay in range because we are using the normalizing operations
* in GeographyPointValue.
*
* @param offset The point by which to translate vertices in this
* @return The resulting GeographyValue.
*/
public GeographyValue add(GeographyPointValue offset) {
List<List<GeographyPointValue>> newLoops = new ArrayList<List<GeographyPointValue>>();
for (List<XYZPoint> oneLoop : m_loops) {
List<GeographyPointValue> loop = new ArrayList<GeographyPointValue>();
for (XYZPoint p : oneLoop) {
loop.add(p.toGeographyPointValue().add(offset));
}
loop.add(oneLoop.get(0).toGeographyPointValue().add(offset));
newLoops.add(loop);
}
return new GeographyValue(newLoops);
}
}
|
package gov.nih.nci.calab.dto.function;
import java.util.ArrayList;
import java.util.List;
/**
* @author zengje
*
*/
public class AgentBean {
private String id;
private String type="Peptide";
private String name;
private String description;
// otherValue can be "compoundName" for SamllMolecule; "type" for Probe and ImageContrastAgent;
//"speicies" for Antibody; or "sequence" for DNA and Peptide
private String otherValue;
private String numberOfAgentTargets;
private List<AgentTargetBean>agentTargets=new ArrayList<AgentTargetBean>();
public AgentBean() {
super();
// TODO Auto-generated constructor stub
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOtherValue() {
return otherValue;
}
public void setOtherValue(String otherValue) {
this.otherValue = otherValue;
}
public String getNumberOfAgentTargets() {
return numberOfAgentTargets;
}
public void setNumberOfAgentTargets(String numberOfAgentTargets) {
this.numberOfAgentTargets = numberOfAgentTargets;
}
public List<AgentTargetBean> getAgentTargets() {
return agentTargets;
}
public void setAgentTargets(List<AgentTargetBean> agentTargets) {
this.agentTargets = agentTargets;
}
}
|
package io.miti.beetle.exporters;
import io.miti.beetle.util.FakeNode;
import io.miti.beetle.util.FakeSpecParser;
import io.miti.beetle.util.Logger;
import io.miti.beetle.util.NodeInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.DateFormat;
import java.util.List;
public class SQLDBFileWriter extends DBFileWriter
{
public SQLDBFileWriter(final String sFilename, final String sData, final ResultSetMetaData pRSMD) {
super(sFilename, sData, pRSMD);
}
public SQLDBFileWriter(final String sFilename, final String sData, final FakeSpecParser spec) {
super(sFilename, sData, spec);
}
public SQLDBFileWriter(final String sFilename) {
super(sFilename);
}
@Override
public void writeHeader() {
// Write a comment with the date/time
sb.append("-- SQL file generated by Beetle on ")
.append(DateFormat.getDateTimeInstance().format(new java.util.Date()))
.append(EOL);
writeString();
}
@Override
public void writeFooter() {
// Nothing to do for a CSV footer
}
@Override
public void writeObject(final FakeSpecParser spec) {
// Write the start of the line (table name, columns names)
writeStartOfLine();
// Iterate over the data
final int nodeCount = nodes.size();
final List<FakeNode> fakes = spec.getNodes();
for (int i = 0; i < nodeCount; ++i) {
final NodeInfo node = nodes.get(i);
// Write out the value
final Object obj = getValueFromSpec(fakes.get(i));
sb.append(outputValue(obj, node.getClazz()));
// Add a comma if we have more data to write
if (i < (nodeCount - 1)) {
sb.append(", ");
}
writeString();
}
sb.append(");");
sb.append(EOL);
}
@Override
public void writeObject(final ResultSet rs) {
// Write the start of the line (table name, columns names)
writeStartOfLine();
// Iterate over the data
final int nodeCount = nodes.size();
for (int i = 0; i < nodeCount; ++i) {
final NodeInfo node = nodes.get(i);
// Write out the value
final Object obj = getValueFromRow(rs, node.getClazz(), i + 1);
sb.append(outputValue(obj, node.getClazz()));
// Add a comma if we have more data to write
if (i < (nodeCount - 1)) {
sb.append(", ");
}
writeString();
}
sb.append(");");
sb.append(EOL);
}
private void writeStartOfLine() {
// Start the line (fileData has the table name)
sb.append("insert into ").append(fileData).append(" (");
// Write the row of column names
try {
final int colCount = nodes.size();
sb.append(nodes.get(0).getName());
for (int i = 1; i < colCount; ++i) {
sb.append(", ").append(nodes.get(i).getName());
}
} catch (Exception ex) {
System.err.println("Exception writing CSV header: " + ex.getMessage());
}
sb.append(")").append(EOL).append(" values (");
}
private String outputValue(final Object obj, final Class<?> clazz) {
// Handle the different values
if (obj == null) {
return "";
}
if (obj instanceof Boolean) {
return Boolean.toString(((Boolean) obj).booleanValue());
} else if (obj instanceof Long) {
return Long.toString(((Long) obj).longValue());
} else if (obj instanceof Double) {
return Double.toString(((Double) obj).doubleValue());
} else if (obj instanceof String) {
return quoteString(obj.toString());
} else if (obj instanceof java.util.Date) {
return quoteString(toGMTDate((java.util.Date) obj));
}
// Unknown type
Logger.error("Unknown data type: " + obj.getClass().getName());
return "";
}
/**
* Surround the string with single quotes, and backquote any
* single quotes in the string.
*
* @param str the input string
* @return the quoted string
*/
private static String quoteString(final String str)
{
// Check the input
if (str == null)
{
// It's null, so just return that
return "null";
}
final String outStr = str.replace("'", "\\'");
final String outStr2 = "'" + outStr + "'";
return outStr2;
}
}
|
package com.github.ptest.element;
import com.github.ptest.PTestUtil;
import com.github.ptest.runConfiguration.PTestRunConfiguration;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.PyClass;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class PTestClass extends PTestElement<PyClass> {
public PTestClass(PyClass pyClass) {
super(pyClass);
}
@Override
public boolean setupConfiguration(PTestRunConfiguration configuration) {
try {
configuration.setValueForEmptyWorkingDirectory();
configuration.setRunTest(true);
String testTarget = PTestUtil.findShortestImportableName(myElement.getContainingFile()) + "."
+ myElement.getName();
configuration.setTestTargets(testTarget);
configuration.setSuggestedName("ptests in " + myElement.getName());
return true;
} catch (Exception e) {
return false;
}
}
@Override
public List<PTestElement> getChildren() {
List<PTestElement> children = new ArrayList<>();
myElement.visitMethods(pyFunction -> {
if (PTestUtil.hasDecorator(pyFunction, "Test", null, null)) {
PTestMethod pTestMethod = new PTestMethod(this, pyFunction);
// deal with duplicated & inherited tests
if (children.contains(pTestMethod)) {
if (!pTestMethod.isInherited()) {
children.remove(pTestMethod);
children.add(pTestMethod);
}
} else {
children.add(pTestMethod);
}
}
for (String configName : new String[]{"BeforeMethod", "AfterMethod", "BeforeGroup", "AfterGroup",
"BeforeClass", "AfterClass", "BeforeSuite", "AfterSuite"}) {
if (PTestUtil.hasDecorator(pyFunction, configName, null, null)) {
PTestConfiguration pTestConfiguration = new PTestConfiguration(this, pyFunction, configName);
// deal with duplicated & inherited test configurations
if (children.contains(pTestConfiguration)) {
if (!pTestConfiguration.isInherited()) {
children.remove(pTestConfiguration);
children.add(pTestConfiguration);
}
} else {
children.add(pTestConfiguration);
}
}
}
return true;
}, true, null);
return children;
}
@Override
public ItemPresentation getPresentation() {
return new ItemPresentation() {
@Override
public String getPresentableText() {
ItemPresentation presentation = myElement.getPresentation();
return presentation != null ? presentation.getPresentableText() : PyNames.UNNAMED_ELEMENT;
}
@Override
public String getLocationString() {
long childrenCount = getChildren().stream().filter(pTestElement -> pTestElement instanceof PTestMethod).count();
if (childrenCount == 0) {
return "· no tests";
}
if (childrenCount == 1) {
return "· 1 test";
}
return "· " + childrenCount + " tests";
}
@Override
public Icon getIcon(boolean open) {
return myElement.getIcon(0);
}
};
}
@Override
public boolean equals(Object other) {
// deal with duplicated test classes, only consider in the same module
return other instanceof PTestClass && Objects.equals(getValue().getName(), ((PTestClass) other).getValue().getName());
}
public static PTestClass createFrom(PsiElement element) {
final PyClass pyClass = PsiTreeUtil.getParentOfType(element, PyClass.class, false);
if (pyClass == null) return null;
if (PTestUtil.hasDecorator(pyClass, "TestClass", null, null)) return new PTestClass(pyClass);
for (PyClass ancestorClass : pyClass.getAncestorClasses(null)) {
if (PTestUtil.hasDecorator(ancestorClass, "TestClass", null, null)) {
return new PTestClass(pyClass);
}
}
return null;
}
}
|
package io.compgen.ngsutils.fastq;
import java.io.IOException;
import java.io.OutputStream;
public class FastqRead {
private String name;
private String comment;
private String seq;
private String qual;
public FastqRead(String name, String seq, String qual) {
this(name, seq, qual, null);
}
public FastqRead(String name, String seq, String qual, String comment) {
this.name = name;
if (comment != null && !comment.equals("")) {
this.comment = comment;
} else {
this.comment = null;
}
this.seq = seq.toUpperCase();
this.qual = qual;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
public String getSeq() {
return seq;
}
public String getQual() {
return qual;
}
public void write(OutputStream out) throws IOException {
// technically the seq and qual can be wrapped, but it's rarely used and not recommended.
// so, that's not implemented here.
String rec;
if (comment != null) {
rec = "@"+name+" "+comment+"\n"+seq+"\n+\n"+qual+"\n";
} else {
rec = "@"+name+"\n"+seq+"\n+\n"+qual+"\n";
}
out.write(rec.getBytes());
}
// needed to reset name of a read if there is a pair flag (/1, /2)
public void setName(String name) {
this.name = name;
}
// needed to reset name of a read if there is a pair flag (/1, /2)
public void setComment(String comment) {
this.comment = comment;
}
}
|
package nl.b3p.kar.stripes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;
import nl.b3p.incaa.IncaaImport;
import nl.b3p.kar.hibernate.Gebruiker;
import nl.b3p.kar.hibernate.RoadsideEquipment;
import nl.b3p.kar.jaxb.Kv9Def;
import nl.b3p.kar.jaxb.TmiPush;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Meine Toonen
*/
@StrictBinding
@UrlBinding("/action/import")
public class ImportActionBean implements ActionBean {
private final Log log = LogFactory.getLog(this.getClass());
private final static String OVERVIEW = "/WEB-INF/jsp/import/import.jsp";
private ActionBeanContext context;
@Validate(required = true, on = {"importPtx", "importXml"})
private FileBean bestand;
// <editor-fold desc="getters and setters">
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public FileBean getBestand() {
return bestand;
}
public void setBestand(FileBean bestand) {
this.bestand = bestand;
}
// </editor-fold>
@DefaultHandler
public Resolution overview() {
return new ForwardResolution(OVERVIEW);
}
public Resolution importXml() {
try {
JAXBContext ctx = JAXBContext.newInstance(TmiPush.class);
Unmarshaller u = ctx.createUnmarshaller();
EntityManager em = Stripersist.getEntityManager();
TmiPush push = (TmiPush) u.unmarshal(bestand.getInputStream());
int num = 0;
List<Kv9Def> defs = push.getRseqs();
for (Kv9Def kv9Def : defs) {
List<RoadsideEquipment> rseqs = kv9Def.getRoadsideEquipments();
for (RoadsideEquipment roadsideEquipment : rseqs) {
em.persist(roadsideEquipment);
num ++;
}
}
em.getTransaction().commit();
this.context.getMessages().add(new SimpleMessage(("Er zijn " + num + " verkeerssystemen succesvol geïmporteerd.")));
} catch (JAXBException jaxbEx) {
this.context.getValidationErrors().addGlobalError(new SimpleError("Er zijn fouten opgetreden bij het importeren van verkeerssystemen: \n" + ExceptionUtils.getMessage(jaxbEx)));
} catch (IOException ex) {
this.context.getValidationErrors().addGlobalError(new SimpleError("Er zijn fouten opgetreden bij het importeren van verkeerssystemen: \n" + ExceptionUtils.getMessage(ex)));
}
return new ForwardResolution(OVERVIEW);
}
public Resolution importPtx() {
final FileBean zipFile = bestand;
IncaaImport importer = new IncaaImport();
try {
List<RoadsideEquipment> rseqs = importer.importPtx(zipFile.getReader(), getGebruiker());
this.context.getMessages().add(new SimpleMessage(("Er zijn " + rseqs.size() + " verkeerssystemen succesvol geïmporteerd.")));
} catch (Exception e) {
log.error(e);
this.context.getValidationErrors().addGlobalError(new SimpleError("Er zijn fouten opgetreden bij het importeren van verkeerssystemen: \n" + ExceptionUtils.getMessage(e)));
} finally {
try {
bestand.delete();
} catch (IOException ex) {
log.error(ex);
}
}
return new ForwardResolution(OVERVIEW);
}
public Gebruiker getGebruiker() {
final String attribute = this.getClass().getName() + "_GEBRUIKER";
Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute);
if (g != null) {
return g;
}
Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal();
g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId());
getContext().getRequest().setAttribute(attribute, g);
return g;
}
}
|
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.tools.postag;
import java.io.StringReader;
import opennlp.maxent.DataStream;
import opennlp.maxent.Event;
import opennlp.maxent.EventCollector;
import opennlp.maxent.EventStream;
import opennlp.tools.ngram.Dictionary;
/**
* An implementation of EventStream whcih assumes the data stream gives a
* sentence at a time with tokens as word_tag pairs.
*/
public class POSEventStream implements EventStream {
private POSContextGenerator cg;
private DataStream data;
private Event[] events;
private int ei;
/** The last line read in from the data file. */
private String line;
public POSEventStream(DataStream d) {
this(d, new DefaultPOSContextGenerator(null));
}
public POSEventStream(DataStream d, Dictionary dict) {
this(d, new DefaultPOSContextGenerator(dict));
}
public POSEventStream(DataStream d, POSContextGenerator cg) {
this.cg = cg;
data = d;
ei = 0;
if (d.hasNext()) {
addNewEvents((String) d.nextToken());
}
else {
events = new Event[0];
}
}
public boolean hasNext() {
if (ei < events.length) {
return true;
}
else if (line != null) { // previous result has not been consumed
return true;
}
//find next non-blank line
while (data.hasNext()) {
line = (String) data.nextToken();
if (line.equals("")) {
}
else {
return true;
}
}
return false;
}
public Event nextEvent() {
if (ei == events.length) {
addNewEvents(line);
ei = 0;
line = null;
}
return ((Event) events[ei++]);
}
private void addNewEvents(String sentence) {
//String sentence = "the_DT stories_NNS about_IN well-heeled_JJ communities_NNS and_CC developers_NNS";
EventCollector ec = new POSEventCollector(new StringReader(sentence), cg);
events = ec.getEvents();
//System.err.println("POSEventStream.addNewEvents: got "+events.length+" events");
}
public static void main(String[] args) throws java.io.IOException {
EventStream es = new POSEventStream(new opennlp.maxent.PlainTextByLineDataStream(new java.io.InputStreamReader(System.in)),new Dictionary(args[0]));
while (es.hasNext()) {
System.out.println(es.nextEvent());
}
}
}
|
package org.apache.lucene.document;
import java.util.Enumeration;
import java.util.List;
import java.util.ArrayList;
import org.apache.lucene.index.IndexReader; // for javadoc
/** Documents are the unit of indexing and search.
*
* A Document is a set of fields. Each field has a name and a textual value.
* A field may be stored with the document, in which case it is returned with
* search hits on the document. Thus each document should typically contain
* stored fields which uniquely identify it.
* */
public final class Document implements java.io.Serializable {
DocumentFieldList fieldList = null;
private float boost = 1.0f;
/** Constructs a new document with no fields. */
public Document() {}
/** Sets a boost factor for hits on any field of this document. This value
* will be multiplied into the score of all hits on this document.
*
* <p>Values are multiplied into the value of {@link Field#getBoost()} of
* each field in this document. Thus, this method in effect sets a default
* boost for the fields of this document.
*
* @see Field#setBoost(float)
*/
public void setBoost(float boost) {
this.boost = boost;
}
/** Returns the boost factor for hits on any field of this document.
*
* <p>The default value is 1.0.
*
* <p>Note: This value is not stored directly with the document in the index.
* Documents returned from {@link IndexReader#document(int)} and {@link
* Hits#doc(int)} may thus not have the same value present as when this
* document was indexed.
*
* @see #setBoost(float)
*/
public float getBoost() {
return boost;
}
/** Adds a field to a document. Several fields may be added with
* the same name. In this case, if the fields are indexed, their text is
* treated as though appended for the purposes of search. */
public final void add(Field field) {
fieldList = new DocumentFieldList(field, fieldList);
}
/** Returns a field with the given name if any exist in this document, or
null. If multiple fields exists with this name, this method returns the
last field value added. */
public final Field getField(String name) {
for (DocumentFieldList list = fieldList; list != null; list = list.next)
if (list.field.name().equals(name))
return list.field;
return null;
}
/** Returns the string value of the field with the given name if any exist in
this document, or null. If multiple fields exist with this name, this
method returns the last value added. */
public final String get(String name) {
Field field = getField(name);
if (field != null)
return field.stringValue();
else
return null;
}
/** Returns an Enumeration of all the fields in a document. */
public final Enumeration fields() {
return new DocumentFieldEnumeration(this);
}
/**
* Returns an array of {@link Field}s with the given name.
* This method can return <code>null</code>.
*
* @param name the name of the field
* @return a <code>Field[]</code> array
*/
public final Field[] getFields(String name) {
List tempFieldList = new ArrayList();
for (DocumentFieldList list = fieldList; list != null; list = list.next) {
if (list.field.name().equals(name)) {
tempFieldList.add(list.field);
}
}
int fieldCount = tempFieldList.size();
if (fieldCount == 0) {
return null;
}
else {
return (Field[])tempFieldList.toArray(new Field[] {});
}
}
/**
* Returns an array of values of the field specified as the method parameter.
* This method can return <code>null</code>.
* UnStored fields' values cannot be returned by this method.
*
* @param name the name of the field
* @return a <code>String[]</code> of field values
*/
public final String[] getValues(String name) {
Field[] namedFields = getFields(name);
if (namedFields == null)
return null;
String[] values = new String[namedFields.length];
for (int i = 0; i < namedFields.length; i++) {
values[i] = namedFields[i].stringValue();
}
return values;
}
/** Prints the fields of a document for human consumption. */
public final String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Document<");
for (DocumentFieldList list = fieldList; list != null; list = list.next) {
buffer.append(list.field.toString());
if (list.next != null)
buffer.append(" ");
}
buffer.append(">");
return buffer.toString();
}
}
final class DocumentFieldList implements java.io.Serializable {
DocumentFieldList(Field f, DocumentFieldList n) {
field = f;
next = n;
}
Field field;
DocumentFieldList next;
}
final class DocumentFieldEnumeration implements Enumeration {
DocumentFieldList fields;
DocumentFieldEnumeration(Document d) {
fields = d.fieldList;
}
public final boolean hasMoreElements() {
return fields == null ? false : true;
}
public final Object nextElement() {
Field result = fields.field;
fields = fields.next;
return result;
}
}
|
package org.jivesoftware.admin;
import org.jivesoftware.util.*;
import org.jivesoftware.wildfire.XMPPServer;
import org.jivesoftware.wildfire.container.PluginManager;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.DocumentFactory;
import org.dom4j.io.SAXReader;
import java.util.*;
import java.io.InputStream;
import java.net.URL;
/**
* A model for admin tab and sidebar info. This class loads in XML definitions of the
* data and produces an in-memory model.<p>
*
* This class loads its data from the <tt>admin-sidebar.xml</tt> file which is assumed
* to be in the main application jar file. In addition, it will load files from
* <tt>META-INF/admin-sidebar.xml</tt> if they're found. This allows developers to
* extend the functionality of the admin console to provide more options. See the main
* <tt>admin-sidebar.xml</tt> file for documentation of its format.
*/
public class AdminConsole {
private static Element coreModel;
private static Map<String,Element> overrideModels;
private static Element generatedModel;
static {
overrideModels = new LinkedHashMap<String,Element>();
load();
// The admin console model has special logic to include an informational
// Enterprise tab when the Enterprise plugin is not installed. A property
// controls whether to show that tab. Listen for the property value changing
// and rebuild the model when that happens.
PropertyEventDispatcher.addListener(new PropertyEventListener() {
public void propertySet(String property, Map params) {
if ("enterpriseInfoEnabled".equals(property)) {
rebuildModel();
}
}
public void propertyDeleted(String property, Map params) {
if ("enterpriseInfoEnabled".equals(property)) {
rebuildModel();
}
}
public void xmlPropertySet(String property, Map params) {
// Do nothing
}
public void xmlPropertyDeleted(String property, Map params) {
// Do nothing
}
});
}
/** Not instantiatable */
private AdminConsole() {
}
/**
* Adds XML stream to the tabs/sidebar model.
*
* @param name the name.
* @param in the XML input stream.
* @throws Exception if an error occurs when parsing the XML or adding it to the model.
*/
public static void addModel(String name, InputStream in) throws Exception {
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(in);
addModel(name, (Element)doc.selectSingleNode("/adminconsole"));
}
/**
* Adds an <adminconsole> Element to the tabs/sidebar model.
*
* @param name the name.
* @param element the Element
* @throws Exception if an error occurs.
*/
public static void addModel(String name, Element element) throws Exception {
overrideModels.put(name, element);
rebuildModel();
}
/**
* Removes an <adminconsole> Element from the tabs/sidebar model.
*
* @param name the name.
*/
public static void removeModel(String name) {
overrideModels.remove(name);
rebuildModel();
}
/**
* Returns the name of the application.
*
* @return the name of the application.
*/
public static synchronized String getAppName() {
Element appName = (Element)generatedModel.selectSingleNode("//adminconsole/global/appname");
if (appName != null) {
String pluginName = appName.attributeValue("plugin");
return getAdminText(appName.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the URL of the main logo image for the admin console.
*
* @return the logo image.
*/
public static synchronized String getLogoImage() {
Element globalLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/logo-image");
if (globalLogoImage != null) {
String pluginName = globalLogoImage.attributeValue("plugin");
return getAdminText(globalLogoImage.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the URL of the login image for the admin console.
*
* @return the login image.
*/
public static synchronized String getLoginLogoImage() {
Element globalLoginLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/login-image");
if (globalLoginLogoImage != null) {
String pluginName = globalLoginLogoImage.attributeValue("plugin");
return getAdminText(globalLoginLogoImage.getText(), pluginName);
}
else {
return null;
}
}
/**
* Returns the version string displayed in the admin console.
*
* @return the version string.
*/
public static synchronized String getVersionString() {
Element globalVersion = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/version");
if (globalVersion != null) {
String pluginName = globalVersion.attributeValue("plugin");
return getAdminText(globalVersion.getText(), pluginName);
}
else {
// Default to the Wildfire version if none has been provided via XML.
XMPPServer xmppServer = XMPPServer.getInstance();
return xmppServer.getServerInfo().getVersion().getVersionString();
}
}
/**
* Returns the model. The model should be considered read-only.
*
* @return the model.
*/
public static synchronized Element getModel() {
return generatedModel;
}
/**
* Convenience method to select an element from the model by its ID. If an
* element with a matching ID is not found, <tt>null</tt> will be returned.
*
* @param id the ID.
* @return the element.
*/
public static synchronized Element getElemnetByID(String id) {
/**
* Returns a text element for the admin console, applying the appropriate locale.
* Internationalization logic will only be applied if the String is specially encoded
* in the format "${key.name}". If it is, the String is pulled from the resource bundle.
* If the pluginName is not <tt>null</tt>, the plugin's resource bundle will be used
* to look up the key.
*
* @param string the String.
* @param pluginName the name of the plugin that the i18n String can be found in,
* or <tt>null</tt> if the standard Wildfire resource bundle should be used.
* @return the string, or if the string is encoded as an i18n key, the value from
* the appropriate resource bundle.
*/
public static String getAdminText(String string, String pluginName) {
if (string == null) {
return null;
}
// Look for the key symbol:
if (string.indexOf("${") == 0 && string.indexOf("}") == string.length()-1) {
return LocaleUtils.getLocalizedString(string.substring(2, string.length()-1), pluginName);
}
return string;
}
private static void load() {
// Load the core model as the admin-sidebar.xml file from the classpath.
InputStream in = ClassUtils.getResourceAsStream("/admin-sidebar.xml");
if (in == null) {
Log.error("Failed to load admin-sidebar.xml file from Wildfire classes - admin "
+ "console will not work correctly.");
return;
}
try {
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(in);
coreModel = (Element)doc.selectSingleNode("/adminconsole");
}
catch (Exception e) {
Log.error("Failure when parsing main admin-sidebar.xml file", e);
}
try {
in.close();
}
catch (Exception ignored) {
// Ignore.
}
// Load other admin-sidebar.xml files from the classpath
ClassLoader[] classLoaders = getClassLoaders();
for (int i=0; i<classLoaders.length; i++) {
URL url = null;
try {
if (classLoaders[i] != null) {
Enumeration e = classLoaders[i].getResources("/META-INF/admin-sidebar.xml");
while (e.hasMoreElements()) {
url = (URL)e.nextElement();
try {
in = url.openStream();
addModel("admin", in);
}
finally {
try { if (in != null) { in.close(); } }
catch (Exception ignored) {
// Ignore.
}
}
}
}
}
catch (Exception e) {
String msg = "Failed to load admin-sidebar.xml";
if (url != null) {
msg += " from resource: " + url.toString();
}
Log.warn(msg, e);
}
}
rebuildModel();
}
/**
* Rebuilds the generated model.
*/
private static synchronized void rebuildModel() {
Document doc = DocumentFactory.getInstance().createDocument();
generatedModel = coreModel.createCopy();
doc.add(generatedModel);
// Add in all overrides.
for (Element element : overrideModels.values()) {
// See if global settings are overriden.
Element appName = (Element)element.selectSingleNode("//adminconsole/global/appname");
if (appName != null) {
Element existingAppName = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/appname");
existingAppName.setText(appName.getText());
if (appName.attributeValue("plugin") != null) {
existingAppName.addAttribute("plugin", appName.attributeValue("plugin"));
}
}
Element appLogoImage = (Element)element.selectSingleNode("//adminconsole/global/logo-image");
if (appLogoImage != null) {
Element existingLogoImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/logo-image");
existingLogoImage.setText(appLogoImage.getText());
if (appLogoImage.attributeValue("plugin") != null) {
existingLogoImage.addAttribute("plugin", appLogoImage.attributeValue("plugin"));
}
}
Element appLoginImage = (Element)element.selectSingleNode("//adminconsole/global/login-image");
if (appLoginImage != null) {
Element existingLoginImage = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/login-image");
existingLoginImage.setText(appLoginImage.getText());
if (appLoginImage.attributeValue("plugin") != null) {
existingLoginImage.addAttribute("plugin", appLoginImage.attributeValue("plugin"));
}
}
Element appVersion = (Element)element.selectSingleNode("//adminconsole/global/version");
if (appVersion != null) {
Element existingVersion = (Element)generatedModel.selectSingleNode(
"//adminconsole/global/version");
if (existingVersion != null) {
existingVersion.setText(appVersion.getText());
if (appVersion.attributeValue("plugin") != null) {
existingVersion.addAttribute("plugin", appVersion.attributeValue("plugin"));
}
}
else {
((Element)generatedModel.selectSingleNode(
"//adminconsole/global")).add(appVersion.createCopy());
}
}
// Tabs
for (Iterator i=element.selectNodes("//tab").iterator(); i.hasNext(); ) {
Element tab = (Element)i.next();
String id = tab.attributeValue("id");
Element existingTab = getElemnetByID(id);
// Simple case, there is no existing tab with the same id.
if (existingTab == null) {
// Make sure that the URL on the tab is set. If not, default to the
// url of the first item.
if (tab.attributeValue("url") == null) {
Element firstItem = (Element)tab.selectSingleNode(
"//item[@url]");
if (firstItem != null) {
tab.addAttribute("url", firstItem.attributeValue("url"));
}
}
generatedModel.add(tab.createCopy());
}
// More complex case -- a tab with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideTab(existingTab, tab);
}
}
}
// Special case: show an informational tab about Wildfire Enterprise if Enterprise
// is not installed and if the user has not chosen to hide tab.
PluginManager pluginManager = XMPPServer.getInstance().getPluginManager();
boolean pluginExists = pluginManager != null && pluginManager.isPluginDownloaded(
"enterprise.jar");
if (!pluginExists && JiveGlobals.getBooleanProperty("enterpriseInfoEnabled", true)) {
Element enterprise = generatedModel.addElement("tab");
enterprise.addAttribute("id", "tab-enterprise");
enterprise.addAttribute("name", "Enterprise");
enterprise.addAttribute("url", "enterprise-info.jsp");
enterprise.addAttribute("description", "Click for Enterprise information.");
Element sidebar = enterprise.addElement("sidebar");
sidebar.addAttribute("id", "sidebar-enterprise-info");
sidebar.addAttribute("name", "Wildfire Enterprise");
Element item = sidebar.addElement("item");
item.addAttribute("id", "enterprise-info");
item.addAttribute("name", "Try Enterprise");
item.addAttribute("url", "enterprise-info.jsp");
item.addAttribute("description", "Wildfire Enterprise overview inforation");
}
}
private static void overrideTab(Element tab, Element overrideTab) {
// Override name, url, description.
if (overrideTab.attributeValue("name") != null) {
tab.addAttribute("name", overrideTab.attributeValue("name"));
}
if (overrideTab.attributeValue("url") != null) {
tab.addAttribute("url", overrideTab.attributeValue("url"));
}
if (overrideTab.attributeValue("description") != null) {
tab.addAttribute("description", overrideTab.attributeValue("description"));
}
if (overrideTab.attributeValue("plugin") != null) {
tab.addAttribute("plugin", overrideTab.attributeValue("plugin"));
}
// Override sidebar items.
for (Iterator i=overrideTab.elementIterator(); i.hasNext(); ) {
Element sidebar = (Element)i.next();
String id = sidebar.attributeValue("id");
Element existingSidebar = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingSidebar == null) {
tab.add(sidebar.createCopy());
}
// More complex case -- a sidebar with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideSidebar(existingSidebar, sidebar);
}
}
}
private static void overrideSidebar(Element sidebar, Element overrideSidebar) {
// Override name.
if (overrideSidebar.attributeValue("name") != null) {
sidebar.addAttribute("name", overrideSidebar.attributeValue("name"));
}
if (overrideSidebar.attributeValue("plugin") != null) {
sidebar.addAttribute("plugin", overrideSidebar.attributeValue("plugin"));
}
// Override entries.
for (Iterator i=overrideSidebar.elementIterator(); i.hasNext(); ) {
Element entry = (Element)i.next();
String id = entry.attributeValue("id");
Element existingEntry = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingEntry == null) {
sidebar.add(entry.createCopy());
}
// More complex case -- an entry with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideEntry(existingEntry, entry);
}
}
}
private static void overrideEntry(Element entry, Element overrideEntry) {
// Override name.
if (overrideEntry.attributeValue("name") != null) {
entry.addAttribute("name", overrideEntry.attributeValue("name"));
}
if (overrideEntry.attributeValue("url") != null) {
entry.addAttribute("url", overrideEntry.attributeValue("url"));
}
if (overrideEntry.attributeValue("description") != null) {
entry.addAttribute("description", overrideEntry.attributeValue("description"));
}
if (overrideEntry.attributeValue("plugin") != null) {
entry.addAttribute("plugin", overrideEntry.attributeValue("plugin"));
}
// Override any sidebars contained in the entry.
for (Iterator i=overrideEntry.elementIterator(); i.hasNext(); ) {
Element sidebar = (Element)i.next();
String id = sidebar.attributeValue("id");
Element existingSidebar = getElemnetByID(id);
// Simple case, there is no existing sidebar with the same id.
if (existingSidebar == null) {
entry.add(sidebar.createCopy());
}
// More complex case -- a sidebar with the same id already exists.
// In this case, we have to overrite only the difference between
// the two elements.
else {
overrideSidebar(existingSidebar, sidebar);
}
}
}
/**
* Returns an array of class loaders to load resources from.
*
* @return an array of class loaders to load resources from.
*/
private static ClassLoader[] getClassLoaders() {
ClassLoader[] classLoaders = new ClassLoader[3];
classLoaders[0] = AdminConsole.class.getClass().getClassLoader();
classLoaders[1] = Thread.currentThread().getContextClassLoader();
classLoaders[2] = ClassLoader.getSystemClassLoader();
return classLoaders;
}
}
|
package org.neo4j.util.shell;
import java.io.Serializable;
import java.rmi.RemoteException;
/**
* A common implementation of a {@link ShellClient}.
*/
public abstract class AbstractClient implements ShellClient
{
/**
* The session key for the prompt key, just like in Bash.
*/
public static final String PROMPT_KEY = "PS1";
/**
* The session key for whether or not to print stack traces for exceptions.
*/
public static final String STACKTRACES_KEY = "STACKTRACES";
private Console console;
public void grabPrompt()
{
this.init();
while ( true )
{
try
{
this.console.format( tryGetProperPromptString() );
String line = this.readLine();
String result = this.getServer().interpretLine(
line, this.session(), this.getOutput() );
if ( result == null || result.trim().length() == 0 )
{
continue;
}
if ( result.contains( "e" ) )
{
break;
}
}
catch ( Exception e )
{
if ( this.shouldPrintStackTraces() )
{
e.printStackTrace();
}
this.console.format( e.getMessage() + "\n" );
}
}
this.shutdown();
}
protected String tryGetProperPromptString()
{
String result = null;
try
{
result = ( String ) getSessionVariable( PROMPT_KEY, null, true );
}
catch ( Exception e )
{
result = ( String ) getSessionVariable( PROMPT_KEY, null, false );
}
return result;
}
protected void shutdown()
{
}
private boolean shouldPrintStackTraces()
{
try
{
Object value = this.session().get( STACKTRACES_KEY );
return this.getSafeBooleanValue( value, false );
}
catch ( RemoteException e )
{
return true;
}
}
private boolean getSafeBooleanValue( Object value, boolean def )
{
if ( value == null )
{
return def;
}
return Boolean.parseBoolean( value.toString() );
}
private void init()
{
try
{
possiblyGrabDefaultVariableFromServer( PROMPT_KEY, "$ " );
this.getOutput().println( this.getServer().welcome() );
// Grab a jline console if available, else a standard one.
this.console = JLineConsole.newConsoleOrNullIfNotFound( this );
if ( this.console == null )
{
System.out.println( "Want bash-like features? throw in " +
"jLine on the classpath" );
this.console = new StandardConsole();
}
}
catch ( RemoteException e )
{
throw new RuntimeException( e );
}
}
protected void possiblyGrabDefaultVariableFromServer( String key,
Serializable defaultValue )
{
try
{
if ( this.session().get( key ) == null )
{
Serializable value = this.getServer().getProperty( key );
if ( value == null )
{
value = defaultValue;
}
if ( value != null )
{
this.session().set( key, value );
}
}
}
catch ( RemoteException e )
{
throw new RuntimeException( e );
}
}
protected Serializable getSessionVariable( String key,
Serializable defaultValue, boolean interpret )
{
try
{
Serializable result = this.session().get( key );
if ( result == null )
{
result = defaultValue;
}
if ( interpret && result != null )
{
result = this.getServer().interpretVariable( key, result,
session() );
}
return result;
}
catch ( RemoteException e )
{
throw new RuntimeException( e );
}
}
public String readLine()
{
return this.console.readLine();
}
}
|
package jsaf.intf.windows.system;
import jsaf.intf.system.IComputerSystem;
import jsaf.intf.windows.identity.IDirectory;
import jsaf.intf.windows.io.IWindowsFilesystem;
import jsaf.intf.windows.powershell.IRunspacePool;
import jsaf.intf.windows.registry.IRegistry;
import jsaf.intf.windows.wmi.IWmiProvider;
/**
* A representation of a Windows session.
*
* @author David A. Solin
* @version %I% %G%
* @since 1.0
*/
public interface IWindowsSession extends IComputerSystem {
/**
* Property indicating the number of milliseconds to wait for a WMI query to return, before quitting and throwing an
* exception.
*
* @since 1.2
*/
String PROP_WMI_TIMEOUT = "wmi.timeout";
/**
* Property indicating the default number of milliseconds to wait for output from a Powershell command, before quitting
* and throwing an exception.
*
* @since 1.3.5
*/
String PROP_POWERSHELL_TIMEOUT = "powershell.timeout";
/**
* Name of the environment variable containing the processor architecture (when running in 32-bit mode on a 64-bit
* machine, the value will actually be the emulated architecture).
*
* @since 1.0
*/
String ENV_ARCH = "PROCESSOR_ARCHITECTURE";
/**
* Name of the environment variable containing the actual processor architecture, when running in 32-bit mode on a
* 64-bit machine.
*
* @since 1.0
*/
String ENV_AR32 = "PROCESSOR_ARCHITEW6432";
/**
* SID for the Administrators group.
*
* @since 1.1
*/
String ADMINISTRATORS_SID = "S-1-5-32-544";
/**
* An enumeration of possible views.
*
* @since 1.0
*/
public enum View {
/**
* 32-bit view.
*
* @since 1.0
*/
_32BIT,
/**
* 64-bit view.
*
* @since 1.0
*/
_64BIT;
}
/**
* Get the native view of the session.
*
* @since 1.0
*/
View getNativeView();
/**
* Obtain an IRegistry for the machine. For a 32-bit machine, the view is ignored.
*
* @since 1.0
*/
IRegistry getRegistry(View view);
/**
* Test whether the session supports the specified view.
*
* @since 1.0
*/
boolean supports(View view);
/**
* Test whether the session has the ability to run commands requiring UAC privileges.
*
* @since 1.3
*/
boolean privileged();
/**
* As an IComputerSystem, the getFilesystem() call always returns a non-redirected view, i.e.,
* getFilesystem(getNativeView()). This method facilitates access to the 32-bit view on a 64-bit machine.
* (For a 32-bit machine, the view is ignored).
*
* @since 1.0
*/
IWindowsFilesystem getFilesystem(View view);
/**
* Obtain a WMI provider for the machine. (This should always be a WMI provider for the native processor architecture).
*
* @since 1.0
*/
IWmiProvider getWmiProvider();
/**
* Obtain the IDirectory for the machine.
*
* @since 1.0
*/
IDirectory getDirectory();
/**
* Obtain the session's runspace pool.
*
* @since 1.0
*/
IRunspacePool getRunspacePool();
}
|
package org.videolan;
import java.io.File;
import java.io.IOException;
class CacheDir {
private static synchronized File getCacheRoot() throws IOException {
if (cacheRoot != null) {
return cacheRoot;
}
String base = System.getProperty("java.io.tmpdir") + File.separator +
"libbluray-bdj-cache" + File.separator;
for (int i = 0; i < 100; i++) {
File tmpDir = new File(base + System.nanoTime());
tmpDir = new File(tmpDir.getCanonicalPath());
if (tmpDir.mkdirs()) {
cacheRoot = tmpDir;
logger.info("Created cache in " + tmpDir.getPath());
return cacheRoot;
}
logger.error("error creating " + tmpDir.getPath());
}
logger.error("failed to create temporary cache directory");
throw new IOException();
}
public static synchronized File create(String domain) throws IOException {
File tmpDir = new File(getCacheRoot().getPath() + File.separator + domain);
if (!tmpDir.exists() && !tmpDir.mkdirs()) {
logger.error("Error creating " + tmpDir.getPath());
throw new IOException();
}
return tmpDir;
}
public static File create(String domain, String name) throws IOException {
return create(domain + File.separator + name);
}
private static void removeImpl(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
removeImpl(file);
} else {
if (!file.delete()) {
logger.info("Error removing " + file.getPath());
}
}
}
}
if (!dir.delete()) {
logger.error("Error removing " + dir.getPath());
}
}
public static synchronized void remove(File dir) {
String path = dir.getPath();
if (path.indexOf(cacheRoot.getPath()) != 0) {
logger.error("Error removing " + dir.getPath() + ": not inside cache !");
return;
}
if (path.indexOf("..") >= 0) {
logger.error("Error removing " + dir.getPath() + ": not canonical path !");
return;
}
removeImpl(dir);
}
public static synchronized void remove() {
if (cacheRoot != null) {
remove(cacheRoot);
cacheRoot = null;
}
}
private static File cacheRoot = null;
private static final Logger logger = Logger.getLogger(MountManager.class.getName());
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package magpie.data.materials;
import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;
import magpie.data.BaseEntry;
import magpie.data.materials.util.LookupData;
import magpie.data.materials.util.PropertyLists;
import org.apache.commons.math3.stat.*;
/**
* This class stores entries that describe a material based solely on its
* composition.<p>
*
* Some of the available features include:
* <ul>
* <li>Generate attributes based on composition only</li>
* <li>Read in data from specially-formatted input file</li>
* <li>Store multiple properties for a each entry</li>
* </ul>
*
* When reading data in from text using the <code>importText</code> function,
* the data must be in the following format:
*
* <p>
* Composition property_1 property_2 ... property_N<br>
* As,0.2,B,0.8, 0.1 0.4 0.8 ...<br>
* As,1,B,4, 0.2 0.9 none ...<br>
* Cu,2,Zr,4, 0.2 0.1 10.8 ...<br>
* <as many entries as you desire><br>
*
* <p>
* Please see the documentation provided with this package for more information.
*
* <p><b><u>Implemented Commands:</u></b>
*
* <command><p><b>attributes composition <true|false></b> -
* Set whether to use composition as attributes
* <br><pr><i>true|false</i> - Whether to use composition as attributes
* <br>By default, this class does not use composition (by itself) as attributes</command>
*
* <command><p><b>attributes properties</b> - List which elemental properties are used to generate attributes</command>
*
* <command><p><b>attributes properties add <names...></b> - Add elemental properties to use when generating attributes</command>
* <br><pr><i>name...</i>: Name of a elemental properties</command>
*
* <command><p><b>attributes properties add set <name</b> - Add in all elemental properties from a pre-defined set
* <br><pr><i>name</i>: Name of the pre-defined set</command>
*
* <command><p><b>attributes properties remove <names...></b> - Remove properties from list of those used when generating attributes
* <br><pr><i>names...</i>: Name of properties to remove</command>
*
* <command><p><b>properties <directory></b> - Specify directory that contains the elemental property lookup files
* <br><pr><i>directory</i>: Desired directory</command>
*
* @author Logan Ward
* @version 0.2
*/
public class CompositionDataset extends magpie.data.MultiPropertyDataset {
/**
* List of element names
*/
public String[] ElementNames = LookupData.ElementNames;
/**
* Order in which elements are sorted (used when printing)
*/
protected int[] SortingOrder = LookupData.SortingOrder;
/**
* Location of lookup date files
*/
public String DataDirectory = "./Lookup Data";
/**
* List of properties used when generating attributes
*/
public List<String> ElementalProperties = new LinkedList<>();
/**
* Map of property names to values
*/
public Map<String, double[]> PropertyData = LookupData.ElementalProperties;
/** Whether to use composition as attributes */
protected boolean UseComposition = false;
@Override
@SuppressWarnings("CloneDeclaresCloneNotSupported")
public CompositionDataset clone() {
CompositionDataset x = (CompositionDataset) super.clone();
x.ElementNames = ElementNames.clone();
return x;
}
@Override
public CompositionDataset emptyClone() {
CompositionDataset x = (CompositionDataset) super.emptyClone();
x.ElementNames = ElementNames.clone();
return x;
}
@Override
public CompositionEntry getEntry(int index) {
return (CompositionEntry) super.getEntry(index);
}
@Override
public void addEntry(String input) {
addEntry(new CompositionEntry(input));
}
/**
* Get the order in which elements are sorted when storing a composition. Sorting
* makes it faster to detect whether compounds are equal
* @return Sorting order
*/
public int[] getSortingOrder() {
return SortingOrder.clone();
}
/**
* Read in an dataset from file. See documentation for format information.
*
* @param filename Path of file to be imported
* @throws java.lang.Exception
*/
@Override
@SuppressWarnings("empty-statement")
public void importText(String filename, Object[] options) throws Exception {
// Count the number of lines (1 per entry + 1 header)
LineNumberReader lr = new LineNumberReader(new FileReader(filename));
while (lr.skip(Long.MAX_VALUE) > 0) {
};
int Entry_Count = lr.getLineNumber() + 1;
lr.close();
// Define the reader
BufferedReader is = Files.newBufferedReader(Paths.get(filename), Charset.forName("US-ASCII"));
String Line;
String[] Words;
// Read in the header
Line = is.readLine();
Words = Line.split(" ");
for (int i = 1; i < Words.length; i++) {
addProperty(Words[i]);
}
// Determine which property is the energy ("energy_pa")
int energy_id = getPropertyIndex("energy_pa");
// Read in each entry
TreeMap<BaseEntry, CompositionEntry> acceptedEntries = new TreeMap<>();
TreeMap<BaseEntry, List<double[]>> duplicateProperties = new TreeMap<>();
CompositionEntry Entry;
for (int i = 0; i < Entry_Count; i++) {
double[] properties;
// Read a line and tokenize it
Line = is.readLine();
if (Line == null) {
break;
}
Words = Line.split("\\s+");
// Get the properties
properties = new double[NProperties()];
for (int j = 0; j < NProperties(); j++) {
try {
properties[j] = Double.parseDouble(Words[j + 1]);
} catch (NumberFormatException e) {
// System.err.println("Warning: Entry #"+i+" has an invalid property.");
properties[j] = Double.NaN;
}
}
// Make an entry
Entry = new CompositionEntry(Words[0]);
Entry.setMeasuredProperties(properties);
// Add if the set does not already have it
if (!acceptedEntries.containsKey(Entry)) {
acceptedEntries.put(Entry, Entry);
} else {
// If the entries have a "energy_pa" as a property, supplant the existing
// entry if it is higher in energy
if (energy_id != -1) {
CompositionEntry oldBest = (CompositionEntry) acceptedEntries.get(Entry);
if (oldBest.getMeasuredProperty(energy_id)
> Entry.getMeasuredProperty(energy_id)) {
acceptedEntries.remove(oldBest);
acceptedEntries.put(Entry, Entry);
}
} else {
// Add to list of entries to duplicate properties if there is no "energy" property
if (!duplicateProperties.containsKey(Entry)) {
// Add in the property data of the accepted entry
double[] props = acceptedEntries.get(Entry).getMeasuredProperties();
List<double[]> newList = new LinkedList<>();
newList.add(props);
duplicateProperties.put(Entry, newList);
}
duplicateProperties.get(Entry).add(Entry.getMeasuredProperties());
}
}
}
// If we have any duplicate properties, average them
Iterator<BaseEntry> Eiter = duplicateProperties.keySet().iterator();
while (Eiter.hasNext()) {
CompositionEntry E = (CompositionEntry) Eiter.next();
CompositionEntry accepted = acceptedEntries.get(E);
List<double[]> dupProps = duplicateProperties.get(E);
for (int p = 0; p < NProperties(); p++) {
double sum = 0, count = 0;
for (double[] props : dupProps) {
double toAdd = props[p];
if (! Double.isNaN(toAdd)) {
sum += toAdd; count++;
}
}
if (count > 0) {
accepted.setMeasuredProperty(p, sum / count);
}
}
}
// Close the file
is.close();
// Copy the entries
this.Entries = new ArrayList<>(acceptedEntries.keySet());
}
/**
* Set whether to use composition (i.e. fraction of each element present) as attributes.
*
* <p>By default: This class does not use fractions as attributes.
* @param decision Whether to use it or not
*/
public void useCompositionAsAttributes(boolean decision) {
this.UseComposition = decision;
}
/**
* Define whether to look for elemental property lookup tables.
*
* <p>
* Elemental property tables should have the properties for each element on
* a separate line, sorted by Atomic Number. If the property is not known,
* write "None". You will be alerted if that property was needed generating
* attributes.
*
* @param DataDirectory PAth to the elemental property lookup directory
*/
public void setDataDirectory(String DataDirectory) {
this.DataDirectory = DataDirectory;
}
/**
* Define a new elemental property to use when generating attributes.
*
* @param Name Name of property
*/
public void addElementalProperty(String Name) {
if (! ElementalProperties.contains(Name)) {
ElementalProperties.add(Name);
}
}
/**
* Remove an elemental property from the list used when generating
* attributes
*
* @param Name Name of property
* @return Whether the property was found and removed
*/
public boolean removeElementalProperty(String Name) {
if (ElementalProperties.contains(Name)) {
ElementalProperties.remove(Name);
return true;
} else {
return false;
}
}
/**
* Calculate attributes for each entry. Currently, this set is equipped to
* calculate four kinds of properties:
*
* <ol>
* <li><b>Fraction Only:</b> Only depends on the fraction of elements
* present, and not what they are.
* <li><b>Elemental Properties:</b> Various statistics based on the supplied
* properties of each present element
* <li><b>Band structure:</b> Fraction of electrons expected to be in each
* orbital (s/p/d/f)
* <li><b>Other:</b> Bond ionicity, sum of oxidation states, etc
* </ol>
*
* <p>Depending on value of {@linkplain #UseComposition}, may also use fractions
* of each element as attributes.
*/
@Override
protected void calculateAttributes() {
// --> Create attributes based on elemental fractions, if desired
if (UseComposition) {
generateElementFractionAttributes();
}
// --> Add attributes that are dependant on fraction only (not element type)
generateCompositionAttributes();
// --> Add attributes related to properties
generatePropertyBasedAttributes();
// --> Add attributes related to valance shell occupation
generateValenceShellAttributes();
// --> Calculate the percent ionic character for each entry
generateIonicCharacter();
// --> Add attribute based on whether it can form an ionic compound
generateCanFormIonic();
}
/**
* Reads in a data file that contains properties for each element.
* MeasuredProperty list should be contained in a file named
* PropertyName.table
*
* @param PropertyName MeasuredProperty of interest
* @return That property for each element
*/
public double[] getPropertyLookupTable(String PropertyName) {
// Check if it has been loaded in yet
if (PropertyData.containsKey(PropertyName)) {
return PropertyData.get(PropertyName);
}
// If not, load it in
// Open the file for reading
Path datafile = Paths.get(DataDirectory);
BufferedReader is;
try {
is = Files.newBufferedReader(
datafile.resolve(PropertyName + ".table"), Charset.forName("US-ASCII"));
// Read the file
double[] output = new double[ElementNames.length];
for (int i = 0; i < ElementNames.length; i++) {
try {
output[i] = Double.parseDouble(is.readLine());
} catch (IOException | NumberFormatException e) {
output[i] = Double.NaN;
}
}
is.close();
/// Return the data table, and save a copy
PropertyData.put(PropertyName, output);
return output;
} catch (IOException e) {
throw new Error("Property " + PropertyName + " failed to read due to " + e);
}
}
/**
* Reads in a data file that contains known oxidation states for each
* element. List should be contained in a file named OxidationStates.table
*
* @param DataDirectory Location of data files
* @return List of possible oxidation states for each element
*/
protected double[][] getOxidationStates(String DataDirectory) {
// Open the file for reading
Path datafile = Paths.get(DataDirectory);
BufferedReader is;
try {
is = Files.newBufferedReader(
datafile.resolve("OxidationStates.table"), Charset.forName("US-ASCII"));
// Read the file
int i, j; // Counters
double[][] output = new double[ElementNames.length][];
for (i = 0; i < ElementNames.length; i++) {
String[] States = is.readLine().split(" ");
if (States[0].isEmpty()) {
output[i] = null;
} else {
output[i] = new double[States.length];
for (j = 0; j < output[i].length; j++) {
output[i][j] = Double.parseDouble(States[j]);
}
}
}
is.close();
return output;
} catch (IOException | NumberFormatException e) {
throw new Error("Oxidation states failed to read due to " + e);
}
}
/**
* Generate attributes that only deal with composition (ignores element
* types)
*/
protected void generateCompositionAttributes() {
double x;
// --> Generate the variables only dependant on composition
// Number of components
AttributeName.add("NComp");
for (int i = 0; i < NEntries(); i++) {
getEntry(i).addAttribute((double) getEntry(i).getElements().length);
}
// L2 Norm of composition
AttributeName.add("Comp_L2Norm");
for (int i = 0; i < NEntries(); i++) {
x = StatUtils.sumSq(getEntry(i).getFractions());
getEntry(i).addAttribute(Math.sqrt(x));
}
// Some other norms
double[] norms = new double[]{3, 5, 7, 10};
for (int i = 0; i < norms.length; i++) {
AttributeName.add("Comp_L" + ((int) norms[i]) + "Norm");
}
for (int j = 0; j < NEntries(); j++) {
double[] fractions = getEntry(j).getFractions();
double[] newAttributes = new double[norms.length];
for (int n = 0; n < norms.length; n++) {
newAttributes[n] = 0.0;
for (int k = 0; k < fractions.length; k++) {
newAttributes[n] += Math.pow(fractions[k], norms[n]);
}
newAttributes[n] = Math.pow(newAttributes[n], 1.0 / norms[n]);
}
getEntry(j).addAttributes(newAttributes);
}
}
/**
* Generate attributes that are simply the fraction of each element present
*/
protected void generateElementFractionAttributes() {
for (String ElementName : ElementNames) {
AttributeName.add("X_" + ElementName);
}
// Determine the composition for each element
double[] composition = new double[ElementNames.length], fractions;
int[] elements;
for (int i = 0; i < NEntries(); i++) {
Arrays.fill(composition, 0);
elements = getEntry(i).getElements();
fractions = getEntry(i).getFractions();
for (int j = 0; j < elements.length; j++) {
composition[elements[j]] = fractions[j];
}
// Copy it into the feature array
getEntry(i).addAttributes(composition);
}
}
/**
* Generate attributes that are based on elemental properties
*/
protected void generatePropertyBasedAttributes() {
// Create list of entries with missing elemental properties and properties
// with key missing values
// Dev Note: I am not sure what to do with these entries, options:
// 1) Remove them from the dataset, which is a viable option
// 2) Remove offending properties, which means different datasets will have different attributes
// For now, I am passing the problem onto the user by issuing a warning
Set<String> MissingData = new TreeSet<>();
// Add in property names
for (String prop : ElementalProperties) {
AttributeName.add("mean_" + prop);
AttributeName.add("maxdiff_" + prop);
AttributeName.add("dev_" + prop);
AttributeName.add("max_" + prop);
AttributeName.add("min_" + prop);
AttributeName.add("most_" + prop);
}
// Generate attributes for each entry
double[] toAdd = new double[ElementalProperties.size() * 6];
for (int e = 0; e < NEntries(); e++) {
CompositionEntry entry = getEntry(e);
int count = 0;
// Generate data for each property
for (String prop : ElementalProperties) {
// Get the lookup table for this property
double[] lookup = getPropertyLookupTable(prop);
// Check if any required lookup data is missing;
for (int i = 0; i < entry.getElements().length; i++) {
if (lookup[entry.Element[i]] == Double.NaN) {
MissingData.add(ElementNames[entry.Element[i]] + ":" + prop);
}
}
// Calculate the mean
double mean = entry.getMean(lookup);
toAdd[count++] = mean;
// Calculate the maximum diff
toAdd[count++] = entry.getMaxDifference(lookup);
// Calculate the mean deviation
toAdd[count++] = entry.getAverageDeviation(lookup, mean);
toAdd[count++] = entry.getMaximum(lookup);
toAdd[count++] = entry.getMinimum(lookup);
toAdd[count++] = entry.getMost(lookup);
}
// Add attributes to entry
entry.addAttributes(toAdd);
}
// Print out warning of which properties have missing (see def of
// OffendingProperties)
if (MissingData.size() > 0) {
System.err.println("WARNING: There are " + MissingData.size()
+ " missing elmental properties:");
int i = 0;
Iterator<String> iter = MissingData.iterator();
while (iter.hasNext()) {
System.err.format("%32s", iter.next());
if (i % 2 == 1) {
System.err.println();
}
i++;
}
if (i % 2 == 1) {
System.err.println();
}
System.err.println();
System.err.flush();
}
}
/**
* Generate attributes related to valence shell occupation
*/
protected void generateValenceShellAttributes() {
// Load in the number of electrons in each shell
Character[] shell = new Character[]{'s', 'p', 'd', 'f'};
double[][] n_valance = new double[4][];
for (int i = 0; i < 4; i++) {
n_valance[i] = getPropertyLookupTable("N" + shell[i] + "Valence");
}
// Determine the fraction of electrons in each valence cell
for (int i = 0; i < 4; i++) {
AttributeName.add("frac_" + shell[i] + "Valence");
}
for (int i = 0; i < NEntries(); i++) {
double[] total_e = new double[4];
double sum_e = 0.0;
// First, get the average number of electrons in each shell
for (int j = 0; j < 4; j++) {
total_e[j] = getEntry(i).getMean(n_valance[j]);
sum_e += total_e[j];
}
// Convert to fractions
for (int j = 0; j < 4; j++) {
total_e[j] /= sum_e;
}
// Add to entry
getEntry(i).addAttributes(total_e);
}
}
/**
* Generate the percent ionic character for each entry
*/
protected void generateIonicCharacter() {
double x;
// --> Calculate the maximum and mean %Ionic character
double[] en = getPropertyLookupTable("Electronegativity");
AttributeName.add("MaxIonicChar");
AttributeName.add("MeanIonicChar");
for (int i = 0; i < NEntries(); i++) {
getEntry(i).addAttribute(1
- Math.exp(-0.25 * Math.pow(getEntry(i).getMaxDifference(en), 2.0)));
int[] elem = getEntry(i).getElements();
double[] frac = getEntry(i).getFractions();
x = 0.0;
for (int j = 0; j < elem.length; j++) {
for (int k = 0; k < elem.length; k++) {
x += frac[j] * frac[k] * (1 - Math.exp(-0.25
* Math.pow(en[elem[j]] - en[elem[k]], 2.0)));
}
}
getEntry(i).addAttribute(x);
}
}
/**
* Determine whether each entry can form an ionic compound. Assumes that
* each element can only take on a single oxidation state
*/
protected void generateCanFormIonic() {
double x, y;
AttributeName.add("CanFormIonic");
double[][] states = getOxidationStates(DataDirectory);
for (int i = 0; i < NEntries(); i++) {
int[] elem = getEntry(i).getElements();
double[] frac = getEntry(i).getFractions();
x = 0; // Initially assume that it cannot form
// If any of the compounds are noble gasses, it cannot form an ionic compound
for (int j = 0; j < elem.length; j++) {
if (states[elem[j]] == null) {
x = -1;
break;
}
}
if (x == -1) {
x = 0;
getEntry(i).addAttribute(x);
continue;
}
// Loop through each possible combination
int[] guess = new int[elem.length]; // Initialize a guess
boolean was_incremented = true;
while (was_incremented) {
// Calculate the charge
y = 0; // Start the charge out at zero
for (int j = 0; j < elem.length; j++) {
y += frac[j] * states[elem[j]][guess[j]];
}
// If the charge is equal to zero, we have found a valid compound
if (y == 0) {
x = 1;
break;
}
// If not, increment the compound
was_incremented = false;
for (int j = 0; j < guess.length; j++) {
guess[j]++;
if (guess[j] == states[elem[j]].length) {
guess[j] = 0;
} else {
was_incremented = true;
break;
}
}
}
getEntry(i).addAttribute(x);
}
}
@Override
public Object runCommand(List<Object> Command) throws Exception {
if (Command.isEmpty()) return super.runCommand(Command);
String Action = Command.get(0).toString();
switch (Action.toLowerCase()) {
default:
return super.runCommand(Command);
}
}
@Override
protected Object runAttributeCommand(List<Object> Command) throws Exception {
if (Command.isEmpty()) {
return super.runAttributeCommand(Command);
}
String Action = Command.get(0).toString().toLowerCase();
switch (Action) {
case "properties": case "prop": {
return runPropertyCommand(Command.subList(1, Command.size()));
}
case "composition": {
boolean useComp;
try {
switch (Command.get(1).toString().toLowerCase()) {
case "true": useComp = true; break;
case "false": useComp = false; break;
default: throw new Exception();
}
} catch (Exception e) {
throw new Exception("Usage: <dataset> attributes composition <true|false>");
}
useCompositionAsAttributes(useComp);
if (useComp) {
System.out.println("\tSet dataset to use composition as attributes");
} else {
System.out.println("\tSet dataset to not use composition as attributes");
}
return null;
}
default:
return super.runAttributeCommand(Command);
}
}
/**
* Run commands that control which elemental properties are used when
* generating attributes
*
* @param Command Command to act on
* @return Any output from operation (null if no output)
* @throws Exception
*/
protected Object runPropertyCommand(List<Object> Command) throws Exception {
if (Command.isEmpty()) {
Iterator<String> iter = ElementalProperties.iterator();
int count = 0;
while (iter.hasNext()) {
count++;
System.out.print("\t" + iter.next());
if (count % 5 == 0) {
System.out.println();
}
}
if (count % 5 != 0) {
System.out.println();
}
return null;
}
String Action = Command.get(0).toString();
switch (Action.toLowerCase()) {
case "add": {
// Usage: add <name> or add set <name>
if (Command.size() < 2) {
throw new Exception("Usage: \"<dataset> attributes properties add set <set name>\""
+ " or properties add <property names...>");
}
// Add in new properties
int originalSize = ElementalProperties.size();
if (Command.get(1).toString().equalsIgnoreCase("set")) {
// Add properties from a known set
String[] Properties = PropertyLists.getPropertySet(Command.get(2).toString());
for (String p : Properties) {
addElementalProperty(p);
}
} else {
// Add in properties one by one
for (int i = 1; i < Command.size(); i++) {
addElementalProperty(Command.get(i).toString());
}
}
System.out.println("\tAdded " + (ElementalProperties.size() - originalSize)
+ " new properties.");
}
break;
case "remove": {
// Usage: remove <names...>
if (Command.size() < 2) {
throw new Exception("Usage: <dataset> attributes properties remove <property names...>");
}
// Remove those property from the set
String output = "\tRemoved properties:";
int nRemoved = 0;
for (int i = 1; i < Command.size(); i++) {
boolean wasRemoved = removeElementalProperty(Command.get(i).toString());
if (wasRemoved) {
output += " " + Command.get(i).toString();
nRemoved++;
}
}
if (nRemoved > 0) {
System.out.println(output);
} else {
System.out.println("\tWARNING: No attributes were removed.");
}
break;
}
case "directory": {
// Define the lookup directory
if (Command.size() < 2) {
throw new Exception("Usage: <dataset> attributes properties directory <directory name>");
}
DataDirectory = Command.get(1).toString();
for (int i = 2; i < Command.size(); i++) {
DataDirectory += " " + Command.get(i).toString();
}
}
break;
default:
throw new Exception("ERROR: Property command not recognized: " + Action);
}
return null;
}
}
|
package com.iappsam.search;
import com.iappsam.Supplier;
public class SupplierSearcher extends AbstractSearcher<Supplier> {
public SupplierSearcher() {
super(Supplier.class, "name", "address", "contactPerson.person.name");
}
}
|
package network;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConectorDB {
static String userName;
static String password;
static String db;
static int port;
static String url = "jdbc:mysql://localhost";
static Connection conn = null;
static Statement s;
public ConectorDB(String usr, String pass, String db, int port) {
ConectorDB.userName = usr;
ConectorDB.password = pass;
ConectorDB.db = db;
ConectorDB.port = port;
ConectorDB.url += ":"+port+"/";
ConectorDB.url += db;
}
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, "root", "");
if (conn != null) {
System.out.println("Conexi a base de dades "+url+" ... Ok");
}
}
catch(SQLException ex) {
System.out.println("Problema al connecta-nos a la BBDD --> "+url);
ex.printStackTrace();
}
catch(ClassNotFoundException ex) {
System.out.println(ex);
}
}
public static boolean insertUser(String nickname, String password){
String query = new String("INSERT INTO usuari (nickname,pasword,score) VALUES ('"+nickname+"','"+password+"','0')");
try {
s =(Statement) conn.createStatement();
s.executeUpdate(query);
} catch (SQLException ex) {
System.out.println("Problema al Inserir --> " + ex.getSQLState());
return false;
}
return true;
}
public static void updateScore(String nickname, int score){
String query = new String("UPDATE usuari SET score='"+score+"' WHERE nickname='"+nickname+"'");
try {
s =(Statement) conn.createStatement();
s.executeUpdate(query);
} catch (SQLException ex) {
System.out.println("Problema al Modificar --> " + ex.getSQLState());
}
}
public static void deleteUser(String nickname){
String query = new String("DELETE FROM usuari WHERE nickname='"+nickname+"'");
try {
s =(Statement) conn.createStatement();
s.executeUpdate(query);
} catch (SQLException ex) {
System.out.println("Problema al Eliminar --> " + ex.getSQLState());
}
}
public static ResultSet selectAllUsers(){
ResultSet rs = null;
String query = new String("SELECT * FROM usuari");
try {
s =(Statement) conn.createStatement();
rs = s.executeQuery (query);
} catch (SQLException ex) {
System.out.println("Problema al Recuperar les dades --> " + ex.getSQLState());
}
return rs;
}
public static ResultSet selectUser(String nickname){
ResultSet rs = null;
String query = new String("SELECT * FROM usuari WHERE nickname='"+nickname+"'");
try {
s =(Statement) conn.createStatement();
rs = s.executeQuery (query);
} catch (SQLException ex) {
System.out.println("Problema al Recuperar les dades --> " + ex.getSQLState());
}
return rs;
}
public static void insertGame(String nickname, String mode, int score){
ResultSet consulta = null;
int id = 0;
consulta = selectAllGames();
try {
while (consulta.next()){
id = (int) consulta.getObject("id");
}
id++;
} catch (SQLException e) {
System.out.println("Problema al recuperar les dades... select->insert");
}
String query = new String("INSERT INTO game (id,mode,name,score) VALUES ('"+id+"','"+mode+"','"+nickname+"','"+score+"')");
try {
s =(Statement) conn.createStatement();
s.executeUpdate(query);
} catch (SQLException ex) {
System.out.println("Problema al Inserir --> " + ex.getSQLState());
}
}
public static ResultSet selectAllGames(){
ResultSet rs = null;
String query = new String("SELECT * FROM game");
try {
s =(Statement) conn.createStatement();
rs = s.executeQuery (query);
} catch (SQLException ex) {
System.out.println("Problema al Recuperar les dades --> " + ex.getSQLState());
}
return rs;
}
public ResultSet selectGames(String name){
ResultSet rs = null;
String query = new String("SELECT * FROM game WHERE name='"+name+"'");
try {
s =(Statement) conn.createStatement();
rs = s.executeQuery (query);
} catch (SQLException ex) {
System.out.println("Problema al Recuperar les dades --> " + ex.getSQLState());
}
return rs;
}
public void disconnect(){
try {
conn.close();
} catch (SQLException e) {
System.out.println("Problema al tancar la connexi --> " + e.getSQLState());
}
}
}
|
package neural;
import java.util.Random;
import java.util.function.BiFunction;
import java.util.function.DoubleFunction;
public class Matrix {
/** Matrix dimensions */
private final int height, width;
/** Matrix elements */
private final double[][] matrix;
/**
* Constructs a new copy of an existing matrix
* @param input Matrix to copy
*/
public Matrix(Matrix input) {
this(input.getHeight(), input.getWidth());
for(int j=0; j<getHeight(); j++) {
for(int i=0; i<getWidth(); i++) {
set(j, i, input.get(j, i));
}
}
}
public Matrix(double[][] array) {
this(array.length, array[0].length);
for(int j=0; j<getHeight(); j++) {
if(array[j].length != getWidth()) {
throw new IllegalArgumentException("Input array not rectangular!");
}
for(int i=0; i<getWidth(); i++) {
set(j, i, array[j][i]);
}
}
}
public Matrix(int height, int width) {
if(height < 1 || width < 1) {
throw new IllegalArgumentException("Dimension(s) less than 1!");
}
this.height = height;
this.width = width;
matrix = new double[height][width];
}
/**
* Sets the value of a specific element
* @param row Row index of the element
* @param column Column index of the element
* @param value Value to set the element to
* @throws ArrayIndexOutOfBoundsException If the indices are smaller than 0
* or bigger than the width/height -1
*/
public void set(int row, int column, double value) {
if(row < 0 || row >= getHeight() || column < 0 || column >= getWidth()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
matrix[row][column] = value;
}
/**
* Returns the value of a specific element
* @param row Row index of the element
* @param column Column index of the element
* @return The value of the element
* @throws ArrayIndexOutOfBoundsException If the indices are smaller than 0
* or bigger than the width/height -1
*/
public double get(int row, int column) {
if(row < 0 || row >= getHeight() || column < 0 || column >= getWidth()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
return matrix[row][column];
}
/**
* Returns the height (number of rows) of the matrix
* @return Height of the matrix
*/
public int getHeight() {
return height;
}
/**
* Returns the width (number of columns) of the matrix
* @return Width of the matrix
*/
public int getWidth() {
return width;
}
/**
* Sets every element of the matrix to the given value
* @param value Value to set every element to
*/
public void fill(double value) {
for(int j=0; j<getHeight(); j++) {
for(int i=0; i<getWidth(); i++) {
set(j, i, value);
}
}
}
public Matrix add(Matrix matrix2) {
if(matrix2.getHeight() != getHeight()
|| matrix2.getWidth() != getWidth()) {
throw new IllegalArgumentException("Dimensions not compatible!");
}
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i) + matrix2.get(j, i));
}
}
return result;
}
public Matrix subtract(Matrix matrix2) {
if(matrix2.getHeight() != getHeight()
|| matrix2.getWidth() != getWidth()){
throw new IllegalArgumentException("Dimensions not compatible!");
}
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i) - matrix2.get(j, i));
}
}
return result;
}
public Matrix multiply(Matrix matrix2) {
if(matrix2.getHeight() != getWidth()) {
throw new IllegalArgumentException("Matrix dimensions not compatible!");
}
final Matrix result = new Matrix(getHeight(), matrix2.getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
double sum = 0;
for(int k=0; k<getWidth(); k++) {
sum += get(j, k) * matrix2.get(k, i);
}
result.set(j, i, sum);
}
}
return result;
}
public Matrix multiplyElementwise(Matrix matrix2) {
if(matrix2.getHeight() != getHeight()
|| matrix2.getWidth() != getWidth()) {
throw new IllegalArgumentException("Dimensions not compatible!");
}
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i) * matrix2.get(j, i));
}
}
return result;
}
/**
* Scalar multiplies this matrix with the given factor.
* C = b * A
* C[i, j] = b * A[i, j]
* @param value Scalar to multiply every element with
* @return Scaled matrix
*/
public Matrix multiply(double value) {
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, value * get(j, i));
}
}
return result;
}
public Matrix divideElementwise(Matrix matrix2) {
if(matrix2.getHeight() != getHeight()
|| matrix2.getWidth() != getWidth()) {
throw new IllegalArgumentException("Dimensions not compatible!");
}
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i) / matrix2.get(j, i));
}
}
return result;
}
/**
* Applies the given function on every element of the matrix.
* B[i, j] = f(A[i, j])
* @param function Function that gets applied on every element
* @return Resulting matrix
*/
public Matrix apply(DoubleFunction<Double> function) {
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, function.apply(get(j, i)));
}
}
return result;
}
/**
* Applies the given function,
* on every element of this and the given matrix,
* and writes the output into the corresponding element of a new matrix.
* C[i, j] = f(A[i, j], B[i, j])
* @param matrix2
* @param function Function that gets applied on every element
* @return Resulting matrix
*/
public Matrix apply(Matrix matrix2,
BiFunction<Double, Double, Double> function) {
final Matrix result = new Matrix(getHeight(), getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, function.apply(get(j, i), matrix2.get(j, i)));
}
}
return result;
}
/**
* Transposes this matrix
* @return Transpose
*/
public Matrix transpose() {
final Matrix result = new Matrix(getWidth(), getHeight());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(i, j));
}
}
return result;
}
/**
* Extracts a single row as a new Matrix
* @param index Index of the row that should be extracted
* @return The single row as a new Matrix
* @throws ArrayIndexOutOfBoundsException If the index does not point
* to an existing row
*/
public Matrix getRow(int index) {
if(index < 0 || index >= getWidth()) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds!");
}
return getRows(index, index + 1);
}
/**
* Extracts multiple rows as a new Matrix
* @param fromIndex Index of the first row
* that should be extracted (inclusive)
* @param toIndex Index of the last row that should be extracted (exclusive)
* @return The rows as a new Matrix
* @throws ArrayIndexOutOfBoundsException If an index does not point
* to an existing row
*/
public Matrix getRows(int fromIndex, int toIndex) {
if(fromIndex < 0 || fromIndex >= getHeight()
|| toIndex < 0 || toIndex > getHeight()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
if(fromIndex >= toIndex) {
throw new IllegalArgumentException("Illegal index direction!");
}
final Matrix result = new Matrix(toIndex - fromIndex, getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(fromIndex + j, i));
}
}
return result;
}
public Matrix appendRows(Matrix rows) {
if(rows.getWidth() != getWidth()) {
throw new IllegalArgumentException("Rows not compatible!");
}
final Matrix result =
new Matrix(getHeight() + rows.getHeight(), getWidth());
for(int j=0; j<getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i));
}
}
for(int j=0; j<rows.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(getHeight() + j, i, rows.get(j, i));
}
}
return result;
}
/**
* Removes a single row of this matrix
* @param index Index of the row that should be removed
* @return Resulting matrix
* @throws ArrayIndexOutOfBoundsException If this matrix is to small to
* remove a row or the index does not point to an existing row
*/
public Matrix removeRow(int index) {
if(getHeight() < 2) {
throw new ArrayIndexOutOfBoundsException("Matrix to small!");
}
if(index < 0 || index >= getHeight()) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds!");
}
return removeRows(index, index + 1);
}
/**
* Removes multiple rows of this matrix
* @param fromIndex Index of the first row that should be removed (inclusive)
* @param toIndex Index of the last row that should be removed (exclusive)
* @return Resulting matrix
* @throws ArrayIndexOutOfBoundsException If this matrix is to small to
* remove the rows or an index does not point to an existing row
*/
public Matrix removeRows(int fromIndex, int toIndex) {
if(getHeight() <= toIndex - fromIndex) {
throw new ArrayIndexOutOfBoundsException("Matrix to small!");
}
if(fromIndex < 0 || fromIndex >= getHeight()
|| toIndex < 0 || toIndex > getHeight()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
if(fromIndex >= toIndex) {
throw new IllegalArgumentException("Illegal index direction!");
}
final Matrix result =
new Matrix(getHeight() - (toIndex - fromIndex), getWidth());
for(int j=0; j<fromIndex; j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, i));
}
}
for(int j=fromIndex; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get((toIndex - fromIndex) + j, i));
}
}
return result;
}
/**
* Extracts a single column as a new Matrix
* @param index Index of the column that should be extracted
* @return The single column as a new Matrix
* @throws ArrayIndexOutOfBoundsException If the index does not point
* to an existing column
*/
public Matrix getColumn(int index) {
if(index < 0 || index >= getHeight()) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds!");
}
return getColumns(index, index + 1);
}
/**
* Extracts multiple columns as a new Matrix
* @param fromIndex Index of the first column
* that should be extracted (inclusive)
* @param toIndex Index of the last column
* that should be extracted (exclusive)
* @return The columns as a new Matrix
* @throws ArrayIndexOutOfBoundsException If an index does not point
* to an existing column
*/
public Matrix getColumns(int fromIndex, int toIndex) {
if(fromIndex < 0 || fromIndex >= getWidth()
|| toIndex < 0 || toIndex > getWidth()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
if(fromIndex >= toIndex) {
throw new IllegalArgumentException("Illegal index direction!");
}
final Matrix result = new Matrix(getHeight(), toIndex - fromIndex);
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<result.getWidth(); i++) {
result.set(j, i, get(j, fromIndex + i));
}
}
return result;
}
public Matrix appendColumns(Matrix columns) {
if(columns.getHeight() != getHeight()) {
throw new IllegalArgumentException("Column not compatible!");
}
final Matrix result =
new Matrix(getHeight(), getWidth() + columns.getWidth());
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<getWidth(); i++) {
result.set(j, i, get(j, i));
}
for(int i=0; i<columns.getWidth(); i++) {
result.set(j, getWidth() + i, columns.get(j, i));
}
}
return result;
}
/**
* Removes a single column of this matrix
* @param index Index of the column that should be remove
* @return Resulting matrix
* @throws ArrayIndexOutOfBoundsException If this matrix is to small to
* remove a column or the index does not point to an existing column
*/
public Matrix removeColumn(int index) {
if(getWidth() < 2) {
throw new ArrayIndexOutOfBoundsException("Matrix to small!");
}
if(index < 0 || index >= getWidth()) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds!");
}
return removeColumns(index, index + 1);
}
/**
* Removes multiple columns of this matrix
* @param fromIndex Index of the first column
* that should be removed (inclusive)
* @param toIndex Index of the last column that should be removed (exclusive)
* @return Resulting matrix
* @throws ArrayIndexOutOfBoundsException If this matrix is to small to
* remove the columns or an index does not point to an existing column
*/
public Matrix removeColumns(int fromIndex, int toIndex) {
if(getWidth() <= toIndex - fromIndex) {
throw new ArrayIndexOutOfBoundsException("Matrix to small!");
}
if(fromIndex < 0 || fromIndex >= getWidth()
|| toIndex < 0 || toIndex > getWidth()) {
throw new ArrayIndexOutOfBoundsException("Indices out of bounds!");
}
if(fromIndex >= toIndex) {
throw new IllegalArgumentException("Illegal index direction!");
}
final Matrix result =
new Matrix(getHeight(), getWidth() - (toIndex - fromIndex));
for(int j=0; j<result.getHeight(); j++) {
for(int i=0; i<fromIndex; i++) {
result.set(j, i, get(j, i));
}
for(int i=fromIndex; i<result.getWidth(); i++) {
result.set(j, i, get(j, (toIndex - fromIndex) + i));
}
}
return result;
}
/**
* Fills the matrix with random values
*/
public void rand() {
rand(new Random(), -Double.MAX_VALUE, Double.MAX_VALUE);
}
/**
* Fills the matrix with random values,
* from minimum (inclusive) to maximum (exclusive),
* given by the random number generator
* @param rand Random number generator
* @param minimum Minimum value (inclusive)
* @param maximum Maximum value (exclusive)
*/
public void rand(Random rand, double minimum, double maximum) {
final double range = maximum - minimum;
for(int j=0; j<getHeight(); j++) {
for(int i=0; i<getWidth(); i++) {
set(j, i, range*rand.nextDouble() + minimum);
}
}
}
/**
* Copies the content of the matrix into a 2-dimensional array
* @return Array copy
*/
public double[][] toArray() {
final double[][] array = new double[getHeight()][getWidth()];
for(int j=0; j<array.length; j++) {
for(int i=0; i<array[j].length; i++) {
array[j][i] = get(j, i);
}
}
return array;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder("[[").append(get(0, 0));
for(int i=1; i<getWidth(); i++) {
builder.append(", ").append(get(0, i));
}
builder.append("]");
for(int j=1; j<getHeight(); j++) {
builder.append("\n [").append(get(j, 0));
for(int i=1; i<getWidth(); i++) {
builder.append(", ").append(get(j, i));
}
builder.append("]");
}
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
double scalar = 2;
Matrix matrix1 = new Matrix(new double[][] {
{1, 2, 3},
{4, 42, 6},
{7, 8, 9}});
Matrix matrix2 = new Matrix(new double[][] {
{1, 4, 7},
{2, 5, 8},
{3, 6, 9}});
System.out.println("Scalar:");
System.out.println(scalar + "\n");
System.out.println("Matrix1:");
System.out.println(matrix1 + "\n");
System.out.println("Matrix2:");
System.out.println(matrix2 + "\n");
System.out.println();
System.out.println("Set [1, 1] to 5:");
matrix1.set(1, 1, 5);
System.out.println(matrix1 + "\n");
System.out.println("Get [1, 1]:" + matrix1.get(1, 1));
System.out.println("Height: " + matrix1.getHeight());
System.out.println("Width: " + matrix1.getWidth() + "\n\n");
System.out.println("Addition (Matrix1 & Matrix2):");
System.out.println(matrix1.add(matrix2) + "\n");
System.out.println("Subtraction (Matrix1 & Matrix2):");
System.out.println(matrix1.subtract(matrix2) + "\n");
System.out.println("Matrix multiplication:");
System.out.println(matrix1.multiply(matrix2) + "\n");
System.out.println("Elementwise multiplication:");
System.out.println(matrix1.multiplyElementwise(matrix2) + "\n");
System.out.println("Scalar multiplication:");
System.out.println(matrix1.multiply(scalar) + "\n");
System.out.println("Elementwise division:");
System.out.println(matrix1.divideElementwise(matrix2) + "\n");
System.out.println("Applying sine:");
System.out.println(matrix1.apply(x -> Math.sin(x)) + "\n\n");
System.out.println("Transpose:");
System.out.println(matrix1.transpose() + "\n\n");
System.out.println("Get row 1:");
System.out.println(matrix1.getRow(1) + "\n");
System.out.println("Get rows 1 & 2:");
System.out.println(matrix1.getRows(1, 3) + "\n");
System.out.println("Append rows:");
System.out.println(matrix1.appendRows(matrix2) + "\n");
System.out.println("Remove row 1:");
System.out.println(matrix1.removeRow(1) + "\n");
System.out.println("Remove rows 0 & 1:");
System.out.println(matrix1.removeRows(0, 2) + "\n\n");
System.out.println("Get column 1:");
System.out.println(matrix1.getColumn(1) + "\n");
System.out.println("Get columns 1 & 2:");
System.out.println(matrix1.getColumns(1, 3) + "\n");
System.out.println("Append columns:");
System.out.println(matrix1.appendColumns(matrix2) + "\n");
System.out.println("Remove column 1:");
System.out.println(matrix1.removeColumn(1) + "\n");
System.out.println("Remove columns 0 & 1:");
System.out.println(matrix1.removeColumns(0, 2) + "\n");
System.out.println("Randomize within [-1, 1[:");
matrix1.rand(new Random(), -1, 1);
System.out.println(matrix1 + "\n");
}
}
|
package org.sqlite;
import java.sql.*;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Calendar;
import java.util.Map;
/**
* Implements a JDBC ResultSet.
*/
final class RS extends Unused implements ResultSet, ResultSetMetaData, Codes
{
private final Stmt stmt;
private final DB db;
boolean open = false ; // true means have results and can iterate them
int maxRows; // max. number of rows as set by a Statement
String[] cols = null; // if null, the RS is closed()
String[] colsMeta = null; // same as cols, but used by Meta interface
boolean[][] meta = null;
private int limitRows; // 0 means no limit, must check against maxRows
private int row = 1; // number of current row, starts at 1
private int lastCol; // last column accessed, for wasNull(). -1 if none
RS(Stmt stmt) {
this.stmt = stmt;
this.db = stmt.db;
}
// INTERNAL FUNCTIONS ///////////////////////////////////////////
boolean isOpen() { return open; }
/* Throws SQLException if ResultSet is not open. */
void checkOpen() throws SQLException {
if (!open) throw new SQLException("ResultSet closed");
}
// takes col in [1,x] form, returns in [0,x-1] form
private int checkCol(int col) throws SQLException {
if (colsMeta == null) throw new IllegalStateException(
"SQLite JDBC: inconsistent internal state");
if (col < 1 || col > colsMeta.length) throw new SQLException(
"column " + col + " out of bounds [1," + colsMeta.length + "]");
return --col;
}
// takes col in [1,x] form, marks it as last accessed and returns [0,x-1]
private int markCol(int col) throws SQLException {
checkOpen(); checkCol(col); lastCol = col; return --col;
}
private void checkMeta() throws SQLException {
checkCol(1);
if (meta == null) meta = db.column_metadata(stmt.pointer);
}
// ResultSet Functions //////////////////////////////////////////
public void close() throws SQLException {
cols = null;
colsMeta = null;
meta = null;
open = false;
limitRows = 0;
row = 1;
lastCol = -1;
if (stmt == null)
return;
if (stmt != null && stmt.pointer != 0)
db.reset(stmt.pointer);
}
// returns col in [1,x] form
public int findColumn(String col) throws SQLException {
checkOpen();
int c = -1;
for (int i=0; i < cols.length; i++) {
if (col.equalsIgnoreCase(cols[i])
|| (cols[i].toUpperCase().endsWith(col.toUpperCase()) &&
cols[i].charAt(cols[i].length() - col.length()) == '.')) {
if (c == -1)
c = i;
else
throw new SQLException("ambiguous column: '"+col+"'");
}
}
if (c == -1)
throw new SQLException("no such column: '"+col+"'");
else
return c + 1;
}
public boolean next() throws SQLException {
if (!open) return false; // finished ResultSet
lastCol = -1;
// first row is loaded by execute(), so do not step() again
if (row == 1) { row++; return true; }
// check if we are row limited by the statement or the ResultSet
if (maxRows != 0 && row > maxRows) return false;
if (limitRows != 0 && row >= limitRows) return false;
// do the real work
switch (db.step(stmt.pointer)) {
case SQLITE_DONE:
close(); // agressive closing to avoid writer starvation
return false;
case SQLITE_ROW: row++; return true;
case SQLITE_BUSY:
throw new SQLException("database locked");
default:
db.throwex(); return false;
}
}
public int getType() throws SQLException { return TYPE_FORWARD_ONLY; }
public int getFetchSize() throws SQLException { return limitRows; }
public void setFetchSize(int rows) throws SQLException {
if (0 > rows || (maxRows != 0 && rows > maxRows))
throw new SQLException("fetch size " + rows
+ " out of bounds " + maxRows);
limitRows = rows;
}
public int getFetchDirection() throws SQLException {
checkOpen(); return ResultSet.FETCH_FORWARD; }
public void setFetchDirection(int d) throws SQLException {
checkOpen();
if (d != ResultSet.FETCH_FORWARD)
throw new SQLException("only FETCH_FORWARD direction supported");
}
public boolean isAfterLast() throws SQLException { return !open; }
public boolean isBeforeFirst() throws SQLException {
return open && row == 1; }
public boolean isFirst() throws SQLException { return row == 2; }
public boolean isLast() throws SQLException { // FIXME
throw new SQLException("function not yet implemented for SQLite"); }
protected void finalize() throws SQLException { close(); }
public int getRow() throws SQLException { return row; }
public boolean wasNull() throws SQLException {
return db.column_type(stmt.pointer, markCol(lastCol)) == SQLITE_NULL;
}
// DATA ACCESS FUNCTIONS ////////////////////////////////////////
public boolean getBoolean(int col) throws SQLException {
return getInt(col) == 0 ? false : true; }
public boolean getBoolean(String col) throws SQLException {
return getBoolean(findColumn(col)); }
public byte getByte(int col) throws SQLException {
return (byte)getInt(col); }
public byte getByte(String col) throws SQLException {
return getByte(findColumn(col)); }
public byte[] getBytes(int col) throws SQLException {
return db.column_blob(stmt.pointer, markCol(col)); }
public byte[] getBytes(String col) throws SQLException {
return getBytes(findColumn(col)); }
public Date getDate(int col) throws SQLException {
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return null;
return new Date(db.column_long(stmt.pointer, markCol(col)));
}
public Date getDate(int col, Calendar cal) throws SQLException {
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return null;
if (cal == null) return getDate(col);
cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col)));
return new Date(cal.getTime().getTime());
}
public Date getDate(String col) throws SQLException {
return getDate(findColumn(col), Calendar.getInstance()); }
public Date getDate(String col, Calendar cal) throws SQLException {
return getDate(findColumn(col), cal); }
public double getDouble(int col) throws SQLException {
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return 0;
return db.column_double(stmt.pointer, markCol(col));
}
public double getDouble(String col) throws SQLException {
return getDouble(findColumn(col)); }
public float getFloat(int col) throws SQLException {
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return 0;
return (float)db.column_double(stmt.pointer, markCol(col));
}
public float getFloat(String col) throws SQLException {
return getFloat(findColumn(col)); }
public int getInt(int col) throws SQLException {
return db.column_int(stmt.pointer, markCol(col)); }
public int getInt(String col) throws SQLException {
return getInt(findColumn(col)); }
public long getLong(int col) throws SQLException {
return db.column_long(stmt.pointer, markCol(col)); }
public long getLong(String col) throws SQLException {
return getLong(findColumn(col)); }
public short getShort(int col) throws SQLException {
return (short)getInt(col); }
public short getShort(String col) throws SQLException {
return getShort(findColumn(col)); }
public String getString(int col) throws SQLException {
return db.column_text(stmt.pointer, markCol(col)); }
public String getString(String col) throws SQLException {
return getString(findColumn(col)); }
public Time getTime(int col) throws SQLException {
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return null;
return new Time(db.column_long(stmt.pointer, markCol(col))); }
public Time getTime(int col, Calendar cal) throws SQLException {
if (cal == null) return getTime(col);
if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL)
return null;
cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col)));
return new Time(cal.getTime().getTime());
}
public Time getTime(String col) throws SQLException {
return getTime(findColumn(col)); }
public Time getTime(String col, Calendar cal) throws SQLException {
return getTime(findColumn(col), cal); }
public Timestamp getTimestamp(int col) throws SQLException {
return new Timestamp(db.column_long(stmt.pointer, markCol(col))); }
public Timestamp getTimestamp(int col, Calendar cal) throws SQLException {
if (cal == null) return getTimestamp(col);
cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col)));
return new Timestamp(cal.getTime().getTime());
}
public Timestamp getTimestamp(String col) throws SQLException {
return getTimestamp(findColumn(col)); }
public Timestamp getTimestamp(String c, Calendar ca) throws SQLException {
return getTimestamp(findColumn(c), ca); }
public Object getObject(int col) throws SQLException {
switch (db.column_type(stmt.pointer, checkCol(col))) {
case SQLITE_INTEGER:
long val = getLong(col);
if (val > (long)Integer.MAX_VALUE
|| val < (long)Integer.MIN_VALUE)
return new Long(val);
else
return new Integer((int)val);
case SQLITE_FLOAT: return new Double(getDouble(col));
case SQLITE_BLOB: return getBytes(col);
case SQLITE_NULL: return null;
case SQLITE_TEXT:
default:
return getString(col);
}
}
public Object getObject(String col) throws SQLException {
return getObject(findColumn(col)); }
public Statement getStatement() { return stmt; }
public String getCursorName() throws SQLException { return null; }
public SQLWarning getWarnings() throws SQLException { return null; }
public void clearWarnings() throws SQLException {}
// ResultSetMetaData Functions //////////////////////////////////
// we do not need to check the RS is open, only that colsMeta
// is not null, done with checkCol(int).
public ResultSetMetaData getMetaData() throws SQLException {
return this; }
public String getCatalogName(int col) throws SQLException {
return db.column_table_name(stmt.pointer, checkCol(col)); }
public String getColumnClassName(int col) throws SQLException {
checkCol(col); return "java.lang.Object"; }
public int getColumnCount() throws SQLException {
checkCol(1); return colsMeta.length;
}
public int getColumnDisplaySize(int col) throws SQLException {
return Integer.MAX_VALUE; }
public String getColumnLabel(int col) throws SQLException {
return getColumnName(col); }
public String getColumnName(int col) throws SQLException {
return db.column_name(stmt.pointer, checkCol(col)); }
public int getColumnType(int col) throws SQLException {
switch (db.column_type(stmt.pointer, checkCol(col))) {
case SQLITE_INTEGER: return Types.INTEGER;
case SQLITE_FLOAT: return Types.FLOAT;
case SQLITE_BLOB: return Types.BLOB;
case SQLITE_NULL: return Types.NULL;
case SQLITE_TEXT:
default:
return Types.VARCHAR;
}
}
public String getColumnTypeName(int col) throws SQLException {
return db.column_decltype(stmt.pointer, checkCol(col));
}
public int getPrecision(int col) throws SQLException { return 0; } // FIXME
public int getScale(int col) throws SQLException { return 0; }
public String getSchemaName(int col) throws SQLException { return ""; }
public String getTableName(int col) throws SQLException {
return db.column_table_name(stmt.pointer, checkCol(col)); }
public int isNullable(int col) throws SQLException {
checkMeta();
return meta[checkCol(col)][1] ? columnNoNulls: columnNullable;
}
public boolean isAutoIncrement(int col) throws SQLException {
checkMeta(); return meta[checkCol(col)][2]; }
public boolean isCaseSensitive(int col) throws SQLException { return true; }
public boolean isCurrency(int col) throws SQLException { return false; }
public boolean isDefinitelyWritable(int col) throws SQLException {
return true; } // FIXME: check db file constraints?
public boolean isReadOnly(int col) throws SQLException { return false; }
public boolean isSearchable(int col) throws SQLException { return true; }
public boolean isSigned(int col) throws SQLException { return false; }
public boolean isWritable(int col) throws SQLException { return true; }
public int getConcurrency() throws SQLException { return CONCUR_READ_ONLY; }
public boolean rowDeleted() throws SQLException { return false; }
public boolean rowInserted() throws SQLException { return false; }
public boolean rowUpdated() throws SQLException { return false; }
}
|
package es.prometheus.dds;
import com.rti.dds.dynamicdata.DynamicData;
import com.rti.dds.dynamicdata.DynamicDataReader;
import com.rti.dds.dynamicdata.DynamicDataSeq;
import com.rti.dds.infrastructure.ConditionSeq;
import com.rti.dds.infrastructure.Duration_t;
import com.rti.dds.infrastructure.RETCODE_NO_DATA;
import com.rti.dds.infrastructure.ResourceLimitsQosPolicy;
import com.rti.dds.infrastructure.StringSeq;
import com.rti.dds.infrastructure.WaitSet;
import com.rti.dds.subscription.InstanceStateKind;
import com.rti.dds.subscription.QueryCondition;
import com.rti.dds.subscription.SampleInfo;
import com.rti.dds.subscription.SampleInfoSeq;
import com.rti.dds.subscription.SampleStateKind;
import com.rti.dds.subscription.ViewStateKind;
import java.awt.event.ActionListener;
import java.util.Arrays;
public abstract class LectorBase {
private final TopicoControl control;
private final DynamicDataReader reader;
private final DataCallback callback;
private final Thread dataThread;
protected LectorBase(final TopicoControl control, final String expresion,
final String[] params) {
this.control = control;
this.reader = control.creaLector();
// Crea el filtro de datos.
QueryCondition condicion = reader.create_querycondition(
SampleStateKind.ANY_SAMPLE_STATE,
ViewStateKind.ANY_VIEW_STATE,
InstanceStateKind.ANY_INSTANCE_STATE,
expresion,
new StringSeq(Arrays.asList(params)));
this.callback = new DataCallback(this.reader, condicion);
this.dataThread = new Thread(this.callback);
this.dataThread.start();
}
/**
* Libera los recursos del lector.
*/
public void dispose() {
this.dataThread.interrupt();
this.reader.delete_contained_entities();
this.control.eliminaLector(this.reader);
}
public void setExtraListener(final ActionListener listener) {
this.callback.setExtraListener(listener);
}
public final void cambioParametros(final String[] params) {
this.callback.cambiaParametros(params);
}
/**
* Para de recibir datos de DDS.
*/
public void parar() {
this.callback.parar();
}
public void reanudar() {
this.callback.reanudar();
}
protected abstract void getDatos(DynamicData sample);
private class DataCallback implements Runnable {
private final DynamicDataReader reader;
private final QueryCondition condicion;
private final WaitSet waitset;
private final Duration_t duracion;
private ActionListener extraListener;
private boolean parado;
private boolean terminar;
public DataCallback(final DynamicDataReader reader, final QueryCondition condicion) {
this.parado = true;
this.terminar = false;
this.reader = reader;
this.condicion = condicion;
this.duracion = new Duration_t(5, 0);
this.waitset = new WaitSet();
this.waitset.attach_condition(condicion);
}
@Override
public void run() {
while (!this.terminar) {
ConditionSeq activadas = new ConditionSeq();
this.waitset.wait(activadas, duracion);
// Si nos dicen que paremos, nosotros paramos.
if (this.parado)
continue;
// Procesamos los datos recibidos.
this.processData();
}
}
/**
* Procesa los datos recibidos de DDS.
*/
private void processData() {
// Obtiene todos los sample de DDS
DynamicDataSeq dataSeq = new DynamicDataSeq();
SampleInfoSeq infoSeq = new SampleInfoSeq();
try {
// Obtiene datos aplicandole el filtro
this.reader.take_w_condition(
dataSeq,
infoSeq,
ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
this.condicion);
// Procesamos todos los datos recibidos
for (int i = 0; i < dataSeq.size(); i++) {
SampleInfo info = (SampleInfo)infoSeq.get(i);
if (!info.valid_data)
continue;
// Deserializa los datos
DynamicData sample = (DynamicData)dataSeq.get(i);
getDatos(sample);
// Llama al listener externo
if (this.extraListener != null)
this.extraListener.actionPerformed(null);
}
} catch (RETCODE_NO_DATA e) {
// No hace nada, al filtrar datos pues se da la cosa de que no haya
} finally {
// Es para liberar recursos del sistema.
this.reader.return_loan(dataSeq, infoSeq);
}
}
/**
* Deja de procesar los datos que recibe.
*/
public void parar() {
this.parado = true;
}
/**
* Comienza a procesar los datos recibidos de nuevo.
*/
public void reanudar() {
this.parado = false;
}
public void terminar() {
this.terminar = true;
}
/**
* Establece un listener extra para cuando se reciben los datos.
*
* @param listener Listener extra.
*/
public void setExtraListener(final ActionListener listener) {
this.extraListener = listener;
}
public void cambiaParametros(final String[] params) {
this.condicion.set_query_parameters(new StringSeq(Arrays.asList(params)));
}
}
}
|
package cz.muni.fi.pa165.methanolmanager.service;
import cz.muni.fi.pa165.methanolmanager.dal.domain.Bottle;
import cz.muni.fi.pa165.methanolmanager.dal.repository.BottleRepository;
import cz.muni.fi.pa165.methanolmanager.service.dto.BottleDto;
import cz.muni.fi.pa165.methanolmanager.service.exception.EntityNotFoundException;
import org.dozer.Mapper;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
/**
* @author Pavel Vomacka
*/
@Service
@Transactional(readOnly = true)
public class BottleService {
@Inject
BottleRepository bottleRepository;
@Inject
Mapper mapper;
@Transactional
public void createBottle(BottleDto bottleDto) {
Bottle bottle = mapper.map(bottleDto, Bottle.class);
bottleRepository.save(bottle);
}
@Transactional
public void deleteBottle(int bottleId) {
try {
bottleRepository.delete(bottleId);
} catch (EmptyResultDataAccessException e) {
throw new EntityNotFoundException(bottleId);
}
}
@Transactional
public void stampBottle(int bottleId) {
Bottle bottle = bottleRepository.findOne(bottleId);
if(bottle == null) {
throw new EntityNotFoundException(bottleId);
}
if (!bottle.isStamped()) {
bottle.stamp();
}
bottleRepository.save(bottle);
}
}
|
package org.wanna.jabbot.binding.spark;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wanna.jabbot.binding.AbstractRoom;
import org.wanna.jabbot.binding.BindingListener;
import org.wanna.jabbot.binding.config.RoomConfiguration;
import org.wanna.jabbot.binding.event.MessageEvent;
import org.wanna.jabbot.messaging.*;
import org.wanna.jabbot.messaging.body.BodyPart;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Stack;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author tsearle <tsearle>
* @since 2016-03-08
*/
public class SparkRoom extends AbstractRoom<SparkBinding> implements Runnable {
private final static Logger logger = LoggerFactory.getLogger(SparkRoom.class);
// private RoomConfiguration configuration;
private final List<BindingListener> listeners;
private com.ciscospark.Room room;
private com.ciscospark.Spark spark;
private com.ciscospark.SparkServlet servlet;
private boolean useWebhook;
private String webhookUrl;
private boolean running;
private Pattern urlPattern = Pattern.compile("((http|https):[^\\\\s]+\\.(doc|docx|ppt|pptx|pdf|jpg|jpeg|png|gif|bmp))");
public SparkRoom(SparkBinding connection,List<BindingListener> listeners) {
super(connection);
this.listeners = (listeners==null?new ArrayList<BindingListener>() : listeners);
spark = connection.spark;
servlet = connection.sparkServlet;
useWebhook = connection.useWebhook;
webhookUrl = connection.webhookUrl;
}
@Override
public void run()
{
logger.info("SPARK Room started");
String lastId = null;
while (running) {
Stack<com.ciscospark.Message> msgList = new Stack<com.ciscospark.Message>();
while (running) {
String nextId = null;
try {
Iterator<com.ciscospark.Message> msgs = spark.messages()
.queryParam("roomId", room.getId())
.queryParam("max", "20")
.iterate();
while(msgs.hasNext()) {
com.ciscospark.Message imsg = msgs.next();
if (lastId == null) {
nextId = imsg.getId();
break;
}
if (nextId == null) {
nextId = imsg.getId();
}
if (lastId.equals(imsg.getId())) {
//caught up
break;
}
logger.info("MessageContent Received (" + imsg.getPersonEmail() + ") " + imsg.getText());
msgList.push(imsg);
}
lastId = nextId;
if (!msgList.empty()) break;
} catch (Exception e) {
logger.error("Error in message handling!" , e);
}
try {
Thread.sleep(5000);
} catch(Exception e) {}
}
while(!msgList.empty()) {
try {
com.ciscospark.Message msg = msgList.pop();
dispatchMessage(msg);
}catch(Exception e){
logger.error("error dispatching message {}",msgList,e);
}
}
}
}
public boolean create(String roomId) {
com.ciscospark.Room room = spark.rooms().path("/"+roomId).get();
if (room == null) {
return false;
}
return create(room);
}
public boolean create(com.ciscospark.Room room) {
this.room = room;
if (!useWebhook) {
new Thread(this).start();
} else {
com.ciscospark.Webhook hook = new com.ciscospark.Webhook();
hook.setName("midori hook");
hook.setTargetUrl(URI.create(webhookUrl));
hook.setResource("messages");
hook.setEvent("created");
hook.setFilter("roomId=" + room.getId());
hook = spark.webhooks().post(hook);
logger.info("created webhook " + hook.getName() + " id: " + hook.getId() + " for room: " + room.getTitle());
final String roomId = room.getId();
servlet.addListener( new com.ciscospark.WebhookEventListener() {
public void onEvent(com.ciscospark.WebhookEvent event) {
com.ciscospark.Message msg = event.getData();
if(event.getData().getRoomId().equals(roomId)) {
if (msg.getText() == null) {
logger.info("Getting full message for " + event.getData().getId());
msg = spark.messages().path("/" + event.getData().getId()).get();
} else {
logger.info("MessageContent already in webhook, delivering");
}
dispatchMessage(msg);
}
}
});
}
return true;
}
private void dispatchMessage(com.ciscospark.Message msg) {
if (connection.me != null && msg.getId().equals(connection.me.getId())) {
logger.info("Ignoring message from myself!");
}
for (BindingListener listener : listeners) {
String html = msg.getHtml();
String text = null;
if (html != null) {
logger.info("About reformat html: " + html);
HtmlReformat he = new HtmlReformat(connection.me, html);
text = he.removeMentions();
} else {
text = msg.getText();
if (connection.me != null) {
text = text.replace(connection.me.getDisplayName(), "").trim();
}
}
logger.info("Got a message of: " + text);
RxMessage request = new DefaultRxMessage(new DefaultMessageContent(text),
new DefaultResource(room.getId(),msg.getPersonEmail()));
listener.eventReceived(new MessageEvent(this.connection,request));
}
}
public boolean sendMessage(TxMessage response) {
String body = response.getMessageContent().getBody();
BodyPart html = response.getMessageContent().getBody(BodyPart.Type.XHTML);
if (html == null) {
sendMessage(body, null);
} else {
String htmlTxt = html.getText();
HtmlReformat he = new HtmlReformat(connection.me, htmlTxt);
htmlTxt = he.emojiify();
sendMessage(body, htmlTxt);
}
return true;
}
public void sendMessage(String body, String html) {
com.ciscospark.Message msg = new com.ciscospark.Message();
msg.setRoomId(room.getId());
msg.setText(body);
Matcher m = urlPattern.matcher(body);
if (m.find()) {
msg.setFile(m.group(0));
}
if (html != null) {
html = html.replace("\n","");
msg.setHtml(html);
}
logger.info("Sending Message (file): " + msg.getFile());
logger.info("Sending Message (txt): " + msg.getText());
logger.info("Sending Message (html): " + msg.getHtml());
spark.messages().post(msg);
}
@Override
public boolean join(RoomConfiguration configuration) {
return false;
}
@Override
public void leave() {
running = false;
}
@Override
public String getRoomName() {
return room.getTitle();
}
}
|
package org.biojava.nbio.protmod.phosphosite;
import org.biojava.nbio.phosphosite.Dataset;
import org.biojava.nbio.phosphosite.Site;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TestAcetylation {
/** Make sure an Acetylation file is available locally.
* Downloads from Phosphosite if needed.
*
*/
@Before
public void setUp(){
Dataset ds = new Dataset();
String f = Dataset.ACETYLATION;
File localFile = getLocalFileName(f);
try {
if (!localFile.exists()) {
ds.downloadFile(new URL(f), localFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/** returns the local file name where the Acetylation file will get cached locally.
*
* @param phosphoSiteFileLocation location of file at PhosphoSitePlus.
* @return a File pointing to the location of the locally cached file.
*/
private File getLocalFileName(String phosphoSiteFileLocation){
Dataset ds = new Dataset();
File localDir = ds.getLocalDir();
if ( ! localDir.exists()) {
boolean success = localDir.mkdir();
if ( ! success)
fail("Could not create directory " + localDir.getAbsolutePath());
}
int slashIndex = phosphoSiteFileLocation.lastIndexOf("/");
String fileName = phosphoSiteFileLocation.substring(slashIndex);
return new File(localDir + "/" + fileName);
}
/** Tests that the acetylation file can get parsed without problems.
*
*/
@Test
public void testAcetylation() {
try {
File localFile = getLocalFileName(Dataset.ACETYLATION);
List<Site> sites = Site.parseSites(localFile);
assertTrue(sites.size() > 0);
for (Site s : sites) {
assertTrue(s.getResidue() != null);
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
|
package com.sinnerschrader.smaller.uglifyjs;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import com.sinnerschrader.smaller.javascript.JavaScriptExecutor;
import com.sinnerschrader.smaller.resource.Processor;
import com.sinnerschrader.smaller.resource.Resource;
import com.sinnerschrader.smaller.resource.StringResource;
import com.sinnerschrader.smaller.resource.Type;
/**
* @author marwol
*/
public class UglifyjsProcessor implements Processor {
private final JavaScriptExecutor executor;
public UglifyjsProcessor() {
this.executor = new JavaScriptExecutor("uglify-1.3.3");
this.executor.addScriptSource("module = {};", "rhino.js");
this.executor.addScriptFile("/uglify-1.3.3/uglify-js.js");
this.executor.addCallScript("uglify(%s, {});");
}
/**
* @see com.sinnerschrader.smaller.resource.Processor#supportsType(com.sinnerschrader.smaller.resource.Type)
*/
@Override
public boolean supportsType(final Type type) {
return type == Type.JS;
}
/**
* @see com.sinnerschrader.smaller.resource.Processor#execute(com.sinnerschrader.smaller.resource.Resource)
*/
@Override
public Resource execute(final Resource resource) throws IOException {
final StringWriter writer = new StringWriter();
this.executor.run(new StringReader(resource.getContents()), writer);
return new StringResource(resource.getResolver(), resource.getType(),
resource.getPath(), writer.toString());
}
}
|
package lt.baraksoft.summersystem.portal.controller;
import lt.baraksoft.summersystem.dao.PaymentDao;
import lt.baraksoft.summersystem.dao.UserDao;
import lt.baraksoft.summersystem.model.Payment;
import lt.baraksoft.summersystem.model.User;
import lt.baraksoft.summersystem.portal.view.UserView;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.AfterBegin;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.*;
import javax.transaction.TransactionSynchronizationRegistry;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Named
@ConversationScoped
@Stateful
public class AnnualFeeController implements Serializable {
private static final long serialVersionUID = 390311249488898840L;
private static final String PAGE_INDEX_REDIRECT = "index?faces-redirect=true";
@PersistenceContext(unitName = "summerhousePU", type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED)
private EntityManager em;
@Inject
private Conversation conversation;
@Inject
private UserLoginController userLoginController;
@EJB
private PaymentDao paymentDao;
@EJB
private UserDao userDao;
private int activeIndex = 0;
private String selectedPaymentValue;
private List<String> clubPayTypes = new ArrayList<>();
private User loggedUser;
private String purpose;
private int amount;
private int yearLength;
private CURRENT_FORM currentForm = CURRENT_FORM.PAYMENT_TYPE;
private enum CURRENT_FORM {
PAYMENT_TYPE, PAYMENT_PROPERTIES, CONFIRMATION
}
@PostConstruct
public void init() {
clubPayTypes.add("1 metams");
clubPayTypes.add("2 metams");
clubPayTypes.add("3 metams");
}
public boolean isCurrentForm(CURRENT_FORM form) {
return currentForm == form;
}
public void calculateSum(){
yearLength = Character.getNumericValue(selectedPaymentValue.charAt(0));
amount = yearLength * 20;
}
public void checkPaymentAmount() {
if (!conversation.isTransient()) {
conversation.end();
currentForm = CURRENT_FORM.PAYMENT_TYPE;
activeIndex = 0;
return;
}
conversation.begin();
if (selectedPaymentValue.equals("")) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Klaida", "Nepasirinkote mokėjimo!");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
yearLength = Character.getNumericValue(selectedPaymentValue.charAt(0));
amount = yearLength * 20;
UserView loggedUserView = userLoginController.getLoggedUser();
loggedUser = userDao.get(loggedUserView.getId());
int points = loggedUser.getPoints();
if (points < amount) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Klaida", "Mokėjimui reikia " + amount + " taškų, Jūs turite " + points + " taškų");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
else {
purpose = "Narystės pratęsimas " + selectedPaymentValue;
loggedUser.setPoints(points - amount);
currentForm = CURRENT_FORM.PAYMENT_PROPERTIES;
activeIndex = 1;
}
}
}
public void createPayment() {
if (conversation.isTransient()) {
currentForm = CURRENT_FORM.PAYMENT_TYPE;
activeIndex = 0;
return;
}
Payment payment = new Payment();
payment.setAmount(new BigDecimal(amount));
payment.setExecutionDate(LocalDate.now());
payment.setPurpose(purpose);
payment.setUser(loggedUser);
paymentDao.save(payment);
loggedUser.getPaymentList().add(payment);
if (loggedUser.getValidTo() != null) {
loggedUser.setValidTo(loggedUser.getValidTo().plusDays(365 * yearLength));
} else {
loggedUser.setValidTo(LocalDate.now().plusDays(365 * yearLength));
}
currentForm = CURRENT_FORM.CONFIRMATION;
activeIndex = 2;
}
public String ok() {
if (conversation.isTransient()) {
currentForm = CURRENT_FORM.PAYMENT_TYPE;
activeIndex = 0;
return PAGE_INDEX_REDIRECT;
}
try {
em.joinTransaction();
em.flush();
conversation.end();
return PAGE_INDEX_REDIRECT;
} catch (OptimisticLockException ole) {
em.clear();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Klaida", "Apmokėjimas atšauktas. Taškai nenuimti");
FacesContext.getCurrentInstance().addMessage(null, msg);
return PAGE_INDEX_REDIRECT;
} catch (PersistenceException pe) {
em.clear();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Persistence exception", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return PAGE_INDEX_REDIRECT;
}
}
public String cancel() {
if (!conversation.isTransient()) {
conversation.end();
}
return PAGE_INDEX_REDIRECT;
}
public List<String> getClubPayTypes() {
return clubPayTypes;
}
public void setClubPayTypes(List<String> clubPayTypes) {
this.clubPayTypes = clubPayTypes;
}
public String getSelectedPaymentValue() {
return selectedPaymentValue;
}
public void setSelectedPaymentValue(String selectedPaymentValue) {
this.selectedPaymentValue = selectedPaymentValue;
}
public int getActiveIndex() {
return activeIndex;
}
public void setActiveIndex(int activeIndex) {
this.activeIndex = activeIndex;
}
public User getLoggedUser() {
return loggedUser;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
public int getYearLength() {
return yearLength;
}
public void setYearLength(int yearLength) {
this.yearLength = yearLength;
}
}
|
package org.eclipse.birt.report.item.crosstab.core.de;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.birt.report.item.crosstab.core.IAggregationCellConstants;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabCellConstants;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.IMeasureViewConstants;
import org.eclipse.birt.report.item.crosstab.core.i18n.Messages;
import org.eclipse.birt.report.item.crosstab.core.util.CrosstabExtendedItemFactory;
import org.eclipse.birt.report.item.crosstab.core.util.CrosstabUtil;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.extension.CompatibilityStatus;
import org.eclipse.birt.report.model.api.extension.IllegalContentInfo;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
/**
* MeasureViewHandle.
*/
public class MeasureViewHandle extends AbstractCrosstabItemHandle implements
IMeasureViewConstants,
ICrosstabConstants
{
/**
*
* @param handle
*/
MeasureViewHandle( DesignElementHandle handle )
{
super( handle );
}
/**
* Gets the referred OLAP measure handle of this measure view.
*
* @return the referred OLAP measure handle
*/
public MeasureHandle getCubeMeasure( )
{
return (MeasureHandle) handle.getElementProperty( MEASURE_PROP );
}
/**
* Gets name of the referred OLAP measure handle in this measure view.
*
* @return name of the referred OLAP measure handle
*/
public String getCubeMeasureName( )
{
return handle.getStringProperty( MEASURE_PROP );
}
/**
* Gets the data type of this measure view. It is identical with the data
* type set in the referred cube measure element.
*
* @return
*/
public String getDataType( )
{
MeasureHandle cubeMeasure = getCubeMeasure( );
return cubeMeasure == null ? null : cubeMeasure.getDataType( );
}
/**
* Gets the aggregations property handle of this measure view.
*
* @return the aggregations property handle
*/
PropertyHandle getAggregationsProperty( )
{
return handle.getPropertyHandle( AGGREGATIONS_PROP );
}
/**
* Gets the detail slot handle of this measure view.
*
* @return the detail slot handle
*/
PropertyHandle getDetailProperty( )
{
return handle.getPropertyHandle( DETAIL_PROP );
}
/**
* Gets the header slot handle of this measure view.
*
* @return the header slot handle
*/
PropertyHandle getHeaderProperty( )
{
return handle.getPropertyHandle( HEADER_PROP );
}
/**
* Gets the detail cell of this measure view.
*
* @return the detail cell of this measure view if set, otherwise null
*/
public AggregationCellHandle getCell( )
{
PropertyHandle propHandle = getDetailProperty( );
return propHandle.getContentCount( ) == 0 ? null
: (AggregationCellHandle) CrosstabUtil.getReportItem( propHandle.getContent( 0 ),
AGGREGATION_CELL_EXTENSION_NAME );
}
/**
* Adds an aggregation cell with the specific row/column dimension and
* level.
*
* @param rowDimension
* qualified name of the row dimension
* @param rowLevel
* qualified name of the row level
* @param colDimension
* qualified name of the column dimension
* @param colLevel
* qualifed name of the column level
* @return the added aggregation cell if succeed, otherwise null
* @throws SemanticException
*/
public AggregationCellHandle addAggregation( String rowDimension,
String rowLevel, String colDimension, String colLevel )
throws SemanticException
{
AggregationCellHandle aggregation = getAggregationCell( rowDimension,
rowLevel,
colDimension,
colLevel );
if ( aggregation != null )
{
logger.log( Level.INFO,
Messages.getString( "MeasureViewHandle.info.aggregation.already.exist" ) ); //$NON-NLS-1$
return aggregation;
}
ExtendedItemHandle aggregationCell = CrosstabExtendedItemFactory.createAggregationCell( moduleHandle );
if ( aggregationCell != null )
{
CommandStack stack = getCommandStack( );
stack.startTrans( Messages.getString( "MeasureViewHandle.msg.add.aggregation" ) ); //$NON-NLS-1$
try
{
aggregationCell.setProperty( IAggregationCellConstants.AGGREGATION_ON_ROW_PROP,
rowLevel );
aggregationCell.setProperty( IAggregationCellConstants.AGGREGATION_ON_COLUMN_PROP,
colLevel );
getAggregationsProperty( ).add( aggregationCell );
}
catch ( SemanticException e )
{
stack.rollback( );
throw e;
}
stack.commit( );
}
return (AggregationCellHandle) CrosstabUtil.getReportItem( aggregationCell );
}
/**
*
* @param rowDimension
* qualified name of the row dimension
* @param rowLevel
* qualified name of the row level
* @param colDimension
* qualified name of the column dimension
* @param colLevel
* qualifed name of the column level
* @throws SemanticException
*/
public void removeAggregation( String rowDimension, String rowLevel,
String colDimension, String colLevel ) throws SemanticException
{
AggregationCellHandle cell = getAggregationCell( rowDimension,
rowLevel,
colDimension,
colLevel );
if ( cell != null )
{
cell.handle.drop( );
}
}
/**
* Finds an aggregation cell which uses the given row/column dimension and
* level.
*
* @param rowDimension
* qualified name of the row dimension
* @param rowLevel
* qualified name of the row level
* @param colDimension
* qualified name of the column dimension
* @param colLevel
* qualifed name of the column level
* @return the aggregation cell handle if found, otherwise null
*/
public AggregationCellHandle getAggregationCell( String rowDimension,
String rowLevel, String colDimension, String colLevel )
{
int count = getAggregationCount( );
if ( count == 0 )
return null;
DesignElementHandle found = null;
for ( int i = 0; i < count; i++ )
{
DesignElementHandle element = getAggregationsProperty( ).getContent( i );
String row = element.getStringProperty( IAggregationCellConstants.AGGREGATION_ON_ROW_PROP );
String column = element.getStringProperty( IAggregationCellConstants.AGGREGATION_ON_COLUMN_PROP );
if ( ( rowLevel != null && rowLevel.equals( row ) )
|| ( rowLevel == null && row == null ) )
{
if ( ( colLevel != null && colLevel.equals( column ) )
|| ( colLevel == null && column == null ) )
{
found = element;
break;
}
}
}
return (AggregationCellHandle) CrosstabUtil.getReportItem( found,
AGGREGATION_CELL_EXTENSION_NAME );
}
/**
* Gets the aggregation cell count for this measure.
*
* @return count of aggregation cell for this measure
*/
public int getAggregationCount( )
{
return getAggregationsProperty( ).getContentCount( );
}
/**
* Gets the aggregation cell with the given index. Position index is 0-based
* integer.
*
* @param index
* a 0-based integer of the aggregation cell position
* @return the aggregation cell handle if found, otherwise null
*/
public AggregationCellHandle getAggregationCell( int index )
{
DesignElementHandle element = getAggregationsProperty( ).getContent( index );
return (AggregationCellHandle) CrosstabUtil.getReportItem( element,
AGGREGATION_CELL_EXTENSION_NAME );
}
/**
* Removes aggregation cell at the given position. The position index is
* 0-based integer.
*
* @param index
* the position index of the aggregation cell to remove
* @throws SemanticException
*/
public void removeAggregation( int index ) throws SemanticException
{
getAggregationsProperty( ).drop( index );
}
/**
* Gets the position index where this measure lies in the crosstab
* container. The returned value is a 0-based integer if this level is in
* the design tree. Otherwise return -1.
*
* @return position index if found, otherwise -1
*/
public int getIndex( )
{
return handle.getIndex( );
}
/**
* Gets measure header cell for specific dimension and level.
*
* @param dimensionName
* name of the dimension to find
* @param levelName
* name of the level to find
* @return the header cell which refers the given dimension and level
*/
public CrosstabCellHandle getHeader( )
{
DesignElementHandle headerCell = getHeaderCell( );
return (CrosstabCellHandle) ( headerCell == null ? null
: CrosstabUtil.getReportItem( headerCell,
CROSSTAB_CELL_EXTENSION_NAME ) );
}
/**
* Gets measure header cell.
*
* @return the design element handle for the header cell if found, otherwise
* null
*/
private DesignElementHandle getHeaderCell( )
{
PropertyHandle propHandle = getHeaderProperty( );
if ( propHandle.getContentCount( ) <= 0 )
return null;
return propHandle.getContent( 0 );
}
/**
* Removes header cell for current measure.
*
* @throws SemanticException
*/
public void removeHeader( ) throws SemanticException
{
DesignElementHandle headerCell = getHeaderCell( );
if ( headerCell != null )
{
headerCell.drop( );
}
}
/**
* Adds header cell for current measure. If header cell already exists, this
* method just does nothing.
*
* @throws SemanticException
*/
public void addHeader( ) throws SemanticException
{
PropertyHandle propHandle = getHeaderProperty( );
if ( propHandle.getContentCount( ) > 0 )
{
logger.log( Level.INFO,
"Measure header is set, need not add another" ); //$NON-NLS-1$
return;
}
ExtendedItemHandle headerCell = CrosstabExtendedItemFactory.createCrosstabCell( moduleHandle );
propHandle.add( headerCell );
}
/**
* Returns the iterator for filter list defined on this measure view. The
* element in the iterator is the corresponding
* <code>DesignElementHandle</code> that deal with a
* <code>FilterConditionElementHandle</code> in the list.
*
* @return the iterator for <code>FilterConditionElementHandle</code>
* element list
*/
public Iterator filtersIterator( )
{
PropertyHandle propHandle = handle.getPropertyHandle( FILTER_PROP );
if ( propHandle == null )
{
return Collections.EMPTY_LIST.iterator( );
}
return propHandle.getListValue( ).iterator( );
}
private LevelHandle getInnerestLevel( CrosstabReportItemHandle crosstab,
int axisType )
{
int dimCount = crosstab.getDimensionCount( axisType );
if ( dimCount > 0 )
{
// TODO check visibility?
DimensionViewHandle dv = crosstab.getDimension( axisType,
dimCount - 1 );
LevelViewHandle lv = dv.getLevel( dv.getLevelCount( ) - 1 );
return lv.getCubeLevel( );
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.api.extension.ReportItem#checkCompatibility()
*/
public CompatibilityStatus checkCompatibility( )
{
// update old version
CrosstabReportItemHandle crosstab = getCrosstab( );
if ( crosstab.compStatus < 0 )
{
ExtendedItemHandle exhandle = (ExtendedItemHandle) getModelHandle( );
Map illegalContents = exhandle.getIllegalContents( );
// do compatibility for "detail" property since 2.3, update old
// "crosstabCell" to new "aggregationCell"
if ( illegalContents.containsKey( IMeasureViewConstants.DETAIL_PROP ) )
{
List detailInfoList = (List) illegalContents.get( IMeasureViewConstants.DETAIL_PROP );
if ( detailInfoList.size( ) > 0 )
{
IllegalContentInfo detailInfo = (IllegalContentInfo) detailInfoList.get( 0 );
ExtendedItemHandle oldDetail = (ExtendedItemHandle) detailInfo.getContent( );
if ( oldDetail != null )
{
CompatibilityStatus status = new CompatibilityStatus( );
try
{
status.setStatusType( CompatibilityStatus.CONVERT_COMPATIBILITY_TYPE );
ExtendedItemHandle newDetail = CrosstabExtendedItemFactory.createAggregationCell( getModuleHandle( ) );
handle.getPropertyHandle( DETAIL_PROP )
.setValue( newDetail );
// set new aggregateOn properties
LevelHandle rowLevel = getInnerestLevel( crosstab,
ROW_AXIS_TYPE );
LevelHandle columnLevel = getInnerestLevel( crosstab,
COLUMN_AXIS_TYPE );
if ( rowLevel != null )
{
newDetail.setProperty( IAggregationCellConstants.AGGREGATION_ON_ROW_PROP,
rowLevel );
}
if ( columnLevel != null )
{
newDetail.setProperty( IAggregationCellConstants.AGGREGATION_ON_COLUMN_PROP,
columnLevel );
}
// TODO copy local properties.
List contents = oldDetail.getContents( ICrosstabCellConstants.CONTENT_PROP );
for ( int i = 0; i < contents.size( ); i++ )
{
( (DesignElementHandle) contents.get( i ) ).moveTo( newDetail,
IAggregationCellConstants.CONTENT_PROP );
}
}
catch ( SemanticException e )
{
List errorList = new ArrayList( 1 );
errorList.add( e );
status.setErrors( errorList );
}
return status;
}
}
}
}
return COMP_OK_STATUS;
}
}
|
package view;
import controller.MapEditorController;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
public class MapEditorPanel extends JPanel{
private JTextField mapName;
private JButton exit;
private JButton save;
private JButton addOrRemove;
private JPanel topArea;
private JPanel bottomArea;
private java.util.List<PanelObserver> observers = new ArrayList<PanelObserver>();
private TileSelectionPanel tileSelectionPanel = new TileSelectionPanel();
private BoardPanel board = new BoardPanel();
public MapEditorPanel(Dimension d) {
this.setPreferredSize(d);
this.setLayout(new GridBagLayout());
this.topArea = new JPanel(new GridBagLayout());
this.exit = new JButton("Exit");
this.save = new JButton("Save");
this.addOrRemove = new JButton("Add/Remove");
Dimension mN = new Dimension(300, 30);
this.mapName = new JTextField("");
mapName.setPreferredSize(mN);
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
notifyAllObservers();
}
});
Dimension b = new Dimension(90, 30);
//mapName.setPreferredSize(b);
save.setPreferredSize(b);
exit.setPreferredSize(b);
GridBagConstraints c = new GridBagConstraints();
// BoardPanel board = new BoardPanel();
board.setBackground(Color.white);
JScrollPane jSP = new JScrollPane(board);
Dimension jPB = new Dimension(1200, 550);
jSP.setPreferredSize(jPB);
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
topArea.add(mapName, c);
c.gridx = 1;
topArea.add(save, c);
c.gridx = 2;
topArea.add(exit, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
topArea.add(jSP, c);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.PAGE_START;
this.add(topArea, c);
bottomArea = new JPanel(new GridBagLayout());
// tileSelectionPanel = new TileSelectionPanel(); //init JPanel to TileSelectionPanel
Dimension terrainInfoDimension = new Dimension(500, 120);
tileSelectionPanel.setPreferredSize(terrainInfoDimension);
tileSelectionPanel.setBackground(Color.white);
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.insets = new Insets(0,250, 5, 20);
c.anchor = GridBagConstraints.CENTER;
bottomArea.add(tileSelectionPanel, c);
JPanel zoomedTilePanel = new JPanel();
Dimension zoomedTileDimension = new Dimension(120, 120);
zoomedTilePanel.setPreferredSize(zoomedTileDimension);
zoomedTilePanel.setBackground(Color.blue);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(0, 10, 5, 0);
bottomArea.add(zoomedTilePanel, c);
c.gridx = 2;
c.insets = new Insets(0,40,0,0);
bottomArea.add(addOrRemove, c);
GridBagConstraints bA = new GridBagConstraints();
bA.gridx = 0;
bA.gridy = 1;
bA.gridwidth = 5;
bA.anchor = GridBagConstraints.LAST_LINE_START;
this.add(bottomArea, bA);
}
//sets JLabel text in TileSelectionPanel for terrain
public void setTerrainInTileSelectionText(String terrain){
// terrain = mec.getCurrentTerrainType();
tileSelectionPanel.setTerrainTypeLabelText(terrain);
}
//sets JLabel text in TileSelectionPanel for river
public void setRiverConnectorsInTileSelectionText(String riverConnectors){
// riverConnectors = mec.getCurrentRiverNumber();
tileSelectionPanel.setRiverConnectorsLabelText(riverConnectors);
}
public void setControllerAsKeyListener(MapEditorController mec){
board.setFocusable(true);
board.addKeyListener(mec);
}
public void attach(PanelObserver observer){
observers.add(observer);
}
public void notifyAllObservers(){
for(PanelObserver observer : observers){
observer.update("MainMenuPanel");
}
}
}
|
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static com.google.common.base.Verify.verify;
import static java.util.Objects.requireNonNull;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementStateAware;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not
* backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only
* effective substatements, which are either transformed from that prototype or added by inference.
*/
final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode {
// An effective copy view, with enough information to decide what to do next
private static final class EffectiveCopy implements Immutable {
// Original statement
private final ReactorStmtCtx<?, ?, ?> orig;
// Effective view, if the statement is to be reused it equals to orig
private final ReactorStmtCtx<?, ?, ?> copy;
EffectiveCopy(final ReactorStmtCtx<?, ?, ?> orig, final ReactorStmtCtx<?, ?, ?> copy) {
this.orig = requireNonNull(orig);
this.copy = requireNonNull(copy);
}
boolean isReused() {
return orig == copy;
}
ReactorStmtCtx<?, ?, ?> toChildContext(final @NonNull InferredStatementContext<?, ?, ?> parent) {
return isReused() ? orig.replicaAsChildOf(parent) : copy;
}
ReactorStmtCtx<?, ?, ?> toReusedChild(final @NonNull InferredStatementContext<?, ?, ?> parent) {
verify(isReused(), "Attempted to discard copy %s", copy);
return orig.replicaAsChildOf(parent);
}
}
private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class);
// Sentinel objects for 'substatements', String is a good enough type
private static final @NonNull String REUSED_SUBSTATEMENTS = "reused";
private static final @NonNull String SWEPT_SUBSTATEMENTS = "swept";
private final @NonNull StatementContextBase<A, D, E> prototype;
private final @NonNull StatementContextBase<?, ?, ?> parent;
private final @NonNull StmtContext<A, D, E> originalCtx;
private final @NonNull CopyType childCopyType;
private final QNameModule targetModule;
private final A argument;
/**
* Effective substatements, lazily materialized. This field can have four states:
* <ul>
* <li>it can be {@code null}, in which case no materialization has taken place</li>
* <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li>
* <li>it can be a {@link List}, in which case full materialization has taken place</li>
* <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li>
* </ul>
*/
private Object substatements;
private InferredStatementContext(final InferredStatementContext<A, D, E> original,
final StatementContextBase<?, ?, ?> parent) {
super(original);
this.parent = requireNonNull(parent);
this.childCopyType = original.childCopyType;
this.targetModule = original.targetModule;
this.prototype = original.prototype;
this.originalCtx = original.originalCtx;
this.argument = original.argument;
// Substatements are initialized here
this.substatements = ImmutableList.of();
}
InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype,
final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) {
super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history()));
this.parent = requireNonNull(parent);
this.prototype = requireNonNull(prototype);
this.argument = targetModule == null ? prototype.argument()
: prototype.definition().adaptArgumentValue(prototype, targetModule);
this.childCopyType = requireNonNull(childCopyType);
this.targetModule = targetModule;
this.originalCtx = prototype.getOriginalCtx().orElse(prototype);
// Mark prototype as blocking statement cleanup
prototype.incRef();
}
@Override
public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
return ImmutableList.of();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
return mutableEffectiveSubstatements(ensureEffectiveSubstatements());
}
@Override
public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() {
// No need to concat with declared
return effectiveSubstatements();
}
@Override
public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() {
// No need to concat with declared
return effectiveSubstatements().stream();
}
@Override
public StatementSourceReference sourceReference() {
return originalCtx.sourceReference();
}
@Override
public String rawArgument() {
return originalCtx.rawArgument();
}
@Override
public Optional<StmtContext<A, D, E>> getOriginalCtx() {
return Optional.of(originalCtx);
}
@Override
public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
return Optional.of(prototype);
}
@Override
public D declared() {
/*
* Share original instance of declared statement between all effective statements which have been copied or
* derived from this original declared statement.
*/
return originalCtx.declared();
}
@Override
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef);
}
@Override
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
final String statementArg) {
substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef,
statementArg);
}
@Override
public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement);
}
@Override
void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) {
substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements);
}
@Override
InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) {
return new InferredStatementContext<>(this, newParent);
}
@Override
E createEffective(final StatementFactory<A, D, E> factory) {
// If we have not materialized we do not have a difference in effective substatements, hence we can forward
// towards the source of the statement.
accessSubstatements();
return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory);
}
private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) {
final E origEffective = prototype.buildEffective();
final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements =
origEffective.effectiveSubstatements();
// First check if we can reuse the entire prototype
if (!factory.canReuseCurrent(this, prototype, origSubstatements)) {
return deduplicate(tryToReuseSubstatements(factory, origEffective));
}
// We can reuse this statement let's see if all statements agree...
// ... no substatements to deal with, we can freely reuse the original
if (origSubstatements.isEmpty()) {
LOG.debug("Reusing empty: {}", origEffective);
substatements = ImmutableList.of();
prototype.decRef();
return origEffective;
}
// ... all are context independent, reuse the original
if (allSubstatementsContextIndependent()) {
LOG.debug("Reusing context-independent: {}", origEffective);
substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
prototype.decRef();
return origEffective;
}
// ... copy-sensitive check
final List<EffectiveCopy> declCopy = prototype.streamDeclared()
.map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
.filter(Objects::nonNull)
.collect(Collectors.toUnmodifiableList());
final List<EffectiveCopy> effCopy = prototype.streamEffective()
.map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub))
.filter(Objects::nonNull)
.collect(Collectors.toUnmodifiableList());
// ... are any copy-sensitive?
if (allReused(declCopy) && allReused(effCopy)) {
LOG.debug("Reusing after substatement check: {}", origEffective);
substatements = noRefs() ? REUSED_SUBSTATEMENTS
: reusePrototypeReplicas(Streams.concat(declCopy.stream(), effCopy.stream())
.map(copy -> copy.toReusedChild(this)));
prototype.decRef();
return origEffective;
}
// *sigh*, ok, heavy lifting through a shallow copy
final List<ReactorStmtCtx<?, ?, ?>> declared = declCopy.stream()
.map(copy -> copy.toChildContext(this))
.collect(ImmutableList.toImmutableList());
final List<ReactorStmtCtx<?, ?, ?>> effective = effCopy.stream()
.map(copy -> copy.toChildContext(this))
.collect(ImmutableList.toImmutableList());
substatements = declared.isEmpty() ? effective
: Streams.concat(declared.stream(), effective.stream()).collect(ImmutableList.toImmutableList());
prototype.decRef();
// Values are the effective copies, hence this efficiently deals with recursion.
return deduplicate(factory.createEffective(this, declared.stream(), effective.stream()));
}
private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull E original) {
if (allSubstatementsContextIndependent()) {
LOG.debug("Reusing substatements of: {}", prototype);
substatements = noRefs() ? REUSED_SUBSTATEMENTS : reusePrototypeReplicas();
prototype.decRef();
return factory.copyEffective(this, original);
}
// Fall back to full instantiation, which populates our substatements. Then check if we should be reusing
// the substatement list, as this operation turned out to not affect them.
final E effective = super.createEffective(factory);
// Since we have forced instantiation to deal with this case, we also need to reset the 'modified' flag
setUnmodified();
if (sameSubstatements(original.effectiveSubstatements(), effective)) {
LOG.debug("Reusing unchanged substatements of: {}", prototype);
return factory.copyEffective(this, original);
}
return effective;
}
private @NonNull E deduplicate(final @NonNull E effective) {
if (effective instanceof EffectiveStatementStateAware) {
final ReactorStmtCtx<A, D, E> source = unmodifiedEffectiveSource();
if (source != this) {
return source.attachCopy(((EffectiveStatementStateAware) effective).toEffectiveStatementState(),
effective);
}
}
return effective;
}
private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas() {
return reusePrototypeReplicas(Streams.concat(prototype.streamDeclared(), prototype.streamEffective()));
}
private List<ReactorStmtCtx<?, ?, ?>> reusePrototypeReplicas(final Stream<StmtContext<?, ?, ?>> stream) {
return stream
.map(stmt -> {
final ReplicaStatementContext<?, ?, ?> ret = ((ReactorStmtCtx<?, ?, ?>) stmt).replicaAsChildOf(this);
ret.buildEffective();
return ret;
})
.collect(Collectors.toUnmodifiableList());
}
private static boolean sameSubstatements(final Collection<?> original, final EffectiveStatement<?, ?> effective) {
final Collection<?> copied = effective.effectiveSubstatements();
if (copied != effective.effectiveSubstatements() || original.size() != copied.size()) {
// Do not bother if result is treating substatements as transient
return false;
}
final Iterator<?> oit = original.iterator();
final Iterator<?> cit = copied.iterator();
while (oit.hasNext()) {
verify(cit.hasNext());
// Identity comparison on purpose to side-step whatever equality there might be. We want to reuse instances
// after all.
if (oit.next() != cit.next()) {
return false;
}
}
verify(!cit.hasNext());
return true;
}
private static boolean allReused(final List<EffectiveCopy> entries) {
return entries.stream().allMatch(EffectiveCopy::isReused);
}
@Override
ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource() {
return isModified() ? this : prototype.unmodifiedEffectiveSource();
}
@Override
boolean hasEmptySubstatements() {
if (substatements == null) {
return prototype.hasEmptySubstatements();
}
return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty();
}
@Override
boolean noSensitiveSubstatements() {
accessSubstatements();
if (substatements == null) {
// No difference, defer to prototype
return prototype.allSubstatementsContextIndependent();
}
if (substatements instanceof List) {
// Fully materialized, walk all statements
return noSensitiveSubstatements(castEffective(substatements));
}
// Partially-materialized. This case has three distinct outcomes:
// - prototype does not have a sensitive statement (1)
// - protype has a sensitive substatement, and
// - we have not marked is as unsupported (2)
// - we have marked it as unsupported (3)
// Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side
// and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it
// as affecting the result.
return prototype.allSubstatementsContextIndependent()
&& noSensitiveSubstatements(castMaterialized(substatements).values());
}
@Override
<X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
final @NonNull Class<Z> type) {
if (substatements instanceof List) {
return super.findSubstatementArgumentImpl(type);
}
final Optional<X> templateArg = prototype.findSubstatementArgument(type);
if (templateArg.isEmpty()) {
return templateArg;
}
if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) {
// X is known to be QName
return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule));
}
return templateArg;
}
@Override
boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
return substatements instanceof List ? super.hasSubstatementImpl(type)
// We do not allow deletion of partially-materialized statements, hence this is accurate
: prototype.hasSubstatement(type);
}
@Override
public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>>
StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) {
if (substatements instanceof List) {
// We have performed materialization, hence we have triggered creation of all our schema tree child
// statements.
return null;
}
final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype));
LOG.debug("Materializing child {} from {}", qname, templateQName);
final StmtContext<?, ?, ?> template;
if (prototype instanceof InferredStatementContext) {
// Note: we need to access namespace here, as the target statement may have already been populated, in which
// case we want to obtain the statement in local namespace storage.
template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace(
SchemaTreeNamespace.class, templateQName);
} else {
template = prototype.allSubstatementsStream()
.filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class)
&& templateQName.equals(stmt.argument()))
.findAny()
.orElse(null);
}
if (template == null) {
// We do not have a template, this child does not exist. It may be added later, but that is someone else's
// responsibility.
LOG.debug("Child {} does not have a template", qname);
return null;
}
@SuppressWarnings("unchecked")
final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
.orElseThrow(
() -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
ensureCompletedPhase(ret);
addMaterialized(template, ret);
LOG.debug("Child {} materialized", qname);
return ret;
}
// Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall
// BuildGlobalContext, hence it must be called at most once.
private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() {
accessSubstatements();
return substatements instanceof List ? castEffective(substatements)
: initializeSubstatements(castMaterialized(substatements));
}
@Override
Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() {
// When we have not initialized, there are no statements to catch up: we will catch up when we are copying
// from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL).
if (substatements == null) {
return ImmutableList.of();
}
accessSubstatements();
if (substatements instanceof HashMap) {
return castMaterialized(substatements).values();
} else {
return castEffective(substatements);
}
}
@Override
Stream<? extends @NonNull StmtContext<?, ?, ?>> streamDeclared() {
return Stream.empty();
}
@Override
Stream<? extends @NonNull StmtContext<?, ?, ?>> streamEffective() {
return ensureEffectiveSubstatements().stream().filter(StmtContext::isSupportedToBuildEffective);
}
private void accessSubstatements() {
if (substatements instanceof String) {
throw new VerifyException("Access to " + substatements + " substatements of " + this);
}
}
@Override
void markNoParentRef() {
final Object local = substatements;
if (local != null) {
markNoParentRef(castEffective(local));
}
}
@Override
int sweepSubstatements() {
final Object local = substatements;
substatements = SWEPT_SUBSTATEMENTS;
int count = 0;
if (local instanceof List) {
final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local);
sweep(list);
count = countUnswept(list);
}
return count;
}
private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements(
final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements();
final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements();
final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
for (final Mutable<?, ?, ?> stmtContext : declared) {
if (stmtContext.isSupportedByFeatures()) {
copySubstatement(stmtContext, buffer, materializedSchemaTree);
}
}
for (final Mutable<?, ?, ?> stmtContext : effective) {
copySubstatement(stmtContext, buffer, materializedSchemaTree);
}
final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size());
ret.addAll((Collection) buffer);
substatements = ret;
setModified();
prototype.decRef();
return ret;
}
// Statement copy mess starts here. As it turns out, it's not that much of a mess, but it does make your head spin
// sometimes. Tread softly because you tread on my dreams.
private EffectiveCopy effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) {
final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType, targetModule);
return effective == null ? null : new EffectiveCopy(stmt, effective);
}
private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer,
final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) {
// Consult materialized substatements. We are in a copy operation and will end up throwing materialized
// statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation.
// We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order
// against parent would change -- and we certainly do not want that to happen.
final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement);
if (materialized == null) {
copySubstatement(substatement).ifPresent(copy -> {
ensureCompletedPhase(copy);
buffer.add(copy);
});
} else {
buffer.add(materialized);
}
}
private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) {
return substatement.copyAsChildOf(this, childCopyType, targetModule);
}
private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) {
final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree;
if (substatements == null) {
// Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit
// here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and
// defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a
// resizing operation.
materializedSchemaTree = new HashMap<>(4);
substatements = materializedSchemaTree;
setModified();
} else {
verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements);
materializedSchemaTree = castMaterialized(substatements);
}
final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template,
(StatementContextBase<?, ?, ?>) copy);
if (existing != null) {
throw new VerifyException(
"Unexpected duplicate request for " + copy.argument() + " previous result was " + existing);
}
}
private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized(
final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree,
final StmtContext<?, ?, ?> template) {
return materializedSchemaTree == null ? null : materializedSchemaTree.get(template);
}
@SuppressWarnings("unchecked")
private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) {
return (List<ReactorStmtCtx<?, ?, ?>>) substatements;
}
@SuppressWarnings("unchecked")
private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) {
return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements;
}
// Statement copy mess ends here
/*
* KEEP THINGS ORGANIZED!
*
* below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is
* properly updated there.
*/
@Override
@Deprecated
public SchemaPath schemaPath() {
return substatementGetSchemaPath();
}
@Override
public A argument() {
return argument;
}
@Override
public StatementContextBase<?, ?, ?> getParentContext() {
return parent;
}
@Override
public StorageNodeType getStorageNodeType() {
return StorageNodeType.STATEMENT_LOCAL;
}
@Override
public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
return parent;
}
@Override
public RootStatementContext<?, ?, ?> getRoot() {
return parent.getRoot();
}
@Override
public EffectiveConfig effectiveConfig() {
return effectiveConfig(parent);
}
@Override
protected boolean isIgnoringIfFeatures() {
return isIgnoringIfFeatures(parent);
}
@Override
protected boolean isIgnoringConfig() {
return isIgnoringConfig(parent);
}
@Override
protected boolean isParentSupportedByFeatures() {
return parent.isSupportedByFeatures();
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc157.ProtoBot2017;
import org.usfirst.frc157.FRC2016.JoystickPOVButton;
import org.usfirst.frc157.FRC2016.commands.ArmShoulderManual;
import org.usfirst.frc157.FRC2016.commands.PrintButton;
import org.usfirst.frc157.ProtoBot2017.commands.AlignForShot;
import org.usfirst.frc157.ProtoBot2017.commands.AlignToField;
import org.usfirst.frc157.ProtoBot2017.commands.AutonomousCommand;
import org.usfirst.frc157.ProtoBot2017.commands.ClimbCommand;
import org.usfirst.frc157.ProtoBot2017.commands.CollectorCommand;
import org.usfirst.frc157.ProtoBot2017.commands.DebugPrintInfo;
import org.usfirst.frc157.ProtoBot2017.commands.DebugPrintInfo.DebugSelection;
import org.usfirst.frc157.ProtoBot2017.commands.GateCommand;
import org.usfirst.frc157.ProtoBot2017.commands.GearStateCommand;
import org.usfirst.frc157.ProtoBot2017.commands.HelixCommand;
import org.usfirst.frc157.ProtoBot2017.commands.OperatorGear;
import org.usfirst.frc157.ProtoBot2017.commands.SetCamera;
import org.usfirst.frc157.ProtoBot2017.commands.SetCameraTarget;
import org.usfirst.frc157.ProtoBot2017.commands.ShootCommand;
import org.usfirst.frc157.ProtoBot2017.commands.StoreImages;
import org.usfirst.frc157.ProtoBot2017.commands.ToggleCollection;
import org.usfirst.frc157.ProtoBot2017.commands.ClimbCommand.ClimbCommandSpeed;
import org.usfirst.frc157.ProtoBot2017.subsystems.Climb;
import org.usfirst.frc157.ProtoBot2017.subsystems.Collect;
import org.usfirst.frc157.ProtoBot2017.subsystems.Gate;
import org.usfirst.frc157.ProtoBot2017.subsystems.Gear;
import org.usfirst.frc157.ProtoBot2017.subsystems.Helix;
import org.usfirst.frc157.ProtoBot2017.subsystems.Shoot;
import org.usfirst.frc157.ProtoBot2017.subsystems.Vision;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public JoystickButton joystickButtonA; // Controller A
public JoystickButton joystickButtonB; // Controller B
public JoystickButton joystickButtonX; // Controller X
public JoystickButton joystickButtonY; // Controller Y
public JoystickButton joystickButton7;
public JoystickButton joystickButton8;
public JoystickButton joystickButton12;
public JoystickButton joystickButton5;// left bumper
public JoystickButton joystickButton6;// right bumper
public JoystickButton joystickButtonRightStickPress; // Press Right Stick
private JoystickPOVButton operatorStickHatFore; // Hat Button Forward
private JoystickPOVButton operatorStickHatForeRight; // Hat Button Forward Right
private JoystickPOVButton operatorStickHatRight; // Hat Button Right
private JoystickPOVButton operatorStickHatAftRight; // Hat Button Aft Right
private JoystickPOVButton operatorStickHatAft; // Hat Button Aft
private JoystickPOVButton operatorStickHatAftLeft; // Hat Button Aft Left
private JoystickPOVButton operatorStickHatLeft; // Hat Button Left
private JoystickPOVButton operatorStickHatForeLeft; // Hat Button Forward Left
public XboxController driver;
public Joystick operatorJoystick = new Joystick(1);// instantiates thye operator joystick
public Button trigger ;
public Button operatorButton2;
public Button operatorButton8;
public Button operatorButton10;
public Button operatorButton12;
public Button operatorButton5;
public Button operatorButton3;
public Button operatorButton4;
public Button operatorButton6;
// for gate
public Button operatorButton7;
public Button operatorButton9;
public Button operatorButton11;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public OI() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driver = new XboxController(0);
joystickButtonA = new JoystickButton(driver, 1);
// joystickButtonA.whileHeld(new AlignForShot(Vision.BoilerRange.FAR));
joystickButtonA.whileHeld(new ShootCommand(Shoot.ShootCommand.FAR));
joystickButtonB = new JoystickButton(driver, 2);
joystickButtonB.whenPressed(new SetCameraTarget());
joystickButtonX = new JoystickButton(driver, 3);
// joystickButtonX.whileHeld(new AlignForShot(Vision.BoilerRange.FAR));
joystickButtonX.whenPressed(new ToggleCollection());
joystickButtonY = new JoystickButton(driver, 4);
joystickButtonY.whenPressed(new StoreImages());
joystickButton5 = new JoystickButton(driver, 5);
joystickButton5.whileHeld(new ShootCommand( Shoot.ShootCommand.FAR ));
joystickButton6 = new JoystickButton(driver, 6);
joystickButton6.whenPressed(new GearStateCommand());
joystickButton7 = new JoystickButton(driver, 7);
joystickButton7.whenPressed(new OperatorGear(Gear.GearCommand.CLOSE));
joystickButton8 = new JoystickButton(driver, 8);
joystickButton8.whenPressed(new OperatorGear(Gear.GearCommand.CLOSE));
joystickButtonRightStickPress = new JoystickButton(driver, 10);
joystickButtonRightStickPress.whenPressed(new AlignToField());
trigger = new JoystickButton(operatorJoystick, 1);
trigger.whileHeld(new CollectorCommand(Collect.collectorCommand.LOAD));
operatorButton2 = new JoystickButton(operatorJoystick, 2);
operatorButton2.whileHeld(new ClimbCommand(ClimbCommand.ClimbCommandSpeed.SLOW));
operatorButton8 = new JoystickButton(operatorJoystick, 8);
operatorButton8.whenPressed(new ShootCommand(Shoot.ShootCommand.FAR));
operatorButton10 = new JoystickButton(operatorJoystick, 10);
operatorButton10.whenPressed(new ShootCommand(Shoot.ShootCommand.NEAR));
operatorButton12 = new JoystickButton(operatorJoystick, 12);
operatorButton12.whenPressed(new ShootCommand(Shoot.ShootCommand.IDLE));
operatorButton4 = new JoystickButton(operatorJoystick, 4);
operatorButton4.whenPressed(new HelixCommand(Helix.helixCommand.LOADRIGHT));
operatorButton6 = new JoystickButton(operatorJoystick, 6);
operatorButton6.whenPressed(new HelixCommand(Helix.helixCommand.IDLERIGHT));
operatorButton3 = new JoystickButton(operatorJoystick, 3);
operatorButton3.whenPressed(new HelixCommand(Helix.helixCommand.LOADLEFT));
operatorButton5 = new JoystickButton(operatorJoystick, 5);
operatorButton5.whenPressed(new HelixCommand(Helix.helixCommand.IDLELEFT));
operatorButton7 = new JoystickButton(operatorJoystick, 7);
operatorButton7.whenPressed(new GateCommand(Gate.gateCommand.OPEN));
operatorButton9 = new JoystickButton(operatorJoystick, 9);
operatorButton9.whenPressed(new GateCommand(Gate.gateCommand.OFF));
operatorButton11 = new JoystickButton(operatorJoystick, 11);
operatorButton11.whenPressed(new GateCommand(Gate.gateCommand.CLOSED));
// using lefts and rights for mitigating operator eror during compotitions
operatorStickHatFore = new JoystickPOVButton(operatorJoystick, 0);
operatorStickHatFore.whileHeld(new ClimbCommand( ClimbCommandSpeed.FAST));
operatorStickHatForeRight = new JoystickPOVButton(operatorJoystick, 45);
operatorStickHatForeRight.whenPressed(new ClimbCommand( ClimbCommandSpeed.FAST));
operatorStickHatForeLeft = new JoystickPOVButton(operatorJoystick, 315);
operatorStickHatForeLeft.whenPressed(new ClimbCommand( ClimbCommandSpeed.FAST));
// operatorStickHatRight = new JoystickPOVButton(operatorJoystick, 90);
// operatorStickHatRight.whenPressed(new PrintButton("O Hat Right"));
operatorStickHatAftRight = new JoystickPOVButton(operatorJoystick, 135);
operatorStickHatAftRight.whenPressed(new ClimbCommand( ClimbCommandSpeed.SLOW));
operatorStickHatAft = new JoystickPOVButton(operatorJoystick, 180);
operatorStickHatAft.whileHeld(new ClimbCommand( ClimbCommandSpeed.SLOW));
operatorStickHatAftLeft = new JoystickPOVButton(operatorJoystick, 225);
operatorStickHatAft.whileHeld(new ClimbCommand( ClimbCommandSpeed.SLOW));
// operatorStickHatLeft = new JoystickPOVButton(operatorJoystick, 270);
// operatorStickHatLeft.whenPressed(new ClimbCommand("O Hat Left"));
// SmartDashboard Buttons
SmartDashboard.putData("AlignToField", new AlignToField());
SmartDashboard.putData("Toggle Camera Targeting", new SetCameraTarget());
SmartDashboard.putData("Toggle Camera Targeting", new SetCamera());
SmartDashboard.putData("Store Camera Images", new StoreImages());
SmartDashboard.putData("Autonomous Command", new AutonomousCommand());
SmartDashboard.putData("DebugButton", new DebugPrintInfo("ScreenButton", DebugSelection.NOPRINT));
SmartDashboard.putData("Align for Near Shot", new AlignForShot(Vision.BoilerRange.NEAR));
SmartDashboard.putData("Align for Far Shot", new AlignForShot(Vision.BoilerRange.FAR));
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
public XboxController getDriver() {
return driver;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.subsystems;
import org.usfirst.frc330.Robot;
import org.usfirst.frc330.RobotMap;
import org.usfirst.frc330.commands.*;
import org.usfirst.frc330.constants.ArmPos;
import org.usfirst.frc330.constants.HandConst;
import org.usfirst.frc330.util.CSVLoggable;
import org.usfirst.frc330.wpilibj.DualSpeedController;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.command.Subsystem;
public class Hand extends Subsystem implements PIDSource, PIDOutput{
double verticalHandAngle = HandConst.defaultVerticalHandAngle;
boolean handLevelActivated = false;
protected PIDController wristPID;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
DoubleSolenoid handLeft = RobotMap.handhandLeft;
DoubleSolenoid handCenter = RobotMap.handhandCenter;
DoubleSolenoid handRight = RobotMap.handhandRight;
DualSpeedController wrist = RobotMap.handwrist;
AnalogInput wristPot = RobotMap.handwristPot;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public Hand() {
super();
wristPID = new PIDController(HandConst.proportional,
HandConst.integral,
HandConst.derivitive,this,this);
wristPID.setAbsoluteTolerance(HandConst.tolerance);
// LOG IT!
CSVLoggable temp = new CSVLoggable(true) {
public double get() { return getAngleFromArm(); }
};
Robot.csvLogger.add("WristAngleFromArm", temp);
temp = new CSVLoggable() {
public double get() { return wrist.get(); }
};
Robot.csvLogger.add("WristOutput", temp);
temp = new CSVLoggable() {
public double get() { return Robot.powerDP.getWristLeftCurrent(); }
};
Robot.csvLogger.add("WristLeftCurrent", temp);
temp = new CSVLoggable() {
public double get() { return Robot.powerDP.getWristRightCurrent(); }
};
Robot.csvLogger.add("WristRightCurrent", temp);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new handLevel());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void setAngle(double angle)
{
//TODO: Finish Implementation
}
public double getAngleFromArm(){
double sensorRange = getHandRearLimit() - getHandFrontLimit();
double angleRange = HandConst.rearLimitAngle - HandConst.frontLimitAngle;
double angleFromArm = sensorRange/angleRange * (wristPot.getAverageVoltage()- getHandFrontLimit()) + HandConst.frontLimitAngle;
return angleFromArm;
}
public void setHandFrontLimit()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeHandFrontLimit";
else
name = "CompetitionHandFrontLimit";
Preferences.getInstance().putDouble(name, wristPot.getAverageVoltage());
Preferences.getInstance().save();
}
public void setHandRearLimit()
{
String name;
if (Robot.isPracticerobot())
name = "PracticeHandRearLimit";
else
name = "CompetitionHandRearLimit";
Preferences.getInstance().putDouble(name, wristPot.getAverageVoltage());
Preferences.getInstance().save();
}
public double getHandFrontLimit() {
String name;
if (Robot.isPracticerobot())
name = "PracticeHandFrontLimit";
else
name = "CompetitionHandFrontLimit";
return Preferences.getInstance().getDouble(name, HandConst.frontLimit);
}
public double getHandRearLimit() {
String name;
if (Robot.isPracticerobot())
name = "PracticeArmHandLimit";
else
name = "CompetitionHandRearLimit";
return Preferences.getInstance().getDouble(name, HandConst.rearLimit);
}
public double getVerticalHandAngle() {
return verticalHandAngle;
}
public void setVerticalHandAngle(double verticalHandAngle) {
this.verticalHandAngle = verticalHandAngle;
}
// Hand (Grabber) Open and Close Functions
public void closeHandLeft()
{
handLeft.set(DoubleSolenoid.Value.kReverse);
}
public void openHandLeft()
{
handLeft.set(DoubleSolenoid.Value.kForward);
}
public void closeHandRight()
{
handRight.set(DoubleSolenoid.Value.kReverse);
}
public void openHandRight()
{
handRight.set(DoubleSolenoid.Value.kForward);
}
public void closeHandCenter()
{
handCenter.set(DoubleSolenoid.Value.kReverse);
}
public void openHandCenter()
{
handCenter.set(DoubleSolenoid.Value.kForward);
}
// Hand Leveling Code
public boolean isHandLevelActivated() {
return handLevelActivated;
}
public void setHandLevelActivated(boolean handLevelActivated) {
this.handLevelActivated = handLevelActivated;
}
public void stopHand()
{
if(wristPID.isEnable())
{
wristPID.disable();
}
}
public void pidWrite(double output) {
set(output);
}
public double pidGet() {
return getAngleFromArm();
}
public void set(double output){
if (output > 0 && getAngleFromArm() < HandConst.frontLimitAngle)
{
wrist.set(0);
}
else if (output < 0 && getAngleFromArm() > HandConst.rearLimitAngle)
{
wrist.set(0);
}
//TODO: Update this code for the wrist
// if (output > 0 && Robot.powerDP.getWristLeftCurrent() < HandConst.currentLowerLimit)
// wrist.set(0);
// else if (output < 0 && Robot.powerDP.getWristLeftCurrent() > HandConst.currentUpperLimit)
// wrist.set(0);
// else if (output > 0 && Robot.powerDP.getWristRightCurrent() < HandConst.currentLowerLimit)
// wrist.set(0);
// else if (output < 0 && Robot.powerDP.getWristRightCurrent() > HandConst.currentUpperLimit)
// wrist.set(0);
else
{
wrist.set(output);
}
}
public void setAbsoluteTolerance(double absvalue) {
wristPID.setAbsoluteTolerance(absvalue);
}
public synchronized boolean onTarget() {
return wristPID.onTarget();
}
}
|
package org.eclipse.birt.report.debug.internal.ui.script.launcher;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.debug.internal.core.launcher.IReportLaunchConstants;
import org.eclipse.birt.report.debug.internal.core.launcher.LauncherEngineConfig;
import org.eclipse.birt.report.debug.internal.core.launcher.ReportLauncher;
import org.eclipse.birt.report.debug.internal.ui.script.util.ScriptDebugUtil;
import org.eclipse.birt.report.debug.ui.DebugUI;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.dialogs.InputParameterDialog;
import org.eclipse.birt.report.designer.ui.parameters.ParameterFactory;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
/**
* ReportLaunchHelper
*/
public class ReportLaunchHelper implements IReportLaunchConstants
{
private Map paramValues = new HashMap( );
String fileName;
String engineHome;
String tempFolder;
String targetFormat;
boolean isOpenTargetFile;
// boolean useDefaultEngineHome;
int debugType;
int taskType;
int listenPort;
private static final Logger logger = Logger.getLogger( ReportLaunchHelper.class.getName( ) );
void init( ILaunchConfiguration configuration ) throws CoreException
{
fileName = covertVariables( configuration.getAttribute( ATTR_REPORT_FILE_NAME,
"" ) ); //$NON-NLS-1$
engineHome = covertVariables( configuration.getAttribute( ATTR_ENGINE_HOME,
"" ) ); //$NON-NLS-1$
tempFolder = covertVariables( configuration.getAttribute( ATTR_TEMP_FOLDER,
"" ) ); //$NON-NLS-1$
// useDefaultEngineHome = configuration.getAttribute( ATTR_USE_DEFULT_ENGINE_HOME,
// true );
targetFormat = configuration.getAttribute( ATTR_TARGET_FORMAT,
DEFAULT_TARGET_FORMAT );
isOpenTargetFile = configuration.getAttribute( ATTR_OPEN_TARGET, false );
debugType = configuration.getAttribute( ATTR_DEBUG_TYPE,
DEFAULT_DEBUG_TYPE );
taskType = configuration.getAttribute( ATTR_TASK_TYPE,
DEFAULT_TASK_TYPE );
}
void addUserClassPath( List list, ILaunchConfiguration config )
{
list.add( "-D" + ATTR_USER_CLASS_PATH + "=" + convertClassPath( getUserClasspath( config ) ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
void addResourceFolder(List list)
{
String str = getResourceFolder( fileName );
if (str != null)
{
list.add( "-D" + ATTR_RESOURCE_FOLDER + "=" + str);
}
}
private String getResourceFolder(String fileName)
{
IPath path = new Path(fileName);
IFile[] files = ResourcesPlugin.getWorkspace( ).getRoot( ).findFilesForLocation( path );
if (files == null || files.length == 0)
{
return null;
}
return ReportPlugin.getDefault( ).getResourceFolder( files[0].getProject( ) );
}
void addPortArgs( List list )
{
listenPort = findFreePort( );
list.add( "-D" + ATTR_LISTEN_PORT + "=" + listenPort ); //$NON-NLS-1$ //$NON-NLS-2$
}
void addParameterArgs( List list )
{
Iterator iterator = paramValues.keySet( ).iterator( );
while ( iterator.hasNext( ) )
{
String key = (String) iterator.next( );
Object obj = paramValues.get( key );
if (obj == null)
{
obj = ReportLauncher.NULLVALUE;
}
if ( obj instanceof Object[] )
{
// continue;
Object[] temp = (Object[]) obj;
for ( int i = 0; i < temp.length; i++ )
{
String value = String.valueOf( temp[i] );
StringBuffer buff = new StringBuffer( );
buff.append( "-D" ); //$NON-NLS-1$
buff.append( ATTR_MULPARAMRTER );
buff.append( i );
buff.append( key );
buff.append( "=" ); //$NON-NLS-1$
buff.append( value );
list.add( buff.toString( ) );
}
}
else
{
String value = null;
if (obj instanceof Date)
{
value = String.valueOf( ((Date)obj ).getTime( ));
}
else
{
value = String.valueOf( obj );
}
StringBuffer buff = new StringBuffer( );
buff.append( "-D" ); //$NON-NLS-1$
buff.append( ATTR_PARAMRTER );
buff.append( key );
buff.append( "=" ); //$NON-NLS-1$
buff.append( value );
list.add( buff.toString( ) );
}
}
}
void addDataLimitArgs(List list)
{
String value = ReportPlugin.getDefault( ).getPluginPreferences( ).getString( ReportPlugin.DATA_MODEL_MEMORY_LIMIT_PREFERENCE );
StringBuffer buff = new StringBuffer( );
buff.append( "-D" ); //$NON-NLS-1$
buff.append( ATTR_DATA_LIMIT_SIZE );//$NON-NLS-1$
buff.append( "=" ); //$NON-NLS-1$
buff.append( value );
list.add( buff.toString( ) );
}
void addTypeArgs( List list )
{
list.add( "-D" + ATTR_DEBUG_TYPE + "=" + debugType ); //$NON-NLS-1$ //$NON-NLS-2$
list.add( "-D" + ATTR_TASK_TYPE + "=" + taskType ); //$NON-NLS-1$ //$NON-NLS-2$
list.add( "-D" + ATTR_TARGET_FORMAT + "=" + targetFormat ); //$NON-NLS-1$ //$NON-NLS-2$
}
void addTempFolder( List list )
{
list.add( "-D" + ATTR_TEMP_FOLDER + "=" + tempFolder ); //$NON-NLS-1$ //$NON-NLS-2$
}
void addFileNameArgs( List list )
{
list.add( "-D" + ATTR_REPORT_FILE_NAME + "=" + fileName ); //$NON-NLS-1$ //$NON-NLS-2$
}
void addEngineHomeArgs( List list )
{
list.add( "-D" + ATTR_ENGINE_HOME + "=" + engineHome ); //$NON-NLS-1$ //$NON-NLS-2$
}
private static String covertVariables( String str )
{
try
{
return ScriptDebugUtil.getSubstitutedString( str );
}
catch ( CoreException e )
{
return str;
}
}
private static String[] getUserClasspath( ILaunchConfiguration configuration )
{
try
{
ScriptDebugClasspathProvider provider = new ScriptDebugClasspathProvider( );
IRuntimeClasspathEntry[] entries = provider.computeUserClasspath( configuration );
entries = JavaRuntime.resolveRuntimeClasspath( entries,
configuration );
List userEntries = new ArrayList( );
Set set = new HashSet( entries.length );
for ( int i = 0; i < entries.length; i++ )
{
if ( entries[i].getClasspathProperty( ) == IRuntimeClasspathEntry.USER_CLASSES )
{
String location = entries[i].getLocation( );
if ( location != null )
{
if ( !set.contains( location ) )
{
userEntries.add( location );
set.add( location );
}
}
}
}
return (String[]) userEntries.toArray( new String[userEntries.size( )] );
}
catch ( CoreException e )
{
e.printStackTrace( );
}
return null;
}
private static String convertClassPath( String[] cp )
{
int pathCount = 0;
StringBuffer buf = new StringBuffer( );
if ( cp == null || cp.length == 0 )
{
return ""; //$NON-NLS-1$
}
for ( int i = 0; i < cp.length; i++ )
{
if ( pathCount > 0 )
{
buf.append( File.pathSeparator );
}
buf.append( cp[i] );
pathCount++;
}
return buf.toString( );
}
private static int findFreePort( )
{
ServerSocket socket = null;
try
{
socket = new ServerSocket( 0 );
return socket.getLocalPort( );
}
catch ( IOException e )
{
}
finally
{
if ( socket != null )
{
try
{
socket.close( );
}
catch ( IOException e )
{
}
}
}
return -1;
}
/**
* Gets the parameter
*
* @param params
* @return
*/
private static boolean getParameterValues( String reportDesignFile,
int taskType, IReportEngine engine, Map paramValues )
{
IGetParameterDefinitionTask task = null;
IReportDocument document = null;
boolean launch = false;
try
{
if ( taskType == TASK_TYPE_RENDER )
{
document = engine.openReportDocument( reportDesignFile );
task = engine.createGetParameterDefinitionTask( document
.getReportRunnable( ) );
}
else
{
task = engine.createGetParameterDefinitionTask( engine.openReportDesign( reportDesignFile ) );
}
ParameterFactory factory = new ParameterFactory( task );
List params = factory.getRootChildren( false );
if ( params != null && params.size( ) > 0 )
{
InputParameterDialog dialog = new InputParameterDialog( DebugUI.getShell( ),
params,
paramValues );
// InputParameterDailog uses reportrunnable set in
// GetParameterDefinitionTask execution context.Close
// GetParameterDefinitionTask after InputParameterDialog
// completes reading the default values for the report
// parameters.
if ( dialog.open( ) == Window.OK )
{
paramValues.clear( );
paramValues.putAll( dialog.getParameters( ) );
launch = true;
}
}
else
{
launch = true;
}
}
catch ( EngineException e )
{
logger.log( Level.SEVERE, e.getMessage( ), e);
}finally{
if ( task != null )
{
task.close( );
}
if (document != null)
{
document.close();
}
}
return launch;
}
boolean finalLaunchCheck( final ILaunchConfiguration configuration,
String mode, IProgressMonitor monitor ) throws CoreException
{
paramValues = new HashMap( );
LauncherEngineConfig engineConfig = new LauncherEngineConfig( );
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
final IReportEngine engine = factory.createReportEngine( engineConfig );
engine.changeLogLevel( Level.WARNING );
final String fileName = covertVariables( configuration.getAttribute( ATTR_REPORT_FILE_NAME,
"" ) ); //$NON-NLS-1$
if (getResourceFolder( fileName ) != null)
{
engineConfig.setResourcePath( getResourceFolder( fileName ) );
}
final int taskType = configuration.getAttribute( ATTR_TASK_TYPE,
DEFAULT_TASK_TYPE );
Display display = DebugUI.getStandardDisplay( );
if ( display.getThread( ).equals( Thread.currentThread( ) ) )
{
return getParameterValues(fileName,
taskType,
engine, paramValues );
}
final Object[] result = new Object[]{
Boolean.FALSE
};
Runnable r = new Runnable( ) {
public void run( )
{
result[0] = Boolean.valueOf( getParameterValues( fileName,
taskType,
engine ,
paramValues ) );
}
};
DebugUI.getStandardDisplay( ).syncExec( r );
return ( (Boolean) result[0] ).booleanValue( );
}
static void handleProcessTermination( ILaunch launch,
final IProcess process, final String fileName,
final String outputFolder ) throws CoreException
{
if ( launch.getLaunchConfiguration( ).getAttribute( ATTR_OPEN_TARGET,
false )
&& launch.getLaunchConfiguration( )
.getAttribute( ATTR_TASK_TYPE, DEFAULT_TASK_TYPE ) != TASK_TYPE_RUN )
{
final String suffix = launch.getLaunchConfiguration( )
.getAttribute( ATTR_TARGET_FORMAT, DEFAULT_TARGET_FORMAT );
Thread monitorThread = new Thread( new Runnable( ) {
public void run( )
{
while ( !process.isTerminated( ) )
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
// donothing
}
}
DebugUI.getStandardDisplay( ).asyncExec( new Runnable( ) {
public void run( )
{
try
{
if ( process.getExitValue( ) == ReportLauncher.EXIT_OK )
{
File file = new File( fileName );
String openName = ReportLauncher.getOutputFileName( outputFolder,
file.getName( ),
suffix );
if ( openName != null
&& new File( openName ).exists( ) )
{
Program.launch( openName );
}
}
}
catch ( DebugException e )
{
// donothing
}
}
} );
}
},
"Process Termination Monitor" ); //$NON-NLS-1$
monitorThread.setDaemon( true );
monitorThread.start( );
}
}
}
|
package org.springframework.roo.addon.web.mvc.controller.scaffold;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.COUNT_ALL_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.FIND_ALL_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.FIND_ENTRIES_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.FIND_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.MERGE_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.PERSIST_METHOD;
import static org.springframework.roo.classpath.customdata.CustomDataKeys.REMOVE_METHOD;
import static org.springframework.roo.model.JavaType.INT_OBJECT;
import static org.springframework.roo.model.JavaType.STRING;
import static org.springframework.roo.model.JavaType.VOID_PRIMITIVE;
import static org.springframework.roo.model.JdkJavaType.ARRAYS;
import static org.springframework.roo.model.JdkJavaType.ARRAY_LIST;
import static org.springframework.roo.model.JdkJavaType.LIST;
import static org.springframework.roo.model.JdkJavaType.UNSUPPORTED_ENCODING_EXCEPTION;
import static org.springframework.roo.model.Jsr303JavaType.VALID;
import static org.springframework.roo.model.SpringJavaType.AUTOWIRED;
import static org.springframework.roo.model.SpringJavaType.BINDING_RESULT;
import static org.springframework.roo.model.SpringJavaType.CONVERSION_SERVICE;
import static org.springframework.roo.model.SpringJavaType.LOCALE_CONTEXT_HOLDER;
import static org.springframework.roo.model.SpringJavaType.MODEL;
import static org.springframework.roo.model.SpringJavaType.PATH_VARIABLE;
import static org.springframework.roo.model.SpringJavaType.REQUEST_MAPPING;
import static org.springframework.roo.model.SpringJavaType.REQUEST_METHOD;
import static org.springframework.roo.model.SpringJavaType.REQUEST_PARAM;
import static org.springframework.roo.model.SpringJavaType.URI_UTILS;
import static org.springframework.roo.model.SpringJavaType.WEB_UTILS;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import org.springframework.roo.addon.web.mvc.controller.details.DateTimeFormatDetails;
import org.springframework.roo.addon.web.mvc.controller.details.JavaTypeMetadataDetails;
import org.springframework.roo.addon.web.mvc.controller.details.JavaTypePersistenceMetadataDetails;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.customdata.tagkeys.MethodMetadataCustomDataKey;
import org.springframework.roo.classpath.details.ConstructorMetadata;
import org.springframework.roo.classpath.details.ConstructorMetadataBuilder;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.MethodMetadataBuilder;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder;
import org.springframework.roo.classpath.details.annotations.BooleanAttributeValue;
import org.springframework.roo.classpath.details.annotations.EnumAttributeValue;
import org.springframework.roo.classpath.details.annotations.StringAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.classpath.layers.MemberTypeAdditions;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.model.DataType;
import org.springframework.roo.model.EnumDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.LogicalPath;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
/**
* Metadata for {@link RooWebScaffold}.
*
* @author Stefan Schmidt
* @author Andrew Swan
* @since 1.0
*/
public class WebScaffoldMetadata extends
AbstractItdTypeDetailsProvidingMetadataItem {
// Constants
private static final JavaSymbolName CS_FIELD = new JavaSymbolName(
"conversionService");
private static final JavaType HTTP_SERVLET_REQUEST = new JavaType(
"javax.servlet.http.HttpServletRequest");
private static final String PROVIDES_TYPE_STRING = WebScaffoldMetadata.class
.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils
.create(PROVIDES_TYPE_STRING);
private static final StringAttributeValue PRODUCES_HTML = new StringAttributeValue(
new JavaSymbolName("produces"), "text/html");
public static String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static String createIdentifier(final JavaType javaType,
final LogicalPath path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(
PROVIDES_TYPE_STRING, javaType, path);
}
public static JavaType getJavaType(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(
PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static LogicalPath getPath(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING,
metadataIdentificationString);
}
public static boolean isValid(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING,
metadataIdentificationString);
}
// Fields
private boolean compositePk;
private JavaType formBackingType;
private JavaTypeMetadataDetails javaTypeMetadataHolder;
private Map<JavaSymbolName, DateTimeFormatDetails> dateTypes;
private String controllerPath;
private String entityName;
private WebScaffoldAnnotationValues annotationValues;
/**
* Constructor
*
* @param identifier
* @param aspectName
* @param governorPhysicalType
* @param annotationValues
* @param specialDomainTypes
* @param dependentTypes
* @param dateTypes
* @param crudAdditions
* @param editableFieldTypes
*/
public WebScaffoldMetadata(
final String identifier,
final JavaType aspectName,
final PhysicalTypeMetadata governorPhysicalType,
final WebScaffoldAnnotationValues annotationValues,
final SortedMap<JavaType, JavaTypeMetadataDetails> specialDomainTypes,
final List<JavaTypeMetadataDetails> dependentTypes,
final Map<JavaSymbolName, DateTimeFormatDetails> dateTypes,
final Map<MethodMetadataCustomDataKey, MemberTypeAdditions> crudAdditions,
final Collection<JavaType> editableFieldTypes) {
super(identifier, aspectName, governorPhysicalType);
Assert.isTrue(isValid(identifier), "Metadata identification string '"
+ identifier + "' is invalid");
Assert.notNull(annotationValues, "Annotation values required");
Assert.notNull(specialDomainTypes, "Special domain types map required");
Assert.notNull(dependentTypes, "Dependent types list required");
if (!isValid()) {
return;
}
this.annotationValues = annotationValues;
this.controllerPath = annotationValues.getPath();
this.dateTypes = dateTypes;
this.formBackingType = annotationValues.getFormBackingObject();
this.entityName = JavaSymbolName.getReservedWordSafeName(
formBackingType).getSymbolName();
this.javaTypeMetadataHolder = specialDomainTypes.get(formBackingType);
Assert.notNull(javaTypeMetadataHolder,
"Metadata holder required for form backing type: "
+ formBackingType);
if (javaTypeMetadataHolder.getPersistenceDetails() != null
&& !javaTypeMetadataHolder.getPersistenceDetails()
.getRooIdentifierFields().isEmpty()) {
this.compositePk = true;
builder.addField(getField(CS_FIELD, CONVERSION_SERVICE));
builder.addConstructor(getConstructor());
}
// "create" methods
final MemberTypeAdditions persistMethod = crudAdditions
.get(PERSIST_METHOD);
if (annotationValues.isCreate() && persistMethod != null) {
builder.addMethod(getCreateMethod(persistMethod));
builder.addMethod(getCreateFormMethod(dependentTypes));
persistMethod.copyAdditionsTo(builder, governorTypeDetails);
}
// "list" method
final MemberTypeAdditions countAllMethod = crudAdditions
.get(COUNT_ALL_METHOD);
final MemberTypeAdditions findMethod = crudAdditions.get(FIND_METHOD);
final MemberTypeAdditions findAllMethod = crudAdditions
.get(FIND_ALL_METHOD);
final MemberTypeAdditions findEntriesMethod = crudAdditions
.get(FIND_ENTRIES_METHOD);
// "show" method
if (findMethod != null) {
builder.addMethod(getShowMethod(findMethod));
findMethod.copyAdditionsTo(builder, governorTypeDetails);
}
if (countAllMethod != null && findAllMethod != null
&& findEntriesMethod != null) {
builder.addMethod(getListMethod(findAllMethod, countAllMethod,
findEntriesMethod));
countAllMethod.copyAdditionsTo(builder, governorTypeDetails);
findAllMethod.copyAdditionsTo(builder, governorTypeDetails);
findEntriesMethod.copyAdditionsTo(builder, governorTypeDetails);
}
// "update" methods
final MemberTypeAdditions updateMethod = crudAdditions
.get(MERGE_METHOD);
if (annotationValues.isUpdate() && updateMethod != null
&& findMethod != null) {
builder.addMethod(getUpdateMethod(updateMethod));
builder.addMethod(getUpdateFormMethod(findMethod));
updateMethod.copyAdditionsTo(builder, governorTypeDetails);
}
// "delete" method
final MemberTypeAdditions deleteMethod = crudAdditions
.get(REMOVE_METHOD);
if (annotationValues.isDelete() && deleteMethod != null
&& findMethod != null) {
builder.addMethod(getDeleteMethod(deleteMethod, findMethod));
deleteMethod.copyAdditionsTo(builder, governorTypeDetails);
}
if (!dateTypes.isEmpty()) {
builder.addMethod(getDateTimeFormatHelperMethod());
}
if (annotationValues.isCreate() || annotationValues.isUpdate()) {
builder.addMethod(getPopulateEditFormMethod(formBackingType,
specialDomainTypes.values(), editableFieldTypes));
builder.addMethod(getEncodeUrlPathSegmentMethod());
}
this.itdTypeDetails = builder.build();
}
private ConstructorMetadataBuilder getConstructor() {
final ConstructorMetadata constructor = governorTypeDetails
.getDeclaredConstructor(Arrays.asList(CONVERSION_SERVICE));
if (constructor != null) {
return null;
}
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("this." + CS_FIELD + " = " + CS_FIELD
+ ";");
final ConstructorMetadataBuilder constructorBuilder = new ConstructorMetadataBuilder(
getId());
constructorBuilder.addAnnotation(new AnnotationMetadataBuilder(
AUTOWIRED));
constructorBuilder.addParameterType(AnnotatedJavaType
.convertFromJavaType(CONVERSION_SERVICE));
constructorBuilder.addParameterName(CS_FIELD);
constructorBuilder.setModifier(Modifier.PUBLIC);
constructorBuilder.setBodyBuilder(bodyBuilder);
return constructorBuilder;
}
private MethodMetadataBuilder getDeleteMethod(
final MemberTypeAdditions deleteMethodAdditions,
final MemberTypeAdditions findMethod) {
final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataHolder = javaTypeMetadataHolder
.getPersistenceDetails();
if (javaTypePersistenceMetadataHolder == null) {
return null;
}
final JavaSymbolName methodName = new JavaSymbolName("delete");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"),
"id"));
final AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(
PATH_VARIABLE, attributes);
final List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>();
firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName(
"value"), "page"));
firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName(
"required"), false));
final AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(
REQUEST_PARAM, firstResultAttributes);
final List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>();
maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName(
"value"), "size"));
maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName(
"required"), false));
final AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(
REQUEST_PARAM, maxResultsAttributes);
final List<AnnotatedJavaType> parameterTypes = Arrays.asList(
new AnnotatedJavaType(javaTypePersistenceMetadataHolder
.getIdentifierType(), pathVariableAnnotation.build()),
new AnnotatedJavaType(new JavaType(Integer.class.getName()),
firstResultAnnotation.build()), new AnnotatedJavaType(
new JavaType(Integer.class.getName()),
maxResultAnnotation.build()), new AnnotatedJavaType(
MODEL));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("id"), new JavaSymbolName("page"),
new JavaSymbolName("size"), new JavaSymbolName("uiModel"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(
new JavaSymbolName("value"), "/{id}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName(
"method"), new EnumDetails(REQUEST_METHOD, new JavaSymbolName(
"DELETE"))));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
final String formBackingTypeName = formBackingType
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(formBackingTypeName + " " + entityName
+ " = " + findMethod.getMethodCall() + ";");
bodyBuilder.appendFormalLine(deleteMethodAdditions.getMethodCall()
+ ";");
bodyBuilder.appendFormalLine("uiModel.asMap().clear();");
bodyBuilder
.appendFormalLine("uiModel.addAttribute(\"page\", (page == null) ? \"1\" : page.toString());");
bodyBuilder
.appendFormalLine("uiModel.addAttribute(\"size\", (size == null) ? \"10\" : size.toString());");
bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath
+ "\";");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
/**
* Returns the metadata for the "list" method that this ITD introduces into
* the controller.
*
* @param findAllAdditions
* @param countAllAdditions
* @param findEntriesAdditions
* @return <code>null</code> if no such method is to be introduced
*/
private MethodMetadataBuilder getListMethod(
final MemberTypeAdditions findAllAdditions,
final MemberTypeAdditions countAllAdditions,
final MemberTypeAdditions findEntriesAdditions) {
final JavaSymbolName methodName = new JavaSymbolName("list");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>();
firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName(
"value"), "page"));
firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName(
"required"), false));
final AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(
REQUEST_PARAM, firstResultAttributes);
final List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>();
maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName(
"value"), "size"));
maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName(
"required"), false));
final AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(
REQUEST_PARAM, maxResultsAttributes);
final List<AnnotatedJavaType> parameterTypes = Arrays
.asList(new AnnotatedJavaType(INT_OBJECT, firstResultAnnotation
.build()), new AnnotatedJavaType(INT_OBJECT,
maxResultAnnotation.build()), new AnnotatedJavaType(
MODEL));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("page"), new JavaSymbolName("size"),
new JavaSymbolName("uiModel"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(PRODUCES_HTML);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(new AnnotationMetadataBuilder(REQUEST_MAPPING,
requestMappingAttributes));
final String plural = javaTypeMetadataHolder.getPlural().toLowerCase();
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (page != null || size != null) {");
bodyBuilder.indent();
bodyBuilder
.appendFormalLine("int sizeNo = size == null ? 10 : size.intValue();");
bodyBuilder
.appendFormalLine("final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;");
bodyBuilder.appendFormalLine("uiModel.addAttribute(\"" + plural
+ "\", " + findEntriesAdditions.getMethodCall() + ");");
bodyBuilder.appendFormalLine("float nrOfPages = (float) "
+ countAllAdditions.getMethodCall() + " / sizeNo;");
bodyBuilder
.appendFormalLine("uiModel.addAttribute(\"maxPages\", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("} else {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("uiModel.addAttribute(\"" + plural
+ "\", " + findAllAdditions.getMethodCall() + ");");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(uiModel);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getShowMethod(
final MemberTypeAdditions findMethod) {
final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataHolder = javaTypeMetadataHolder
.getPersistenceDetails();
if (javaTypePersistenceMetadataHolder == null) {
return null;
}
final JavaSymbolName methodName = new JavaSymbolName("show");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"),
"id"));
final AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(
PATH_VARIABLE, attributes);
final List<AnnotatedJavaType> parameterTypes = Arrays.asList(
new AnnotatedJavaType(javaTypePersistenceMetadataHolder
.getIdentifierType(), pathVariableAnnotation.build()),
new AnnotatedJavaType(MODEL));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("id"), new JavaSymbolName("uiModel"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(
new JavaSymbolName("value"), "/{id}"));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(uiModel);");
}
bodyBuilder.appendFormalLine("uiModel.addAttribute(\""
+ entityName.toLowerCase() + "\", "
+ findMethod.getMethodCall() + ");");
bodyBuilder.appendFormalLine("uiModel.addAttribute(\"itemId\", "
+ (compositePk ? "conversionService.convert(" : "") + "id"
+ (compositePk ? ", String.class)" : "") + ");");
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/show\";");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getCreateMethod(
final MemberTypeAdditions persistMethod) {
final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataHolder = javaTypeMetadataHolder
.getPersistenceDetails();
if (javaTypePersistenceMetadataHolder == null
|| javaTypePersistenceMetadataHolder
.getIdentifierAccessorMethod() == null) {
return null;
}
final JavaSymbolName methodName = new JavaSymbolName("create");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(
VALID);
final List<AnnotatedJavaType> parameterTypes = Arrays
.asList(new AnnotatedJavaType(formBackingType, validAnnotation
.build()), new AnnotatedJavaType(BINDING_RESULT),
new AnnotatedJavaType(MODEL), new AnnotatedJavaType(
HTTP_SERVLET_REQUEST));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName(entityName), new JavaSymbolName(
"bindingResult"), new JavaSymbolName("uiModel"),
new JavaSymbolName("httpServletRequest"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName(
"method"), new EnumDetails(REQUEST_METHOD, new JavaSymbolName(
"POST"))));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (bindingResult.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("populateEditForm(uiModel, " + entityName
+ ");");
bodyBuilder.appendFormalLine("return \"" + controllerPath
+ "/create\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("uiModel.asMap().clear();");
bodyBuilder.appendFormalLine(persistMethod.getMethodCall() + ";");
bodyBuilder.appendFormalLine("return \"redirect:/"
+ controllerPath
+ "/\" + encodeUrlPathSegment("
+ (compositePk ? "conversionService.convert(" : "")
+ entityName
+ "."
+ javaTypePersistenceMetadataHolder
.getIdentifierAccessorMethod().getMethodName() + "()"
+ (compositePk ? ", String.class)" : ".toString()")
+ ", httpServletRequest);");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getCreateFormMethod(
final List<JavaTypeMetadataDetails> dependentTypes) {
final JavaSymbolName methodName = new JavaSymbolName("createForm");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<JavaType> parameterTypes = Arrays.asList(MODEL);
final List<JavaSymbolName> parameterNames = Arrays
.asList(new JavaSymbolName("uiModel"));
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(
new JavaSymbolName("params"), "form"));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
annotations.add(requestMapping);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("populateEditForm(uiModel, new "
+ formBackingType.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver()) + "());");
boolean listAdded = false;
for (final JavaTypeMetadataDetails dependentType : dependentTypes) {
if (dependentType.getPersistenceDetails().getCountMethod() == null) {
continue;
}
if (!listAdded) {
final JavaType stringArrayType = new JavaType(
STRING.getFullyQualifiedTypeName(), 1, DataType.TYPE,
null, null);
final JavaType listType = new JavaType(
LIST.getFullyQualifiedTypeName(), 0, DataType.TYPE,
null, Arrays.asList(stringArrayType));
final String listShort = listType
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
final JavaType arrayListType = new JavaType(
ARRAY_LIST.getFullyQualifiedTypeName(), 0,
DataType.TYPE, null, Arrays.asList(stringArrayType));
final String arrayListShort = arrayListType
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
bodyBuilder.appendFormalLine(listShort + " dependencies = new "
+ arrayListShort + "();");
listAdded = true;
}
bodyBuilder.appendFormalLine("if ("
+ dependentType.getPersistenceDetails().getCountMethod()
.getMethodCall() + " == 0) {");
bodyBuilder.indent();
// Adding string array which has the fieldName at position 0 and the
// path at position 1
bodyBuilder.appendFormalLine("dependencies.add(new String[] { \""
+ dependentType.getJavaType().getSimpleTypeName()
.toLowerCase() + "\", \""
+ dependentType.getPlural().toLowerCase() + "\" });");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
}
if (listAdded) {
bodyBuilder
.appendFormalLine("uiModel.addAttribute(\"dependencies\", dependencies);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath
+ "/create\";");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING,
AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getUpdateMethod(
final MemberTypeAdditions updateMethod) {
final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataHolder = javaTypeMetadataHolder
.getPersistenceDetails();
if (javaTypePersistenceMetadataHolder == null
|| javaTypePersistenceMetadataHolder.getMergeMethod() == null) {
return null;
}
final JavaSymbolName methodName = new JavaSymbolName("update");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(
VALID);
final List<AnnotatedJavaType> parameterTypes = Arrays
.asList(new AnnotatedJavaType(formBackingType, validAnnotation
.build()), new AnnotatedJavaType(BINDING_RESULT),
new AnnotatedJavaType(MODEL), new AnnotatedJavaType(
HTTP_SERVLET_REQUEST));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName(entityName), new JavaSymbolName(
"bindingResult"), new JavaSymbolName("uiModel"),
new JavaSymbolName("httpServletRequest"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName(
"method"), new EnumDetails(REQUEST_METHOD, new JavaSymbolName(
"PUT"))));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (bindingResult.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("populateEditForm(uiModel, " + entityName
+ ");");
bodyBuilder.appendFormalLine("return \"" + controllerPath
+ "/update\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("uiModel.asMap().clear();");
bodyBuilder.appendFormalLine(updateMethod.getMethodCall() + ";");
bodyBuilder.appendFormalLine("return \"redirect:/"
+ controllerPath
+ "/\" + encodeUrlPathSegment("
+ (compositePk ? "conversionService.convert(" : "")
+ entityName
+ "."
+ javaTypePersistenceMetadataHolder
.getIdentifierAccessorMethod().getMethodName() + "()"
+ (compositePk ? ", String.class)" : ".toString()")
+ ", httpServletRequest);");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getUpdateFormMethod(
final MemberTypeAdditions findMethod) {
final JavaTypePersistenceMetadataDetails javaTypePersistenceMetadataHolder = javaTypeMetadataHolder
.getPersistenceDetails();
if (javaTypePersistenceMetadataHolder == null) {
return null;
}
final JavaSymbolName methodName = new JavaSymbolName("updateForm");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"),
"id"));
final AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(
PATH_VARIABLE, attributes);
final List<AnnotatedJavaType> parameterTypes = Arrays.asList(
new AnnotatedJavaType(javaTypePersistenceMetadataHolder
.getIdentifierType(), pathVariableAnnotation.build()),
new AnnotatedJavaType(MODEL));
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("id"), new JavaSymbolName("uiModel"));
final List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(
new JavaSymbolName("value"), "/{id}"));
requestMappingAttributes.add(new StringAttributeValue(
new JavaSymbolName("params"), "form"));
requestMappingAttributes.add(PRODUCES_HTML);
final AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(
REQUEST_MAPPING, requestMappingAttributes);
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("populateEditForm(uiModel, "
+ findMethod.getMethodCall() + ");");
bodyBuilder.appendFormalLine("return \"" + controllerPath
+ "/update\";");
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(
getId(), Modifier.PUBLIC, methodName, STRING, parameterTypes,
parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder;
}
private MethodMetadataBuilder getEncodeUrlPathSegmentMethod() {
final JavaSymbolName methodName = new JavaSymbolName(
"encodeUrlPathSegment");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<JavaType> parameterTypes = Arrays.asList(STRING,
HTTP_SERVLET_REQUEST);
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("pathSegment"), new JavaSymbolName(
"httpServletRequest"));
builder.getImportRegistrationResolver().addImport(
UNSUPPORTED_ENCODING_EXCEPTION);
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder
.appendFormalLine("String enc = httpServletRequest.getCharacterEncoding();");
bodyBuilder.appendFormalLine("if (enc == null) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("enc = "
+ WEB_UTILS.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver())
+ ".DEFAULT_CHARACTER_ENCODING;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("try {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("pathSegment = "
+ URI_UTILS.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver())
+ ".encodePathSegment(pathSegment, enc);");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("} catch ("
+ UNSUPPORTED_ENCODING_EXCEPTION
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver())
+ " uee) {}");
bodyBuilder.appendFormalLine("return pathSegment;");
return new MethodMetadataBuilder(getId(), 0, methodName, STRING,
AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
parameterNames, bodyBuilder);
}
private MethodMetadataBuilder getDateTimeFormatHelperMethod() {
final JavaSymbolName methodName = new JavaSymbolName(
"addDateTimeFormatPatterns");
if (governorHasMethodWithSameName(methodName)) {
return null;
}
final List<JavaType> parameterTypes = Arrays.asList(MODEL);
final List<JavaSymbolName> parameterNames = Arrays
.asList(new JavaSymbolName("uiModel"));
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
for (final Entry<JavaSymbolName, DateTimeFormatDetails> javaSymbolNameDateTimeFormatDetailsEntry : dateTypes
.entrySet()) {
String pattern;
if (javaSymbolNameDateTimeFormatDetailsEntry.getValue().pattern != null) {
pattern = "\""
+ javaSymbolNameDateTimeFormatDetailsEntry.getValue().pattern
+ "\"";
}
else {
final JavaType dateTimeFormat = new JavaType(
"org.joda.time.format.DateTimeFormat");
final String dateTimeFormatSimple = dateTimeFormat
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
final String localeContextHolderSimple = LOCALE_CONTEXT_HOLDER
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
pattern = dateTimeFormatSimple
+ ".patternForStyle(\""
+ javaSymbolNameDateTimeFormatDetailsEntry.getValue().style
+ "\", " + localeContextHolderSimple + ".getLocale())";
}
bodyBuilder.appendFormalLine("uiModel.addAttribute(\""
+ entityName
+ "_"
+ javaSymbolNameDateTimeFormatDetailsEntry.getKey()
.getSymbolName().toLowerCase() + "_date_format\", "
+ pattern + ");");
}
return new MethodMetadataBuilder(getId(), 0, methodName,
VOID_PRIMITIVE,
AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
parameterNames, bodyBuilder);
}
private MethodMetadata getPopulateEditFormMethod(final JavaType entity,
final Collection<JavaTypeMetadataDetails> specialDomainTypes,
final Collection<JavaType> editableFieldTypes) {
final JavaSymbolName methodName = new JavaSymbolName("populateEditForm");
final JavaType[] parameterTypes = { MODEL, entity };
final List<JavaSymbolName> parameterNames = Arrays.asList(
new JavaSymbolName("uiModel"), new JavaSymbolName(entityName));
if (governorHasMethod(methodName, parameterTypes)) {
return null;
}
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("uiModel.addAttribute(\"" + entityName
+ "\", " + entityName + ");");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(uiModel);");
}
if (annotationValues.isPopulateMethods()) {
for (final JavaTypeMetadataDetails domainType : specialDomainTypes) {
if (editableFieldTypes.contains(domainType.getJavaType())) {
final JavaTypePersistenceMetadataDetails persistenceDetails = domainType
.getPersistenceDetails();
final String modelAttribute = domainType.getPlural()
.toLowerCase();
if (persistenceDetails != null
&& persistenceDetails.getFindAllMethod() != null) {
bodyBuilder.appendFormalLine("uiModel.addAttribute(\""
+ modelAttribute
+ "\", "
+ persistenceDetails.getFindAllMethod()
.getMethodCall() + ");");
persistenceDetails.getFindAllMethod().copyAdditionsTo(
builder, governorTypeDetails);
}
else if (domainType.isEnumType()) {
final String enumTypeName = domainType
.getJavaType()
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
final String arraysTypeName = ARRAYS
.getNameIncludingTypeParameters(false,
builder.getImportRegistrationResolver());
bodyBuilder.appendFormalLine("uiModel.addAttribute(\""
+ modelAttribute + "\", " + arraysTypeName
+ ".asList(" + enumTypeName + ".values())"
+ ");");
}
}
}
}
return new MethodMetadataBuilder(getId(), 0, methodName,
VOID_PRIMITIVE,
AnnotatedJavaType.convertFromJavaTypes(parameterTypes),
parameterNames, bodyBuilder).build();
}
public WebScaffoldAnnotationValues getAnnotationValues() {
return annotationValues;
}
@Override
public String toString() {
final ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
}
|
package org.dellroad.stuff.pobj;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Comparator;
import javax.xml.transform.stream.StreamSource;
import org.dellroad.stuff.schema.SchemaUpdate;
import org.dellroad.stuff.spring.BeanNameComparator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.core.io.Resource;
public class SpringPersistentObjectSchemaUpdater<T> extends PersistentObjectSchemaUpdater<T>
implements BeanFactoryAware, InitializingBean, DisposableBean {
private ListableBeanFactory beanFactory;
private T initialValue;
private Resource initialXML;
/**
* Set the initial value to be used on an uninitialized persistent object.
*
* <p>
* Either this or a {@linkplain #setInitialXML initial XML resource} should be configured
* to handle the case that no persistent file exists yet.
*/
public void setInitialValue(T initialValue) {
this.initialValue = initialValue;
}
/**
* Set the resource containing the initial value, encoded as XML, to be used on an uninitialized persistent object.
* This can be used as an alternative to {@link #setInitialValue}.
*
* <p>
* Either this or an explicit {@linkplain #setInitialValue initial value} should be configured
* to handle the case that no persistent file exists yet.
*/
public void setInitialXML(Resource resource) {
this.initialXML = resource;
}
/**
* Get the initial value for the persistent object when no persistent file is found.
*
* <p>
* The implementation in {@link SpringPersistentObjectSchemaUpdater} returns the {@linkplain #setInitialValue initial value},
* if any, otherwise it falls back to decoding the initial value from the {@linkplain #setInitialXML initial value
* resource}, if any. If neither property is configured, a {@link PersistentObjectException} is thrown.
*/
@Override
protected T getInitialValue() {
// If value is provided explicitly, just return it
if (this.initialValue != null)
return this.initialValue;
// Use configured XML if available
if (this.initialXML == null)
return null;
try {
InputStream input = this.initialXML.getInputStream();
try {
return this.delegate.deserialize(
new StreamSource(new BufferedInputStream(input), this.initialXML.getURI().toString()));
} finally {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PersistentObjectException(e);
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ListableBeanFactory)
this.beanFactory = (ListableBeanFactory)beanFactory;
}
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
// Check config
if (this.file == null)
throw new IllegalArgumentException("no file configured");
if (this.writeDelay < 0)
throw new IllegalArgumentException("negative writeDelay file configured");
if (this.delegate == null)
throw new IllegalArgumentException("no delegate configured");
if (this.getUpdates() == null) {
if (this.beanFactory == null) {
throw new IllegalArgumentException("no updates explicitly configured and the containing BeanFactory"
+ " is not a ListableBeanFactory: " + this.beanFactory);
}
this.setUpdates((Collection<SpringPersistentObjectSchemaUpdate<T>>)(Object)this.beanFactory.getBeansOfType(
SpringPersistentObjectSchemaUpdate.class).values());
}
// Start
this.start();
}
@Override
public void destroy() {
this.stop();
}
/**
* Get the preferred ordering of two updates that do not have any predecessor constraints
* (including implied indirect constraints) between them.
*
* <p>
* In the case no schema updates are explicitly configured, the {@link Comparator} returned by the
* implementation in {@link SpringPersistentObjectSchemaUpdater} sorts updates in the same order that they appear
* in the containing {@link ListableBeanFactory}. Otherwise, the
* {@linkplain org.dellroad.stuff.schema.AbstractSchemaUpdater#getOrderingTieBreaker superclass method} is used.
*/
@Override
protected Comparator<SchemaUpdate<PersistentFileTransaction>> getOrderingTieBreaker() {
if (this.beanFactory == null)
return super.getOrderingTieBreaker();
final BeanNameComparator beanNameComparator = new BeanNameComparator(this.beanFactory);
return new Comparator<SchemaUpdate<PersistentFileTransaction>>() {
@Override
public int compare(SchemaUpdate<PersistentFileTransaction> update1, SchemaUpdate<PersistentFileTransaction> update2) {
return beanNameComparator.compare(update1.getName(), update2.getName());
}
};
}
}
|
package stroom.lmdb;
import stroom.util.io.FileUtil;
import stroom.util.logging.LambdaLogger;
import stroom.util.logging.LambdaLoggerFactory;
import stroom.util.logging.LogUtil;
import stroom.util.shared.ModelStringUtil;
import com.google.common.collect.ImmutableMap;
import org.lmdbjava.Dbi;
import org.lmdbjava.DbiFlags;
import org.lmdbjava.Env;
import org.lmdbjava.EnvInfo;
import org.lmdbjava.Stat;
import org.lmdbjava.Txn;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.StampedLock;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.concurrent.NotThreadSafe;
/**
* A wrapper around {@link org.lmdbjava.Env<java.nio.ByteBuffer>} with additional concurrency
* protection features to control the number of concurrent read and write transactions.
*/
public class LmdbEnv implements AutoCloseable {
private static final LambdaLogger LOGGER = LambdaLoggerFactory.getLogger(LmdbEnv.class);
private final Path localDir;
private final Env<ByteBuffer> env;
// Lock to ensure only one thread can hold a write txn at once.
// If doWritesBlockReads is true then will only one thread can hold an open txn
// of any kind at once.
private final Lock writeTxnLock;
private final Function<Function<Txn<ByteBuffer>, ?>, ?> readTxnGetMethod;
private final ReadWriteLock readWriteLock;
private final Semaphore activeReadTransactionsSemaphore;
LmdbEnv(final Path localDir,
final Env<ByteBuffer> env) {
this(localDir, env, false);
}
LmdbEnv(final Path localDir,
final Env<ByteBuffer> env,
final boolean isReaderBlockedByWriter) {
this.localDir = localDir;
this.env = env;
// Limit concurrent readers java side to ensure we don't get a max readers reached error
final int maxReaders = env.info().maxReaders;
activeReadTransactionsSemaphore = new Semaphore(maxReaders);
if (isReaderBlockedByWriter) {
// Read/write lock enforces writes block reads and the semphore ensures we don't have
// too many readers.
readWriteLock = new StampedLock().asReadWriteLock();
writeTxnLock = readWriteLock.writeLock();
// Read txns open concurrently with write txns mean the writes can't reclaim unused space
// in the db, so can lead to excessive growth of the db file.
LOGGER.debug("Initialising Environment with isReaderBlockedByWriter: {}",
isReaderBlockedByWriter);
readTxnGetMethod = work ->
getWithReadTxnUnderReadWriteLock(work, readWriteLock.readLock());
} else {
// No lock for readers, only the sempaphor to enforce max concurrent readers
// Simple re-entrant lock to enforce max one concurrent writer
readWriteLock = null;
writeTxnLock = new ReentrantLock();
LOGGER.debug("Initialising Environment with permits: {}, isReaderBlockedByWriter: {}",
maxReaders,
isReaderBlockedByWriter);
readTxnGetMethod = this::getWithReadTxnUnderMaxReaderSemaphore;
}
}
public Path getLocalDir() {
return localDir;
}
/**
* @link Env#sync
*/
public void sync(final boolean force) {
env.sync(force);
}
/**
* Opens a database with the supplied name. If no dbiFlags are supplied then
* {@link DbiFlags#MDB_CREATE} is used to create the database if it doesn't exist.
*/
public Dbi<ByteBuffer> openDbi(final String name,
final DbiFlags... dbiFlags) {
final DbiFlags[] flags = (dbiFlags != null && dbiFlags.length > 0)
? dbiFlags
: (new DbiFlags[]{DbiFlags.MDB_CREATE});
LOGGER.debug(() ->
LogUtil.message("Opening LMDB database with name: {}, flags: {}, path: {}",
name,
Arrays.toString(flags),
localDir.toAbsolutePath().normalize()));
try {
return env.openDbi(name, DbiFlags.MDB_CREATE);
} catch (final Exception e) {
final String message = LogUtil.message("Error opening LMDB database '{}' in '{}' ({})",
name,
FileUtil.getCanonicalPath(localDir),
e.getMessage());
LOGGER.error(message, e);
throw new RuntimeException(message, e);
}
}
/**
* Perform the supplied work using a new write transaction. The transaction will
* be committed and closed after performing the work.
* The txn should be left in a state where a commit is permitted.
*/
public void doWithWriteTxn(final Consumer<Txn<ByteBuffer>> work) {
getWithWriteTxn(txn -> {
work.accept(txn);
return null;
});
}
/**
* Get a value using a write transaction. The txn will be committed and closed after
* the work is complete.
* The txn should be left in a state where a commit is permitted.
*/
public <T> T getWithWriteTxn(final Function<Txn<ByteBuffer>, T> work) {
LOGGER.trace("Acquiring write txn lock");
try {
writeTxnLock.lockInterruptibly();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread interrupted while waiting for write lock on "
+ localDir.toAbsolutePath().normalize());
}
try {
LOGGER.trace("About to open write tx");
try (final Txn<ByteBuffer> writeTxn = env.txnWrite()) {
LOGGER.trace("Performing work with write txn");
T result = work.apply(writeTxn);
LOGGER.trace("Committing the txn");
writeTxn.commit();
return result;
} catch (RuntimeException e) {
throw new RuntimeException(LogUtil.message(
"Error performing work in read transaction: {}",
e.getMessage()), e);
}
} finally {
LOGGER.trace("Releasing the write lock");
writeTxnLock.unlock();
}
}
/**
* @return An {@link AutoCloseable} wrapper round the open write txn that also releases
* the single write lock. A call to this method will result in a write lock being obtained.
*/
public WriteTxn openWriteTxn() {
try {
LOGGER.trace("Acquiring write txn lock");
writeTxnLock.lockInterruptibly();
LOGGER.trace("Opening new write txn");
return new WriteTxn(writeTxnLock, env.txnWrite());
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted while waiting for write lock on "
+ localDir.toAbsolutePath().normalize());
}
}
/**
* @param batchSize
* @return An {@link AutoCloseable} wrapper that can provide multiple write txns all while holding
* the single write lock. Useful for large jobs that need to commit periodically but don't want to release
* the lock to avoid the risk of deadlocks.
* A call to this method will result in a write lock being obtained.
*/
public BatchingWriteTxn openBatchingWriteTxn(final int batchSize) {
try {
LOGGER.trace("Acquiring write txn lock");
writeTxnLock.lockInterruptibly();
return new BatchingWriteTxn(writeTxnLock, env::txnWrite, batchSize);
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted while waiting for write lock on "
+ localDir.toAbsolutePath().normalize());
}
}
public <T> T getWithReadTxn(final Function<Txn<ByteBuffer>, T> work) {
return (T) readTxnGetMethod.apply(work);
}
public void doWithReadTxn(final Consumer<Txn<ByteBuffer>> work) {
readTxnGetMethod.apply(txn -> {
work.accept(txn);
return null;
});
}
private <T> T getWithReadTxnUnderMaxReaderSemaphore(final Function<Txn<ByteBuffer>, T> work) {
LOGGER.trace("About to acquire permit");
try {
activeReadTransactionsSemaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread interrupted", e);
}
try {
LOGGER.trace(() ->
LogUtil.message("Permit acquired, remaining {}, queue length {}",
activeReadTransactionsSemaphore.availablePermits(),
activeReadTransactionsSemaphore.getQueueLength()));
try (final Txn<ByteBuffer> txn = env.txnRead()) {
LOGGER.trace("Performing work with read txn");
return work.apply(txn);
} catch (RuntimeException e) {
throw new RuntimeException(LogUtil.message(
"Error performing work in read transaction: {}",
e.getMessage()), e);
}
} finally {
LOGGER.trace("Releasing permit");
activeReadTransactionsSemaphore.release();
}
}
public <T> T getWithReadTxnUnderReadWriteLock(final Function<Txn<ByteBuffer>, T> work,
final Lock readLock) {
try {
LOGGER.trace("About to acquire lock");
// Wait for writers to finish
readLock.lockInterruptibly();
LOGGER.trace("Lock acquired");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread interrupted", e);
}
try {
return getWithReadTxnUnderMaxReaderSemaphore(work);
} finally {
LOGGER.trace("Releasing lock");
readLock.unlock();
}
}
@Override
public void close() {
LOGGER.debug(() -> "Closing LMDB environment at " + localDir.toAbsolutePath().normalize());
env.close();
}
/**
* Deletes {@link LmdbEnv} from the filesystem if it is already closed.
*/
public void delete() {
if (!env.isClosed()) {
throw new RuntimeException(("LMDB environment at {} is still open"));
}
LOGGER.doIfDebugEnabled(() -> {
LOGGER.debug("Deleting {} and all its contents", localDir.toAbsolutePath().normalize());
// May be useful to see the sizes of db before they are deleted
dumpMdbFileSize();
});
if (!FileUtil.deleteDir(localDir)) {
throw new RuntimeException("Unable to delete dir: " + FileUtil.getCanonicalPath(localDir));
}
}
private void dumpMdbFileSize() {
if (Files.isDirectory(localDir)) {
try (Stream<Path> stream = Files.list(localDir)) {
stream
.filter(path ->
!Files.isDirectory(path))
.filter(file ->
file.toString().toLowerCase().endsWith("data.mdb"))
.map(file -> {
try {
final long fileSizeBytes = Files.size(file);
return localDir.getFileName().resolve(file.getFileName())
+ " - file size: "
+ ModelStringUtil.formatIECByteSizeString(fileSizeBytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.forEach(LOGGER::debug);
} catch (IOException e) {
LOGGER.debug("Unable to list dir {} due to {}",
localDir.toAbsolutePath().normalize(), e.getMessage());
}
}
}
public List<String> getDbiNames() {
return env.getDbiNames().stream()
.map(bytes ->
new String(bytes, StandardCharsets.UTF_8))
.collect(Collectors.toList());
}
public int getMaxKeySize() {
return env.getMaxKeySize();
}
public EnvInfo info() {
return env.info();
}
public boolean isClosed() {
return env.isClosed();
}
public Stat stat() {
return env.stat();
}
public Map<String, String> getEnvInfo() {
return getWithReadTxn(txn -> {
final Map<String, String> statMap = convertStatToMap(env.stat());
final Map<String, String> envInfo = convertEnvInfoToMap(env.info());
final String dbNames = String.join(",", getDbiNames());
return ImmutableMap.<String, String>builder()
.putAll(statMap)
.putAll(envInfo)
.put("maxKeySize", Integer.toString(env.getMaxKeySize()))
.put("dbNames", dbNames)
.build();
});
}
public Map<String, String> getDbInfo(final Dbi<ByteBuffer> db) {
return getWithReadTxn(txn -> {
final Stat stat = db.stat(txn);
return convertStatToMap(stat);
});
}
private static ImmutableMap<String, String> convertStatToMap(final Stat stat) {
return ImmutableMap.<String, String>builder()
.put("pageSize", Integer.toString(stat.pageSize))
.put("branchPages", Long.toString(stat.branchPages))
.put("depth", Integer.toString(stat.depth))
.put("entries", Long.toString(stat.entries))
.put("leafPages", Long.toString(stat.leafPages))
.put("overFlowPages", Long.toString(stat.overflowPages))
.build();
}
private static ImmutableMap<String, String> convertEnvInfoToMap(final EnvInfo envInfo) {
return ImmutableMap.<String, String>builder()
.put("maxReaders", Integer.toString(envInfo.maxReaders))
.put("numReaders", Integer.toString(envInfo.numReaders))
.put("lastPageNumber", Long.toString(envInfo.lastPageNumber))
.put("lastTransactionId", Long.toString(envInfo.lastTransactionId))
.put("mapAddress", Long.toString(envInfo.mapAddress))
.put("mapSize", Long.toString(envInfo.mapSize))
.build();
}
@NotThreadSafe
public static class WriteTxn implements AutoCloseable {
private final Lock writeLock;
private Txn<ByteBuffer> writeTxn;
/**
* @param writeLock Should already be held by this thread.
*/
private WriteTxn(final Lock writeLock,
final Txn<ByteBuffer> writeTxn) {
this.writeLock = writeLock;
this.writeTxn = writeTxn;
}
/**
* @return The write txn object. Do NOT call close() on the returned txn,
* use {@link WriteTxn#close()} or a try-with-resources block.
*/
public Txn<ByteBuffer> getTxn() {
Objects.requireNonNull(writeTxn, "Transaction is closed");
return writeTxn;
}
/**
* {@link Txn#abort()}
*/
public void abort() {
writeTxn.abort();
}
/**
* {@link Txn#commit()}
*/
public void commit() {
writeTxn.commit();
}
/**
* Closes the txn and releases the single write lock
*/
@Override
public void close() throws Exception {
Objects.requireNonNull(writeTxn, "Transaction has already been closed");
try {
writeTxn.close();
} finally {
writeLock.unlock();
writeTxn = null;
}
}
}
/**
* Creates a write txn on calls to {@link BatchingWriteTxn#getTxn()}
*/
@NotThreadSafe
public static class BatchingWriteTxn implements AutoCloseable {
private final Lock writeLock;
private Supplier<Txn<ByteBuffer>> writeTxnSupplier;
private Txn<ByteBuffer> writeTxn;
private final int maxBatchSize;
private int batchCounter = 0;
private final BooleanSupplier commitFunc;
/**
* @param writeLock Should already be held by this thread.
* @param maxBatchSize
*/
private BatchingWriteTxn(final Lock writeLock,
final Supplier<Txn<ByteBuffer>> writeTxnSupplier,
final int maxBatchSize) {
this.writeLock = writeLock;
this.writeTxnSupplier = writeTxnSupplier;
this.maxBatchSize = maxBatchSize == 0
? Integer.MAX_VALUE
: maxBatchSize;
if (maxBatchSize == 0) {
commitFunc = () -> {
// a max batch size of zero means don't commit
return false;
};
} else {
commitFunc = this::commitWithBatchCheck;
}
}
/**
* @return The write txn object. Do NOT call close() on the returned txn,
* use {@link WriteTxn#close()} or a try-with-resources block.
*/
public Txn<ByteBuffer> getTxn() {
if (writeTxn == null) {
Objects.requireNonNull(writeTxnSupplier, "Has already been closed");
writeTxn = writeTxnSupplier.get();
}
return writeTxn;
}
/**
* {@link Txn#abort()}
*/
public void abort() {
if (writeTxn != null) {
writeTxn.abort();
writeTxn = null;
}
}
/**
* Increment the count of items processed in the batch
*
* @return True if the batch is full, false if not.
*/
public boolean incrementBatchCount() {
return (++batchCounter >= maxBatchSize);
}
/**
* Force a commit regardless of batch size
* {@link Txn#commit()}
*/
public boolean commit() {
if (writeTxn != null) {
LOGGER.trace("Committing txn with batchCounter: {}", batchCounter);
writeTxn.commit();
writeTxn.close();
writeTxn = null;
batchCounter = 0;
return true;
} else {
return false;
}
}
/**
* Commit if the batch has reach its max size
*/
public boolean commitIfRequired() {
return commitFunc.getAsBoolean();
}
private boolean commitWithBatchCheck() {
if (++batchCounter >= maxBatchSize) {
return commit();
} else {
return false;
}
}
/**
* Closes the txn and releases the single write lock
*/
@Override
public void close() {
try {
if (writeTxn != null) {
try {
writeTxn.close();
} finally {
writeTxn = null;
writeTxnSupplier = null;
}
}
} finally {
// whatever happens we must release the lock
writeLock.unlock();
}
}
@Override
public String toString() {
return "BatchingWriteTxnWrapper{" +
"maxBatchSize=" + maxBatchSize +
", batchCounter=" + batchCounter +
'}';
}
}
}
|
package org.csstudio.trends.databrowser2.waveformview;
import org.csstudio.archive.vtype.TimestampHelper;
import org.csstudio.archive.vtype.VTypeHelper;
import org.csstudio.swt.xygraph.figures.ToolbarArmedXYGraph;
import org.csstudio.swt.xygraph.figures.Trace;
import org.csstudio.swt.xygraph.figures.Trace.PointStyle;
import org.csstudio.swt.xygraph.figures.XYGraph;
import org.csstudio.swt.xygraph.figures.XYGraphFlags;
import org.csstudio.trends.databrowser2.Messages;
import org.csstudio.trends.databrowser2.editor.DataBrowserAwareView;
import org.csstudio.trends.databrowser2.model.AxisConfig;
import org.csstudio.trends.databrowser2.model.Model;
import org.csstudio.trends.databrowser2.model.ModelItem;
import org.csstudio.trends.databrowser2.model.ModelListener;
import org.csstudio.trends.databrowser2.model.PVItem;
import org.csstudio.trends.databrowser2.model.PlotSamples;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Text;
import org.epics.vtype.VType;
/** View for inspecting Waveform (Array) Samples of the current Model
* @author Kay Kasemir
* @author Takashi Nakamoto changed WaveformView to handle multiple itesm with
* the same name.
* @author Xihui Chen (Added some work around to make it work for rap).
*/
public class WaveformView extends DataBrowserAwareView
implements ModelListener
{
/** View ID registered in plugin.xml */
final public static String ID =
"org.csstudio.trends.databrowser.waveformview.WaveformView"; //$NON-NLS-1$
/** PV Name selector */
private Combo pv_name;
/** XY Graph */
private XYGraph xygraph;
/** Selector for model_item's current sample */
private Slider sample_index;
/** Timestamp of current sample. */
private Text timestamp;
/** Status/severity of current sample. */
private Text status;
/** Model of the currently active Data Browser plot or <code>null</code> */
private Model model;
/** Selected model item in model, or <code>null</code> */
private ModelItem model_item = null;
/** Color for trace of model_item's current sample */
private Color color = null;
/** Waveform for the currently selected sample */
private WaveformValueDataProvider waveform = null;
/** {@inheritDoc} */
@Override
protected void doCreatePartControl(final Composite parent)
{
// Arrange disposal
parent.addDisposeListener(new DisposeListener()
{
@Override
public void widgetDisposed(DisposeEvent e)
{
if (color != null)
color.dispose();
// Be ignorant of any change of the current model after
// this view is disposed.
if (model != null)
model.removeListener(WaveformView.this);
}
});
final GridLayout layout = new GridLayout(4, false);
parent.setLayout(layout);
// PV: .pvs..... [Refresh]
// <<<<<< Slider >>>>>>
// PV: .pvs..... [Refresh]
Label l = new Label(parent, 0);
l.setText(Messages.SampleView_Item);
l.setLayoutData(new GridData());
pv_name = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
pv_name.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns-2, 1));
pv_name.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(final SelectionEvent e)
{
widgetDefaultSelected(e);
}
@Override
public void widgetDefaultSelected(final SelectionEvent e)
{ // First item is "--select PV name--"
if (pv_name.getSelectionIndex() == 0)
selectPV(null);
else
selectPV(model.getItem(pv_name.getSelectionIndex() - 1));
}
});
final Button refresh = new Button(parent, SWT.PUSH);
refresh.setText(Messages.SampleView_Refresh);
refresh.setToolTipText(Messages.SampleView_RefreshTT);
refresh.setLayoutData(new GridData());
refresh.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(final SelectionEvent e)
{ // Trigger GUI update by switching to current model
updateModel(model, model);
}
});
//The canvas has to be wrapped in a composite so that the canvas has (0,0) coordinate.
//This is a work around for the inconsistency between figure.getBounds() and gc.getclipping().
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, layout.numColumns, 1));
composite.setLayout(new FillLayout());
//Double_BUFFERED is required to force RAP to use NativeGraphicsSource.
//By default, it uses BufferedGraphicsSource which has problem to render it in web browser.
final Canvas canvas = new Canvas(composite, SWT.DOUBLE_BUFFERED);
// Create plot with basic configuration
final LightweightSystem lws = new LightweightSystem(canvas);
final ToolbarArmedXYGraph plot =
new ToolbarArmedXYGraph(new XYGraph(), XYGraphFlags.COMBINED_ZOOM);
xygraph = plot.getXYGraph();
// Configure axes
xygraph.primaryXAxis.setTitle(Messages.WaveformIndex);
xygraph.primaryYAxis.setTitle(Messages.WaveformAmplitude);
lws.setContents(plot);
// <<<<<< Slider >>>>>>
sample_index = new Slider(parent, SWT.HORIZONTAL);
sample_index.setToolTipText(Messages.WaveformTimeSelector);
sample_index.setLayoutData(new GridData(SWT.FILL, 0, true, false, layout.numColumns, 1));
sample_index.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
showSelectedSample();
}
});
l = new Label(parent, 0);
l.setText(Messages.WaveformTimestamp);
l.setLayoutData(new GridData());
timestamp = new Text(parent, SWT.BORDER | SWT.READ_ONLY);
timestamp.setLayoutData(new GridData(SWT.FILL, 0, true, false));
l = new Label(parent, 0);
l.setText(Messages.WaveformStatus);
l.setLayoutData(new GridData());
status = new Text(parent, SWT.BORDER | SWT.READ_ONLY);
status.setLayoutData(new GridData(SWT.FILL, 0, true, false));
}
/** {@inheritDoc} */
// Remove Override annotation for RAP
// @Override
public void setFocus() {
pv_name.setFocus();
}
/** {@inheritDoc} */
@Override
protected void updateModel(final Model old_model, final Model model)
{
this.model = model;
if (old_model != model) {
if (old_model != null)
old_model.removeListener(this);
if (model != null)
model.addListener(this);
}
update(old_model != model);
}
/** Update combo box of this view.
* @param model_changed set true if the model was changed
*/
private void update(final boolean model_changed)
{
if (model == null)
{ // Clear/disable GUI
pv_name.setItems(new String[] { Messages.SampleView_NoPlot});
pv_name.select(0);
pv_name.setEnabled(false);
selectPV(null);
return;
}
// Show PV names
final String names[] = new String[model.getItemCount()+1];
names[0] = Messages.SampleView_SelectItem;
for (int i=1; i<names.length; ++i)
names[i] = model.getItem(i-1).getName();
if (!model_changed && pv_name.getSelectionIndex() > 0)
{
// Is the previously selected item still valid?
if (model.indexOf(model_item) != -1)
{ // Show same PV name again in combo box
pv_name.setItems(names);
pv_name.select(model.indexOf(model_item) + 1);
pv_name.setEnabled(true);
return;
}
}
// Previously selected item no longer valid.
// Show new items, clear rest
pv_name.setItems(names);
pv_name.select(0);
pv_name.setEnabled(true);
selectPV(null);
}
/** Select given PV item (or <code>null</code>). */
private void selectPV(final ModelItem new_item)
{
if (new_item == null)
model_item = null;
else
model_item = new_item;
// Delete all existing traces
int N = xygraph.getPlotArea().getTraceList().size();
while (N > 0)
xygraph.removeTrace(xygraph.getPlotArea().getTraceList().get(--N));
// No or unknown PV name?
if (model_item == null)
{
pv_name.setText(""); //$NON-NLS-1$
sample_index.setEnabled(false);
return;
}
// Prepare to show waveforms of model item in plot
waveform = new WaveformValueDataProvider();
// Create trace for waveform
final Trace trace = new Trace(model_item.getDisplayName(),
xygraph.primaryXAxis, xygraph.primaryYAxis, waveform);
// Configure color, ...
final Color old_color = color;
color = new Color(pv_name.getDisplay(), model_item.getColor());
trace.setTraceColor(color);
trace.setLineWidth(model_item.getLineWidth());
trace.setPointStyle(PointStyle.POINT);
trace.setPointSize(5);
// Add to graph
xygraph.addTrace(trace);
// Dispose previous color
if (old_color != null)
old_color.dispose();
// Enable waveform selection and update slider's range
sample_index.setEnabled(true);
showSelectedSample();
}
/** Show the current sample of the current model item. */
private void showSelectedSample()
{
// Get selected sample (= one waveform)
final PlotSamples samples = model_item.getSamples();
final VType value;
synchronized (samples)
{
sample_index.setMaximum(samples.getSize());
final int idx = sample_index.getSelection();
value = samples.getSample(idx).getValue();
}
waveform.setValue(value);
if (value == null)
clearInfo();
else
{
timestamp.setText(TimestampHelper.format(VTypeHelper.getTimestamp(value)));
status.setText(NLS.bind(Messages.SeverityStatusFmt, VTypeHelper.getSeverity(value).toString(), VTypeHelper.getMessage(value)));
}
}
/** Clear all the info fields. */
private void clearInfo()
{
timestamp.setText(""); //$NON-NLS-1$
status.setText(""); //$NON-NLS-1$
}
/** {@inheritDoc} */
@Override
public void itemAdded(ModelItem item) {
// Be aware of the addition of a new item to update combo box.
update(false);
}
/** {@inheritDoc} */
@Override
public void itemRemoved(ModelItem item) {
// Be aware of the addition of a new item to update combo box.
update(false);
}
/** {@inheritDoc} */
@Override
public void changedItemLook(ModelItem item) {
// Be aware of the change of the item name.
update(false);
}
/** {@inheritDoc} */
@Override
public void changedColors() {
// Be aware of the change of the item color.
// TODO: this update does not trigger color change. Fix it.
update(false);
}
// Following methods are defined as they are mandatory to fulfill
// ModelListener interface, but they are not used at all to update
// this sample view.
@Override
public void changedUpdatePeriod() {}
@Override
public void changedArchiveRescale() {}
@Override
public void changedTimerange() {}
@Override
public void changedAxis(AxisConfig axis) {}
@Override
public void changedItemVisibility(ModelItem item) {}
@Override
public void changedItemDataConfig(PVItem item) {}
@Override
public void scrollEnabled(boolean scroll_enabled) {}
@Override
public void changedAnnotations() {}
@Override
public void changedXYGraphConfig() {}
}
|
package peergos.shared.user.fs;
import java.nio.file.*;
import java.util.logging.*;
import jsinterop.annotations.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.inode.*;
import peergos.shared.storage.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.cryptree.*;
import peergos.shared.user.fs.transaction.*;
import peergos.shared.util.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.AlphaComposite;
import java.awt.RenderingHints;
import java.io.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.stream.*;
/** This class is used to read and modify files and directories and represents a single file or directory and the keys
* to access it.
*
*/
public class FileWrapper {
private static final Logger LOG = Logger.getGlobal();
private final static int THUMBNAIL_SIZE = 100;
private static final NativeJSThumbnail thumbnail = new NativeJSThumbnail();
private final RetrievedCapability pointer;
private final Optional<RetrievedCapability> linkPointer;
private final Optional<SigningPrivateKeyAndPublicHash> entryWriter;
private final FileProperties props;
private final String ownername;
private final Optional<TrieNode> capTrie;
public final Snapshot version;
private final boolean isWritable;
private AtomicBoolean modified = new AtomicBoolean(); // This only used as a guard against concurrent modifications
/**
*
* @param capTrie This is only present if this is the global root, or this is read only
* @param pointer
* @param ownername
*/
public FileWrapper(Optional<TrieNode> capTrie,
RetrievedCapability pointer,
Optional<RetrievedCapability> linkPointer,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
String ownername,
Snapshot version) {
this.capTrie = capTrie;
this.pointer = pointer;
this.linkPointer = linkPointer;
this.entryWriter = entryWriter;
this.ownername = ownername;
this.version = version;
this.isWritable = pointer != null &&
pointer.capability instanceof WritableAbsoluteCapability ||
entryWriter.map(s -> s.publicKeyHash.equals(pointer.capability.writer)).orElse(false);
if (pointer == null)
props = new FileProperties("/", true, false, "", 0, LocalDateTime.MIN, false, Optional.empty(), Optional.empty());
else {
SymmetricKey parentKey = this.getParentKey();
FileProperties directProps = pointer.fileAccess.getProperties(parentKey);
if (linkPointer.isPresent()) {
RetrievedCapability link = linkPointer.get();
FileProperties linkProps = link.getProperties();
this.props = directProps.withLink(linkProps);
} else {
this.props = directProps;
}
}
if (isWritable() && !signingPair().publicKeyHash.equals(pointer.capability.writer))
throw new IllegalStateException("Invalid FileWrapper! public writing keys don't match!");
}
public FileWrapper(RetrievedCapability pointer,
Optional<RetrievedCapability> linkPointer,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
String ownername,
Snapshot version) {
this(Optional.empty(), pointer, linkPointer, entryWriter, ownername, version);
}
public FileWrapper withTrieNode(TrieNode trie) {
return new FileWrapper(Optional.of(trie), pointer, linkPointer, entryWriter, ownername, version);
}
public FileWrapper withTrieNodeOpt(Optional<TrieNode> trie) {
return new FileWrapper(trie, pointer, linkPointer, entryWriter, ownername, version);
}
public FileWrapper withLinkPointer(Optional<RetrievedCapability> link) {
return new FileWrapper(capTrie, pointer, link, entryWriter, ownername, version);
}
public FileWrapper withVersion(Snapshot version) {
return new FileWrapper(capTrie, pointer, linkPointer, entryWriter, ownername, version);
}
public CommittedWriterData getVersionRoot() {
return version.get(writer());
}
@JsMethod
public CompletableFuture<FileWrapper> getLatest(NetworkAccess network) {
return network.synchronizer.getValue(owner(), writer())
.thenCompose(latest -> getUpdated(latest, network));
}
@JsMethod
public boolean equals(Object other) {
if (other == null)
return false;
if (!(other instanceof FileWrapper))
return false;
return pointer.equals(((FileWrapper) other).getPointer());
}
public CompletableFuture<FileWrapper> getUpdated(NetworkAccess network) {
return network.synchronizer.getValue(owner(), writer())
.thenCompose(v -> getUpdated(v, network));
}
public CompletableFuture<FileWrapper> getUpdated(Snapshot version, NetworkAccess network) {
if (this.version.get(writer()).equals(version.get(writer())))
return CompletableFuture.completedFuture(this);
return network.getFile(version, pointer.capability, entryWriter, ownername)
.thenApply(Optional::get)
.thenApply(f -> f.withTrieNodeOpt(capTrie));
}
public PublicKeyHash owner() {
try {
return pointer.capability.owner;
} catch (Exception e) {
System.out.println();
throw e;
}
}
public PublicKeyHash writer() {
return pointer.capability.writer;
}
public RetrievedCapability getPointer() {
return pointer;
}
public RetrievedCapability getLinkPointer() {
return linkPointer.get();
}
public boolean isRoot() {
return props.name.equals("/");
}
public CompletableFuture<String> getPath(NetworkAccess network) {
return retrieveParent(network).thenCompose(parent -> {
if (!parent.isPresent() || parent.get().isRoot())
return CompletableFuture.completedFuture("/" + props.name);
return parent.get().getPath(network).thenApply(parentPath -> parentPath + "/" + props.name);
});
}
public CompletableFuture<Optional<FileWrapper>> getDescendentByPath(String path,
Hasher hasher,
NetworkAccess network) {
return getDescendentByPath(path, version, hasher, network);
}
public CompletableFuture<Optional<FileWrapper>> getDescendentByPath(String path,
Snapshot version,
Hasher hasher,
NetworkAccess network) {
ensureUnmodified();
if (path.length() == 0)
return CompletableFuture.completedFuture(Optional.of(this));
if (path.equals("/"))
if (isDirectory())
return CompletableFuture.completedFuture(Optional.of(this));
else
return CompletableFuture.completedFuture(Optional.empty());
if (path.startsWith("/"))
path = path.substring(1);
int slash = path.indexOf("/");
String prefix = slash > 0 ? path.substring(0, slash) : path;
String suffix = slash > 0 ? path.substring(slash + 1) : "";
return getChild(version, prefix, hasher, network).thenCompose(child -> {
if (child.isPresent())
return child.get().getDescendentByPath(suffix, child.get().version, hasher, network);
return CompletableFuture.completedFuture(Optional.empty());
});
}
private void ensureUnmodified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
}
private void setModified() {
if (modified.get())
throw new IllegalStateException("This file has already been modified, use the returned instance");
modified.set(true);
}
public CompletableFuture<Snapshot> updateChildLinks(
Snapshot version,
Committer committer,
Collection<Pair<AbsoluteCapability, NamedAbsoluteCapability>> childCases,
NetworkAccess network,
SafeRandom random,
Hasher hasher) {
return pointer.fileAccess
.updateChildLinks(version, committer, (WritableAbsoluteCapability) pointer.capability, signingPair(),
childCases, network, hasher);
}
public CompletableFuture<Boolean> hasChildWithName(Snapshot version, String name, Hasher hasher, NetworkAccess network) {
ensureUnmodified();
return getChildren(version, hasher, network)
.thenApply(children -> children.stream().anyMatch(c -> c.props.name.equals(name)));
}
/**
*
* @param child
* @param network
* @return Updated version of this directory without the child
*/
public CompletableFuture<FileWrapper> removeChild(FileWrapper child, NetworkAccess network, Hasher hasher) {
setModified();
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(cwd, committer) -> pointer.fileAccess
.removeChildren(cwd, committer, Arrays.asList(child.getPointer().capability), writableFilePointer(), entryWriter, network, hasher))
.thenCompose(newRoot -> getUpdated(newRoot, network));
}
public CompletableFuture<Snapshot> removeChild(Snapshot version,
Committer committer,
FileWrapper child,
NetworkAccess network,
Hasher hasher) {
return pointer.fileAccess.removeChildren(version, committer,
Arrays.asList(child.getPointer().capability), writableFilePointer(), entryWriter, network, hasher);
}
@JsMethod
public String toLink() {
return pointer.capability.readOnly().toLink();
}
@JsMethod
public String toWritableLink() {
if (! isWritable())
throw new IllegalStateException("You do not have write access to " + getName());
return pointer.capability.toLink();
}
@JsMethod
public boolean isWritable() {
return isWritable;
}
@JsMethod
public boolean isReadable() {
return pointer.fileAccess.isReadable(pointer.capability.rBaseKey);
}
public SymmetricKey getKey() {
return pointer.capability.rBaseKey;
}
public Location getLocation() {
return new Location(pointer.capability.owner, pointer.capability.writer, pointer.capability.getMapKey());
}
public CompletableFuture<Set<NamedAbsoluteCapability>> getChildrenCapabilities(Hasher hasher, NetworkAccess network) {
ensureUnmodified();
if (!this.isDirectory())
return CompletableFuture.completedFuture(Collections.emptySet());
return pointer.fileAccess.getAllChildrenCapabilities(version, pointer.capability, hasher, network);
}
public CompletableFuture<Optional<FileWrapper>> retrieveParent(NetworkAccess network) {
ensureUnmodified();
return retrieveParent(linkPointer.orElse(pointer), ownername, version, network);
}
public CompletableFuture<Optional<RetrievedCapability>> getAnyLinkPointer(NetworkAccess network) {
if (pointer == null)
return CompletableFuture.completedFuture(Optional.empty());
AbsoluteCapability cap = pointer.capability;
CompletableFuture<RetrievedCapability> parent = pointer.fileAccess.getParent(cap.owner, cap.writer, cap.rBaseKey, network, version);
return parent.thenApply(parentRFP -> {
if (parentRFP == null)
return Optional.empty();
FileProperties parentProps = parentRFP.getProperties();
if (! parentProps.isLink)
return Optional.empty();
return Optional.of(parentRFP);
});
}
public static CompletableFuture<Optional<FileWrapper>> retrieveParent(RetrievedCapability pointer,
String ownerName,
Snapshot version,
NetworkAccess network) {
if (pointer == null)
return CompletableFuture.completedFuture(Optional.empty());
AbsoluteCapability cap = pointer.capability;
CompletableFuture<RetrievedCapability> parent = pointer.fileAccess.getParent(cap.owner, cap.writer, cap.rBaseKey, network, version);
return parent.thenCompose(parentRFP -> {
if (parentRFP == null)
return Futures.of(Optional.empty());
FileProperties parentProps = parentRFP.getProperties();
if (! parentProps.isLink)
return Futures.of(Optional.of(new FileWrapper(parentRFP, Optional.empty(), Optional.empty(), ownerName, version)));
return retrieveParent(parentRFP, ownerName, version, network);
});
}
@JsMethod
public boolean isUserRoot() {
if (pointer == null)
return false;
return ! pointer.fileAccess.hasParentLink(pointer.capability.rBaseKey);
}
public SymmetricKey getParentKey() {
return pointer.getParentKey();
}
private Optional<SigningPrivateKeyAndPublicHash> getChildsEntryWriter() {
return pointer.capability.wBaseKey
.map(wBase -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, wBase, entryWriter));
}
@JsMethod
public CompletableFuture<Set<FileWrapper>> getChildren(Hasher hasher, NetworkAccess network) {
if (capTrie.isPresent())
return capTrie.get().getChildren("/", hasher, network);
return getChildren(version, hasher, network);
}
public CompletableFuture<Set<FileWrapper>> getChildren(Snapshot version, Hasher hasher, NetworkAccess network) {
return getChildren(version, false, hasher, network);
}
public CompletableFuture<Set<FileWrapper>> getChildrenWithSameWriter(Hasher hasher, NetworkAccess network) {
return getChildren(version, true, hasher, network);
}
public CompletableFuture<Set<FileWrapper>> getChildren(Snapshot version, boolean sameWriterOnly, Hasher hasher, NetworkAccess network) {
if (capTrie.isPresent())
return capTrie.get().getChildren("/", hasher, version.merge(this.version), network);
if (isReadable()) {
Optional<SigningPrivateKeyAndPublicHash> childsEntryWriter = pointer.capability.wBaseKey
.map(wBase -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, wBase, entryWriter));
return pointer.fileAccess.getAllChildrenCapabilities(version, pointer.capability, hasher, network)
.thenCompose(childCaps -> sameWriterOnly ?
getFilesWithSameWriter(owner(), childCaps, childsEntryWriter, ownername, network, version) :
getFiles(owner(), childCaps, childsEntryWriter, ownername, network, version)
);
}
throw new IllegalStateException("Unreadable FileWrapper!");
}
private static CompletableFuture<Set<FileWrapper>> getFiles(PublicKeyHash owner,
Set<NamedAbsoluteCapability> caps,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
String ownername,
NetworkAccess network,
Snapshot version) {
Set<PublicKeyHash> childWriters = caps.stream()
.map(c -> c.cap.writer)
.collect(Collectors.toSet());
return version.withWriters(owner, childWriters, network)
.thenCompose(fullVersion -> network.retrieveAllMetadata(caps.stream().map(n -> n.cap).collect(Collectors.toList()), fullVersion)
.thenCompose(rcs -> Futures.combineAll(rcs.stream()
.map(rc -> {
FileProperties props = rc.getProperties();
if (! props.isLink)
return Futures.of(new FileWrapper(rc, Optional.empty(), entryWriter, ownername, fullVersion));
return NetworkAccess.getFileFromLink(owner, rc, entryWriter, ownername, network, version);
})
.collect(Collectors.toSet()))));
}
private static CompletableFuture<Set<FileWrapper>> getFilesWithSameWriter(PublicKeyHash owner,
Set<NamedAbsoluteCapability> caps,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
String ownername,
NetworkAccess network,
Snapshot version) {
Set<PublicKeyHash> childWriters = caps.stream()
.map(c -> c.cap.writer)
.collect(Collectors.toSet());
return version.withWriters(owner, childWriters, network)
.thenCompose(fullVersion -> network.retrieveAllMetadata(caps.stream().map(n -> n.cap).collect(Collectors.toList()), fullVersion)
.thenCompose(rcs -> Futures.combineAll(rcs.stream()
.filter(rc -> ! rc.getProperties().isLink)
.map(rc -> Futures.of(new FileWrapper(rc, Optional.empty(), entryWriter, ownername, fullVersion)))
.collect(Collectors.toSet()))));
}
@JsMethod
public CompletableFuture<Optional<FileWrapper>> getChild(String name, Hasher hasher, NetworkAccess network) {
return getChild(version, name, hasher, network);
}
public CompletableFuture<Optional<FileWrapper>> getChild(Snapshot version,
String name,
Hasher hasher,
NetworkAccess network) {
if (capTrie.isPresent())
return capTrie.get().getByPath("/" + name, version.merge(this.version), hasher, network);
return pointer.fileAccess.getChild(name, pointer.capability, version, hasher, network)
.thenCompose(rcOpt -> {
if (rcOpt.isEmpty())
return Futures.of(Optional.empty());
RetrievedCapability rc = rcOpt.get();
FileProperties props = rc.getProperties();
Optional<SigningPrivateKeyAndPublicHash> childsEntryWriter = pointer.capability.wBaseKey
.map(wBase -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, wBase, entryWriter));
if (! props.isLink)
return Futures.of(Optional.of(new FileWrapper(rc, Optional.empty(), childsEntryWriter, ownername, version)));
return version.withWriter(owner(), rc.capability.writer, network)
.thenCompose(fullVersion ->
NetworkAccess.getFileFromLink(owner(), rc, childsEntryWriter, ownername, network, fullVersion)
.thenApply(Optional::of));
});
}
@JsMethod
public String getOwnerName() {
return ownername;
}
@JsMethod
public boolean isDirectory() {
boolean isNull = pointer == null;
return isNull || pointer.fileAccess.isDirectory();
}
public boolean isLink() {
return linkPointer.isPresent();
}
public boolean isDirty() {
ensureUnmodified();
return pointer.fileAccess.isDirty(pointer.capability.rBaseKey);
}
/**
*
* @param current
* @param committer
* @param network
* @param crypto
* @return updated cleaned version
*/
public CompletableFuture<Pair<FileWrapper, Snapshot>> clean(Snapshot current,
Committer committer,
NetworkAccess network,
Crypto crypto) {
if (!isDirty())
return CompletableFuture.completedFuture(new Pair<>(this, current));
if (isDirectory()) {
throw new IllegalStateException("Directories are never dirty (they are cleaned immediately)!");
} else {
WritableAbsoluteCapability currentCap = writableFilePointer();
boolean isLink = isLink();
Optional<RelativeCapability> parentCap = pointer.fileAccess.getParentCapability(pointer.capability.rBaseKey);
Location parentOrLinkLocation = isLink ?
linkPointer.get().capability.getLocation() :
parentCap.get().getLocation(owner(), writer());
SymmetricKey parentOrLinkParentKey = isLink ?
linkPointer.get().getParentKey() :
parentCap.get().rBaseKey;
return pointer.fileAccess.cleanAndCommit(current, committer, currentCap, currentCap, props.streamSecret,
Optional.empty(), signingPair(), SymmetricKey.random(),
parentOrLinkLocation, parentOrLinkParentKey, network, crypto)
.thenCompose(cwd -> {
setModified();
return getUpdated(cwd, network).thenApply(updated -> new Pair<>(updated, cwd));
});
}
}
public CompletableFuture<byte[]> getMapKey(long offset, NetworkAccess network, Crypto crypto) {
CryptreeNode fileAccess = pointer.fileAccess;
return fileAccess.retriever(pointer.capability.rBaseKey, props.streamSecret, getLocation().getMapKey(), crypto.hasher)
.thenCompose(retriever -> retriever
.getMapLabelAt(version.get(writer()).props, writableFilePointer(),
getFileProperties().streamSecret, offset, crypto.hasher, network)
.thenApply(Optional::get));
}
@JsMethod
public CompletableFuture<FileWrapper> truncate(long newSize, NetworkAccess network, Crypto crypto) {
return network.synchronizer.applyComplexUpdate(owner(), signingPair(), (current, committer) ->
truncate(current, committer, newSize, network, crypto)
).thenCompose(finished -> getUpdated(finished, network));
}
public CompletableFuture<Snapshot> truncate(Snapshot initialVersion, Committer committer, long newSize, NetworkAccess network, Crypto crypto) {
if (isDirectory())
return Futures.errored(new IllegalStateException("You cannot truncate a directory!"));
FileProperties props = getFileProperties();
if (props.size <= newSize)
return CompletableFuture.completedFuture(initialVersion);
return initialVersion.withWriter(owner(), writer(), network)
.thenCompose(snapshot -> getMapKey(newSize, network, crypto).thenCompose(endMapKey ->
getInputStream(snapshot.get(writer()).props, network, crypto, props.size, x -> {}).thenCompose(originalReader -> {
long startOfLastChunk = newSize - (newSize % Chunk.MAX_SIZE);
return originalReader.seek(startOfLastChunk).thenCompose(seekedOriginal -> {
byte[] lastChunk = new byte[(int)(newSize % Chunk.MAX_SIZE)];
return seekedOriginal.readIntoArray(lastChunk, 0, lastChunk.length).thenCompose(read -> {
if (newSize <= Chunk.MAX_SIZE)
return CompletableFuture.completedFuture(snapshot);
return IpfsTransaction.call(owner(), tid ->
deleteAllChunks(writableFilePointer().withMapKey(endMapKey),
signingPair(), tid, crypto.hasher, network, snapshot, committer),
network.dhtClient);
}).thenCompose(deleted -> pointer.fileAccess.updateProperties(deleted, committer, writableFilePointer(),
entryWriter, props.withSize(startOfLastChunk), network).thenCompose(resized ->
getUpdated(resized, network).thenCompose(f -> f.clean(resized, committer, network, crypto)
.thenCompose(p -> p.left.overwriteSection(p.right, committer,
AsyncReader.build(lastChunk), startOfLastChunk, newSize, network, crypto, x -> {})))));
});
}))
);
}
public static int getNumberOfChunks(long size) {
if (size == 0)
return 1;
return (int)((size + Chunk.MAX_SIZE - 1)/Chunk.MAX_SIZE);
}
public List<Location> generateChildLocationsFromSize(long fileSize, SafeRandom random) {
return generateChildLocations(getNumberOfChunks(fileSize), random);
}
public List<Location> generateChildLocations(int numberOfChunks,
SafeRandom random) {
return IntStream.range(0, numberOfChunks + 1) //have to have one extra location
.mapToObj(e -> new Location(owner(), writer(), random.randomBytes(32)))
.collect(Collectors.toList());
}
@JsMethod
public CompletableFuture<FileWrapper> uploadFileJS(String filename,
AsyncReader fileData,
int lengthHi,
int lengthLow,
boolean overwriteExisting,
boolean truncateExisting,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor,
TransactionService transactions) {
long fileSize = LongUtil.intsToLong(lengthHi, lengthLow);
if (transactions == null) // we are in a public writable link
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(s, committer) -> uploadFileSection(s, committer, filename, fileData,
false, 0, fileSize, Optional.empty(), overwriteExisting, truncateExisting,
network, crypto, monitor, crypto.random.randomBytes(32))
).thenCompose(finished -> getUpdated(finished, network));
return getPath(network).thenCompose(path ->
Transaction.buildFileUploadTransaction(Paths.get(path).resolve(filename).toString(), fileSize, fileData, signingPair(),
generateChildLocationsFromSize(fileSize, crypto.random)))
.thenCompose(txn -> network.synchronizer.applyComplexUpdate(owner(), transactions.getSigner(),
(s, committer) -> transactions.open(s, committer, txn).thenCompose(v -> fileData.reset()
.thenCompose(reset -> uploadFileSection(v, committer, filename, reset,
false, 0, fileSize, Optional.empty(), overwriteExisting, truncateExisting,
network, crypto, monitor, txn.getLocations().get(0).getMapKey()))
.thenCompose(uploaded -> transactions.close(uploaded, committer, txn))
))
.exceptionally(t -> {
// clean up after failed upload
network.synchronizer.applyComplexUpdate(owner(), transactions.getSigner(),
(s, committer) -> transactions.close(s, committer, txn));
throw new RuntimeException(t);
})
).thenCompose(finished -> getUpdated(finished, network));
}
public CompletableFuture<FileWrapper> uploadOrReplaceFile(String filename,
AsyncReader fileData,
long length,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor,
byte[] firstChunkMapKey) {
return uploadFileSection(filename, fileData, false, 0, length, Optional.empty(),
true, network, crypto, monitor, firstChunkMapKey)
.thenCompose(f -> f.getChild(filename, crypto.hasher, network)
.thenCompose(childOpt -> childOpt.get().truncate(length, network, crypto))
.thenCompose(c -> f.getUpdated(f.version.mergeAndOverwriteWith(c.version), network)));
}
public CompletableFuture<FileWrapper> uploadAndReturnFile(String filename,
AsyncReader fileData,
long length,
boolean isHidden,
NetworkAccess network,
Crypto crypto) {
return uploadFileSection(filename, fileData, isHidden, 0, length, Optional.empty(),
true, network, crypto, x -> {}, crypto.random.randomBytes(32))
.thenCompose(f -> f.getChild(filename, crypto.hasher, network)
.thenCompose(childOpt -> childOpt.get().truncate(length, network, crypto)));
}
@JsMethod
public CompletableFuture<FileWrapper> overwriteFileJS(AsyncReader fileData,
int endHigh,
int endLow,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
long newSize = LongUtil.intsToLong(endHigh, endLow);
return overwriteFile(fileData, newSize, network, crypto, monitor);
}
public CompletableFuture<FileWrapper> overwriteFile(AsyncReader fileData,
long newSize,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
long size = getSize();
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(s, committer) -> clean(s, committer, network, crypto)
.thenCompose(u -> u.left.overwriteSection(u.right, committer, fileData,
0L, newSize, network, crypto, monitor))
.thenCompose(v -> newSize >= size ?
Futures.of(v) :
getUpdated(v, network)
.thenCompose(f -> f.truncate(v, committer, newSize, network, crypto)))
).thenCompose(v -> getUpdated(v, network));
}
@JsMethod
public CompletableFuture<FileWrapper> overwriteSectionJS(AsyncReader fileData,
int startHigh,
int startLow,
int endHigh,
int endLow,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(s, committer) -> overwriteSection(s, committer, fileData,
LongUtil.intsToLong(startHigh, startLow),
LongUtil.intsToLong(endHigh, endLow), network, crypto, monitor))
.thenCompose(v -> getUpdated(v, network));
}
public CompletableFuture<Snapshot> overwriteSection(Snapshot current,
Committer committer,
AsyncReader fileData,
long inputStartIndex,
long endIndex,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
if (! isWritable())
return Futures.errored(new IllegalStateException("Unable to modify file without write access!"));
if (isDirty())
return Futures.errored(new IllegalStateException("File needs cleaning before modification."));
FileProperties props = getFileProperties();
String filename = props.name;
LOG.info("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of: " + filename);
Supplier<Location> legacyLocs = () -> new Location(getLocation().owner, getLocation().writer, crypto.random.randomBytes(32));
SymmetricKey parentParentKey = getPointer().getParentParentKey();
Location parentLocation = getPointer().getParentCap().getLocation(owner(), writer());
WritableAbsoluteCapability ourCap = writableFilePointer();
return current.withWriter(owner(), writer(), network)
.thenCompose(base -> {
FileWrapper us = this;
final AtomicLong filesSize = new AtomicLong(props.size);
return us.getRetriever(crypto.hasher).thenCompose(retriever -> {
SymmetricKey baseKey = us.pointer.capability.rBaseKey;
CryptreeNode fileAccess = us.pointer.fileAccess;
SymmetricKey dataKey = fileAccess.getDataKey(baseKey);
List<Long> startIndexes = new ArrayList<>();
for (long startIndex = inputStartIndex; startIndex < endIndex; startIndex = startIndex + Chunk.MAX_SIZE - (startIndex % Chunk.MAX_SIZE))
startIndexes.add(startIndex);
BiFunction<Snapshot, Long, CompletableFuture<Snapshot>> composer = (version, startIndex) -> {
MaybeMultihash currentHash = us.pointer.fileAccess.committedHash();
return retriever.getChunk(version.get(us.writer()).props, network, crypto, startIndex,
filesSize.get(), ourCap, props.streamSecret, currentHash, monitor)
.thenCompose(currentLocation -> {
CompletableFuture<Optional<Location>> locationAt = retriever
.getMapLabelAt(version.get(us.writer()).props, ourCap,
props.streamSecret, startIndex + Chunk.MAX_SIZE, crypto.hasher, network)
.thenApply(x -> x.map(m -> getLocation().withMapKey(m)));
return locationAt.thenCompose(location ->
CompletableFuture.completedFuture(new Pair<>(currentLocation, location)));
}
).thenCompose(pair -> {
if (!pair.left.isPresent()) {
CompletableFuture<Snapshot> result = new CompletableFuture<>();
result.completeExceptionally(new IllegalStateException("Current chunk not present"));
return result;
}
LocatedChunk currentOriginal = pair.left.get();
Optional<Location> nextChunkLocationOpt = pair.right;
CompletableFuture<Location> nextChunkLocationFut = nextChunkLocationOpt
.map(Futures::of)
.orElseGet(() -> props.streamSecret
.map(streamSecret -> FileProperties.calculateNextMapKey(streamSecret,
currentOriginal.location.getMapKey(), crypto.hasher)
.thenApply(nextMapKey -> us.getLocation().withMapKey(nextMapKey)))
.orElseGet(() -> Futures.of(legacyLocs.get())));
return nextChunkLocationFut.thenCompose(nextChunkLocation -> {
LOG.info("********** Writing to chunk at mapkey: " + ArrayOps.bytesToHex(currentOriginal.location.getMapKey()) + " next: " + nextChunkLocation);
// modify chunk, re-encrypt and upload
int internalStart = (int) (startIndex % Chunk.MAX_SIZE);
int internalEnd = endIndex - (startIndex - internalStart) > Chunk.MAX_SIZE ?
Chunk.MAX_SIZE : (int) (endIndex - (startIndex - internalStart));
byte[] rawData = currentOriginal.chunk.data();
// extend data array if necessary
if (rawData.length < internalEnd)
rawData = Arrays.copyOfRange(rawData, 0, internalEnd);
byte[] raw = rawData;
Optional<SymmetricLinkToSigner> writerLink = startIndex < Chunk.MAX_SIZE ?
us.pointer.fileAccess.getWriterLink(us.pointer.capability.rBaseKey) :
Optional.empty();
return fileData.readIntoArray(raw, internalStart, internalEnd - internalStart).thenCompose(read -> {
Chunk updated = new Chunk(raw, dataKey, currentOriginal.location.getMapKey(), dataKey.createNonce());
LocatedChunk located = new LocatedChunk(currentOriginal.location, currentOriginal.existingHash, updated);
long currentSize = filesSize.get();
FileProperties newProps = new FileProperties(props.name, false,
props.isLink, props.mimeType,
endIndex > currentSize ? endIndex : currentSize,
LocalDateTime.now(), props.isHidden,
props.thumbnail, props.streamSecret);
CompletableFuture<Snapshot> chunkUploaded = FileUploader.uploadChunk(version, committer, us.signingPair(),
newProps, parentLocation, parentParentKey, baseKey, located,
nextChunkLocation, writerLink, crypto.hasher, network, monitor);
return chunkUploaded.thenCompose(updatedBase -> {
//update indices to be relative to next chunk
long updatedLength = startIndex + internalEnd - internalStart;
if (updatedLength > filesSize.get()) {
filesSize.set(updatedLength);
if (updatedLength > Chunk.MAX_SIZE) {
// update file size in FileProperties of first chunk
return network.getFile(updatedBase, ourCap, entryWriter, ownername)
.thenCompose(updatedUs -> {
FileProperties correctedSize = updatedUs.get()
.getPointer().fileAccess.getProperties(ourCap.rBaseKey)
.withSize(endIndex);
return updatedUs.get()
.getPointer().fileAccess.updateProperties(updatedBase,
committer, ourCap, entryWriter, correctedSize, network);
});
}
}
return CompletableFuture.completedFuture(updatedBase);
});
});
});
});
};
return Futures.reduceAll(startIndexes, base, composer, (a, b) -> b)
.thenCompose(updatedBase -> {
// update file size
if (props.size >= endIndex)
return CompletableFuture.completedFuture(updatedBase);
WritableAbsoluteCapability cap = us.writableFilePointer();
FileProperties newProps = props.withSize(endIndex);
return network.getFile(updatedBase, cap, entryWriter, ownername)
.thenCompose(updatedChild -> updatedChild.get()
.getPointer().fileAccess.updateProperties(updatedBase, committer, cap,
entryWriter, newProps, network));
});
});
});
}
/**
*
* @param filename
* @param fileData
* @param isHidden
* @param startIndex
* @param endIndex
* @param baseKey The desired base key for the uploaded file. If absent a random key is generated.
* @param overwriteExisting
* @param network
* @param crypto
* @param monitor A way to report back progress in number of bytes of file written
* @param firstChunkMapKey The planned location for the first chunk
* @return The updated version of this directory after the upload
*/
public CompletableFuture<FileWrapper> uploadFileSection(String filename,
AsyncReader fileData,
boolean isHidden,
long startIndex,
long endIndex,
Optional<SymmetricKey> baseKey,
boolean overwriteExisting,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor,
byte[] firstChunkMapKey) {
if (isWritable())
return network.synchronizer.applyComplexUpdate(owner(), signingPair(), (current, committer) ->
uploadFileSection(current, committer, filename, fileData, isHidden, startIndex, endIndex,
baseKey, overwriteExisting, false, network, crypto, monitor, firstChunkMapKey))
.thenCompose(finalBase -> getUpdated(finalBase, network));
if (! overwriteExisting)
return Futures.errored(new IllegalStateException("Cannot upload a file to a directory without write access!"));
return getChild(filename, crypto.hasher, network)
.thenCompose(c -> {
if (! c.isPresent())
return Futures.errored(new IllegalStateException("No child with name " + filename));
FileWrapper child = c.get();
return network.synchronizer.applyComplexUpdate(owner(), child.signingPair(),
(current, committer) -> updateExistingChild(current, committer, child,
fileData, startIndex, endIndex, network, crypto, monitor))
.thenApply(this::withVersion);
});
}
private CompletableFuture<Snapshot> uploadFileSection(Snapshot intialVersion,
Committer committer,
String filename,
AsyncReader fileData,
boolean isHidden,
long startIndex,
long endIndex,
Optional<SymmetricKey> baseKey,
boolean overwriteExisting,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor,
byte[] firstChunkMapKey) {
boolean truncateExisting = false;
return uploadFileSection(intialVersion, committer, filename, fileData, isHidden, startIndex, endIndex, baseKey,
overwriteExisting, truncateExisting, network, crypto, monitor, firstChunkMapKey);
}
private CompletableFuture<Snapshot> updateSize(Committer committer,
long newSize,
NetworkAccess network) {
FileProperties newProps = getFileProperties().withSize(newSize);
return updateProperties(version, committer, newProps, network);
}
public CompletableFuture<Snapshot> uploadFileSection(Snapshot intialVersion,
Committer committer,
String filename,
AsyncReader fileData,
boolean isHidden,
long startIndex,
long endIndex,
Optional<SymmetricKey> baseKey,
boolean overwriteExisting,
boolean truncateExisting,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor,
byte[] firstChunkMapKey) {
if (!isLegalName(filename)) {
CompletableFuture<Snapshot> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Illegal filename: " + filename));
return res;
}
if (! isDirectory()) {
CompletableFuture<Snapshot> res = new CompletableFuture<>();
res.completeExceptionally(new IllegalStateException("Cannot upload a sub file to a file!"));
return res;
}
return intialVersion.withWriter(owner(), writer(), network)
.thenCompose(current -> getUpdated(current, network)
.thenCompose(latest -> latest.getChild(current, filename, crypto.hasher, network)
.thenCompose(childOpt -> {
if (childOpt.isPresent()) {
if (! overwriteExisting)
throw new IllegalStateException("File already exists with name " + filename);
FileWrapper child = childOpt.get();
FileProperties childProps = child.getFileProperties();
TriFunction<FileWrapper, Snapshot, Long, CompletableFuture<Snapshot>> updatePropsIfNecessary =
(updatedChild, latestSnapshot, writeEnd) -> {
if (childProps.thumbnail.isEmpty()) {
if (writeEnd <= childProps.size)
return Futures.of(latestSnapshot);
// update size only
return updatedChild.updateSize(committer, writeEnd, network);
}
return updatedChild.getInputStream(latestSnapshot.get(updatedChild.writer()).props, network, crypto, l -> {})
.thenCompose(is -> updatedChild.recalculateThumbnail(
latestSnapshot, committer, filename, is, isHidden,
updatedChild.getSize(), network, (WritableAbsoluteCapability)updatedChild.pointer.capability,
updatedChild.getFileProperties().streamSecret));
};
if (truncateExisting && endIndex < childProps.size) {
return child.truncate(current, committer, endIndex, network, crypto).thenCompose( updatedSnapshot ->
getUpdated(updatedSnapshot, network).thenCompose( updatedParent ->
child.getUpdated(updatedSnapshot, network).thenCompose( updatedChild ->
updateExistingChild(updatedSnapshot, committer, updatedChild, fileData,
startIndex, endIndex, network, crypto, monitor)
.thenCompose(latestSnapshot -> updatePropsIfNecessary.apply(updatedChild, latestSnapshot, endIndex)))));
} else {
return updateExistingChild(current, committer, child, fileData,
startIndex, endIndex, network, crypto, monitor)
.thenCompose( updatedSnapshot -> child.getUpdated(updatedSnapshot, network)
.thenCompose(updatedChild ->
updatePropsIfNecessary.apply(updatedChild, updatedSnapshot, endIndex)));
}
}
if (startIndex > 0) {
// TODO if startIndex > 0 prepend with a zero section
throw new IllegalStateException("Unimplemented!");
}
SymmetricKey fileWriteKey = SymmetricKey.random();
SymmetricKey fileKey = baseKey.orElseGet(SymmetricKey::random);
SymmetricKey dataKey = SymmetricKey.random();
SymmetricKey rootRKey = latest.pointer.capability.rBaseKey;
CryptreeNode dirAccess = latest.pointer.fileAccess;
SymmetricKey dirParentKey = dirAccess.getParentKey(rootRKey);
Location parentLocation = getLocation();
return calculateMimeType(fileData, endIndex, filename).thenCompose(mimeType -> fileData.reset()
.thenCompose(resetReader -> {
Optional<byte[]> streamSecret = Optional.of(crypto.random.randomBytes(32));
FileProperties fileProps = new FileProperties(filename,
false, false, mimeType, endIndex,
LocalDateTime.now(), isHidden, Optional.empty(), streamSecret);
FileUploader chunks = new FileUploader(filename, mimeType, resetReader,
startIndex, endIndex, fileKey, dataKey, parentLocation,
dirParentKey, monitor, fileProps, firstChunkMapKey);
SigningPrivateKeyAndPublicHash signer = signingPair();
WritableAbsoluteCapability fileWriteCap = new
WritableAbsoluteCapability(owner(),
signer.publicKeyHash,
firstChunkMapKey, fileKey,
fileWriteKey);
return chunks.upload(current, committer, network, parentLocation.owner, signer, crypto.hasher)
.thenCompose(updatedWD -> latest.addChildPointer(updatedWD,
committer, fileWriteCap, new PathElement(filename), network, crypto))
.thenCompose(cwd -> fileData.reset().thenCompose(resetAgain ->
generateThumbnailAndUpdate(cwd, committer, fileWriteCap, filename, resetAgain,
network, isHidden, mimeType,
endIndex, LocalDateTime.now(), streamSecret)));
}));
})
)
);
}
private CompletableFuture<Snapshot> recalculateThumbnail(Snapshot snapshot, Committer committer, String filename, AsyncReader fileData
, boolean isHidden, long fileSize, NetworkAccess network, WritableAbsoluteCapability fileWriteCap, Optional<byte[]> streamSecret
) {
return fileData.reset()
.thenCompose(fileData2 -> calculateMimeType(fileData2, fileSize, filename)
.thenCompose(mimeType -> fileData.reset()
.thenCompose(resetAgain ->
generateThumbnailAndUpdate(snapshot, committer, fileWriteCap, filename, resetAgain,
network, isHidden, mimeType, fileSize, LocalDateTime.now(), streamSecret))));
}
private CompletableFuture<Snapshot> generateThumbnailAndUpdate(Snapshot base,
Committer committer,
WritableAbsoluteCapability cap,
String fileName,
AsyncReader fileData,
NetworkAccess network,
Boolean isHidden,
String mimeType,
long fileSize,
LocalDateTime updatedDateTime,
Optional<byte[]> streamSecret) {
return generateThumbnail(network, fileData, (int) Math.min(fileSize, Integer.MAX_VALUE), fileName)
.thenCompose(thumbData -> {
FileProperties fileProps = new FileProperties(fileName, false, props.isLink, mimeType, fileSize,
updatedDateTime, isHidden, thumbData, streamSecret);
return network.getFile(base, cap, getChildsEntryWriter(), ownername)
.thenCompose(child -> child.get().updateProperties(base, committer, fileProps, network));
});
}
private CompletableFuture<Snapshot> updateProperties(Snapshot base,
Committer committer,
FileProperties newProps,
NetworkAccess network) {
return getPointer().fileAccess.updateProperties(base, committer, writableFilePointer(),
getChildsEntryWriter(), newProps, network);
}
private CompletableFuture<Snapshot> addChildPointer(Snapshot current,
Committer committer,
WritableAbsoluteCapability childPointer,
PathElement filename,
NetworkAccess network,
Crypto crypto) {
NamedRelativeCapability namedCap = new NamedRelativeCapability(filename, writableFilePointer().relativise(childPointer));
List<NamedRelativeCapability> childCaps = Collections.singletonList(namedCap);
return pointer.fileAccess.addChildrenAndCommit(current, committer,
childCaps, writableFilePointer(), signingPair(), network, crypto)
.thenApply(newBase -> {
setModified();
return newBase;
});
}
@JsMethod
public CompletableFuture<FileWrapper> appendToChild(String filename,
byte[] fileData,
boolean isHidden,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
return getChild(filename, crypto.hasher, network)
.thenCompose(child -> child
.flatMap(c -> c.getFileProperties().streamSecret)
.map(secret -> FileProperties.calculateMapKey(secret,
child.get().getLocation().getMapKey(),
child.get().getFileProperties().size, crypto.hasher))
.orElseGet(() -> Futures.of(crypto.random.randomBytes(32)))
.thenCompose(x -> uploadFileSection(filename, AsyncReader.build(fileData), isHidden,
child.map(f -> f.getSize()).orElse(0L),
fileData.length + child.map(f -> f.getSize()).orElse(0L),
child.map(f -> f.getPointer().capability.rBaseKey), true, network, crypto,
monitor, x)));
}
/**
*
* @param current
* @param committer
* @param existingChild
* @param fileData
* @param inputStartIndex
* @param endIndex
* @param network
* @param crypto
* @param monitor
* @return The committed root for the parent (this) directory
*/
private CompletableFuture<Snapshot> updateExistingChild(Snapshot current,
Committer committer,
FileWrapper existingChild,
AsyncReader fileData,
long inputStartIndex,
long endIndex,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
FileProperties existingProps = existingChild.getFileProperties();
String filename = existingProps.name;
LOG.info("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of child with name: " + filename);
return current.withWriter(existingChild.owner(), existingChild.writer(), network)
.thenCompose(state ->
existingChild.clean(state, committer, network, crypto)
.thenCompose(pair -> pair.left.overwriteSection(pair.right, committer, fileData,
inputStartIndex, endIndex, network, crypto, monitor)));
}
static boolean isLegalName(String name) {
return !name.contains("/") && ! name.equals(".") && ! name.equals("..") && ! name.isEmpty();
}
/**
*
* @param newFolderName
* @param network
* @param isSystemFolder
* @param crypto
* @return An updated version of this directory
*/
@JsMethod
public CompletableFuture<FileWrapper> mkdir(String newFolderName,
NetworkAccess network,
boolean isSystemFolder,
Crypto crypto) {
return mkdir(newFolderName, network, null, isSystemFolder, crypto);
}
public CompletableFuture<FileWrapper> mkdir(String newFolderName,
NetworkAccess network,
SymmetricKey requestedBaseSymmetricKey,
boolean isSystemFolder,
Crypto crypto) {
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(state, committer) -> mkdir(newFolderName, Optional.ofNullable(requestedBaseSymmetricKey),
Optional.empty(), Optional.empty(), isSystemFolder, network, crypto, state, committer))
.thenCompose(version -> getUpdated(version, network));
}
private CompletableFuture<Snapshot> mkdir(String newFolderName,
Optional<SymmetricKey> requestedBaseReadKey,
Optional<SymmetricKey> requestedBaseWriteKey,
Optional<byte[]> desiredMapKey,
boolean isSystemFolder,
NetworkAccess network,
Crypto crypto,
Snapshot version,
Committer committer) {
if (!this.isDirectory()) {
return Futures.errored(new IllegalStateException("Cannot mkdir in a file!"));
}
if (!isLegalName(newFolderName)) {
return Futures.errored(new IllegalStateException("Illegal directory name: " + newFolderName));
}
return hasChildWithName(version, newFolderName, crypto.hasher, network).thenCompose(hasChild -> {
if (hasChild) {
return Futures.errored(new IllegalStateException("Child already exists with name: " + newFolderName));
}
return pointer.fileAccess.mkdir(version, committer, newFolderName, network, writableFilePointer(), getChildsEntryWriter(),
requestedBaseReadKey, requestedBaseWriteKey, desiredMapKey, isSystemFolder, crypto).thenApply(x -> {
setModified();
return x;
});
});
}
/** Get or create a descendant directory
*
* @param subPath
* @param network
* @param isSystemFolder
* @param crypto
* @return
*/
public CompletableFuture<FileWrapper> getOrMkdirs(Path subPath,
NetworkAccess network,
boolean isSystemFolder,
Crypto crypto) {
String finalPath = TrieNode.canonicalise(subPath.toString());
List<String> elements = Arrays.asList(finalPath.split("/"));
return network.synchronizer.applyComplexComputation(owner(), signingPair(),
(state, committer) -> getOrMkdirs(elements, isSystemFolder, network, crypto, state, committer))
.thenApply(p -> p.right);
}
private CompletableFuture<Pair<Snapshot, FileWrapper>> getOrMkdirs(List<String> subPath,
boolean isSystemFolder,
NetworkAccess network,
Crypto crypto,
Snapshot version,
Committer committer) {
return Futures.reduceAll(subPath, new Pair<>(version, this), (p, name) -> p.right.getOrMkdir(name,
Optional.empty(), Optional.empty(), Optional.empty(), isSystemFolder, network, crypto, p.left, committer),
(a, b) -> b);
}
private CompletableFuture<Pair<Snapshot, FileWrapper>> getOrMkdir(String newFolderName,
Optional<SymmetricKey> requestedBaseReadKey,
Optional<SymmetricKey> requestedBaseWriteKey,
Optional<byte[]> desiredMapKey,
boolean isSystemFolder,
NetworkAccess network,
Crypto crypto,
Snapshot version,
Committer committer) {
if (! this.isDirectory()) {
return Futures.errored(new IllegalStateException("Cannot mkdir in a file!"));
}
if (! isLegalName(newFolderName)) {
return Futures.errored(new IllegalStateException("Illegal directory name: " + newFolderName));
}
return getChild(version, newFolderName, crypto.hasher, network).thenCompose(childOpt -> {
if (childOpt.isPresent()) {
return Futures.of(new Pair<>(version, childOpt.get()));
}
return pointer.fileAccess.mkdir(version, committer, newFolderName, network, writableFilePointer(), getChildsEntryWriter(),
requestedBaseReadKey, requestedBaseWriteKey, desiredMapKey, isSystemFolder, crypto).thenCompose(x -> {
setModified();
return getUpdated(x, network).thenCompose(us -> us.getChild(newFolderName, crypto.hasher, network))
.thenApply(child -> new Pair<>(x, child.get()));
});
});
}
/**
* @param newFilename
* @param parent
* @param userContext
* @return the updated parent
*/
@JsMethod
public CompletableFuture<FileWrapper> rename(String newFilename,
FileWrapper parent,
Path ourPath,
UserContext userContext) {
if (! isLegalName(newFilename))
return CompletableFuture.completedFuture(parent);
if (! parent.isWritable())
return Futures.errored(new IllegalStateException("Unable to rename something without write access to the parent!"));
CompletableFuture<Optional<FileWrapper>> childExists = parent == null ?
CompletableFuture.completedFuture(Optional.empty()) :
parent.getDescendentByPath(newFilename, userContext.crypto.hasher, userContext.network);
ensureUnmodified();
FileProperties currentProps = getFileProperties();
setModified();
return childExists
.thenCompose(existing -> {
if (existing.isPresent())
throw new IllegalStateException("Cannot rename, child already exists with name: " + newFilename);
//get current props
RetrievedCapability ourPointer = linkPointer.orElse(pointer);
WritableAbsoluteCapability us = (WritableAbsoluteCapability) ourPointer.capability;
CryptreeNode nodeToUpdate = ourPointer.fileAccess;
boolean isDir = this.isDirectory();
boolean isLink = ourPointer.getProperties().isLink;
FileProperties newProps = new FileProperties(newFilename, isDir, isLink,
currentProps.mimeType, currentProps.size,
currentProps.modified, currentProps.isHidden,
currentProps.thumbnail, currentProps.streamSecret);
SigningPrivateKeyAndPublicHash signer = isLink ? parent.signingPair() : signingPair();
return userContext.network.synchronizer.applyComplexUpdate(owner(), signer,
(s, committer) -> nodeToUpdate.updateProperties(s, committer, us,
entryWriter, newProps, userContext.network)
.thenCompose(updated -> parent.updateChildLinks(updated, committer,
Arrays.asList(new Pair<>(us, new NamedAbsoluteCapability(newFilename, us))),
userContext.network, userContext.crypto.random, userContext.crypto.hasher)))
.thenCompose(newVersion -> parent.getUpdated(newVersion, userContext.network));
}).thenCompose(f -> userContext.sharedWithCache
.rename(ourPath, ourPath.getParent().resolve(newFilename))
.thenApply(b -> f));
}
public CompletableFuture<Boolean> setProperties(FileProperties updatedProperties,
Hasher hasher,
NetworkAccess network,
Optional<FileWrapper> parent) {
setModified();
String newName = updatedProperties.name;
if (!isLegalName(newName)) {
return Futures.errored(new IllegalArgumentException("Illegal file name: " + newName));
}
return network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(s, comitter) -> (! parent.isPresent() ?
CompletableFuture.completedFuture(s) :
s.withWriter(owner(), parent.get().writer(), network)
).thenCompose(withParent -> parent.get().hasChildWithName(withParent, newName, hasher, network))
.thenCompose(hasChild -> ! hasChild ?
CompletableFuture.completedFuture(true) :
parent.get().getChildrenCapabilities(hasher, network)
.thenApply(childCaps -> {
if (! childCaps.stream()
.map(l -> new ByteArrayWrapper(l.cap.getMapKey()))
.collect(Collectors.toSet())
.contains(new ByteArrayWrapper(pointer.capability.getMapKey())))
throw new IllegalStateException("Cannot rename to same name as an existing file");
return true;
})).thenCompose(x -> {
CryptreeNode fileAccess = pointer.fileAccess;
return fileAccess.updateProperties(s, comitter, writableFilePointer(),
entryWriter, updatedProperties, network);
}))
.thenApply(fa -> true);
}
/**
*
* @return A capability based on the parent key
*/
public AbsoluteCapability getMinimalReadPointer() {
if (isDirectory()) {
return pointer.capability.withBaseKey(getParentKey());
}
return pointer.capability;
}
public WritableAbsoluteCapability writableFilePointer() {
if (! isWritable())
throw new IllegalStateException("File is not writable!");
return (WritableAbsoluteCapability) pointer.capability;
}
public SigningPrivateKeyAndPublicHash signingPair() {
if (! isWritable())
throw new IllegalStateException("File is not writable!");
return pointer.capability.wBaseKey
.map(w -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, w, entryWriter))
.orElseGet(entryWriter::get);
}
@JsMethod
public CompletableFuture<Boolean> moveTo(FileWrapper target, FileWrapper parent, Path ourPath, UserContext context) {
return copyTo(target, context)
.thenCompose(fw -> remove(parent, ourPath, context))
.thenApply(newAccess -> true);
}
@JsMethod
public CompletableFuture<Boolean> copyTo(FileWrapper target, UserContext context) {
ensureUnmodified();
NetworkAccess network = context.network;
Crypto crypto = context.crypto;
if (! target.isDirectory()) {
return Futures.errored(new IllegalStateException("CopyTo target " + target + " must be a directory"));
}
return context.network.synchronizer.applyComplexUpdate(target.owner(), target.signingPair(),
(version, committer) -> version.withWriter(owner(), writer(), network)
.thenCompose(both -> copyTo(target, network, crypto, both, committer)))
.thenApply(newAccess -> true);
}
public CompletableFuture<Snapshot> copyTo(FileWrapper target,
NetworkAccess network,
Crypto crypto,
Snapshot version,
Committer committer) {
if (! target.isDirectory()) {
return Futures.errored(new IllegalStateException("CopyTo target " + target + " must be a directory"));
}
return target.hasChildWithName(version, getFileProperties().name, crypto.hasher, network).thenCompose(childExists -> {
if (childExists) {
return Futures.errored(new IllegalStateException("CopyTo target " + target + " already has child with name " + getFileProperties().name));
}
if (isDirectory()) {
byte[] newMapKey = crypto.random.randomBytes(32);
SymmetricKey newBaseR = SymmetricKey.random();
SymmetricKey newBaseW = SymmetricKey.random();
WritableAbsoluteCapability newCap = ((WritableAbsoluteCapability)target.getPointer().capability)
.withMapKey(newMapKey)
.withBaseKey(newBaseR)
.withBaseWriteKey(newBaseW);
return getChildren(version, crypto.hasher, network).thenCompose(children ->
target.mkdir(getName(), Optional.of(newBaseR), Optional.of(newBaseW), Optional.of(newMapKey),
getFileProperties().isHidden, network, crypto, version, committer)
.thenCompose(versionWithDir ->
network.getFile(versionWithDir, newCap, target.getChildsEntryWriter(), target.ownername)
.thenCompose(subTargetOpt -> {
FileWrapper newTarget = subTargetOpt.get();
return Futures.reduceAll(children, versionWithDir,
(s, child) -> newTarget.getUpdated(s, network)
.thenCompose(updated ->
child.copyTo(updated, network, crypto, s, committer)),
(a, b) -> a.merge(b));
})));
} else {
return version.withWriter(owner(), writer(), network).thenCompose(snapshot ->
getInputStream(snapshot.get(writer()).props, network, crypto, x -> {})
.thenCompose(stream -> target.uploadFileSection(snapshot, committer,
getName(), stream, false, 0, getSize(),
Optional.empty(), false, network, crypto, x -> {},
crypto.random.randomBytes(32))));
}
});
}
@JsMethod
public CompletableFuture<Boolean> hasChild(String fileName, Hasher hasher, NetworkAccess network) {
if (!isLegalName(fileName)) {
return Futures.errored(new IllegalArgumentException("Illegal file/directory name: " + fileName));
}
return this.hasChildWithName(version, fileName, hasher, network).thenApply(childExists -> childExists);
}
/**
* Move this file/dir and subtree to a new signing key pair.
* @param signer
* @param parent
* @param network
* @return The updated version of this file/dir and its parent
*/
public CompletableFuture<Pair<FileWrapper, FileWrapper>> changeSigningKey(SigningPrivateKeyAndPublicHash signer,
FileWrapper parent,
NetworkAccess network,
Hasher hasher) {
ensureUnmodified();
WritableAbsoluteCapability cap = (WritableAbsoluteCapability)getPointer().capability;
SymmetricLinkToSigner signerLink = SymmetricLinkToSigner.fromPair(cap.wBaseKey.get(), signer);
CryptreeNode fileAccess = getPointer().fileAccess;
RelativeCapability newParentLink = new RelativeCapability(Optional.of(parent.writer()),
parent.getLocation().getMapKey(), parent.getParentKey(), Optional.empty());
CryptreeNode newFileAccess = fileAccess
.withWriterLink(cap.rBaseKey, signerLink)
.withParentLink(getParentKey(), newParentLink);
WritableAbsoluteCapability ourNewCap = cap.withSigner(signer.publicKeyHash);
RetrievedCapability newRetrievedCapability = new RetrievedCapability(ourNewCap, newFileAccess);
// create the new signing subspace move subtree to it
PublicKeyHash owner = owner();
network.synchronizer.putEmpty(owner, signer.publicKeyHash);
return network.synchronizer.applyComplexUpdate(owner, signer, (version, committer) -> IpfsTransaction.call(owner,
tid -> network.uploadChunk(version, committer, newFileAccess, owner, getPointer().capability.getMapKey(), signer, tid)
.thenCompose(newVersion -> copyAllChunks(false, cap, signer, hasher, network, newVersion, committer))
.thenCompose(copiedVersion -> copiedVersion.withWriter(owner, parent.writer(), network))
.thenCompose(withParent -> parent.getPointer().fileAccess
.updateChildLink(withParent, committer, parent.writableFilePointer(),
parent.signingPair(),
getPointer(),
newRetrievedCapability, network, hasher))
.thenCompose(updatedParentVersion -> deleteAllChunks(cap, signingPair(), tid, hasher, network,
updatedParentVersion, committer)),
network.dhtClient)
).thenCompose(finalVersion -> parent.getUpdated(finalVersion, network)
.thenCompose(updatedParent -> network.getFile(finalVersion, ourNewCap, Optional.of(signer), ownername)
.thenApply(updatedUs -> new Pair<>(updatedUs.get(), updatedParent))));
}
/** This copies all the cryptree nodes from one signing key to another for a file or subtree
*
* @param includeFirst
* @param currentCap
* @param targetSigner
* @param network
* @return
*/
private static CompletableFuture<Snapshot> copyAllChunks(boolean includeFirst,
AbsoluteCapability currentCap,
SigningPrivateKeyAndPublicHash targetSigner,
Hasher hasher,
NetworkAccess network,
Snapshot initialVersion,
Committer committer) {
return initialVersion.withWriter(currentCap.owner, currentCap.writer, network)
.thenCompose(version -> network.getMetadata(version.get(currentCap.writer).props, currentCap)
.thenCompose(mOpt -> {
if (! mOpt.isPresent()) {
return CompletableFuture.completedFuture(version);
}
return (includeFirst ?
IpfsTransaction.call(currentCap.owner,
tid -> network.addPreexistingChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(),
targetSigner, tid, version, committer), network.dhtClient) :
CompletableFuture.completedFuture(version))
.thenCompose(updated -> {
CryptreeNode chunk = mOpt.get();
Optional<byte[]> streamSecret = chunk.getProperties(chunk
.getParentKey(currentCap.rBaseKey)).streamSecret;
return chunk.getNextChunkLocation(currentCap.rBaseKey,
streamSecret, currentCap.getMapKey(), hasher)
.thenCompose(nextChunkMapKey ->
copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey),
targetSigner, hasher, network, updated, committer));
})
.thenCompose(updatedVersion -> {
if (! mOpt.get().isDirectory())
return CompletableFuture.completedFuture(updatedVersion);
return mOpt.get().getDirectChildrenCapabilities(currentCap, updatedVersion, network)
.thenCompose(childCaps ->
Futures.reduceAll(childCaps,
updatedVersion,
(v, cap) -> copyAllChunks(true, cap.cap,
targetSigner, hasher, network, v, committer),
(x, y) -> y));
});
}));
}
public static CompletableFuture<Snapshot> deleteAllChunks(WritableAbsoluteCapability currentCap,
SigningPrivateKeyAndPublicHash signer,
TransactionId tid,
Hasher hasher,
NetworkAccess network,
Snapshot version,
Committer committer) {
return version.withWriter(currentCap.owner, currentCap.writer, network)
.thenCompose(current -> network.getMetadata(current.get(currentCap.writer).props, currentCap)
.thenCompose(mOpt -> {
if (! mOpt.isPresent()) {
return CompletableFuture.completedFuture(current);
}
SigningPrivateKeyAndPublicHash ourSigner = mOpt.get()
.getSigner(currentCap.rBaseKey, currentCap.wBaseKey.get(), Optional.of(signer));
return network.deleteChunk(current, committer, mOpt.get(), currentCap.owner,
currentCap.getMapKey(), ourSigner, tid)
.thenCompose(deletedVersion -> {
CryptreeNode chunk = mOpt.get();
Optional<byte[]> streamSecret = chunk.getProperties(chunk
.getParentKey(currentCap.rBaseKey)).streamSecret;
return chunk.getNextChunkLocation(currentCap.rBaseKey, streamSecret,
currentCap.getMapKey(), hasher).thenCompose(nextChunkMapKey ->
deleteAllChunks(currentCap.withMapKey(nextChunkMapKey), signer, tid, hasher,
network, deletedVersion, committer));
})
.thenCompose(updatedVersion -> {
if (! mOpt.get().isDirectory())
return CompletableFuture.completedFuture(updatedVersion);
return mOpt.get().getDirectChildrenCapabilities(currentCap, updatedVersion, network).thenCompose(childCaps ->
Futures.reduceAll(childCaps,
updatedVersion,
(v, cap) -> deleteAllChunks((WritableAbsoluteCapability) cap.cap, signer,
tid, hasher, network, v, committer),
(x, y) -> y));
})
.thenCompose(s -> removeSigningKey(currentCap.writer, signer, currentCap.owner, network, s, committer));
}));
}
/**
* @param parent
* @param userContext
* @return updated parent
*/
@JsMethod
public CompletableFuture<FileWrapper> remove(FileWrapper parent, Path ourPath, UserContext userContext) {
NetworkAccess network = userContext.network;
Hasher hasher = userContext.crypto.hasher;
ensureUnmodified();
if (! pointer.capability.isWritable())
return Futures.errored(new IllegalStateException("Cannot delete file without write access to it"));
boolean writableParent = parent.isWritable();
return (writableParent ? parent.removeChild(this, network, hasher) : CompletableFuture.completedFuture(parent))
.thenCompose(updatedParent -> network.synchronizer.applyComplexUpdate(owner(), signingPair(),
(version, committer) -> IpfsTransaction.call(owner(),
tid -> FileWrapper.deleteAllChunks(
isLink() ?
(WritableAbsoluteCapability) getLinkPointer().capability :
writableFilePointer(),
writableParent ?
parent.signingPair() :
signingPair(), tid, hasher, network, version, committer), network.dhtClient))
.thenCompose(b -> userContext.sharedWithCache.clearSharedWith(ourPath))
.thenApply(b -> updatedParent)
);
}
public static CompletableFuture<Snapshot> removeSigningKey(PublicKeyHash signerToRemove,
SigningPrivateKeyAndPublicHash parentSigner,
PublicKeyHash owner,
NetworkAccess network,
Snapshot current,
Committer committer) {
PublicKeyHash parentWriter = parentSigner.publicKeyHash;
if (parentWriter.equals(signerToRemove))
return CompletableFuture.completedFuture(current);
return current.withWriter(owner, parentWriter, network)
.thenCompose(s -> s.get(parentSigner).props
.removeOwnedKey(owner, parentSigner, signerToRemove, network.dhtClient, network.hasher)
.thenCompose(removed -> IpfsTransaction.call(
owner,
tid -> committer.commit(owner, parentSigner, removed, s.get(parentSigner), tid),
network.dhtClient))
.thenApply(committed -> s.withVersion(parentWriter, committed.get(parentWriter))));
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
return network.synchronizer.getValue(owner(), writer())
.thenCompose(state -> getInputStream(state.get(writer()).props, network, crypto, getFileProperties().size, monitor));
}
public CompletableFuture<? extends AsyncReader> getInputStream(WriterData version,
NetworkAccess network,
Crypto crypto,
ProgressConsumer<Long> monitor) {
return getInputStream(version, network, crypto, getFileProperties().size, monitor);
}
@JsMethod
public CompletableFuture<? extends AsyncReader> getBufferedInputStream(NetworkAccess network,
Crypto crypto,
int fileSizeHi,
int fileSizeLow,
int bufferChunks,
ProgressConsumer<Long> monitor) {
long fileSize = (fileSizeLow & 0xFFFFFFFFL) + ((fileSizeHi & 0xFFFFFFFFL) << 32);
return getInputStream(network, crypto, fileSizeHi, fileSizeLow, monitor)
.thenApply(r -> new BufferedAsyncReader(r, bufferChunks, fileSize));
}
@JsMethod
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
Crypto crypto,
int fileSizeHi,
int fileSizeLow,
ProgressConsumer<Long> monitor) {
long fileSize = (fileSizeLow & 0xFFFFFFFFL) + ((fileSizeHi & 0xFFFFFFFFL) << 32);
return network.synchronizer.getValue(owner(), writer())
.thenCompose(state -> getInputStream(state.get(writer()).props, network, crypto, fileSize, monitor));
}
public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network,
Crypto crypto,
long fileSize,
ProgressConsumer<Long> monitor) {
return network.synchronizer.getValue(owner(), writer())
.thenCompose(state -> getInputStream(state.get(writer()).props, network, crypto, fileSize, monitor));
}
public CompletableFuture<? extends AsyncReader> getInputStream(WriterData version,
NetworkAccess network,
Crypto crypto,
long fileSize,
ProgressConsumer<Long> monitor) {
ensureUnmodified();
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
CryptreeNode fileAccess = pointer.fileAccess;
return fileAccess.retriever(pointer.capability.rBaseKey, props.streamSecret, getLocation().getMapKey(), crypto.hasher)
.thenCompose(retriever ->
retriever.getFile(version, network, crypto, pointer.capability, props.streamSecret,
fileSize, fileAccess.committedHash(), monitor));
}
private CompletableFuture<FileRetriever> getRetriever(Hasher hasher) {
if (pointer.fileAccess.isDirectory())
throw new IllegalStateException("Cannot get input stream for a directory!");
return pointer.fileAccess.retriever(pointer.capability.rBaseKey, props.streamSecret, getLocation().getMapKey(), hasher);
}
@JsMethod
public String getBase64Thumbnail() {
Optional<byte[]> thumbnail = props.thumbnail;
if (thumbnail.isPresent()) {
String base64Data = Base64.getEncoder().encodeToString(thumbnail.get());
return "data:image/png;base64," + base64Data;
} else {
return "";
}
}
@JsMethod
public FileProperties getFileProperties() {
ensureUnmodified();
return props;
}
@JsMethod
public String getName() {
return getFileProperties().name;
}
public long getSize() {
return getFileProperties().size;
}
public String toString() {
return getFileProperties().name;
}
public static FileWrapper createRoot(TrieNode root) {
return new FileWrapper(Optional.of(root), null, Optional.empty(), Optional.empty(), null, new Snapshot(new HashMap<>()));
}
public static Optional<byte[]> generateThumbnail(byte[] imageBlob) {
try {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBlob));
BufferedImage thumbnailImage = new BufferedImage(THUMBNAIL_SIZE, THUMBNAIL_SIZE, image.getType());
Graphics2D g = thumbnailImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, THUMBNAIL_SIZE, THUMBNAIL_SIZE, null);
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(thumbnailImage, "JPG", baos);
baos.close();
return Optional.of(baos.toByteArray());
} catch (IOException ioe) {
LOG.log(Level.WARNING, ioe.getMessage(), ioe);
}
return Optional.empty();
}
public static byte[] generateVideoThumbnail(byte[] videoBlob) {
File tempFile = null;
try {
tempFile = File.createTempFile(UUID.randomUUID().toString(), ".mp4");
Files.write(tempFile.toPath(), videoBlob, StandardOpenOption.WRITE);
return VideoThumbnail.create(tempFile.getAbsolutePath(), THUMBNAIL_SIZE, THUMBNAIL_SIZE);
} catch (IOException ioe) {
LOG.log(Level.WARNING, ioe.getMessage(), ioe);
} finally {
if(tempFile != null) {
try {
Files.delete(tempFile.toPath());
}catch(IOException ioe){
}
}
}
return new byte[0];
}
private CompletableFuture<Optional<byte[]>> generateThumbnail(NetworkAccess network, AsyncReader fileData, int fileSize, String filename) {
CompletableFuture<Optional<byte[]>> fut = new CompletableFuture<>();
if (fileSize > MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE) {
getFileType(fileData, filename).thenAccept(mimeType -> {
if (mimeType.startsWith("image")) {
if (network.isJavascript()) {
thumbnail.generateThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> {
byte[] bytesOfData = Base64.getDecoder().decode(base64Str);
if (bytesOfData.length == 0)
fut.complete(Optional.empty());
else
fut.complete(Optional.of(bytesOfData));
});
} else {
byte[] bytes = new byte[fileSize];
fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> {
fut.complete(generateThumbnail(bytes));
});
}
} else if (mimeType.startsWith("video")) {
if (network.isJavascript()) {
thumbnail.generateVideoThumbnail(fileData, fileSize, filename, mimeType).thenAccept(base64Str -> {
if(base64Str == null) {
fut.complete(Optional.empty());
}
byte[] bytesOfData = Base64.getDecoder().decode(base64Str);
if (bytesOfData.length == 0)
fut.complete(Optional.empty());
else
fut.complete(Optional.of(bytesOfData));
});
} else {
byte[] bytes = new byte[fileSize];
fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> {
fut.complete(Optional.of(generateVideoThumbnail(bytes)));
});
}
} else if (mimeType.startsWith("audio/mpeg")) {
byte[] mp3Data = new byte[fileSize];
fileData.readIntoArray(mp3Data, 0, fileSize).thenAccept(read -> {
try {
Mp3CoverImage mp3CoverImage = Mp3CoverImage.extractCoverArt(mp3Data);
if (mp3CoverImage.imageData == null) {
fut.complete(Optional.empty());
} else {
if (network.isJavascript()) {
AsyncReader.ArrayBacked imageBlob = new AsyncReader.ArrayBacked(mp3CoverImage.imageData);
thumbnail.generateThumbnail(imageBlob, mp3CoverImage.imageData.length, filename)
.thenAccept(base64Str -> {
byte[] bytesOfData = Base64.getDecoder().decode(base64Str);
fut.complete(Optional.of(bytesOfData));
});
} else {
fut.complete(generateThumbnail(mp3CoverImage.imageData));
}
}
} catch(Exception ex) {
fut.complete(Optional.empty());
}
});
} else {
fut.complete(Optional.empty());
}
}).exceptionally(e -> {
e.printStackTrace();
fut.complete(Optional.empty());
return null;
});
} else {
fut.complete(Optional.empty());
}
return fut;
}
private static CompletableFuture<String> getFileType(AsyncReader imageBlob, String filename) {
CompletableFuture<String> result = new CompletableFuture<>();
byte[] data = new byte[MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE];
imageBlob.readIntoArray(data, 0, data.length).thenAccept(numBytesRead -> {
imageBlob.reset().thenAccept(resetResult -> {
if (numBytesRead < data.length) {
result.complete("");
} else {
String mimeType = MimeTypes.calculateMimeType(data, filename);
result.complete(mimeType);
}
});
});
return result;
}
public static CompletableFuture<String> calculateMimeType(AsyncReader data, long fileSize, String filename) {
byte[] header = new byte[(int) Math.min(fileSize, MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE)];
return data.readIntoArray(header, 0, header.length)
.thenApply(read -> MimeTypes.calculateMimeType(header, filename));
}
}
|
package org.helioviewer.jhv.renderable.components;
import java.awt.Color;
import java.awt.Component;
import java.nio.FloatBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import org.helioviewer.jhv.base.astronomy.Position;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.math.Mat4;
import org.helioviewer.jhv.base.math.MathUtils;
import org.helioviewer.jhv.base.math.Quat;
import org.helioviewer.jhv.base.math.Vec2;
import org.helioviewer.jhv.base.scale.GridScale;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.opengl.GLSLSolarShader;
import org.helioviewer.jhv.opengl.GLText;
import org.helioviewer.jhv.renderable.gui.AbstractRenderable;
import com.jogamp.common.nio.Buffers;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.awt.TextRenderer;
public class RenderableGrid extends AbstractRenderable {
public enum GridChoiceType {
VIEWPOINT("Viewpoint grid"), STONYHURST("Stonyhurst grid"), CARRINGTON("Carrington grid"), HCI("HCI grid");
private final String display;
GridChoiceType(String s) {
display = s;
}
@Override
public String toString() {
return display;
}
}
// height of text in solar radii
private static final float textScale = (float) (0.08 * Sun.Radius);
private static final int SUBDIVISIONS = 360;
private static final float[] color1 = new float[] { Color.RED.getRed() / 255f, Color.RED.getGreen() / 255f, Color.RED.getBlue() / 255f };
private static final float[] color2 = new float[] { Color.GREEN.getRed() / 255f, Color.GREEN.getGreen() / 255f, Color.GREEN.getBlue() / 255f };
private static final DecimalFormat formatter1 = MathUtils.numberFormatter("0", 1);
private static final DecimalFormat formatter2 = MathUtils.numberFormatter("0", 2);
private float lonstepDegrees = 15f;
private float latstepDegrees = 20f;
private boolean showAxes = true;
private boolean showLabels = true;
private boolean showRadial = false;
private final Component optionsPanel;
private static final String name = "Grid";
public RenderableGrid() {
optionsPanel = new RenderableGridOptionsPanel(this);
setVisible(true);
makeLatLabels();
makeLonLabels();
makeRadialLabels();
}
private int positionBufferID;
private int colorBufferID;
private GridChoiceType gridChoice = GridChoiceType.VIEWPOINT;
public Vec2 gridPoint(Camera camera, Viewport vp, int x, int y) {
return GridScale.current.mouseToGrid(x, y, vp, camera, gridChoice);
}
public static Quat getGridQuat(Camera camera, GridChoiceType gridChoice) {
switch (gridChoice) {
case VIEWPOINT:
return camera.getViewpoint().orientation;
case STONYHURST:
Position.L p = Sun.getEarth(camera.getViewpoint().time);
return new Quat(0, p.lon);
case HCI:
return Sun.getHCI(camera.getViewpoint().time);
default: // CARRINGTON
return Quat.ZERO;
}
}
private static final int FLAT_STEPS_THETA = 24;
private static final int FLAT_STEPS_RADIAL = 10;
@Override
public void renderScale(Camera camera, Viewport vp, GL2 gl, GLSLSolarShader shader, GridScale scale) {
if (!isVisible[vp.idx])
return;
int pixelsPerSolarRadius = (int) (textScale * vp.height / (2 * camera.getWidth()));
{
drawGridFlat(gl, scale, vp);
if (showLabels) {
drawGridTextFlat(gl, pixelsPerSolarRadius, scale, vp);
}
}
}
private void drawGridFlat(GL2 gl, GridScale scale, Viewport vp) {
float w = (float) vp.aspect;
float h = 1;
gl.glColor3f(color1[0], color1[1], color1[2]);
gl.glLineWidth(1);
{
gl.glBegin(GL2.GL_LINES);
for (int i = 0; i < (FLAT_STEPS_THETA + 1); i++) {
float start = -w / 2 + i * w / FLAT_STEPS_THETA;
if (i == FLAT_STEPS_THETA / 2) {
gl.glColor3f(color2[0], color2[1], color2[2]);
}
gl.glVertex2f(start, -h / 2);
gl.glVertex2f(start, h / 2);
if (i == FLAT_STEPS_THETA / 2) {
gl.glColor3f(color1[0], color1[1], color1[2]);
}
}
for (int i = 0; i < (FLAT_STEPS_RADIAL + 1); i++) {
float start = -h / 2 + i * h / FLAT_STEPS_RADIAL;
if (i == FLAT_STEPS_RADIAL / 2) {
gl.glColor3f(color2[0], color2[1], color2[2]);
}
gl.glVertex2f(-w / 2, start);
gl.glVertex2f(w / 2, start);
if (i == FLAT_STEPS_RADIAL / 2) {
gl.glColor3f(color1[0], color1[1], color1[2]);
}
}
gl.glEnd();
}
}
private void drawGridTextFlat(GL2 gl, int size, GridScale scale, Viewport vp) {
float w = (float) vp.aspect;
float h = 1;
TextRenderer renderer = GLText.getRenderer(size);
float textScaleFactor = textScale / renderer.getFont().getSize2D() / 3 * vp.width / 2048;
renderer.begin3DRendering();
{
for (int i = 0; i < (FLAT_STEPS_THETA + 1); ++i) {
if (i == FLAT_STEPS_THETA / 2) {
continue;
}
float start = -w / 2 + i * w / FLAT_STEPS_THETA;
String label = formatter2.format(scale.getInterpolatedXValue(1. / FLAT_STEPS_THETA * i));
renderer.draw3D(label, start, 0, 0, textScaleFactor);
}
for (int i = 0; i < (FLAT_STEPS_RADIAL + 1); ++i) {
String label = formatter2.format(scale.getInterpolatedYValue(1. / FLAT_STEPS_RADIAL * i));
float start = -h / 2 + i * h / FLAT_STEPS_RADIAL;
renderer.draw3D(label, 0, start, 0, textScaleFactor);
}
}
renderer.end3DRendering();
}
@Override
public void render(Camera camera, Viewport vp, GL2 gl) {
if (!isVisible[vp.idx])
return;
if (showAxes)
drawAxes(gl);
gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID);
gl.glVertexPointer(2, GL2.GL_FLOAT, 0, 0);
int pixelsPerSolarRadius = (int) (textScale * vp.height / (2 * camera.getWidth()));
Mat4 cameraMatrix = getGridQuat(camera, gridChoice).toMatrix();
gl.glPushMatrix();
gl.glMultMatrixd(cameraMatrix.transpose().m, 0);
{
drawGrid(gl);
if (showLabels) {
drawGridText(gl, pixelsPerSolarRadius);
}
}
gl.glPopMatrix();
if (showRadial) {
cameraMatrix = camera.getViewpoint().orientation.toMatrix();
gl.glPushMatrix();
gl.glMultMatrixd(cameraMatrix.transpose().m, 0);
{
drawRadialGrid(gl);
if (showLabels) {
drawRadialGridText(gl, pixelsPerSolarRadius);
}
}
gl.glPopMatrix();
}
drawEarthCircles(gl, Sun.getEarth(camera.getViewpoint().time));
gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0);
}
private static final float AXIS_START = (float) (1. * Sun.Radius);
private static final float AXIS_STOP = (float) (1.2 * Sun.Radius);
private void drawAxes(GL2 gl) {
gl.glLineWidth(2);
gl.glBegin(GL2.GL_LINES);
{
gl.glColor3f(0, 0, 1);
gl.glVertex3f(0, -AXIS_STOP, 0);
gl.glVertex3f(0, -AXIS_START, 0);
gl.glColor3f(1, 0, 0);
gl.glVertex3f(0, AXIS_STOP, 0);
gl.glVertex3f(0, AXIS_START, 0);
}
gl.glEnd();
}
private void drawEarthCircles(GL2 gl, Position.L p) {
gl.glLineWidth(1);
gl.glColor3f(1, 1, 0);
gl.glPushMatrix();
gl.glRotatef((float) (90 - 180 / Math.PI * p.lon), 0, 1, 0);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
gl.glRotatef(-90, 0, 1, 0);
gl.glRotatef((float) (90 - 180 / Math.PI * p.lat), 1, 0, 0);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
gl.glPopMatrix();
}
private static final float END_RADIUS = 30;
private static final float START_RADIUS = 2;
private static final float[] R_LABEL_POS = { 2, 8, 24 };
private static final float STEP_DEGREES = 15;
private void drawRadialGrid(GL2 gl) {
gl.glPushMatrix();
{
gl.glColor3f(1, 1, 1);
gl.glRotatef(90, 0, 0, 1);
{
gl.glPushMatrix();
gl.glScalef(1, 1, 1);
for (float i = START_RADIUS; i <= END_RADIUS; i++) {
if (i % 10 == 0) {
gl.glLineWidth(2);
} else {
gl.glLineWidth(1);
}
gl.glScalef(i / (i - 1), i / (i - 1), i / (i - 1));
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
}
gl.glLineWidth(1);
{
gl.glPushMatrix();
for (float i = 0; i < 360; i += STEP_DEGREES) {
gl.glBegin(GL2.GL_LINES);
gl.glVertex3f(START_RADIUS, 0, 0);
gl.glVertex3f(END_RADIUS, 0, 0);
gl.glEnd();
gl.glRotatef(STEP_DEGREES, 0, 0, 1);
}
gl.glPopMatrix();
}
}
gl.glPopMatrix();
}
private void drawRadialGridText(GL2 gl, int size) {
gl.glDisable(GL2.GL_CULL_FACE);
float fuzz = 0.75f;
for (float rsize : R_LABEL_POS) {
TextRenderer renderer = GLText.getRenderer((int) (fuzz * rsize * size));
float textScaleFactor = textScale / renderer.getFont().getSize2D();
renderer.begin3DRendering();
for (GridLabel label : radialLabels) {
renderer.draw3D(label.txt, rsize * label.x, rsize * label.y, 0, fuzz * rsize * textScaleFactor);
}
renderer.end3DRendering();
}
gl.glEnable(GL2.GL_CULL_FACE);
}
private void drawGrid(GL2 gl) {
gl.glPushMatrix();
{
gl.glLineWidth(1);
gl.glEnableClientState(GL2.GL_COLOR_ARRAY);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, colorBufferID);
gl.glColorPointer(3, GL2.GL_FLOAT, 0, 0);
gl.glRotatef(90, 0, 1, 0);
gl.glPushMatrix();
{
float rotation = 0;
while (rotation <= 180) {
gl.glDrawArrays(GL2.GL_LINE_STRIP, SUBDIVISIONS / 4, SUBDIVISIONS / 2 + 1);
gl.glRotatef(lonstepDegrees, 0, 1, 0);
rotation += lonstepDegrees;
}
}
gl.glPopMatrix();
gl.glPushMatrix();
{
float rotation = 0;
rotation -= lonstepDegrees;
gl.glRotatef(-lonstepDegrees, 0, 1, 0);
while (rotation >= -180) {
gl.glDrawArrays(GL2.GL_LINE_STRIP, SUBDIVISIONS / 4, SUBDIVISIONS / 2 + 1);
gl.glRotatef(-lonstepDegrees, 0, 1, 0);
rotation -= lonstepDegrees;
}
}
gl.glPopMatrix();
gl.glPushMatrix();
{
float scale, rotation = 0;
gl.glRotatef(90, 1, 0, 0);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
while (rotation < 90) {
gl.glPushMatrix();
{
gl.glTranslatef(0, 0, (float) (Sun.Radius * Math.sin(Math.PI / 180. * rotation)));
scale = (float) Math.cos(Math.PI / 180. * rotation);
gl.glScalef(scale, scale, scale);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
rotation += latstepDegrees;
}
rotation = latstepDegrees;
while (rotation < 90) {
gl.glPushMatrix();
{
gl.glTranslatef(0, 0, -(float) (Sun.Radius * Math.sin(Math.PI / 180. * rotation)));
scale = (float) Math.cos(Math.PI / 180. * rotation);
gl.glScalef(scale, scale, scale);
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
rotation += latstepDegrees;
}
gl.glDrawArrays(GL2.GL_LINE_LOOP, 0, SUBDIVISIONS);
}
gl.glPopMatrix();
gl.glDisableClientState(GL2.GL_COLOR_ARRAY);
}
gl.glPopMatrix();
}
private static class GridLabel {
protected final String txt;
protected final float x;
protected final float y;
protected final float theta;
protected GridLabel(String _txt, float _x, float _y, float _theta) {
txt = _txt;
x = _x;
y = _y;
theta = _theta;
}
}
private final ArrayList<GridLabel> latLabels = new ArrayList<GridLabel>();
private final ArrayList<GridLabel> lonLabels = new ArrayList<GridLabel>();
private final ArrayList<GridLabel> radialLabels = new ArrayList<GridLabel>();
private void makeRadialLabels() {
double size = Sun.Radius;
double horizontalAdjustment = textScale / 2.;
double verticalAdjustment = textScale / 3.;
radialLabels.clear();
for (double phi = 0; phi < 360; phi += STEP_DEGREES) {
double angle = -phi * Math.PI / 180.;
String txt = formatter1.format(phi);
radialLabels.add(new GridLabel(txt, (float) (Math.sin(angle) * size - horizontalAdjustment), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
}
}
private void makeLatLabels() {
double size = Sun.Radius * 1.1;
// adjust for font size in horizontal and vertical direction (centering the text approximately)
double horizontalAdjustment = textScale / 2.;
double verticalAdjustment = textScale / 3.;
latLabels.clear();
for (double phi = 0; phi <= 90; phi += latstepDegrees) {
double angle = (90 - phi) * Math.PI / 180.;
String txt = formatter1.format(phi);
latLabels.add(new GridLabel(txt, (float) (Math.sin(angle) * size), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
if (phi != 90) {
latLabels.add(new GridLabel(txt, (float) (-Math.sin(angle) * size - horizontalAdjustment), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
}
}
for (double phi = -latstepDegrees; phi >= -90; phi -= latstepDegrees) {
double angle = (90 - phi) * Math.PI / 180.;
String txt = formatter1.format(phi);
latLabels.add(new GridLabel(txt, (float) (Math.sin(angle) * size), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
if (phi != -90) {
latLabels.add(new GridLabel(txt, (float) (-Math.sin(angle) * size - horizontalAdjustment), (float) (Math.cos(angle) * size - verticalAdjustment), 0));
}
}
}
private void makeLonLabels() {
String txt;
double size = Sun.Radius * 1.05;
lonLabels.clear();
for (double theta = 0; theta <= 180.; theta += lonstepDegrees) {
double angle = (90 - theta) * Math.PI / 180.;
txt = formatter1.format(theta);
lonLabels.add(new GridLabel(txt, (float) (Math.cos(angle) * size), (float) (Math.sin(angle) * size), (float) theta));
}
for (double theta = -lonstepDegrees; theta > -180.; theta -= lonstepDegrees) {
double angle = (90 - theta) * Math.PI / 180.;
if (gridChoice == GridChoiceType.CARRINGTON) {
txt = formatter1.format(theta + 360);
} else {
txt = formatter1.format(theta);
}
lonLabels.add(new GridLabel(txt, (float) (Math.cos(angle) * size), (float) (Math.sin(angle) * size), (float) theta));
}
}
private void drawGridText(GL2 gl, int size) {
TextRenderer renderer = GLText.getRenderer(size);
// the scale factor has to be divided by the current font size
float textScaleFactor = textScale / renderer.getFont().getSize2D();
renderer.begin3DRendering();
gl.glDisable(GL2.GL_CULL_FACE);
for (GridLabel label : latLabels) {
renderer.draw3D(label.txt, label.x, label.y, 0, textScaleFactor);
}
renderer.flush();
gl.glEnable(GL2.GL_CULL_FACE);
for (GridLabel lonLabel : lonLabels) {
gl.glPushMatrix();
{
gl.glTranslatef(lonLabel.x, 0, lonLabel.y);
gl.glRotatef(lonLabel.theta, 0, 1, 0);
renderer.draw3D(lonLabel.txt, 0, 0, 0, textScaleFactor);
renderer.flush();
}
gl.glPopMatrix();
}
renderer.end3DRendering();
}
@Override
public void init(GL2 gl) {
FloatBuffer positionBuffer = FloatBuffer.allocate((SUBDIVISIONS + 1) * 2);
FloatBuffer colorBuffer = FloatBuffer.allocate((SUBDIVISIONS + 1) * 3);
for (int i = 0; i <= SUBDIVISIONS; i++) {
positionBuffer.put((float) (Sun.Radius * Math.cos(2 * Math.PI * i / SUBDIVISIONS)));
positionBuffer.put((float) (Sun.Radius * Math.sin(2 * Math.PI * i / SUBDIVISIONS)));
if (i % 2 == 0) {
colorBuffer.put(color1);
} else {
colorBuffer.put(color2);
}
}
positionBuffer.flip();
colorBuffer.flip();
int positionBufferSize = positionBuffer.capacity();
int colorBufferSize = colorBuffer.capacity();
positionBufferID = generate(gl);
colorBufferID = generate(gl);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID);
gl.glBufferData(GL2.GL_ARRAY_BUFFER, positionBufferSize * Buffers.SIZEOF_FLOAT, positionBuffer, GL2.GL_STATIC_DRAW);
gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, colorBufferID);
gl.glBufferData(GL2.GL_ARRAY_BUFFER, colorBufferSize * Buffers.SIZEOF_FLOAT, colorBuffer, GL2.GL_STATIC_DRAW);
}
private int generate(GL2 gl) {
int[] tmpId = new int[1];
gl.glGenBuffers(1, tmpId, 0);
return tmpId[0];
}
@Override
public void remove(GL2 gl) {
dispose(gl);
}
@Override
public Component getOptionsPanel() {
return optionsPanel;
}
@Override
public String getName() {
return name;
}
public double getLonstepDegrees() {
return lonstepDegrees;
}
public void setLonstepDegrees(double _lonstepDegrees) {
lonstepDegrees = (float) _lonstepDegrees;
makeLonLabels();
}
public double getLatstepDegrees() {
return latstepDegrees;
}
public void setLatstepDegrees(double _latstepDegrees) {
latstepDegrees = (float) _latstepDegrees;
makeLatLabels();
}
public void showLabels(boolean show) {
showLabels = show;
}
public void showAxes(boolean show) {
showAxes = show;
}
public void showRadial(boolean show) {
showRadial = show;
}
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void dispose(GL2 gl) {
gl.glDeleteBuffers(1, new int[] { positionBufferID }, 0);
gl.glDeleteBuffers(1, new int[] { colorBufferID }, 0);
}
public void setCoordinates(GridChoiceType _gridChoice) {
gridChoice = _gridChoice;
makeLonLabels();
}
}
|
package be.bagofwords.db;
import be.bagofwords.db.combinator.Combinator;
import be.bagofwords.db.methods.KeyFilter;
import be.bagofwords.db.methods.ObjectSerializer;
import be.bagofwords.iterator.CloseableIterator;
import be.bagofwords.iterator.DataIterable;
import be.bagofwords.iterator.IterableUtils;
import be.bagofwords.iterator.SimpleIterator;
import be.bagofwords.text.BowString;
import be.bagofwords.util.HashUtils;
import be.bagofwords.util.KeyValue;
import be.bagofwords.util.StreamUtils;
import java.util.Iterator;
import java.util.function.Predicate;
import java.util.stream.Stream;
public interface DataInterface<T extends Object> extends DataIterable<KeyValue<T>> {
T read(long key);
default long readCount(long key) {
Long result = (Long) read(key);
if (result == null)
return 0;
else
return result;
}
default T read(String key) {
return read(HashUtils.hashCode(key));
}
default T read(BowString key) {
return read(HashUtils.hashCode(key));
}
default long readCount(BowString key) {
return readCount(HashUtils.hashCode(key));
}
default long readCount(String key) {
return readCount(HashUtils.hashCode(key));
}
default boolean mightContain(String key) {
return mightContain(HashUtils.hashCode(key));
}
default boolean mightContain(long key) {
return read(key) != null;
}
default CloseableIterator<Long> keyIterator() {
return IterableUtils.mapIterator(iterator(), KeyValue::getKey);
}
default CloseableIterator<T> valueIterator() {
return IterableUtils.mapIterator(iterator(), KeyValue::getValue);
}
default CloseableIterator<T> valueIterator(KeyFilter keyFilter) {
return IterableUtils.mapIterator(iterator(keyFilter), KeyValue::getValue);
}
default CloseableIterator<T> valueIterator(Predicate<T> valueFilter) {
return IterableUtils.mapIterator(iterator(valueFilter), KeyValue::getValue);
}
default CloseableIterator<T> valueIterator(CloseableIterator<Long> keyIterator) {
return IterableUtils.mapIterator(iterator(keyIterator), KeyValue::getValue);
}
default CloseableIterator<T> valueIterator(Stream<Long> keyStream) {
return valueIterator(StreamUtils.iterator(keyStream));
}
default CloseableIterator<KeyValue<T>> iterator(KeyFilter keyFilter) {
final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();
return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {
@Override
public KeyValue<T> next() throws Exception {
while (keyValueIterator.hasNext()) {
KeyValue<T> next = keyValueIterator.next();
if (keyFilter.acceptKey(next.getKey())) {
return next;
}
}
return null;
}
@Override
public void close() throws Exception {
keyValueIterator.close();
}
});
}
default CloseableIterator<KeyValue<T>> iterator(Predicate<T> valueFilter) {
final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();
return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {
@Override
public KeyValue<T> next() throws Exception {
while (keyValueIterator.hasNext()) {
KeyValue<T> next = keyValueIterator.next();
if (valueFilter.test(next.getValue())) {
return next;
}
}
return null;
}
@Override
public void close() throws Exception {
keyValueIterator.close();
}
});
}
default CloseableIterator<KeyValue<T>> iterator(Stream<Long> keyStream) {
return iterator(StreamUtils.iterator(keyStream));
}
default CloseableIterator<KeyValue<T>> iterator(CloseableIterator<Long> keyIterator) {
return new CloseableIterator<KeyValue<T>>() {
KeyValue<T> next;
{
//Constructor
findNext();
}
private void findNext() {
next = null;
while (next == null && keyIterator.hasNext()) {
Long nextKey = keyIterator.next();
T nextValue = read(nextKey);
if (nextValue != null) {
next = new KeyValue<>(nextKey, nextValue);
}
}
}
@Override
protected void closeInt() {
keyIterator.close();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public KeyValue<T> next() {
KeyValue<T> curr = next;
findNext();
return curr;
}
};
}
default CloseableIterator<KeyValue<T>> cachedValueIterator() {
return new CloseableIterator<KeyValue<T>>() {
@Override
protected void closeInt() {
}
@Override
public boolean hasNext() {
return false;
}
@Override
public KeyValue<T> next() {
return null;
}
};
}
CloseableIterator<KeyValue<T>> iterator();
long apprSize();
long apprDataChecksum();
long exactSize();
default Stream<KeyValue<T>> stream() {
return StreamUtils.stream(this, true);
}
default Stream<KeyValue<T>> stream(KeyFilter keyFilter) {
return StreamUtils.stream(iterator(keyFilter), apprSize(), true);
}
default Stream<KeyValue<T>> stream(Predicate<T> valueFilter) {
return StreamUtils.stream(iterator(valueFilter), apprSize(), true);
}
default Stream<KeyValue<T>> stream(CloseableIterator<Long> keyIterator) {
return StreamUtils.stream(iterator(keyIterator), apprSize(), true);
}
default Stream<T> streamValues() {
return StreamUtils.stream(valueIterator(), apprSize(), false);
}
default Stream<T> streamValues(KeyFilter keyFilter) {
return StreamUtils.stream(valueIterator(keyFilter), apprSize(), false);
}
default Stream<T> streamValues(Predicate<T> valueFilter) {
return StreamUtils.stream(valueIterator(valueFilter), apprSize(), false);
}
default Stream<T> streamValues(CloseableIterator<Long> keyIterator) {
return StreamUtils.stream(valueIterator(keyIterator), apprSize(), false);
}
default Stream<T> streamValues(Stream<Long> keysStream) {
//This could be improved... Mapping twice from streams to closeable iterators does have a certain overhead
return StreamUtils.stream(valueIterator(StreamUtils.iterator(keysStream)), apprSize(), false);
}
default Stream<Long> streamKeys() {
return StreamUtils.stream(keyIterator(), apprSize(), true);
}
Class<T> getObjectClass();
String getName();
void optimizeForReading();
void write(long key, T value);
default void write(Iterator<KeyValue<T>> entries) {
write(IterableUtils.iterator(entries));
}
default void write(CloseableIterator<KeyValue<T>> entries) {
while (entries.hasNext()) {
KeyValue<T> entry = entries.next();
write(entry.getKey(), entry.getValue());
}
entries.close();
}
default void write(BowString key, T value) {
write(HashUtils.hashCode(key.getS()), value);
}
default void write(String key, T value) {
write(HashUtils.hashCode(key), value);
}
default void increaseCount(String key, Long value) {
write(key, (T) value);
}
default void increaseCount(long key, Long value) {
write(key, (T) value);
}
default void increaseCount(String key) {
increaseCount(key, 1l);
}
default void increaseCount(long key) {
increaseCount(key, 1l);
}
default void remove(String key) {
remove(HashUtils.hashCode(key));
}
default void remove(long key) {
write(key, null);
}
Combinator<T> getCombinator();
void close();
boolean wasClosed();
boolean isTemporaryDataInterface();
void flush();
void dropAllData();
void ifNotClosed(Runnable action);
/**
* Returns a number of the last flush, monotonically increasing
*/
long lastFlush();
DataInterface<T> getCoreDataInterface();
ObjectSerializer<T> getObjectSerializer();
}
|
package dnss.model;
import dnss.enums.Advancement;
public class Job {
private String name;
private String identifier;
private Advancement advancement;
private float[] spRatio;
private Job parent;
private int[][] skillTree;
private int maxSP;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public Advancement getAdvancement() {
return advancement;
}
public void setAdvancement(int advancement) {
this.advancement = Advancement.getAdvancement(advancement);
}
public float[] getSpRatio() {
return spRatio;
}
public void setSpRatio(float[] spRatio) {
this.spRatio = spRatio;
}
public Job getParent() {
return parent;
}
public void setParent(Job parent) {
this.parent = parent;
}
public int[][] getSkillTree() {
return skillTree;
}
public void setSkillTree(int[][] skillTree) {
this.skillTree = skillTree;
}
public int getMaxSP() {
return maxSP;
}
public void setMaxSP(int maxSP) {
this.maxSP = maxSP;
}
}
|
package com.mararok.epicwar.control.point.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import com.mararok.epiccore.math.Position3D;
import com.mararok.epiccore.misc.StringUtils;
import com.mararok.epicwar.War;
import com.mararok.epicwar.control.ControlAreaPower;
import com.mararok.epicwar.control.ControlPoint;
import com.mararok.epicwar.control.ControlPointData;
import com.mararok.epicwar.control.ControlPointManager;
import com.mararok.epicwar.control.Sector;
import com.mararok.epicwar.control.internal.NamedControlAreaImpl;
import com.mararok.epicwar.control.internal.Occupation;
import com.mararok.epicwar.faction.Faction;
public class ControlPointImpl extends NamedControlAreaImpl implements ControlPoint {
private Position3D position;
private int radius;
private ControlAreaPower power;
private Faction owner;
private Occupation occupation;
private int[] connections;
private Sector sector;
public ControlPointImpl(ControlPointData data, War war) {
super(data);
position = data.position;
radius = data.radius;
power = new ControlAreaPower(data.maxPower);
owner = war.getFactionManager().findById(data.ownerId);
occupation = new Occupation(this);
connections = data.connections;
sector = war.getSectorManager().findById(data.sectorId);
}
@Override
public Position3D getPosition() {
return position.clone();
}
@Override
public int getRadius() {
return radius;
}
@Override
public void setRadius(int newRadius) {
radius = newRadius;
onChangeProperty("radius", radius);
}
@Override
public int getCurrentPower() {
return power.getCurrent();
}
@Override
public void setCurrentPower(int currentPower) {
power.set(currentPower);
}
@Override
public boolean canCapture() {
return power.canCapture();
}
@Override
public int getMaxPower() {
return power.getMax();
}
@Override
public void setMaxPower(int maxPower) {
power.setMax(maxPower);
onChangeProperty("maxPower", power.getMax());
}
@Override
public Faction getOwner() {
return owner;
}
public void setOwner(Faction owner) {
this.owner = owner;
onChangeProperty("ownerId", (this.owner == null) ? 0 : this.owner.getId());
}
@Override
public boolean isOwner(Faction faction) {
return owner == faction;
}
public Occupation getOccupation() {
return occupation;
}
@Override
public boolean isFactionHasAnyConnection(Faction faction) {
if (connections != null) {
ControlPointManager manager = getWar().getControlPointManager();
for (int connection : connections) {
if (manager.findById(connection).isOwner(faction)) {
return true;
}
}
}
return false;
}
@Override
public boolean isConnectedTo(ControlPoint controlPoint) {
for (int connection : connections) {
if (controlPoint.getId() == connection) {
return true;
}
}
return false;
}
@Override
public Collection<ControlPoint> getConnections() {
Collection<ControlPoint> collection = new ArrayList<ControlPoint>();
if (connections != null) {
ControlPointManager manager = getWar().getControlPointManager();
for (int connection : connections) {
collection.add(manager.findById(connection));
}
}
return collection;
}
@Override
public void connectTo(ControlPoint controlPoint) {
if (connections == null) {
connections = new int[1];
connections[0] = controlPoint.getId();
} else {
if (isConnectedTo(controlPoint)) {
return;
}
int oldSize = connections.length;
connections = Arrays.copyOf(connections, oldSize + 1);
connections[oldSize] = controlPoint.getId();
}
controlPoint.connectTo(this);
onChangeProperty("connections", StringUtils.join(connections, ","));
}
@Override
public void disconnectFrom(ControlPoint controlPoint) {
if (connections != null && isConnectedTo(controlPoint)) {
int[] tmpConnections = new int[connections.length - 1];
int i = 0;
for (int connection : connections) {
if (controlPoint.getId() != connection) {
tmpConnections[i++] = connection;
}
}
connections = tmpConnections;
disconnectFrom(this);
onChangeProperty("connections", StringUtils.join(connections, ","));
}
}
@Override
public Sector getSector() {
return sector;
}
@Override
public void setSector(Sector sector) {
this.sector = sector;
onChangeProperty("sectorId", this.sector.getId());
}
@Override
public War getWar() {
return sector.getWar();
}
}
|
package com.auth0;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.*;
public class Auth0ServletCallback extends HttpServlet {
private Properties properties = new Properties();
private String redirectOnSuccess;
private String redirectOnFail;
private Tokens parseTokens(String body) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonAsMap = mapper.readValue(body, Map.class);
String accessToken = jsonAsMap.get("access_token");
String idToken = jsonAsMap.get("id_token");
return new Tokens(idToken, accessToken);
}
protected void saveTokens(HttpServletRequest req, HttpServletResponse resp, Tokens tokens) throws ServletException, IOException {
HttpSession session = req.getSession();
// Save tokens on a persistent session
session.setAttribute("accessToken", tokens.getAccessToken());
session.setAttribute("idToken", tokens.getIdToken());
}
protected void onSuccess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Redirect user to home
resp.sendRedirect(redirectOnSuccess);
}
private URI getURI(Properties properties) {
URI https;
try {
https = new URI("https", (String) properties.get("auth0.domain"), "/oauth/token", "");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return https;
}
private String getAuthorizationCode(HttpServletRequest req) {
String authorizationCode = null;
List<NameValuePair> queryString = URLEncodedUtils.parse(req.getQueryString(), Charset.forName("ASCII"));
for (NameValuePair pair : queryString) {
if ("code".equals(pair.getName())) {
authorizationCode = pair.getValue();
}
}
return authorizationCode;
}
/**
* Fetch properties to be used. User is encourage to override this method.
*
* Auth0 uses the ServletContext parameters:
*
* <dl>
* <dt>auth0.client_id</dd><dd>Application client id</dd>
* <dt>auth0.client_secret</dt><dd>Application client secret</dd>
* <dt>auth0.domain</dt><dd>Auth0 domain</dd>
* </dl>
*
* Auth0ServletCallback uses these ServletConfig parameters:
*
* <dl>
* <dt>auth0.redirect_after</dt><dd>Where to send the user after successful login.</dd>
* </dl>
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
redirectOnSuccess = config.getInitParameter("auth0.redirect_on_success");
if (redirectOnSuccess == null) {
throw new IllegalArgumentException("auth0.redirect_on_success parameter needs to be defined");
}
redirectOnFail = config.getInitParameter("auth0.redirect_on_error");
if (redirectOnFail == null) {
throw new IllegalArgumentException("auth0.redirect_on_error parameter needs to be defined");
}
Map<String, Boolean> requiredParametersChecklist = new HashMap<String, Boolean>();
StringBuilder missingParameters = new StringBuilder();
String [] requiredParametersName = {
"auth0.client_id", "auth0.client_secret",
"auth0.domain"};
for (String requiredParameterName : requiredParametersName) {
requiredParametersChecklist.put(requiredParameterName, false);
}
Enumeration initParameterNames = getServletContext().getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String key = (String) initParameterNames.nextElement();
String value = getServletContext().getInitParameter(key);
properties.put(key, value);
requiredParametersChecklist.put(key, true);
}
for (Map.Entry<String, Boolean> entry : requiredParametersChecklist.entrySet()) {
String key = entry.getKey();
Boolean value = entry.getValue();
if (!value) {
if (missingParameters.length() == 0) {
missingParameters.append("Error: The following required ServletContext parameters where not found: ");
}
missingParameters.append(key);
missingParameters.append(", ");
}
}
if (missingParameters.length() > 0) {
// Removing last ", "
missingParameters.setLength(missingParameters.length() - 2);
missingParameters.append(". They should be present in web.xml in a <context-param> tag.");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
validateRequest(req, resp);
Tokens tokens = fetchTokens(req);
saveTokens(req, resp, tokens);
onSuccess(req, resp);
}
private Tokens fetchTokens(HttpServletRequest req) throws UnsupportedEncodingException, IOException,
ClientProtocolException {
// Parse request to fetch authorization code
String authorizationCode = getAuthorizationCode(req);
URI accessTokenURI = getURI(properties);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(accessTokenURI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("client_id", (String) properties.get("auth0.client_id")));
nameValuePairs.add(new BasicNameValuePair("client_secret", (String) properties.get("auth0.client_secret")));
nameValuePairs.add(new BasicNameValuePair("redirect_uri", req.getRequestURL().toString()));
nameValuePairs.add(new BasicNameValuePair("code", authorizationCode));
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
CloseableHttpResponse response = httpClient.execute(httpPost);
String tokensToParse;
try {
HttpEntity entity = response.getEntity();
tokensToParse = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
// Parse and obtain both access token and id token
return parseTokens(tokensToParse);
}
private void validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (hasError(req) || !isValidState(req)) {
resp.sendRedirect(req.getContextPath() + redirectOnFail + "?" + req.getQueryString());
}
}
private boolean isValidState(HttpServletRequest req) {
return req.getParameter("state") != null && isValidState(req.getParameter("state"));
}
protected boolean isValidState(String state) {
return true;
}
private static boolean hasError(HttpServletRequest req) {
return req.getParameter("error") != null;
}
}
|
package me.johnnywoof;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Timer;
public class GameEngine {
public int moveLeftCount = 0;
public int moveRightCount = 0;
public final boolean[] tiles = new boolean[200];
public final Tetris tetris;
public final SecureRandom random = new SecureRandom();
public final boolean[] fallingTiles = new boolean[200];
private final Timer timer = new Timer();
public GameEngine(Tetris tetris) {
Arrays.fill(this.tiles, false);
Arrays.fill(this.fallingTiles, false);
this.tetris = tetris;
}
public void start() {
this.timer.scheduleAtFixedRate(new GameTickTask(this), 0, 200);
}
public void stopTicking() {
this.timer.cancel();
this.timer.purge();
}
public void tick() {
boolean anyFalling = false;
boolean deleteAllFalling = false;
for (int i = this.fallingTiles.length - 11; i >= 0; i
if (this.fallingTiles[i]) {
//System.out.println(i);
int nextIndex = (i + 10);
if (this.moveLeftCount > 0 || this.moveRightCount > 0) {
String intString = Integer.toString((nextIndex + this.moveRightCount));
if (Integer.parseInt(String.valueOf(intString.charAt(intString.length() - 1))) == 0) {
this.moveLeftCount = 0;
this.moveRightCount = 0;
}
nextIndex -= this.moveLeftCount;
nextIndex += this.moveRightCount;
}
if (this.tiles[nextIndex] && !this.fallingTiles[nextIndex]) {//Block already exists below us.
deleteAllFalling = true;
break;
}
}
}
if (deleteAllFalling) {
Arrays.fill(this.fallingTiles, false);
anyFalling = false;
} else {
for (int i = this.fallingTiles.length - 11; i >= 0; i
if (this.fallingTiles[i]) {
//System.out.println(i);
int nextIndex = (i + 10);
nextIndex -= this.moveLeftCount;
nextIndex += this.moveRightCount;
if (this.tiles[nextIndex]) {//Block already exists below us.
this.fallingTiles[i] = false;
this.tiles[i] = true;
} else {
this.fallingTiles[i] = false;
this.tiles[i] = false;
this.fallingTiles[nextIndex] = true;
this.tiles[nextIndex] = true;
anyFalling = true;
}
}
}
}
this.moveLeftCount = 0;
this.moveRightCount = 0;
if (!anyFalling) {
switch (this.random.nextInt(4)) {
case 0:
//Tri-piece thingy
this.fallingTiles[4] = true;
this.fallingTiles[14] = true;
this.fallingTiles[24] = true;
this.fallingTiles[34] = true;
break;
case 1:
//Long thingy
this.fallingTiles[4] = true;
this.fallingTiles[13] = true;
this.fallingTiles[14] = true;
this.fallingTiles[15] = true;
break;
case 2:
//L-shape
this.fallingTiles[4] = true;
this.fallingTiles[14] = true;
this.fallingTiles[24] = true;
this.fallingTiles[25] = true;
break;
default:
//Square
this.fallingTiles[4] = true;
this.fallingTiles[5] = true;
this.fallingTiles[14] = true;
this.fallingTiles[15] = true;
break;
}
}
this.tetris.repaint();
}
}
|
package ch.uzh.ddis.katts.bolts;
import java.util.Date;
import backtype.storm.tuple.Tuple;
import ch.uzh.ddis.katts.query.stream.StreamConsumer;
import ch.uzh.ddis.katts.query.stream.Variable;
import ch.uzh.ddis.katts.query.stream.VariableList;
public class StreamSynchronizedEventWrapper extends Event {
private Event event;
private Date synchronizationDate;
public StreamSynchronizedEventWrapper(Event event, Date synchronizationDate) {
this.event = event;
this.setSynchronizationDate(synchronizationDate);
}
public void ack() {
this.getBolt().ack(this);
}
@SuppressWarnings("unchecked")
public <T> T getVariableValue(Variable variable) {
return this.event.getVariableValue(variable);
}
public Tuple getTuple() {
return this.event.getTuple();
}
public void setTuple(Tuple tuple) {
this.event.setTuple(tuple);
}
/**
* @return the consumer instance on which this event has been emitted on.
*/
public StreamConsumer getEmittedOn() {
return this.event.getEmittedOn();
}
public void setEmittedOn(StreamConsumer emittedOn) {
this.event.setEmittedOn(emittedOn);
}
public Bolt getBolt() {
return this.event.getBolt();
}
public void setBolt(Bolt bolt) {
this.event.setBolt(bolt);
}
@Override
public int compareTo(Event event) {
Date dateCompareWith = event.getStartDate();
if (event instanceof StreamSynchronizedEventWrapper) {
dateCompareWith = ((StreamSynchronizedEventWrapper)event).getSynchronizationDate();
}
if (getSynchronizationDate().after((dateCompareWith))) {
return 1;
}
else if (getSynchronizationDate().before(dateCompareWith)) {
return -1;
}
else {
return 0;
}
}
public VariableList getVariables() {
return this.event.getVariables();
}
public long getSequenceNumber() {
return this.event.getSequenceNumber();
}
public void setSequenceNumber(long sequenceNumber) {
this.event.setSequenceNumber(sequenceNumber);
}
public Date getStartDate() {
return this.event.getStartDate();
}
public void setStartDate(Date startDate) {
this.event.setStartDate(startDate);
}
public Date getEndDate() {
return this.event.getEndDate();
}
public void setEndDate(Date endDate) {
this.event.setEndDate(endDate);
}
public Date getSynchronizationDate() {
return synchronizationDate;
}
public void setSynchronizationDate(Date synchronizationDate) {
this.synchronizationDate = synchronizationDate;
}
}
|
package com.etsy.statsd.profiler;
import com.etsy.statsd.profiler.profilers.CPUProfiler;
import com.etsy.statsd.profiler.profilers.MemoryProfiler;
import com.etsy.statsd.profiler.worker.ProfilerShutdownHookWorker;
import com.etsy.statsd.profiler.worker.ProfilerThreadFactory;
import com.etsy.statsd.profiler.worker.ProfilerWorkerThread;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import java.lang.instrument.Instrumentation;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* javaagent profiler using StatsD as a backend
*
* @author Andrew Johnson
*/
public class Agent {
public static final int EXECUTOR_DELAY = 0;
/**
* Parses profiler arguments into a map
*
* @param args A string containing the arguments
* @return A map of argument names to values
*/
private static Map<String, String> parseArgs(final String args) {
Map<String, String> parsed = new HashMap<>();
for (String argPair : args.split(",")) {
String[] tokens = argPair.split("=");
if (tokens.length != 2) {
throw new IllegalArgumentException("statsd-jvm-profiler takes a comma-delimited list of arguments in k=v form");
}
parsed.put(tokens[0], tokens[1]);
}
return parsed;
}
/**
* Start the profiler
*
* @param args Profiler arguments
* @param instrumentation Instrumentation agent
*/
public static void premain(final String args, final Instrumentation instrumentation) {
Map<String, String> argMap = parseArgs(args);
String statsdServer = argMap.get("server");
int statsdPort = Integer.valueOf(argMap.get("port"));
String prefix = argMap.get("prefix");
StatsDClient client = new NonBlockingStatsDClient(prefix, statsdServer, statsdPort);
Profiler memoryProfiler = new MemoryProfiler(client);
Profiler cpuProfiler = new CPUProfiler(client);
Collection<Profiler> profilers = Arrays.asList(memoryProfiler, cpuProfiler);
scheduleProfilers(profilers);
registerShutdownHook(profilers);
}
/**
* Schedule profilers with a SchedulerExecutorService
*
* @param profilers Collection of profilers to schedule
*/
private static void scheduleProfilers(Collection<Profiler> profilers) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(profilers.size(),
new ProfilerThreadFactory());
for (Profiler profiler : profilers) {
ProfilerWorkerThread worker = new ProfilerWorkerThread(profiler);
scheduledExecutorService.scheduleAtFixedRate(worker, EXECUTOR_DELAY, profiler.getPeriod(), profiler.getTimeUnit());
}
}
/**
* Register a shutdown hook to flush profiler data to StatsD
*
* @param profilers The profilers to flush at shutdown
*/
private static void registerShutdownHook(Collection<Profiler> profilers) {
Thread shutdownHook = new Thread(new ProfilerShutdownHookWorker(profilers));
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
|
package it.unibz.inf.ontop.model.term.functionsymbol.db.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.exception.MinorOntopInternalBugException;
import it.unibz.inf.ontop.iq.node.VariableNullability;
import it.unibz.inf.ontop.model.template.TemplateComponent;
import it.unibz.inf.ontop.model.term.*;
import it.unibz.inf.ontop.model.term.functionsymbol.FunctionSymbol;
import it.unibz.inf.ontop.model.term.functionsymbol.db.ObjectStringTemplateFunctionSymbol;
import it.unibz.inf.ontop.model.term.functionsymbol.impl.FunctionSymbolImpl;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TermTypeInference;
import it.unibz.inf.ontop.model.type.TypeFactory;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public abstract class ObjectStringTemplateFunctionSymbolImpl extends FunctionSymbolImpl
implements ObjectStringTemplateFunctionSymbol {
private final String template;
private final DBTermType lexicalType;
private final Pattern pattern;
private final boolean isInjective;
private final ImmutableList<TemplateComponent> components;
// Use for checking compatibility
private final String onlyAlwaysSafeSeparators;
/**
* TODO: enrich this list (incomplete)
*/
protected static final ImmutableSet<Character> SOME_SAFE_SEPARATORS = ImmutableSet.of(
'/','!','$','&','\'', '(', ')','*','+',',',';', '=', '
protected static final String NOT_A_SAFE_SEPARATOR_REGEX = "[^"
+ SOME_SAFE_SEPARATORS.stream()
.map(Object::toString)
.map(ObjectStringTemplateFunctionSymbolImpl::makeRegexSafe)
.collect(Collectors.joining())
+ "]*";
protected static final String PLACEHOLDER = "{}";
protected ObjectStringTemplateFunctionSymbolImpl(ImmutableList<TemplateComponent> components, TypeFactory typeFactory) {
super(extractStringTemplate(components), createBaseTypes(components, typeFactory));
this.template = extractStringTemplate(components);
this.lexicalType = typeFactory.getDBTypeFactory().getDBStringType();
this.components = components;
this.pattern = extractPattern(components);
this.isInjective = isInjective();
this.onlyAlwaysSafeSeparators = extractOnlyAlwaysSafeSeparators(template);
}
/**
* Must not produce false positive
*/
private boolean isInjective() {
long arity = components.stream()
.filter(TemplateComponent::isColumnNameReference)
.count();
if (arity < 2)
return true;
// two consecutive columns
for (int i = 1; i < components.size(); i++)
if (components.get(i - 1).isColumnNameReference()
&& components.get(i).isColumnNameReference())
return false;
/*
// the prefix and the suffix of the template do not matter
return components.subList(1, components.size() - 1).stream()
.filter(c -> !c.isColumnNameReference())
.map(TemplateComponent::getComponent)
.allMatch(s -> s.matches("[" + SAFE_SEPARATOR_REGEX_PART + "]"));
*/
return components.stream()
.filter(c -> !c.isColumnNameReference())
.map(TemplateComponent::getComponent)
.allMatch(s -> firstIndexOfSafeSeparator(s, 0) >= 0);
}
public static String extractStringTemplate(ImmutableList<TemplateComponent> template) {
return template.stream()
.map(c -> c.isColumnNameReference() ? PLACEHOLDER : c.getComponent())
.collect(Collectors.joining());
}
private static ImmutableList<TermType> createBaseTypes(ImmutableList<TemplateComponent> template, TypeFactory typeFactory) {
// TODO: require DB string instead
TermType stringType = typeFactory.getXsdStringDatatype();
return template.stream()
.filter(TemplateComponent::isColumnNameReference)
.map(c -> stringType)
.collect(ImmutableCollectors.toList());
}
@Override
public String getTemplate() {
return template;
}
@Override
public Optional<TermTypeInference> inferType(ImmutableList<? extends ImmutableTerm> terms) {
if(terms.stream()
.filter(t -> t instanceof Constant)
.anyMatch(t -> ((Constant)t).isNull())) {
return Optional.empty();
}
return Optional.of(TermTypeInference.declareTermType(lexicalType));
}
@Override
protected ImmutableTerm buildTermAfterEvaluation(ImmutableList<ImmutableTerm> newTerms,
TermFactory termFactory, VariableNullability variableNullability) {
if (newTerms.stream()
.allMatch(t -> t instanceof DBConstant)) {
String value = components.stream()
.map(c -> c.isColumnNameReference()
? encodeParameter((DBConstant)newTerms.get(c.getIndex()), termFactory, variableNullability)
: c.getComponent())
.collect(Collectors.joining());
return termFactory.getDBConstant(value, lexicalType);
}
else
return termFactory.getImmutableFunctionalTerm(this, newTerms);
}
private static String encodeParameter(DBConstant constant, TermFactory termFactory, VariableNullability variableNullability) {
return Optional.of(constant)
.map(termFactory::getR2RMLIRISafeEncodeFunctionalTerm)
.map(t -> t.simplify(variableNullability))
.filter(t -> t instanceof DBConstant)
.map(t -> ((DBConstant) t).getValue())
.orElseThrow(() -> new MinorOntopInternalBugException("Was expecting " +
"the getR2RMLIRISafeEncodeFunctionalTerm to simplify itself to a DBConstant " +
"when receiving a DBConstant"));
}
@Override
public boolean isAlwaysInjectiveInTheAbsenceOfNonInjectiveFunctionalTerms() {
return isInjective;
}
@Override
protected boolean mayReturnNullWithoutNullArguments() {
return false;
}
@Override
protected boolean tolerateNulls() {
return false;
}
@Override
public boolean canBePostProcessed(ImmutableList<? extends ImmutableTerm> arguments) {
return true;
}
@Override
public String getNativeDBString(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
ImmutableList<ImmutableTerm> termsToConcatenate = components.stream()
.map(c -> c.isColumnNameReference()
? termFactory.getR2RMLIRISafeEncodeFunctionalTerm(terms.get(c.getIndex()))
// Avoids the encoding when possible
.simplify()
: termFactory.getDBStringConstant(c.getComponent()))
.collect(ImmutableCollectors.toList());
ImmutableTerm concatTerm = termsToConcatenate.isEmpty()
? termFactory.getDBStringConstant("")
: (termsToConcatenate.size() == 1)
? termsToConcatenate.get(0)
: termFactory.getNullRejectingDBConcatFunctionalTerm(termsToConcatenate)
.simplify();
return termConverter.apply(concatTerm);
}
@Override
protected IncrementalEvaluation evaluateStrictEqWithFunctionalTerm(ImmutableList<? extends ImmutableTerm> terms,
ImmutableFunctionalTerm otherTerm, TermFactory termFactory,
VariableNullability variableNullability) {
FunctionSymbol otherFunctionSymbol = otherTerm.getFunctionSymbol();
if (otherFunctionSymbol instanceof ObjectStringTemplateFunctionSymbol) {
String otherTemplate = ((ObjectStringTemplateFunctionSymbol) otherFunctionSymbol).getTemplate();
if (!areCompatible(otherTemplate))
return IncrementalEvaluation.declareIsFalse();
}
// May decompose in case of injectivity
return super.evaluateStrictEqWithFunctionalTerm(terms, otherTerm, termFactory, variableNullability);
}
/**
* Is guaranteed not to return false negative.
*/
protected boolean areCompatible(String otherTemplate) {
if (template.equals(otherTemplate))
return true;
String prefix = extractPrefix(template);
String otherPrefix = extractPrefix(otherTemplate);
int minPrefixLength = Math.min(prefix.length(), otherPrefix.length());
// Prefix comparison
if (!prefix.substring(0, minPrefixLength).equals(otherPrefix.substring(0, minPrefixLength)))
return false;
/*
String suffix = extractSuffix(template);
String otherSuffix = extractSuffix(otherTemplate);
int minSuffixLength = Math.min(suffix.length(), otherSuffix.length());
if (!suffix.substring(suffix.length() - minSuffixLength).equals(otherSuffix.substring(otherSuffix.length() - minSuffixLength)))
return false;
*/
// Checks that both templates use the same safe separators in the same order
if (!extractOnlyAlwaysSafeSeparators(otherTemplate).equals(onlyAlwaysSafeSeparators))
return false;
ImmutableList<String> fragments = splitOnSafeSeparators(template.substring(minPrefixLength)); // , template.length() - minSuffixLength
ImmutableList<String> otherFragments = splitOnSafeSeparators(otherTemplate.substring(minPrefixLength)); // , otherTemplate.length() - minSuffixLength
if (fragments.size() != otherFragments.size())
throw new MinorOntopInternalBugException("Internal inconsistency detected while splitting IRI templates");
return IntStream.range(0, fragments.size())
.allMatch(i -> matchPatterns(fragments.get(i), otherFragments.get(i)));
}
private static ImmutableList<String> splitOnSafeSeparators(String s) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
int start = 0, end;
while ((end = firstIndexOfSafeSeparator(s, start)) != -1) {
builder.add(s.substring(start, end));
start = end + 1;
}
builder.add(s.substring(start));
return builder.build();
}
private static int firstIndexOfSafeSeparator(String s, int start) {
for (int i = start; i < s.length(); i++)
if (SOME_SAFE_SEPARATORS.contains(s.charAt(i)))
return i;
return -1;
}
private static boolean matchPatterns(String subTemplate1, String subTemplate2) {
return subTemplate1.equals(subTemplate2)
|| extractPattern(subTemplate1).matcher(subTemplate2).find()
|| extractPattern(subTemplate2).matcher(subTemplate1).find();
}
protected static Pattern extractPattern(String template) {
String tmpPlaceholder = UUID.randomUUID().toString().replace("-", "");
String safeTemplate = makeRegexSafe(template
.replace(PLACEHOLDER, tmpPlaceholder));
String patternString = safeTemplate
.replace(tmpPlaceholder, NOT_A_SAFE_SEPARATOR_REGEX);
return Pattern.compile("^" + patternString + "$");
}
protected static Pattern extractPattern(ImmutableList<TemplateComponent> components) {
String patternString = components.stream()
.map(c -> c.isColumnNameReference()
? "(" + NOT_A_SAFE_SEPARATOR_REGEX + ")"
: makeRegexSafe(c.getComponent()))
.collect(Collectors.joining());
return Pattern.compile("^" + patternString + "$");
}
private static String extractOnlyAlwaysSafeSeparators(String template) {
return template.chars()
.mapToObj(c -> (char) c)
.filter(SOME_SAFE_SEPARATORS::contains)
.collect(Collector.of(StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
}
private static String makeRegexSafe(String s) {
return s.replaceAll("[<(\\[{\\\\^=$!|\\]})?*+.>]", "\\\\$0");
}
private static String extractPrefix(String template) {
int index = template.indexOf("{");
return index >= 0
? template.substring(0, index)
: template;
}
private static String extractSuffix(String template) {
int index = template.lastIndexOf("}");
return index >= 0
? template.substring(index + 1)
: template;
}
@Override
protected IncrementalEvaluation evaluateStrictEqWithNonNullConstant(ImmutableList<? extends ImmutableTerm> terms,
NonNullConstant otherTerm, TermFactory termFactory,
VariableNullability variableNullability) {
String otherValue = otherTerm.getValue();
if (isInjective(terms, variableNullability, termFactory)) {
Matcher matcher = pattern.matcher(otherTerm.getValue());
if (matcher.find()) {
ImmutableExpression newExpression = termFactory.getConjunction(
IntStream.range(0, getArity())
.mapToObj(i -> termFactory.getStrictEquality(
termFactory.getR2RMLIRISafeEncodeFunctionalTerm(terms.get(i)),
termFactory.getDBStringConstant(matcher.group(i + 1)))))
.orElseThrow(() -> new MinorOntopInternalBugException(
"An ObjectStringTemplateFunctionSymbolImpl is expected to have a non-null arity"));
return newExpression.evaluate(variableNullability, true);
}
else
return IncrementalEvaluation.declareIsFalse();
}
else if (!areCompatible(otherValue))
return IncrementalEvaluation.declareIsFalse();
return super.evaluateStrictEqWithNonNullConstant(terms, otherTerm, termFactory, variableNullability);
}
@Override
public boolean isPreferringToBePostProcessedOverBeingBlocked() {
return true;
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _118 {
public static class Solution1 {
/**
* fill out values from left to right
*/
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
List<Integer> row = new ArrayList();
for (int i = 0; i < numRows; i++) {
row.add(0, 1);
for (int j = 1; j < row.size() - 1; j++) {
row.set(j, row.get(j) + row.get(j + 1));
}
result.add(new ArrayList(row));
}
return result;
}
}
public static class Solution2 {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
List<Integer> row = new ArrayList();
for (int i = 0; i < numRows; i++) {
for (int j = row.size() - 1; j >= 1; j
row.set(j, row.get(j) + row.get(j - 1));
}
row.add(1);
result.add(new ArrayList<>(row));
}
return result;
}
}
}
|
package com.orientechnologies.orient.core.exception;
import com.orientechnologies.common.exception.OHighLevelException;
/**
* This exception is thrown if access to the manager of tree-based RidBags will be prohibited.
*/
public class OAccessToSBtreeCollectionManagerIsProhibitedException extends OCoreException implements OHighLevelException {
public OAccessToSBtreeCollectionManagerIsProhibitedException(OAccessToSBtreeCollectionManagerIsProhibitedException exception) {
super(exception);
}
public OAccessToSBtreeCollectionManagerIsProhibitedException(String message) {
super(message);
}
}
|
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/
public class _136 {
public static class Solution1 {
/**
* Approach 1: use set, since this problem explicitly states that every element appears twice
* and only one appears once so, we could safely remove the ones that are already in the set,
* O(n) time and O(n) space. HashTable approach works similarly like this one, but it could be
* more easily extend to follow-up questions.
*/
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet();
for (int i : nums) {
if (!set.add(i)) {
set.remove(i);
}
}
Iterator<Integer> it = set.iterator();
return it.next();
}
}
public static class Solution2 {
/**
* Approach 2: bit manipulation, use exclusive or ^ to solve this problem: we're using the trick
* here: every number ^ itself will become zero, so, the only remaining element will be the one
* that appeared only once.
*/
public int singleNumber(int[] nums) {
int res = 0;
for (int i : nums) {
res ^= i;
}
return res;
}
}
}
|
package org.deviceconnect.android.deviceplugin.hue;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.philips.lighting.hue.sdk.PHAccessPoint;
import com.philips.lighting.hue.sdk.PHBridgeSearchManager;
import com.philips.lighting.hue.sdk.PHHueSDK;
import com.philips.lighting.hue.sdk.PHSDKListener;
import com.philips.lighting.model.PHBridge;
import com.philips.lighting.model.PHHueError;
import com.philips.lighting.model.PHHueParsingError;
import org.deviceconnect.android.deviceplugin.hue.profile.HueSystemProfile;
import org.deviceconnect.android.deviceplugin.hue.service.HueService;
import org.deviceconnect.android.message.DConnectMessageService;
import org.deviceconnect.android.profile.SystemProfile;
import org.deviceconnect.android.service.DConnectService;
import org.json.hue.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* DeviceConnect.
*
* @author NTT DOCOMO, INC.
*/
public class HueDeviceService extends DConnectMessageService {
private static final boolean DEBUG = BuildConfig.DEBUG;
private static final String TAG = "hue.dplugin";
private final Logger mLogger = Logger.getLogger("hue.dplugin");
/**
* Hue.
*/
private HueDBHelper mHueDBHelper;
@Override
public void onCreate() {
super.onCreate();
initHueSDK();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnectivityReceiver, filter);
}
@Override
public void onDestroy() {
unregisterReceiver(mConnectivityReceiver);
destroyHueSDK();
super.onDestroy();
}
@Override
protected void onManagerUninstalled() {
// Manager
if (BuildConfig.DEBUG) {
mLogger.info("Plug-in : onManagerUninstalled");
}
}
@Override
protected void onManagerTerminated() {
// Manager
if (BuildConfig.DEBUG) {
mLogger.info("Plug-in : onManagerTerminated");
}
}
@Override
protected void onDevicePluginReset() {
// Device Plug-inReset
if (BuildConfig.DEBUG) {
mLogger.info("Plug-in : onDevicePluginReset");
}
reconnectAccessPoints();
}
@Override
protected SystemProfile getSystemProfile() {
return new HueSystemProfile();
}
/**
* HueSDK.
*/
private void initHueSDK() {
if (DEBUG) {
Log.i(TAG, "HueDeviceService#initHueSDK");
}
mHueDBHelper = new HueDBHelper(getApplicationContext());
// hue SDK
PHHueSDK hueSDK = PHHueSDK.getInstance();
hueSDK.setAppName(HueConstants.APNAME);
hueSDK.setDeviceName(HueConstants.APNAME);
hueSDK.getNotificationManager().registerSDKListener(mPhListener);
if (DEBUG) {
Log.i(TAG, "@@@@@@ PHHueSDK version: " + hueSDK.getSDKVersion());
Log.i(TAG, "@@@@@@ PHHueSDK App Name: " + hueSDK.getAppName());
Log.i(TAG, "@@@@@@ PHHueSDK Device Name: " + hueSDK.getDeviceName());
}
reconnectAccessPoints();
}
/**
* HueSDK.
*/
private void destroyHueSDK() {
if (DEBUG) {
Log.i(TAG, "HueDeviceService#destroyHueSDK");
}
// hue SDK
PHHueSDK hueSDK = PHHueSDK.getInstance();
hueSDK.getNotificationManager().unregisterSDKListener(mPhListener);
hueSDK.disableAllHeartbeat();
hueSDK.destroySDK();
}
/**
* Hue.
*
* @param hueSDK Hue SDK
* @param accessPoint
*/
private void addHueService(final PHHueSDK hueSDK, final PHAccessPoint accessPoint) {
HueService service = (HueService) getServiceProvider().getService(accessPoint.getIpAddress());
if (service == null) {
service = new HueService(accessPoint);
getServiceProvider().addService(service);
}
service.setOnline(hueSDK.isAccessPointConnected(accessPoint));
}
private void reconnectAccessPoints() {
if (DEBUG) {
mLogger.fine("HueDeviceService#reconnectAccessPoints");
}
PHHueSDK hueSDK = PHHueSDK.getInstance();
List<PHAccessPoint> accessPoints = mHueDBHelper.getAccessPoints();
for (PHAccessPoint accessPoint : accessPoints) {
if (DEBUG) {
mLogger.info("AccessPoint: " + accessPoint.getMacAddress() + " " + accessPoint.getIpAddress());
}
if (!hueSDK.isAccessPointConnected(accessPoint)) {
hueSDK.connect(accessPoint);
}
addHueService(hueSDK, accessPoint);
}
PHBridgeSearchManager sm = (PHBridgeSearchManager) hueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(true, true);
}
/**
* DB.
*
* @param service Hue
*/
public void removeHueService(final HueService service) {
mHueDBHelper.removeAccessPointByIpAddress(service.getId());
}
/**
* Hue.
*/
private final PHSDKListener mPhListener = new PHSDKListener() {
@Override
public void onAccessPointsFound(final List<PHAccessPoint> accessPoints) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onAccessPointsFound: accessPoint" +
"=" + accessPoints);
}
PHHueSDK hueSDK = PHHueSDK.getInstance();
if (accessPoints != null && accessPoints.size() > 0) {
hueSDK.getAccessPointsFound().clear();
hueSDK.getAccessPointsFound().addAll(accessPoints);
for (PHAccessPoint accessPoint : accessPoints) {
PHAccessPoint ap = mHueDBHelper.getAccessPointByMacAddress(accessPoint.getMacAddress());
if (ap != null) {
accessPoint.setUsername(ap.getUsername());
}
addHueService(hueSDK, accessPoint);
}
} else {
PHBridgeSearchManager sm = (PHBridgeSearchManager) hueSDK.getSDKService(PHHueSDK.SEARCH_BRIDGE);
sm.search(false, false, true);
}
}
@Override
public void onCacheUpdated(final List<Integer> cacheNotificationsList, final PHBridge bridge) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onCacheUpdated: cacheNotificationsList=" + cacheNotificationsList + ", bridge=" + bridge);
}
}
@Override
public void onBridgeConnected(final PHBridge phBridge, final String userName) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onBridgeConnected: bridge=" + phBridge + ", userName=" + userName);
}
String ipAddress = phBridge.getResourceCache().getBridgeConfiguration().getIpAddress();
String macAddress = phBridge.getResourceCache().getBridgeConfiguration().getMacAddress();
PHHueSDK hueSDK = PHHueSDK.getInstance();
hueSDK.setSelectedBridge(phBridge);
hueSDK.addBridge(phBridge);
hueSDK.enableHeartbeat(phBridge, PHHueSDK.HB_INTERVAL);
hueSDK.getLastHeartbeat().put(ipAddress, System.currentTimeMillis());
DConnectService service = getServiceProvider().getService(ipAddress);
if (service != null) {
service.setOnline(true);
}
PHAccessPoint accessPoint = new PHAccessPoint();
accessPoint.setUsername(userName);
accessPoint.setIpAddress(ipAddress);
accessPoint.setMacAddress(macAddress);
if (!mHueDBHelper.hasAccessPoint(accessPoint)) {
mHueDBHelper.addAccessPoint(accessPoint);
} else {
mHueDBHelper.updateAccessPoint(accessPoint);
}
}
@Override
public void onAuthenticationRequired(final PHAccessPoint accessPoint) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onAuthenticationRequired: accessPoint=" + accessPoint);
}
}
@Override
public void onConnectionResumed(final PHBridge bridge) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onConnectionResumed: bridge=" + bridge);
}
String ipAddress = bridge.getResourceCache().getBridgeConfiguration().getIpAddress();
PHHueSDK hueSDK = PHHueSDK.getInstance();
for (int i = 0; i < hueSDK.getDisconnectedAccessPoint().size(); i++) {
if (hueSDK.getDisconnectedAccessPoint().get(i).getIpAddress().equals(ipAddress)) {
hueSDK.getDisconnectedAccessPoint().remove(i);
}
}
DConnectService service = getServiceProvider().getService(ipAddress);
if (service != null) {
service.setOnline(true);
}
}
@Override
public void onConnectionLost(final PHAccessPoint accessPoint) {
if (DEBUG) {
Log.i(TAG, "PHSDKListener:#onConnectionLost: accessPoint=" + accessPoint);
}
PHHueSDK hueSDK = PHHueSDK.getInstance();
if (!hueSDK.getDisconnectedAccessPoint().contains(accessPoint)) {
hueSDK.getDisconnectedAccessPoint().add(accessPoint);
}
DConnectService service = getServiceProvider().getService(accessPoint.getIpAddress());
if (service != null) {
service.setOnline(false);
}
}
@Override
public void onError(final int code, final String message) {
if (DEBUG) {
Log.e(TAG, "PHSDKListener:#onError: code=" + code + ", message=" + message);
}
if (code == PHHueError.AUTHENTICATION_FAILED) {
PHHueSDK hueSDK = PHHueSDK.getInstance();
List<PHBridge> bridges = new ArrayList<PHBridge>(hueSDK.getAllBridges());
for (PHBridge bridge : bridges) {
hueSDK.disableHeartbeat(bridge);
hueSDK.disconnect(bridge);
}
reconnectAccessPoints();
}
}
@Override
public void onParsingErrors(final List<PHHueParsingError> errors) {
if (DEBUG) {
Log.e(TAG, "PHSDKListener:#onParsingErrors");
for (PHHueParsingError error : errors) {
Log.e(TAG, "
Log.e(TAG, "code: " + error.getCode() + ", " + error.getMessage());
JSONObject obj = error.getJSONContext();
if (obj != null) {
Log.e(TAG, "" + obj.toString(4));
}
}
Log.e(TAG, "==");
}
}
};
private BroadcastReceiver mConnectivityReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
reconnectAccessPoints();
}
}
}
};
}
|
package com.awesometickets.web.controller.response;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.HashMap;
import java.util.Map;
/**
* Store custom error codes and their status code and information.
*/
public class ErrorStatus {
public static final int BAD_REQUEST = 0;
public static final int RESOURCE_NOT_FOUND = 1;
public static final int PHONE_INVALID_FORMAT = 100;
public static final int SMS_SEND_FAIL = 101;
public static final int SMS_MISMATCH = 102;
public static final int SEAT_UNAVAILABLE = 200;
public static final int SEAT_NOT_FOUND = 201;
public static final int PHONE_NOT_VERIFIED = 202;
public static final int PURCHASE_UNAVAILABLE = 203;
public static final int PHONE_MISMATCH = 300;
public static final int TICKET_CODE_NOT_FOUND = 301;
public static final int TICKET_CHECKED = 400;
private static Map<Integer, String> infoMap;
private static Map<Integer, Integer> statusMap;
/**
* Return the information of the custom error code.
*
* @param code The custom error code.
*/
public static String info(int code) {
return infoMap.get(code);
}
/**
* Return the http status code of the custom error code.
*
* @param code The custom error code.
*/
public static int status(int code) {
return (Integer) statusMap.get(code);
}
/**
* Initialize data.
*/
public static void init() {
infoMap = new HashMap<Integer, String>();
statusMap = new HashMap<Integer, Integer>();
infoMap.put(BAD_REQUEST, "Invalid parameters.");
statusMap.put(BAD_REQUEST, 400);
infoMap.put(RESOURCE_NOT_FOUND, "Resource not found.");
statusMap.put(RESOURCE_NOT_FOUND, 404);
infoMap.put(PHONE_INVALID_FORMAT, "Invalid phone number. Require 11 numbers.");
statusMap.put(PHONE_INVALID_FORMAT, 400);
infoMap.put(SMS_SEND_FAIL, "Fail to send sms code.");
statusMap.put(SMS_SEND_FAIL, 400);
infoMap.put(SMS_MISMATCH, "Wrong sms code.");
statusMap.put(SMS_MISMATCH, 400);
infoMap.put(SEAT_UNAVAILABLE, "Seat already taken.");
statusMap.put(SEAT_UNAVAILABLE, 400);
infoMap.put(SEAT_NOT_FOUND, "Seat not found.");
statusMap.put(SEAT_NOT_FOUND, 400);
infoMap.put(PHONE_NOT_VERIFIED, "Unverified phone number.");
statusMap.put(PHONE_NOT_VERIFIED, 400);
infoMap.put(PURCHASE_UNAVAILABLE, "The user with this phone cannot buy more tickets today.");
statusMap.put(PURCHASE_UNAVAILABLE, 403);
infoMap.put(PHONE_MISMATCH, "Wrong phone number.");
statusMap.put(PHONE_MISMATCH, 400);
infoMap.put(TICKET_CODE_NOT_FOUND, "Ticket code not found.");
statusMap.put(TICKET_CODE_NOT_FOUND, 400);
infoMap.put(TICKET_CHECKED, "Ticket already checked.");
statusMap.put(TICKET_CHECKED, 400);
}
}
|
package model.dao.diary;
// #00011 : import change required
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javafx.scene.chart.PieChart.Data;
import jdbc.exception.RecordNotFoundException;
import model.vo.day.Day;
import model.vo.diary.Diary;
import model.vo.diary.Memo;
import model.vo.diary.Note;
import model.vo.diary.Schedule;
import sql.DataSourceManager;
import sql.StringQuery;
import util.CocoaDate;
import util.IntegerRange;
public class DiaryDAO {
private static DiaryDAO dao = new DiaryDAO();
private DiaryDAO() {}
public static DiaryDAO getInstance() {
return dao;
}
// query static
private static final int TRUE = 1;
private static final int FALSE = 0;
public Connection getConnection() throws SQLException{
return DataSourceManager.getInstance().getConnection();
}
public void closeAll(PreparedStatement ps, Connection conn)throws SQLException{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
public void closeAll(ResultSet rs,PreparedStatement ps, Connection conn)throws SQLException{
if(rs!=null){
rs.close();
closeAll(ps, conn);
}
}
public Vector<Note> getAllNote(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Note> n = null;
try {
conn = getConnection();
n = new Vector<Note>();
ps = conn.prepareStatement(StringQuery.GET_ALL_NOTE);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()) {
Note m = new Note(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(new Date(rs.getDate("wrt_date").getTime())), // writeDate
rs.getString("content"), // content
new CocoaDate(new Date(rs.getDate("curr_date").getTime())), // currentDate
rs.getString("title")); // title
n.add(m);
}
} catch(SQLException e) {
System.out.println("ERROR : [DiaryDAO]@getAllMemo : SQLException Caught !");
e.printStackTrace();
} finally {
System.out.println("[DiaryDAO]@getAllMemo : Arrived finally clause");
closeAll(rs,ps,conn);
}
return n;
}
public Vector<Schedule> getAllSchedule(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Schedule> sc = null;
String[] temp_str = {};
try {
conn = getConnection();
sc = new Vector<Schedule>();
ps= conn.prepareStatement(StringQuery.GET_ALL_SCHEDULE);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()) {
sc.add(new Schedule(rs.getInt("schedule_no"),
rs.getString("id"),
rs.getString("title"), // title
rs.getString("content"), // content
temp_str, // group
new CocoaDate(new Date(rs.getTimestamp("start_date").getTime())), // startDate
new CocoaDate(new Date(rs.getTimestamp("end_date").getTime())))); // endDate
}
}catch(Exception e) {
System.out.println("ERROR : [DiaryDAO]@getAllSchedule : SQLException Caught !");
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
System.out.println("[DiaryDAO]@getAllSchedule : Arrived finally clause");
}
return sc;
}
public Vector<Memo> getAllMemo(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Memo> m = null;
try {
conn = getConnection();
m = new Vector<Memo>();
ps= conn.prepareStatement(StringQuery.GET_ALL_MEMO);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()) {
m.add(new Memo(rs.getInt("memo_no"),
id,
new CocoaDate(new Date(rs.getTimestamp("wrt_date").getTime())),
rs.getString("content")));
}
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return m;
}
public Map<Integer,Note> searchNoteByKeyword(String id, String keyword) {
Connection conn = null;
Map<Integer,Note> result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
result = new HashMap<Integer,Note>();
ps = conn.prepareStatement(StringQuery.SEARCH_NOTE_BY_KEYWORD);
ps.setString(1, id);
ps.setString(2, keyword);
ps.setString(3, keyword);
rs = ps.executeQuery();
while(rs.next()) {
if(rs.getString("title").toLowerCase().contains((keyword.toLowerCase())) || rs.getString("content").toLowerCase().contains(keyword.toLowerCase())) {
if(!result.containsKey(rs.getInt("note_no")) ){
Note n = new Note(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(new Date(rs.getTimestamp("wrt_date").getTime())),
rs.getString("content"),
new CocoaDate(new Date(rs.getTimestamp("curr_date").getTime())),
rs.getString("title"));
result.put(rs.getInt("note_no"), n);
}
}
}
} catch (SQLException e) {
}
return result;
}
public Map<Integer,Memo> searchMemoByKeyword(String id, String keyword) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Map<Integer,Memo> memo = null;
try {
conn = getConnection();
memo = new HashMap<Integer,Memo>();
ps = conn.prepareStatement(StringQuery.SEARCH_MEMO_BY_KEYWORD);
ps.setString(1, id);
ps.setString(2, keyword);
rs=ps.executeQuery();
while(rs.next()) {
if(rs.getString("content").toLowerCase().contains(keyword.toLowerCase())) {
if(!memo.containsKey(rs.getInt("memo_no"))){
Memo m = new Memo(rs.getInt("memo_no"),
id,
new CocoaDate(new Date(rs.getTimestamp("wrt_date").getTime())),
rs.getString("content"));
memo.put(rs.getInt("memo_no"), m);
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return memo;
}
public Map<Integer,Schedule> searchScheduleByKeyword(String id, String keyword) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Map<Integer,Schedule> sc = null;
String[] temp_str = {};
try {
conn = getConnection();
sc = new HashMap<Integer, Schedule>();
ps= conn.prepareStatement(StringQuery.SEARCH_SCHEDULE_BY_KEYWORD );
ps.setString(1, id);
ps.setString(2, keyword);
ps.setString(3, keyword);
rs = ps.executeQuery();
while(rs.next()) {
if(rs.getString("title").equalsIgnoreCase(keyword) || rs.getString("content").equalsIgnoreCase(keyword)) {
if(!sc.containsKey(rs.getInt("schedule_no"))){
Schedule s = new Schedule(rs.getInt("schedule_no"),
rs.getString("id"),
rs.getString("title"), // title
rs.getString("content"), // content
temp_str, // group
new CocoaDate(new Date(rs.getTimestamp("start_date").getTime())), // startDate
new CocoaDate(new Date(rs.getTimestamp("end_date").getTime()))); // endDate
sc.put(rs.getInt("schedule_no"), s);
}}}
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return sc;
}
public int getCurrDiaryNo() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int currNo = 0;
try {
conn = getConnection();
ps= conn.prepareStatement(StringQuery.GET_CURR_DIARYNO);
rs = ps.executeQuery();
if(rs.next()) currNo = rs.getInt(1);
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
// #00118
return currNo-1;
}
public Memo writeDiary(Memo memo) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Memo rmemo = memo;
int currNo = 0;
try {
conn = getConnection();
ps= conn.prepareStatement(StringQuery.WRITE_MEMO);
ps.setString(1, memo.getId());
ps.setString(2, memo.getContent());
ps.setString(3, memo.getWriteDate().getDateQuery());
ps.executeUpdate();
currNo = getCurrDiaryNo();
rmemo.setNo(currNo);
}catch(Exception e) {
System.out.println("[DiaryDAO]@writeDiary(Memo memo) : SQLException");
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return rmemo;
}
public Note writeDiary(Note note) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Note rnote = note;
int currNo = 0;
try {
conn = getConnection();
ps= conn.prepareStatement(StringQuery.WRITE_NOTE);
//note_no, id, title, content, wrt_date, curr_date
ps.setString(1, note.getId());
ps.setString(2, note.getTitle());
ps.setString(3, note.getContent());
ps.setString(4, note.getWriteDate().getDateQuery());
ps.setString(5, note.getWriteDate().getDateQuery());
ps.executeUpdate();
currNo = getCurrDiaryNo();
rnote.setNo(currNo);
}catch(Exception e) {
System.out.println("[DiaryDAO]@writeDiary(Note note) : SQLException");
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return rnote;
}
public Schedule writeDiary(Schedule schedule) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
Schedule rSchedule = null;
try {
conn = getConnection();
rSchedule = schedule;
ps = conn.prepareStatement(StringQuery.WRITE_SCHEDULE);
ps.setString(1, schedule.getId());
ps.setString(2, schedule.getStartDate().getDateQuery());
ps.setString(3, schedule.getEndDate().getDateQuery());
ps.setString(4, schedule.getTitle());
ps.setString(5, schedule.getContent());
ps.executeUpdate();
rSchedule.setNo(getCurrDiaryNo());
System.out.println("[DiaryDAO]@writeDiary(Schedule schedule) : currNo : " + rSchedule.getNo());
}catch(Exception e) {
System.out.println("[DiaryDAO]@writeDiary(Schedule schedule) : SQLException !");
e.printStackTrace();
}finally {
closeAll(ps, conn);
}
return rSchedule;
}
public void createScheduleGroup(Schedule schedule, String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(StringQuery.WRITE_SCHEDULE_GROUP);
ps.setInt(1, schedule.getNo());
ps.setString(2, id);
ps.executeUpdate();
System.out.println("[DiaryDAO]@createScheduleGroup(Schedule schedule, String id) : Success ! ");
} catch(SQLException e) {
System.out.println("[DiaryDAO]@createScheduleGroup(Schedule schedule, String id) : SQLException !");
e.printStackTrace();
} finally {
closeAll(ps, conn);
}
}
public ArrayList<Day> getMonthlyDiary(String id, CocoaDate date) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Day> monthlyDiary = new ArrayList<>();
Day day = new Day();
String lookingDate = "";
try {
conn = getConnection();
for(int j=1;j<date.getStartDay();j++) monthlyDiary.add(new Day());
for(int i=date.getRenewCal().get(Calendar.DATE);i<=date.getLastDate();i++) {
lookingDate = date.getDateQuery().substring(0, 6);
day = new Day(new CocoaDate(date.getYear(), date.getMonth(), i));
ps= conn.prepareStatement(StringQuery.GET_DAILY_NOTE_BY_ID);
if(i<10) lookingDate = lookingDate+"0"+i;
else lookingDate = lookingDate+i+"";
ps.setString(1, id);
ps.setString(2, lookingDate);
System.out.println("find for note : " + lookingDate);
rs = ps.executeQuery();
while(rs.next())
day.getNotes().add(new Note(rs.getInt("note_no"),
id, date,
rs.getString("content"),
new CocoaDate(new Date(rs.getTimestamp("curr_date").getTime())),
rs.getString("title")));
ps= conn.prepareStatement(StringQuery.GET_DAILY_SCHEDULE_BY_ID);
ps.setString(1, id);
ps.setString(2, lookingDate);
System.out.println("find for schedule : " + lookingDate);
rs = ps.executeQuery();
while(rs.next())
day.getSchedules().add(new Schedule(rs.getInt("schedule_no"),
id, rs.getString("title"),
rs.getString("content"),
new String[] {},
new CocoaDate(new Date(rs.getTimestamp("start_date").getTime())),
new CocoaDate(new Date(rs.getTimestamp("end_date").getTime()))));
monthlyDiary.add(day);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return monthlyDiary;
}
public Schedule getScheduleByNo(int no) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Schedule sc = null;
String[] temp_str = {};
try {
conn = getConnection();
ps = conn.prepareStatement(StringQuery.GET_SCHEDULE_BY_NO);
ps.setInt(1, no);
rs = ps.executeQuery();
if(rs.next()) {
sc = new Schedule(rs.getInt("schedule_no"),
rs.getString("id"),
rs.getString("title"),
rs.getString("content"),
temp_str,
new CocoaDate(new Date(rs.getTimestamp("start_date").getTime())),
new CocoaDate(new Date(rs.getTimestamp("end_date").getTime())));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(rs, ps, conn);
}
return sc;
}
public int deleteDiary(int no) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
int queryResult = FALSE;
int result = Diary.NAD;
try {
conn = getConnection();
ps = conn.prepareStatement(StringQuery.DELETE_SCHEDULE_BY_NO);
ps.setInt(1, no);
queryResult = ps.executeUpdate();
if (queryResult==TRUE) {
// diary = (Schedule);
System.out.println("[DiaryDAO]@deleteDiary(int no) :" +no+ " .");
return Diary.SCHEDULE;
} else {
ps = conn.prepareStatement(StringQuery.DELETE_MEMO_BY_NO);
ps.setInt(1, no);
queryResult = ps.executeUpdate();
if (queryResult==TRUE) {
System.out.println("[DiaryDAO]@deleteDiary(int no) :" +no+ " .");
return Diary.MEMO;
} else {
ps = conn.prepareStatement(StringQuery.DELETE_NOTE_BY_NO);
ps.setInt(1, no);
queryResult = ps.executeUpdate();
if (queryResult==TRUE) {
System.out.println("[DiaryDAO]@deleteDiary(int no) :" +no+ " .");
return Diary.NOTE;
} else {
// diary
System.out.println("[DiaryDAO]@deleteDiary(int no) : diary . ");
return Diary.NAD;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(ps, conn);
}
return result;
}
public Vector<Note> getNoteList(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Note> n = null;
try {
conn = getConnection();
n = new Vector<Note>();
ps = conn.prepareStatement(StringQuery.GET_ALL_NOTE);
ps.setString(1, id);
rs = ps.executeQuery();
while(rs.next()) {
Note m = new Note(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(new Date(rs.getDate("wrt_date").getTime())), // writeDate
rs.getString("content"), // content
new CocoaDate(new Date(rs.getDate("curr_date").getTime())), // currentDate
rs.getString("title")); // title
n.add(m);
}
} catch(SQLException e) {
System.out.println("ERROR : [DiaryDAO]@getNoteList : SQLException Caught !");
e.printStackTrace();
} finally {
System.out.println("[DiaryDAO]@getNoteList : Arrived finally clause");
closeAll(rs,ps,conn);
}
return n;
}
public Note getNoteByNo(int no) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Note note = new Note();
try {
conn = getConnection();
ps = conn.prepareStatement(StringQuery.GET_NOTE_BY_NO);
ps.setInt(1, no);
rs = ps.executeQuery();
if(rs.next()) {
note = new Note(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(new Date(rs.getDate("wrt_date").getTime())), // writeDate
rs.getString("content"), // content
new CocoaDate(new Date(rs.getDate("curr_date").getTime())), // currentDate
rs.getString("title")); // title
}
} catch(SQLException e) {
System.out.println("ERROR : [DiaryDAO]@getNoteByNo : SQLException Caught !");
e.printStackTrace();
} finally {
System.out.println("[DiaryDAO]@getNoteByNo : Arrived finally clause");
closeAll(rs,ps,conn);
}
return note;
}
public Note updateNote(int no, String title, String content) throws SQLException, RecordNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
Note note = null;
try {
conn = getConnection();
// 1. Search Note by No.
note = getNoteByNo(no);
if(note == null) throw new RecordNotFoundException("[DiaryDAO]@updateNote : No Such Note Found !");
else System.out.println("[DiaryDAO]@updateNote : Found note with no : " + no);
// 2. Excute query (sql.StringQuery.UPDATE_NOTE)
ps = conn.prepareStatement(StringQuery.UPDATE_NOTE);
ps.setString(1, title);
ps.setString(2, content);
ps.setInt(3, no);
ps.executeUpdate();
System.out.println("[DiaryDAO]@updateNote : Update Complete for Note no : " + no);
// To return note instance
note = getNoteByNo(no);
} catch(SQLException e) {
System.out.println("[DiaryDAO]@updateNote : Update Failed for Note.no : " + no);
System.out.println("[DiaryDAO]@updateNote : SQLException !");
e.printStackTrace();
} finally {
closeAll(ps, conn);
}
return note;
}
public Schedule updateSchedule(int no, String title, String content, CocoaDate start_date, CocoaDate end_date) throws SQLException, RecordNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
Schedule schedule = null;
try{
conn = getConnection();
// 1. Find Schedule by No.
schedule = getScheduleByNo(no);
if(schedule == null) throw new RecordNotFoundException("[DiaryDAO]@updateSchedule : No Such Schedule Found with no : " + no);
else System.out.println("[DiaryDAO]@updateSchedule : Found schedule with no : " + no);
// 2. Execute query (sql.StringQuery.UPDATE_SCHEDULE)
ps = conn.prepareStatement(StringQuery.UPDATE_SCHEDULE);
ps.setString(1, title);
ps.setString(2, content);
ps.setString(3, start_date.getDateQuery());
ps.setString(4, end_date.getDateQuery());
ps.setInt(5, no);
ps.executeUpdate();
System.out.println("[DiaryDAO]@updateSchedule : Update Complete for Schedule.no : " + no);
schedule.setTitle(title);
schedule.setContent(content);
schedule.setStartDate(start_date);
schedule.setEndDate(end_date);
} catch(SQLException e) {
System.out.println("[DiaryDAO]@updateSchedule : Update Failed for Schedule.no : " + no);
System.out.println("[DiaryDAO]@updateSchedule : SQLException !");
e.printStackTrace();
} finally {
closeAll(ps, conn);
}
return schedule;
}
public Day getDay(String id, int year, int month, int date) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
CocoaDate searchDate = null;
Day day = null;
Vector<Note> notes;
Vector<Schedule> schedules;
try {
conn = getConnection();
// 1. Find all Diary Items for the member.
searchDate = new CocoaDate(year, month, date);
day = new Day(searchDate);
notes = getAllNote(id);
schedules = getAllSchedule(id);
if( notes == null && schedules == null) {
System.out.println("[DiaryDAO]@getDay : No Notes Found for Member id : " + id);
} else {
// in case member has either notes or schedules
/*
for(Note note : notes) {
if(searchDate.getYear() == note.getWriteDate().getYear() &&
searchDate.getMonth() == note.getWriteDate().getMonth() &&
searchDate.getDate() == note.getWriteDate().getDate()) {
day.getNotes().add(note);
}
}
*/
// #00157 : Apply CocoaDate.compareDate()
for(Note note : notes) if(searchDate.compareDate(note.getWriteDate())) day.getNotes().add(note);
/*
for(Schedule schedule : schedules) {
if(IntegerRange.betweenInclusive(searchDate.getYear(), schedule.getStartDate().getYear(), schedule.getEndDate().getYear()))
if(IntegerRange.betweenInclusive(searchDate.getMonth(), schedule.getStartDate().getMonth(), schedule.getEndDate().getMonth()))
if(IntegerRange.betweenInclusive(searchDate.getDate(), schedule.getStartDate().getDate(), schedule.getEndDate().getDate()))
day.getSchedules().add(schedule);
}
*/
// #00157 : Apply CocoaDate.compareDate()
for(Schedule schedule : schedules)
if(searchDate.compareDate(schedule.getStartDate(), schedule.getEndDate())) day.getSchedules().add(schedule);
}
} catch(SQLException e) {
System.out.println("[DiaryDAO]@getDay : SQLException !");
} finally {
conn.close();
}
return day;
}
public int getCurrNoteNo() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int currNo = 0;
try {
conn = getConnection();
ps= conn.prepareStatement(StringQuery.GET_CURR_NOTE_NO);
rs = ps.executeQuery();
if(rs.next()) currNo = rs.getInt(1);
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
// #00133
return currNo-1;
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.HashSet;
import java.util.Set;
public class _160 {
public static class Solution1 {
/**
* Time: O(max(m, n))
* Space: O(1)
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA = findLen(headA);
int lenB = findLen(headB);
/**align headA and headB to the same starting point and then move together until we find the intersection point*/
while (lenA < lenB) {
headB = headB.next;
lenB
}
while (lenB < lenA) {
headA = headA.next;
lenA
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
private int findLen(ListNode head) {
int len = 0;
while (head != null) {
head = head.next;
len++;
}
return len;
}
}
public static class Solution2 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode a = headA;
ListNode b = headB;
/**if a and b have different lengths, then it will stop the loop after second iteration*/
while (a != b) {
/**for the first iteration, it'll just reset the pointer to the head of another linkedlist*/
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}
public static class Solution3 {
/**
* O(m+n) time
* O(Math.max(m, n)) space
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while (headA != null) {
set.add(headA);
headA = headA.next;
}
while (headB != null) {
if (set.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}
}
|
package com.fishercoder.solutions;
import java.util.Arrays;
public class _259 {
public static class Solution1 {
/**
* Basically, very similar to 3Sum, but the key is that you'll have to add result by (right-left), not just increment result by 1!
*/
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int result = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < target) {
result += right - left;//this line is key!
left++;//then increment left to continue to see all possibilities
} else {
right
}
}
}
return result;
}
}
}
|
package org.eclipse.birt.report.engine.emitter.html;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IHTMLActionHandler;
import org.eclipse.birt.report.engine.api.IHTMLImageHandler;
import org.eclipse.birt.report.engine.api.IImage;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.InstanceID;
import org.eclipse.birt.report.engine.api.RenderOptionBase;
import org.eclipse.birt.report.engine.api.impl.Action;
import org.eclipse.birt.report.engine.api.impl.Image;
import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IElement;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IGroupContent;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListBandContent;
import org.eclipse.birt.report.engine.content.IListGroupContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableBandContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITableGroupContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.css.engine.value.birt.BIRTConstants;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants;
import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter;
import org.eclipse.birt.report.engine.emitter.IEmitterServices;
import org.eclipse.birt.report.engine.emitter.html.util.HTMLEmitterUtil;
import org.eclipse.birt.report.engine.executor.ExecutionContext.ElementExceptionInfo;
import org.eclipse.birt.report.engine.executor.css.HTMLProcessor;
import org.eclipse.birt.report.engine.i18n.EngineResourceHandle;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.EngineIRConstants;
import org.eclipse.birt.report.engine.ir.MasterPageDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
import org.eclipse.birt.report.engine.ir.TemplateDesign;
import org.eclipse.birt.report.engine.parser.TextParser;
import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.core.IModuleModel;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ibm.icu.util.ULocale;
/**
* <code>HTMLReportEmitter</code> is a subclass of
* <code>ContentEmitterAdapter</code> that implements IContentEmitter
* interface to output IARD Report ojbects to HTML file.
*
* <br>
* Metadata information:<br>
* <table border="solid;1px">
* <tr>
* <td rowspan="2">Item</td>
* <td colspan="2">Output position</td>
* </tr>
* <tr>
* <td>EnableMetadata=true</td>
* <td>EnableMetadata=false</td>
* </tr>
* <tr>
* <td>Container</td>
* <td>On self</td>
* <td>On self</td>
* <tr>
* <td>Table</td>
* <td>On self</td>
* <td>On self</td>
* </tr>
* <tr>
* <td>Image</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Chart</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Foreign</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Label</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Template Items( including template table, template label, etc.)</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* </table>
*
*/
public class HTMLReportEmitter extends ContentEmitterAdapter
{
/**
* the output format
*/
public static final String OUTPUT_FORMAT_HTML = "HTML"; //$NON-NLS-1$
/**
* the default target report file name
*/
public static final String REPORT_FILE = "report.html"; //$NON-NLS-1$
/**
* the default image folder
*/
public static final String IMAGE_FOLDER = "image"; //$NON-NLS-1$
/**
* output stream
*/
protected OutputStream out = null;
/**
* the report content
*/
protected IReportContent report;
/**
* the report runnable instance
*/
protected IReportRunnable runnable;
/**
* the render options
*/
protected IRenderOption renderOption;
/**
* should output the page header & footer
*/
protected boolean outputMasterPageContent = true;
/**
* specifies if the HTML output is embeddable
*/
protected boolean isEmbeddable = false;
/**
* the url encoding
*/
protected String urlEncoding = null;
/**
* should we output the report as Right To Left
*/
protected boolean htmlRtLFlag = false;
protected boolean pageFooterFloatFlag = true;
protected boolean enableMetadata = false;
protected List ouputInstanceIDs = null;
/**
* specified the current page number, starting from 0
*/
protected int pageNo = 0;
/**
* the <code>HTMLWriter<code> object that is used to output HTML content
*/
protected HTMLWriter writer;
/**
* the context used to execute the report
*/
protected IReportContext reportContext;
/**
* indicates that the styled element is hidden or not
*/
protected Stack stack = new Stack( );
/**
* An Log object that <code>HTMLReportEmitter</code> use to log the error,
* debug, information messages.
*/
protected static Logger logger = Logger.getLogger( HTMLReportEmitter.class
.getName( ) );
/**
* html image handler
*/
protected IHTMLImageHandler imageHandler;
/**
* html action handler
*/
protected IHTMLActionHandler actionHandler;
/**
* emitter services
*/
protected IEmitterServices services;
/**
* display type of Block
*/
protected static final int DISPLAY_BLOCK = 1;
/**
* display type of Inline
*/
protected static final int DISPLAY_INLINE = 2;
/**
* display type of Inline-Block
*/
protected static final int DISPLAY_INLINE_BLOCK = 4;
/**
* display type of none
*/
protected static final int DISPLAY_NONE = 8;
/**
* display flag which contains all display types
*/
protected static final int DISPLAY_FLAG_ALL = 0xffff;
/**
* content visitor that is used to handle page header/footer
*/
protected ContentEmitterVisitor contentVisitor;
private MetadataEmitter metadataEmitter;
private IDGenerator idGenerator = new IDGenerator( );
static HashMap borderStyleMap = null;
static
{
borderStyleMap = new HashMap( );
borderStyleMap.put( CSSConstants.CSS_NONE_VALUE, new Integer( 0 ) );
borderStyleMap.put( CSSConstants.CSS_INSET_VALUE, new Integer( 1 ) );
borderStyleMap.put( CSSConstants.CSS_GROOVE_VALUE, new Integer( 2 ) );
borderStyleMap.put( CSSConstants.CSS_OUTSET_VALUE, new Integer( 3 ) );
borderStyleMap.put( CSSConstants.CSS_RIDGE_VALUE, new Integer( 4 ) );
borderStyleMap.put( CSSConstants.CSS_DOTTED_VALUE, new Integer( 5 ) );
borderStyleMap.put( CSSConstants.CSS_DASHED_VALUE, new Integer( 6 ) );
borderStyleMap.put( CSSConstants.CSS_SOLID_VALUE, new Integer( 7 ) );
borderStyleMap.put( CSSConstants.CSS_DOUBLE_VALUE, new Integer( 8 ) );
}
/**
* record the leaf cell
*/
private ICellContent leafCell;
/**
* record the leaf cell is filled or not.
*/
private boolean cellFilled = false;
private String layoutPreference;
private boolean enableAgentStyleEngine;
private HTMLEmitter htmlEmitter;
/**
* the constructor
*/
public HTMLReportEmitter( )
{
contentVisitor = new ContentEmitterVisitor( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#initialize(org.eclipse.birt.report.engine.emitter.IEmitterServices)
*/
public void initialize( IEmitterServices services )
{
this.services = services;
Object fd = services.getOption( RenderOptionBase.OUTPUT_FILE_NAME );
File file = null;
try
{
if ( fd != null )
{
file = new File( fd.toString( ) );
File parent = file.getParentFile( );
if ( parent != null && !parent.exists( ) )
{
parent.mkdirs( );
}
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
}
catch ( FileNotFoundException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
if ( out == null )
{
Object value = services.getOption( RenderOptionBase.OUTPUT_STREAM );
if ( value != null && value instanceof OutputStream )
{
out = (OutputStream) value;
}
else
{
try
{
// FIXME
file = new File( REPORT_FILE );
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
catch ( FileNotFoundException e )
{
// FIXME
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
}
Object emitterConfig = services.getEmitterConfig( ).get( "html" ); //$NON-NLS-1$
if ( emitterConfig != null
&& emitterConfig instanceof HTMLEmitterConfig )
{
imageHandler = ( (HTMLEmitterConfig) emitterConfig )
.getImageHandler( );
actionHandler = ( (HTMLEmitterConfig) emitterConfig )
.getActionHandler( );
}
Object im = services.getOption( HTMLRenderOption.IMAGE_HANDLER );
if ( im != null && im instanceof IHTMLImageHandler )
{
imageHandler = (IHTMLImageHandler) im;
}
Object ac = services.getOption( HTMLRenderOption.ACTION_HANDLER );
if ( ac != null && ac instanceof IHTMLActionHandler )
{
actionHandler = (IHTMLActionHandler) ac;
}
reportContext = services.getReportContext( );
renderOption = services.getRenderOption( );
runnable = services.getReportRunnable( );
writer = new HTMLWriter( );
if ( renderOption != null )
{
HTMLRenderOption htmlOption = new HTMLRenderOption( renderOption );
isEmbeddable = htmlOption.getEmbeddable( );
HashMap options = renderOption.getOutputSetting( );
if ( options != null )
{
urlEncoding = (String) options
.get( HTMLRenderOption.URL_ENCODING );
}
outputMasterPageContent = htmlOption.getMasterPageContent( );
IHTMLActionHandler actHandler = htmlOption.getActionHandle( );
if ( ac != null )
{
actionHandler = actHandler;
}
pageFooterFloatFlag = htmlOption.getPageFooterFloatFlag( );
htmlRtLFlag = htmlOption.getHtmlRtLFlag( );
enableMetadata = htmlOption.getEnableMetadata( );
ouputInstanceIDs = htmlOption.getInstanceIDs( );
metadataEmitter = new MetadataEmitter( writer, htmlOption, idGenerator );
layoutPreference = htmlOption.getLayoutPreference( );
enableAgentStyleEngine = htmlOption.getEnableAgentStyleEngine( );
}
if ( enableAgentStyleEngine )
{
htmlEmitter = new HTMLPerformanceOptimize( this,
writer,
isEmbeddable );
}
else
{
// we will use HTMLVisionOptimize as the default emitter.
htmlEmitter = new HTMLVisionOptimize( this, writer, isEmbeddable );
}
}
/**
* @return the <code>Report</code> object.
*/
public IReportContent getReport( )
{
return report;
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* to the style
*
* @param style
*/
public void push( IStyle style )
{
stack.push( new Boolean( peek( style ) ) );
}
/**
* Pops the element of the stack
*
* @return the boolean indicating whether or not the item is hidden
*/
public boolean pop( )
{
return ( (Boolean) stack.pop( ) ).booleanValue( );
}
/**
* Peeks the element of stack
*
* @param style
* @return the boolean indicating whether or not the item is hidden
*/
public boolean peek( IStyle style )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
String formats = style.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
isHidden = true;
}
}
return isHidden;
}
/**
* Checks if the current item is hidden
*
* @return a boolean value
*/
public boolean isHidden( )
{
return ( (Boolean) stack.peek( ) ).booleanValue( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#getOutputFormat()
*/
public String getOutputFormat( )
{
return OUTPUT_FORMAT_HTML;
}
protected void fixTransparentPNG( )
{
writer.writeCode( "<!--[if gte IE 5.5000]>" ); //$NON-NLS-1$
writer
.writeCode( " <script language=\"JavaScript\"> var ie55up = true </script>" ); //$NON-NLS-1$
writer.writeCode( "<![endif]-->" ); //$NON-NLS-1$
writer.writeCode( "<script language=\"JavaScript\">" ); //$NON-NLS-1$
writer
.writeCode( " function fixPNG(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher." ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer.writeCode( " if (window.ie55up)" ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer
.writeCode( " var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgTitle = (myImage.title) ? \"title='\" + myImage.title + \"' \" : \"title='\" + myImage.alt + \"' \"" ); //$NON-NLS-1$
writer
.writeCode( " var imgStyle = \"display:inline-block;\" + myImage.style.cssText" ); //$NON-NLS-1$
writer
.writeCode( " var strNewHTML = \"<span \" + imgID + imgClass + imgTitle" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \" style=\\\"\" + \"width:\" + myImage.width + \"px; height:\" + myImage.height + \"px;\" + imgStyle + \";\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"(src=\\'\" + myImage.src + \"\\', sizingMethod='scale');\\\"></span>\"" ); //$NON-NLS-1$
writer.writeCode( " myImage.outerHTML = strNewHTML" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( "</script>" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#start(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void start( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] Start emitter." ); //$NON-NLS-1$
this.report = report;
writer.open( out, "UTF-8" ); //$NON-NLS-1$
// If it is the body style and htmlRtLFlag has been set true,
// remove the text-align included in the style.
if ( htmlRtLFlag )
{
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
//style.removeProperty( "text-align" );
style.setProperty(IStyle.STYLE_TEXT_ALIGN, IStyle.RIGHT_VALUE);
}
}
if ( null == layoutPreference )
{
// get the layout preference from the report design.
if ( report != null )
{
Report reportDesign = report.getDesign( );
ReportDesignHandle designHandle = reportDesign.getReportDesign( );
String reportLayoutPreference = designHandle.getLayoutPreference( );
if ( DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_FIXED_LAYOUT.equals( reportLayoutPreference ) )
{
layoutPreference = HTMLRenderOption.LAYOUT_PREFERENCE_FIXED;
}
else if ( DesignChoiceConstants.REPORT_LAYOUT_PREFERENCE_AUTO_LAYOUT.equals( reportLayoutPreference ) )
{
layoutPreference = HTMLRenderOption.LAYOUT_PREFERENCE_AUTO;
}
}
}
if ( isEmbeddable )
{
fixTransparentPNG( );
writer.openTag( HTMLTags.TAG_DIV );
if ( report != null )
{
String reportStyleName = report.getDesign( ).getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildStyle( styleBuffer, style, this );
writer.attribute( HTMLTags.ATTR_STYLE,
styleBuffer.toString( ) );
}
}
return;
}
writer.startWriter( );
writer.openTag( HTMLTags.TAG_HTML );
writer.openTag( HTMLTags.TAG_HEAD );
// write the title of the report in html.
Report reportDesign = null;
if ( report != null )
{
reportDesign = report.getDesign( );
ReportDesignHandle designHandle = reportDesign.getReportDesign( );
String title = designHandle.getStringProperty( IModuleModel.TITLE_PROP );
if ( title == null )
{
// set the default title
if ( renderOption != null )
{
HTMLRenderOption htmlOption = new HTMLRenderOption(
renderOption );
title = htmlOption.getHtmlTitle( );
}
}
if ( title != null )
{
writer.openTag( HTMLTags.TAG_TITLE );
writer.text( title );
writer.closeTag( HTMLTags.TAG_TITLE );
}
}
writer.openTag( HTMLTags.TAG_META );
writer.attribute( HTMLTags.ATTR_HTTP_EQUIV, "Content-Type" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_CONTENT, "text/html; charset=UTF-8" ); //$NON-NLS-1$
writer.closeNoEndTag( );
writer.openTag( HTMLTags.TAG_STYLE );
writer.attribute( HTMLTags.ATTR_TYPE, "text/css" ); //$NON-NLS-1$
IStyle style;
StringBuffer styleBuffer = new StringBuffer( );
if ( report == null )
{
logger.log( Level.WARNING,
"[HTMLReportEmitter] Report object is null." ); //$NON-NLS-1$
}
else
{
Map styles = reportDesign.getStyles( );
Iterator iter = styles.entrySet( ).iterator( );
while ( iter.hasNext( ) )
{
Map.Entry entry = (Map.Entry) iter.next( );
String styleName = (String) entry.getKey( );
style = (IStyle) entry.getValue( );
styleBuffer.setLength( 0 );
AttributeBuilder.buildStyle( styleBuffer, style, this );
// Build the vertical-align
String value = style.getVerticalAlign( );
if ( null != value )
{
styleBuffer.append( " vertical-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
// Build the textAlign
value = style.getTextAlign( );
if ( null != value )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( value );
styleBuffer.append( ";" );
}
writer.style( '.' + styleName, styleBuffer.toString( ) );
}
}
writer.closeTag( HTMLTags.TAG_STYLE );
fixTransparentPNG( );
writer.closeTag( HTMLTags.TAG_HEAD );
writer.openTag( HTMLTags.TAG_BODY );
if ( report != null )
{
String reportStyleName = report.getDesign( ).getRootStyleName( );
if ( reportStyleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, reportStyleName );
// remove the default margin of body
writer.attribute( HTMLTags.ATTR_STYLE, " margin:0px;" );
}
}
}
private void appendErrorMessage(EngineResourceHandle rc, int index, ElementExceptionInfo info )
{
writer.writeCode( " <div>" );
writer.writeCode( " <div id=\"error_title\" style=\"text-decoration:underline\">" );
String name = info.getName( );
if ( name != null )
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE,
new Object[]{info.getType( ), name } ), false );
}
else
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE_WITH_ID,
new Object[]{info.getType( ), info.getID( ) } ), false );
}
writer.writeCode( "</div>" );//$NON-NLS-1$
ArrayList errorList = info.getErrorList( );
ArrayList countList = info.getCountList( );
for ( int i = 0; i < errorList.size( ); i++ )
{
String errorId = "document.getElementById('error_detail" + index + "_" + i + "')";
String errorIcon = "document.getElementById('error_icon" + index + "_" + i + "')";
String onClick = "if (" + errorId + ".style.display == 'none') { "
+ errorIcon + ".innerHTML = '- '; " + errorId
+ ".style.display = 'block'; }" + "else { " + errorIcon
+ ".innerHTML = '+ '; " + errorId + ".style.display = 'none'; }";
writer.writeCode("<div>");
BirtException ex = (BirtException) errorList.get( i );
writer.writeCode( "<span id=\"error_icon" + index + "_" + i
+ "\" style=\"cursor:pointer\" onclick=\"" + onClick
+ "\" > + </span>" );
writer.text( ex.getLocalizedMessage( ) );
writer.writeCode( " <pre id=\"error_detail" + index + "_" + i //$NON-NLS-1$
+ "\" style=\"display:none;\" >" );//$NON-NLS-1$
String messageTitle = rc.getMessage(
MessageConstants.REPORT_ERROR_ID, new Object[]{
ex.getErrorCode( ) ,
countList.get( i )} );
String detailTag = rc
.getMessage( MessageConstants.REPORT_ERROR_DETAIL );
String messageBody = getDetailMessage( ex );
boolean indent = writer.isIndent( );
writer.setIndent( false );
writer.text( messageTitle, false );
writer.writeCode( "\r\n" );//$NON-NLS-1$
writer.text( detailTag, false );
writer.text( messageBody, false );
writer.setIndent( indent );
writer.writeCode( " </pre>" ); //$NON-NLS-1$
writer.writeCode("</div>");
}
writer.writeCode( "</div>" ); //$NON-NLS-1$
writer.writeCode( "<br>" ); //$NON-NLS-1$
}
private String getDetailMessage( Throwable t )
{
StringWriter out = new StringWriter( );
PrintWriter print = new PrintWriter( out );
try
{
t.printStackTrace( print );
}
catch ( Throwable ex )
{
}
print.flush( );
return out.getBuffer( ).toString( );
}
protected boolean outputErrors( List errors )
{
// Outputs the error message at the end of the report
if ( errors != null && !errors.isEmpty( ) )
{
writer.writeCode( " <hr style=\"color:red\"/>" );
writer.writeCode( " <div style=\"color:red\">" );
writer.writeCode( " <div>" );
Locale locale = reportContext.getLocale( );
if(locale==null)
{
locale = Locale.getDefault();
}
EngineResourceHandle rc = new EngineResourceHandle( ULocale.forLocale(locale) );
writer.text( rc.getMessage(
MessageConstants.ERRORS_ON_REPORT_PAGE ), false );
writer.writeCode( "</div>" );//$NON-NLS-1$
writer.writeCode( "<br>") ;//$NON-NLS-1$
Iterator it = errors.iterator( );
int index = 0;
while ( it.hasNext( ) )
{
appendErrorMessage(rc, index++, (ElementExceptionInfo) it.next( ) );
}
writer.writeCode( "</div>" );
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#end(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void end( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End body." ); //$NON-NLS-1$
if ( report != null )
{
List errors = report.getErrors( );
if ( errors != null && !errors.isEmpty( ) )
{
outputErrors( errors );
}
}
if ( !isEmbeddable )
{
writer.closeTag( HTMLTags.TAG_BODY );
writer.closeTag( HTMLTags.TAG_HTML );
}
else
{
writer.closeTag( HTMLTags.TAG_DIV );
}
writer.endWriter( );
writer.close( );
if ( out != null )
{
try
{
out.close( );
}
catch ( IOException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void startPage( IPageContent page )
{
pageNo++;
if ( pageNo > 1 && outputMasterPageContent == false )
{
writer.openTag( "hr" );
writer.closeTag( "hr" );
}
// out put the page tag
writer.openTag( HTMLTags.TAG_DIV );
// out put the background and width
if ( page != null )
{
IStyle classStyle = page.getStyle( );
StringBuffer styleBuffer = new StringBuffer( );
// build the background
AttributeBuilder.buildBackgroundStyle( styleBuffer,
classStyle,
this );
if ( HTMLRenderOption.LAYOUT_PREFERENCE_FIXED.equals( layoutPreference ) )
{
// build the width
DimensionType width = page.getPageWidth( );
if ( width != null )
{
styleBuffer.append( " width:" );
styleBuffer.append( width.toString( ) );
styleBuffer.append( ";" );
}
}
// Build MasterPage's margin as padding.
if ( HTMLRenderOption.LAYOUT_PREFERENCE_FIXED.equals( layoutPreference ) )
{
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign SimpleMasterPage = (SimpleMasterPageDesign) genBy;
String padding = SimpleMasterPage.getLeftMargin( )
.toString( );
if ( null != padding )
{
styleBuffer.append( "padding-left: " );
styleBuffer.append( padding );
styleBuffer.append( ";" );
}
padding = SimpleMasterPage.getTopMargin( ).toString( );
if ( null != padding )
{
styleBuffer.append( "padding-top: " );
styleBuffer.append( padding );
styleBuffer.append( ";" );
}
padding = SimpleMasterPage.getRightMargin( ).toString( );
if ( null != padding )
{
styleBuffer.append( "padding-right: " );
styleBuffer.append( padding );
styleBuffer.append( ";" );
}
padding = SimpleMasterPage.getBottomMargin( ).toString( );
if ( null != padding )
{
styleBuffer.append( "padding-bottom: " );
styleBuffer.append( padding );
styleBuffer.append( ";" );
}
}
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
if ( htmlRtLFlag )
{
writer.attribute( HTMLTags.ATTR_HTML_DIR, "RTL" );
}
if ( pageNo > 1 )
{
writer.attribute( HTMLTags.ATTR_STYLE, "page-break-before: always;" );
}
//output page header
if ( page != null )
{
if ( outputMasterPageContent )
{
// output DIV for page header
boolean showHeader = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowHeaderOnFirst( ) )
{
if ( page.getPageNumber( ) == 1 )
{
showHeader = false;
}
}
}
if ( showHeader )
{
writer.openTag( HTMLTags.TAG_DIV );
StringBuffer styleBuffer = new StringBuffer( );
if (isEmbeddable)
{
AttributeBuilder.buildPageStyle(styleBuffer, page.getStyle(), this);
}
else
{
writer.attribute(HTMLTags.ATTR_CLASS, page.getStyleClass());
AttributeBuilder.buildPageStyle(styleBuffer, page.getInlineStyle(), this);
}
//output the page header attribute
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
contentVisitor.visitChildren( page.getPageHeader( ), null );
// close the page header
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// start output the page body , with the body style
writer.openTag( HTMLTags.TAG_DIV );
if ( page != null )
{
Object genBy = page.getGenerateBy( );
if ( genBy instanceof MasterPageDesign )
{
MasterPageDesign masterPage = (MasterPageDesign) genBy;
StringBuffer styleBuffer = new StringBuffer( );
if( !pageFooterFloatFlag )
{
htmlEmitter.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_HEIGHT,
masterPage.getPageHeight( ) );
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void endPage( IPageContent page )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End page." ); //$NON-NLS-1$
//close the page body (DIV)
writer.closeTag( HTMLTags.TAG_DIV );
//output page footer
if ( page != null )
{
if ( outputMasterPageContent )
{
boolean showFooter = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowFooterOnLast( ) )
{
long totalPage = page.getPageNumber( );
IReportContent report = page.getReportContent( );
if ( report != null )
{
totalPage = report.getTotalPage( );
}
if ( page.getPageNumber( ) == totalPage)
{
showFooter = false;
}
}
}
if ( showFooter )
{
// start output the page footer
writer.openTag( HTMLTags.TAG_DIV );
//build page footer style
StringBuffer styleBuffer = new StringBuffer( );
if (isEmbeddable)
{
AttributeBuilder.buildPageStyle(styleBuffer, page.getStyle(), this);
}
else
{
writer.attribute(HTMLTags.ATTR_CLASS, page.getStyleClass());
AttributeBuilder.buildPageStyle(styleBuffer, page.getInlineStyle(), this);
}
//output the page footer attribute
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
contentVisitor.visitChildren( page.getPageFooter( ), null );
// close the page footer
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// close the page tag ( DIV )
writer.closeTag( HTMLTags.TAG_DIV );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void startTable( ITableContent table )
{
assert table != null;
IStyle mergedStyle = table.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start table" ); //$NON-NLS-1$
if ( enableMetadata )
{
metadataEmitter.startWrapTable( table );
}
writer.openTag( HTMLTags.TAG_TABLE );
//output class attribute.
setStyleName( table.getStyleClass( ) );
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildTableStyle( table, styleBuffer, layoutPreference );
// output style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
// bookmark
String bookmark = table.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
table.setBookmark( bookmark );
}
HTMLEmitterUtil.setBookmark( writer, null, bookmark );
// Add it to active id list, and output type iid to html
HTMLEmitterUtil.setActiveIDTypeIID(writer, ouputInstanceIDs, table);
// table caption
String caption = table.getCaption( );
if ( caption != null && caption.length( ) > 0 )
{
writer.openTag( HTMLTags.TAG_CAPTION );
writer.text( caption );
writer.closeTag( HTMLTags.TAG_CAPTION );
}
// include select handle table
if ( enableMetadata )
{
metadataEmitter.startTable( table );
}
writeColumns( table );
}
protected void writeColumns( ITableContent table )
{
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
IColumn column = table.getColumn( i );
if ( isColumnHidden( column ) )
{
continue;
}
writer.openTag( HTMLTags.TAG_COL );
//column style is output in Cell's columnRelatedStyle
// width
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildColumnStyle( column, styleBuffer );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
if ( enableMetadata )
{
// Instance ID
InstanceID iid = column.getInstanceID( );
if ( iid != null )
{
writer.attribute( "iid", iid.toString( ) );
}
}
writer.closeNoEndTag( );
}
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* @param hidden
*/
public void push( boolean hidden )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
isHidden = hidden;
}
stack.push( new Boolean( isHidden ) );
}
/**
* check whether to hide the column.
* @param column
* @return
*/
private boolean isColumnHidden( IColumn column )
{
String formats = column.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void endTable( ITableContent table )
{
if ( pop( ) )
{
return;
}
// include select handle table
if ( enableMetadata )
{
metadataEmitter.endTable( table );
}
writer.closeTag( HTMLTags.TAG_TABLE );
if ( enableMetadata )
{
metadataEmitter.endWrapTable( table );
}
logger.log( Level.FINE, "[HTMLTableEmitter] End table" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TFOOT );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TFOOT );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void startRow( IRowContent row )
{
assert row != null;
IStyle mergedStyle = row.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TR );
if ( enableMetadata )
{
metadataEmitter.startRow( row );
outputRowMetaData( row );
}
setStyleName( row.getStyleClass( ) );
// bookmark
HTMLEmitterUtil.setBookmark( writer, null, row.getBookmark( ) );
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildRowStyle( row, styleBuffer );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
protected void outputRowMetaData( IRowContent rowContent )
{
Object parent = rowContent.getParent( );
if ( parent instanceof ITableBandContent )
{
ITableBandContent bandContent = (ITableBandContent) parent;
IGroupContent group = rowContent.getGroup( );
String groupId = rowContent.getGroupId( );
if ( groupId != null )
{
writer.attribute( HTMLTags.ATTR_GOURP_ID, groupId );
}
String rowType = null;
String metaType = null;
int bandType = bandContent.getBandType( );
if ( bandType == ITableBandContent.BAND_HEADER )
{
metaType = "wrth";
rowType = "header";
}
else if ( bandType == ITableBandContent.BAND_FOOTER )
{
metaType = "wrtf";
rowType = "footer";
}
else if ( bandType == ITableBandContent.BAND_GROUP_HEADER )
{
rowType = "group-header";
if ( group != null )
{
metaType = "wrgh" + group.getGroupLevel( );
}
}
else if ( bandType == ITableBandContent.BAND_GROUP_FOOTER )
{
rowType = "group-footer";
if ( group != null )
{
metaType = "wrgf" + group.getGroupLevel( );
}
}
writer.attribute( HTMLTags.ATTR_TYPE, metaType );
writer.attribute( HTMLTags.ATTR_ROW_TYPE, rowType );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void endRow( IRowContent row )
{
if ( pop( ) )
{
return;
}
if ( enableMetadata )
{
metadataEmitter.endRow( row );
}
// assert currentData != null;
// currentData.adjustCols( );
writer.closeTag( HTMLTags.TAG_TR );
}
private boolean isCellInTableHead( ICellContent cell )
{
IElement row = cell.getParent( );
if ( row instanceof IRowContent )
{
IElement tableBand = row.getParent( );
if ( tableBand instanceof ITableBandContent )
{
int type = ( (ITableBandContent)tableBand ).getBandType( );
if ( type == ITableBandContent.BAND_HEADER )
{
return true;
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void startCell( ICellContent cell )
{
leafCell = cell;
cellFilled = false;
push( false );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start cell." ); //$NON-NLS-1$
// output 'th' tag in table head, otherwise 'td' tag
boolean isInTableHead = isCellInTableHead( cell );
if ( isInTableHead )
{
writer.openTag( HTMLTags.TAG_TH ); //$NON-NLS-1$
}
else
{
writer.openTag( HTMLTags.TAG_TD ); //$NON-NLS-1$
}
// set the 'name' property
setStyleName( cell.getStyleClass( ) );
// colspan
int colSpan = cell.getColSpan( );
if ( colSpan > 1 )
{
writer.attribute( HTMLTags.ATTR_COLSPAN, colSpan );
}
// rowspan
int rowSpan = cell.getRowSpan( );
if ( rowSpan > 1 )
{
writer.attribute( HTMLTags.ATTR_ROWSPAN, rowSpan );
}
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildCellStyle( cell, styleBuffer, isInTableHead );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
htmlEmitter.handleCellAlign( cell );
if ( !startedGroups.isEmpty( ) )
{
Iterator iter = startedGroups.iterator( );
while (iter.hasNext( ))
{
IGroupContent group = (IGroupContent) iter.next( );
outputBookmark( group );
}
startedGroups.clear( );
}
if ( enableMetadata )
{
metadataEmitter.startCell( cell );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void endCell( ICellContent cell )
{
leafCell = null;
cellFilled = false;
if ( pop( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] End cell." ); //$NON-NLS-1$
if ( enableMetadata )
{
metadataEmitter.endCell( cell );
}
if ( isCellInTableHead( cell ) )
{
writer.closeTag( HTMLTags.TAG_TH );
}
else
{
writer.closeTag( HTMLTags.TAG_TD );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void startContainer( IContainerContent container )
{
IStyle mergedStyle = container.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start container" ); //$NON-NLS-1$
htmlEmitter.openContainerTag( container );
// class
setStyleName( container.getStyleClass( ) );
// bookmark
String bookmark = container.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
container.setBookmark( bookmark );
}
HTMLEmitterUtil.setBookmark( writer, HTMLTags.TAG_DIV, bookmark );
HTMLEmitterUtil
.setActiveIDTypeIID( writer, ouputInstanceIDs, container );
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildContainerStyle( container, styleBuffer );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
htmlEmitter.handleHorizontalAlign( mergedStyle );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void endContainer( IContainerContent container )
{
if ( pop( ) )
{
return;
}
htmlEmitter.closeContainerTag( );
logger.log( Level.FINE, "[HTMLContainerEmitter] End container" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startText(org.eclipse.birt.report.engine.content.ITextContent)
*/
public void startText( ITextContent text )
{
IStyle mergedStyle = text.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start text" ); //$NON-NLS-1$
//Resize if the text generated by TemplateDesign
//resizeTemplateElement( text);
DimensionType x = text.getX( );
DimensionType y = text.getY( );
DimensionType width = text.getWidth( );
DimensionType height = text.getHeight( );
String textValue = text.getText( );
if (textValue == null || textValue == "" ) //$NON-NLS-1$
{
textValue = " "; //$NON-NLS-1$
}
int display;
// If the item is multi-line, we should check if it can be inline-block
if ( textValue != null && textValue.indexOf( '\n' ) >= 0 )
{
display = getElementType( x, y, width, height, mergedStyle );
}
else
{
display = getElementType( x, y, null, null, mergedStyle );
}
// action
String tagName;
String url = validate( text.getHyperlinkAction( ) );
boolean metadataOutput = false;
if ( url != null )
{
//output select class
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startText( text,
HTMLTags.TAG_SPAN );
}
tagName = HTMLTags.TAG_A;
outputAction( text.getHyperlinkAction( ), url );
}
else
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startText( text, HTMLEmitterUtil.getTagByType(
display, DISPLAY_FLAG_ALL ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
}
setStyleName( text.getStyleClass( ) );
// bookmark
if ( !metadataOutput )
{
outputBookmark( text, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, text.getHelpText( ) ); //$NON-NLS-1$
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildTextStyle( text, styleBuffer, display, url );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
htmlEmitter.handleVerticalAlignBegine( text );
writer.text( textValue );
htmlEmitter.handleVerticalAlignEnd( text );
writer.closeTag( tagName );
if ( enableMetadata )
{
metadataEmitter.endText( text );
}
cellFilled = true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startForeign(org.eclipse.birt.report.engine.content.IForeignContent)
*/
public void startForeign( IForeignContent foreign )
{
IStyle mergedStyle = foreign.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start foreign" ); //$NON-NLS-1$
resizeTemplateElement( foreign);
DimensionType x = foreign.getX( );
DimensionType y = foreign.getY( );
DimensionType width = foreign.getWidth( );
DimensionType height = foreign.getHeight( );
int display;
display = getElementType( x, y, width, height, mergedStyle );
// create default bookmark if we need output metadata
if ( foreign.getGenerateBy( ) instanceof TemplateDesign )
{
//FIXME: actually, it should be birt-template-design
String bookmark = foreign.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
foreign.setBookmark( bookmark );
}
}
// action
String tagName;
String url = validate( foreign.getHyperlinkAction( ) );
boolean metadataOutput = false;
if ( url != null )
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startForeign( foreign,
HTMLTags.TAG_SPAN );
}
tagName = HTMLTags.TAG_A;
outputAction( foreign.getHyperlinkAction( ), url );
}
else
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startForeign( foreign, HTMLEmitterUtil.getTagByType(
display, DISPLAY_FLAG_ALL ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
}
setStyleName( foreign.getStyleClass( ) );
// bookmark
if ( !metadataOutput )
{
outputBookmark( foreign, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, foreign.getHelpText( ) );
if( isTalbeTemplateElement( foreign ) )
{
//set lines to dotted lines
mergedStyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_BOTTOM_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_FONT_FAMILY, IStyle.SANS_SERIF_VALUE );
}
StringBuffer styleBuffer = new StringBuffer( );
htmlEmitter.buildForeignStyle( foreign, styleBuffer, display, url );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
String rawType = foreign.getRawType( );
boolean isHtml = IForeignContent.HTML_TYPE.equalsIgnoreCase( rawType );
if ( isHtml )
{
htmlEmitter.handleVerticalAlignBegine( foreign );
outputHtmlText( foreign );
htmlEmitter.handleVerticalAlignEnd( foreign );
}
writer.closeTag( tagName );
if ( enableMetadata )
{
metadataEmitter.endForeign( foreign );
}
/**
* We suppose the foreign content will all occupy space now.
* In fact some foreign contents don't occupy space.
* For example: a empty html text will not occupy space in html.
* It needs to be solved in the future.
*/
cellFilled = true;
}
private void outputHtmlText(IForeignContent foreign)
{
Object rawValue = foreign.getRawValue( );
String text = rawValue == null ? null : rawValue.toString( );
Document doc = new TextParser( ).parse( text,
TextParser.TEXT_TYPE_HTML );
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
HTMLProcessor htmlProcessor = new HTMLProcessor( design );
HashMap styleMap = new HashMap( );
Element body = null;
if ( doc != null )
{
NodeList bodys = doc.getElementsByTagName( "body" );
if ( bodys.getLength( ) > 0 )
{
body = (Element) bodys.item( 0 );
}
}
if ( body != null )
{
htmlProcessor.execute( body, styleMap );
processNodes( body, styleMap );
}
}
/**
* Visits the children nodes of the specific node
*
* @param visitor
* the ITextNodeVisitor instance
* @param ele
* the specific node
*/
private void processNodes( Element ele, HashMap cssStyles )
{
for ( Node node = ele.getFirstChild( ); node != null; node = node
.getNextSibling( ) )
{
// At present we only deal with the text and element nodes
if ( node.getNodeType( ) == Node.TEXT_NODE
|| node.getNodeType( ) == Node.ELEMENT_NODE )
{
if ( !node.getNodeName( ).equals( "#text" ) )
{
startNode( node, cssStyles );
}
if ( node.getNodeType( ) == Node.TEXT_NODE )
{
if ( isScriptText( node ) )
{
textForScript( node.getNodeValue( ) );
}
else
{
// bug132213 in text item should only deal with the
// escape special characters: < > &
// writer.text( node.getNodeValue( ), false, true );
writer.textForHtmlItem( node.getNodeValue( ) );
}
}
else
{
processNodes( (Element) node, cssStyles );
}
if ( !node.getNodeName( ).equals( "#text" ) )
{
endNode( node );
}
}
}
}
/**
* test if the text node is in the script
* @param node text node
* @return true if the text is a script, otherwise, false.
*/
private boolean isScriptText( Node node )
{
Node parent = node.getParentNode( );
if ( parent != null )
{
if ( parent.getNodeType( ) == Node.ELEMENT_NODE )
{
String tag = parent.getNodeName( );
if ( HTMLTags.TAG_SCRIPT.equalsIgnoreCase( tag ) )
{
return true;
}
}
}
return false;
}
/**
* the script is output directly.
* @param text
*/
private void textForScript( String text )
{
writer.text( text, false, false );
}
public void startNode( Node node, HashMap cssStyles )
{
String nodeName = node.getNodeName( );
HashMap cssStyle = (HashMap) cssStyles.get( node );
writer.openTag( nodeName );
NamedNodeMap attributes = node.getAttributes( );
if ( attributes != null )
{
for ( int i = 0; i < attributes.getLength( ); i++ )
{
Node attribute = attributes.item( i );
String attrName = attribute.getNodeName( );
String attrValue = attribute.getNodeValue( );
if ( attrValue != null )
{
if ( "img".equalsIgnoreCase( nodeName )
&& "src".equalsIgnoreCase( attrName ) )
{
String attrValueTrue = handleStyleImage( attrValue );
if ( attrValueTrue != null )
{
attrValue = attrValueTrue;
}
}
writer.attribute( attrName, attrValue );
}
}
}
if ( cssStyle != null )
{
StringBuffer buffer = new StringBuffer( );
Iterator ite = cssStyle.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
Object keyObj = entry.getKey( );
Object valueObj = entry.getValue( );
if ( keyObj == null || valueObj == null )
{
continue;
}
String key = keyObj.toString( );
String value = valueObj.toString( );
buffer.append( key );
buffer.append( ":" );
if ( "background-image".equalsIgnoreCase( key ) )
{
String valueTrue = handleStyleImage( value );
if ( valueTrue != null )
{
value = valueTrue;
}
buffer.append( "url(" );
buffer.append( value );
buffer.append( ")" );
}
else
{
buffer.append( value.replaceAll( " ", "" ) );
}
buffer.append( ";" );
}
if ( buffer.length( ) != 0 )
{
writer.attribute( "style", buffer.toString( ) );
}
}
}
public void endNode( Node node )
{
writer.closeTag( node.getNodeName( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startLabel(org.eclipse.birt.report.engine.content.ILabelContent)
*/
public void startLabel( ILabelContent label )
{
String bookmark = label.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
label.setBookmark( bookmark );
}
startText( label );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startData(org.eclipse.birt.report.engine.content.IDataContent)
*/
public void startData( IDataContent data )
{
startText( data );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startImage(org.eclipse.birt.report.engine.content.IImageContent)
*/
public void startImage( IImageContent image )
{
assert image != null;
IStyle mergedStyle = image.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLImageEmitter] Start image" ); //$NON-NLS-1$
StringBuffer styleBuffer = new StringBuffer( );
int display = checkElementType( image.getX( ), image.getY( ),
mergedStyle, styleBuffer );
boolean isSelectHandleTableChart = false;
if ( enableMetadata )
{
isSelectHandleTableChart = metadataEmitter.startImage( image );
}
String tag = openTagByType( display, DISPLAY_BLOCK );
// action
boolean hasAction = handleAction( image.getHyperlinkAction( ) );
String imgUri = getImageURI( image );
boolean useSVG = (( image.getMIMEType( ) != null )
&& image.getMIMEType( ).equalsIgnoreCase( "image/svg+xml" )) //$NON-NLS-1$
|| (( image.getExtension( ) != null )
&& image.getExtension( ).equalsIgnoreCase( ".svg" )) //$NON-NLS-1$
|| (( image.getURI( ) != null )
&& image.getURI( ).toLowerCase( ).endsWith( ".svg" )); //$NON-NLS-1$
if ( useSVG )
{ // use svg
writer.openTag( HTMLTags.TAG_EMBED );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
// onresize gives the SVG a change to change its content
writer.attribute( "onresize", bookmark+".reload()"); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_TYPE, "image/svg+xml" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
setStyleName( image.getStyleClass( ) );
// build style
htmlEmitter.buildImageStyle( image, styleBuffer, display );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
writer.closeNoEndTag( );
}
else
{ // use img
// write image map if necessary
Object imageMapObject = image.getImageMap( );
// use imgUri as the image ID. As we know only the CHART can have
// image maps and each chart
// will have differnt URI, so it is safe for CHART. (If the named
// image also support image
// map, then we must use another way to get the image ID.
String imageMapId = imgUri;
boolean hasImageMap = ( imageMapObject != null )
&& ( imageMapObject instanceof String )
&& ( ( (String) imageMapObject ).length( ) > 0 );
if ( hasImageMap )
{
writer.openTag( HTMLTags.TAG_MAP );
writer.attribute( HTMLTags.ATTR_NAME, imageMapId );
writer.text( (String) imageMapObject, true, false );
writer.closeTag( HTMLTags.TAG_MAP );
}
writer.openTag( HTMLTags.TAG_IMAGE ); //$NON-NLS-1$
setStyleName( image.getStyleClass( ) );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
String ext = image.getExtension( );
// FIXME special process, such as encoding etc
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
if ( hasImageMap )
{
// BUGZILLA 119245 request chart (without hyperlink) can't have
// borders, the BROWSER add blue-solid border to the image with
// maps.
if ( !hasAction )
{
// disable the border, if the user defines border with the
// image, it will be overided by the following style setting
IStyle style = image.getStyle( );
if ( style.getBorderTopStyle( ) == null )
{
// user doesn't define the border, remove it.
styleBuffer.append( "border-top-style:none;" );
}
else
{
// use define the border-style, but not define the
// border color, use the default
// color.
if ( style.getBorderTopColor( ) == null )
{
styleBuffer.append( "border-top-color:black" );
}
}
if ( style.getBorderBottomStyle( ) == null )
{
styleBuffer.append( "border-bottom-style:none;" );
}
else
{
if ( style.getBorderBottomColor( ) == null )
{
styleBuffer.append( "border-bottom-color:black" );
}
}
if ( style.getBorderLeftStyle( ) == null )
{
styleBuffer.append( "border-left-style:none;" );
}
else
{
if ( style.getBorderLeftColor( ) == null )
{
styleBuffer.append( "border-left-color:black" );
}
}
if ( style.getBorderRightStyle( ) == null )
{
styleBuffer.append( "border-right-style:none;" );
}
else
{
if ( style.getBorderRightColor( ) == null )
{
styleBuffer.append( "border-right-color:black" );
}
}
}
writer.attribute( HTMLTags.ATTR_USEMAP, "#" + imageMapId ); //$NON-NLS-1$ //$NON-NLS-2$
}
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
// help text
writer.attribute( HTMLTags.ATTR_TITLE, image.getHelpText( ) );
// build style
htmlEmitter.buildImageStyle( image, styleBuffer, display );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
if ( ".PNG".equalsIgnoreCase( ext ) && imageHandler != null ) //$NON-NLS-1$
{
writer.attribute( HTMLTags.ATTR_ONLOAD, "fixPNG(this)" ); //$NON-NLS-1$
}
writer.closeNoEndTag( );
}
if ( hasAction )
{
writer.closeTag( HTMLTags.TAG_A );
}
writer.closeTag( tag );
// include select handle chart
if ( enableMetadata )
{
metadataEmitter.endImage( image );
}
cellFilled = true;
}
/**
* gets the image's URI
*
* @param image
* the image content
* @return image's URI
*/
protected String getImageURI( IImageContent image )
{
String imgUri = null;
if ( imageHandler != null )
{
Image img = new Image( image );
img.setRenderOption( renderOption );
img.setReportRunnable( runnable );
switch ( img.getSource( ) )
{
case IImage.DESIGN_IMAGE :
imgUri = imageHandler.onDesignImage( img, reportContext );
break;
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( img, reportContext );
break;
case IImage.REPORTDOC_IMAGE :
imgUri = imageHandler.onDocImage( img, reportContext );
break;
case IImage.CUSTOM_IMAGE :
imgUri = imageHandler.onCustomImage( img, reportContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( img, reportContext );
break;
case IImage.INVALID_IMAGE :
break;
}
}
return imgUri;
}
/**
* Sets the <code>'class'</code> property and stores the style to styleMap
* object.
*
* @param styleName
* the style name
*/
protected void setStyleName( String styleName )
{
if ( isEmbeddable )
{
return;
}
if ( styleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, styleName );
}
}
protected void outputBookmark( IContent content, String tagName )
{
String bookmark = content.getBookmark( );
HTMLEmitterUtil.setBookmark( writer, tagName, bookmark );
}
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return The display type of the element.
*/
protected int checkElementType( DimensionType x, DimensionType y,
IStyle style, StringBuffer styleBuffer )
{
return checkElementType( x, y, null, null, style, styleBuffer );
}
protected int checkElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style,
StringBuffer styleBuffer )
{
//if ( x != null || y != null )
// styleBuffer.append( "position: absolute;" ); //$NON-NLS-1$
// AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_LEFT, x );
// AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_TOP, y );
return getElementType( x, y, width, height, style);
}
public int getElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style )
{
return htmlEmitter.getElementType( x, y, width, height, style );
}
/**
* Open a tag according to the display type of the element. Here is the
* mapping table:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>Display Type</th>
* <th align=left>Tag name</th>
* </tr>
* <tr valign=middle>
* <td>DISPLAY_BLOCK</td>
* <td>DIV</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td>DISPLAY_INLINE</td>
* <td>SPAN</td>
* </tr>
* </table>
*
* @param display
* The display type.
* @param mask
* The mask value.
* @return Tag name.
*/
protected String openTagByType( int display, int mask )
{
String tag = HTMLEmitterUtil.getTagByType( display, mask );
if ( tag != null)
{
writer.openTag( tag );
}
return tag;
}
/**
* Checks the Action object and then output corresponding tag and property.
*
* @param action
* The <code>IHyperlinkAction</code> object.
* @return A <code>boolean</code> value indicating whether the Action
* object is valid or not.
*/
protected boolean handleAction( IHyperlinkAction action )
{
String url = validate( action );
if ( url != null )
{
outputAction( action, url );
}
return url != null;
}
/**
* Outputs an hyperlink action.
*
* @param action
* the hyperlink action.
*/
protected void outputAction( IHyperlinkAction action, String url )
{
writer.openTag( HTMLTags.TAG_A );
writer.attribute( HTMLTags.ATTR_HREF, url );
writer.attribute( HTMLTags.ATTR_TARGET, action.getTargetWindow( ) );
}
/**
* Judges if a hyperlink is valid.
*
* @param action
* the hyperlink action
* @return
*/
private String validate( IHyperlinkAction action )
{
if ( action == null )
{
return null;
}
String systemId = runnable == null ? null : runnable.getReportName( );
Action act = new Action( systemId, action );
if ( actionHandler == null )
{
return null;
}
String link = actionHandler.getURL( act, reportContext );
if ( link != null && !link.equals( "" ) )//$NON-NLS-1$
{
return link;
}
return null;
}
/**
* handle style image
*
* @param uri
* uri in style image
* @return
*/
public String handleStyleImage( String uri )
{
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
URL url = design.findResource( uri, IResourceLocator.IMAGE );
if ( url == null )
{
return uri;
}
uri = url.toExternalForm( );
Image image = new Image( uri );
image.setReportRunnable( runnable );
image.setRenderOption( renderOption );
String imgUri = null;
if ( imageHandler != null )
{
switch ( image.getSource( ) )
{
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( image, reportContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( image, reportContext );
break;
case IImage.INVALID_IMAGE :
break;
default :
assert ( false );
}
// imgUri = imgUri.replace( File.separatorChar, '/' );
}
return imgUri;
}
/**
* Resize chart template and table template element.
*
* @param content
* the styled element content
*/
private void resizeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "ExtendedItem".equals(allowedType ) )
{
// Resize chart template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 3, DimensionType.UNITS_IN ) );
content.setHeight( new DimensionType( 3, DimensionType.UNITS_IN ) );
}
else if ( "Table".equals(allowedType) )
{
// Resize table template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 5, DimensionType.UNITS_IN ) );
}
}
}
/**
* judge the content is belong table template element or not.
*
* @param content
* the styled element content
*/
private boolean isTalbeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "Table".equals(allowedType) )
{
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void endGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void endListBand( IListBandContent listBand )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void endListGroup( IListGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void endTableGroup( ITableGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void startGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void startListBand( IListBandContent listBand )
{
}
/**
* used to control the output of group bookmarks.
* @see {@link #startTableGroup(ITableGroupContent)}
* @see {@link #startListGroup(IListGroupContent)}
*/
protected Stack startedGroups = new Stack();
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void startListGroup( IListGroupContent group )
{
outputBookmark( group );
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void startTableGroup( ITableGroupContent group )
{
startedGroups.push( group );
}
private void outputBookmark( IGroupContent group )
{
String bookmark = group.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
group.setBookmark( bookmark );
}
writer.openTag( HTMLTags.TAG_SPAN );
writer.attribute( HTMLTags.ATTR_ID, group.getBookmark( ) );
writer.closeTag( HTMLTags.TAG_SPAN );
}
}
class IDGenerator
{
protected int bookmarkId = 0;
IDGenerator( )
{
this.bookmarkId = 0;
}
protected String generateUniqueID( )
{
bookmarkId ++;
return "AUTOGENBOOKMARK_" + bookmarkId;
}
}
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseTeleportAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class TeleportAction extends BaseTeleportAction
{
private static int DEFAULT_PASSTHROUGH_RANGE = 4;
private boolean autoPassthrough = true;
private int passthroughRange;
private int ledgeSearchDistance = 2;
@Override
public void prepare(CastContext context, ConfigurationSection parameters)
{
super.prepare(context, parameters);
Mage mage = context.getMage();
ledgeSearchDistance = parameters.getInt("ledge_range", 2);
autoPassthrough = parameters.getBoolean("allow_passthrough", true);
passthroughRange = (int)Math.floor(mage.getRangeMultiplier() * parameters.getInt("passthrough_range", DEFAULT_PASSTHROUGH_RANGE));
}
@Override
public SpellResult perform(CastContext context)
{
Entity entity = context.getEntity();
if (entity == null) {
return SpellResult.ENTITY_REQUIRED;
}
boolean isPassthrough = false;
if (autoPassthrough)
{
Block firstBlock = context.getInteractBlock();
if (firstBlock == null) return SpellResult.NO_TARGET;
if (!context.allowPassThrough(firstBlock.getType()))
{
return SpellResult.NO_TARGET;
}
if (firstBlock != null && !context.isTransparent(firstBlock.getType())) {
context.retarget(passthroughRange, 0, passthroughRange, 0, false, new Vector(0, -1, 0), true, 1);
isPassthrough = true;
}
}
Block target = context.getTargetBlock();
Block face = context.getPreviousBlock();
if (target == null)
{
return SpellResult.NO_TARGET;
}
if (face == null)
{
face = target;
}
World world = context.getWorld();
Block destination = face;
int verticalSearchDistance = context.getVerticalSearchDistance();
if (isPassthrough || destination == null)
{
destination = target;
}
// Don't drop the player too far, and make sure there is somewhere to stand - unless they are flying
if (!(entity instanceof Player && ((Player)entity).isFlying())) {
Location safeLocation = context.findPlaceToStand(destination.getLocation(), verticalSearchDistance, false);
if (safeLocation != null)
{
destination = safeLocation.getBlock();
}
}
// Also check for a ledge above the target
Block ledge = null;
if (!isPassthrough && (!face.equals(target.getRelative(BlockFace.DOWN)) || autoPassthrough))
{
int distanceUp = 0;
ledge = target;
Block inFront = face;
Block oneUp = ledge.getRelative(BlockFace.UP);
Block twoUp = oneUp.getRelative(BlockFace.UP);
Block faceOneUp = face.getRelative(BlockFace.UP);
Block faceTwoUp = faceOneUp.getRelative(BlockFace.UP);
if (!autoPassthrough && (!context.isTransparent(oneUp.getType()) || !context.isTransparent(twoUp.getType())
|| !context.isTransparent(face.getType()) || !context.isTransparent(faceOneUp.getType())
|| !context.isTransparent(faceTwoUp.getType())))
{
ledge = null;
}
else
{
// Check for ability to pass through the face block
while
(
(autoPassthrough ||
( context.isTransparent(face.getType())
&& context.isTransparent(faceOneUp.getType())
&& context.isTransparent(faceTwoUp.getType())
)
)
&& distanceUp < ledgeSearchDistance
&& context.isOkToStandIn(inFront.getType())
&& (
!context.isOkToStandOn(ledge.getType())
|| !context.isOkToStandIn(oneUp.getType())
|| !context.isOkToStandIn(twoUp.getType())
)
)
{
faceOneUp = faceOneUp.getRelative(BlockFace.UP);
faceTwoUp = faceOneUp.getRelative(BlockFace.UP);
inFront = inFront.getRelative(BlockFace.UP);
ledge = ledge.getRelative(BlockFace.UP);
distanceUp++;
}
}
} else {
ledge = null;
}
if (ledge != null && context.isOkToStandOn(ledge.getType()))
{
destination = ledge.getRelative(BlockFace.UP);
}
Block oneUp = destination.getRelative(BlockFace.UP);
Block twoUp = oneUp.getRelative(BlockFace.UP);
if (!context.isOkToStandIn(oneUp.getType()) || !context.isOkToStandIn(twoUp.getType()))
{
return SpellResult.NO_TARGET;
}
Location targetLocation = new Location
(
world,
destination.getX() + 0.5,
destination.getY(),
destination.getZ() + 0.5,
entity.getLocation().getYaw(),
entity.getLocation().getPitch()
);
context.teleport(entity, targetLocation, verticalSearchDistance);
return SpellResult.CAST;
}
@Override
public boolean isUndoable() {
return true;
}
@Override
public boolean requiresTarget() {
return true;
}
}
|
package com.fishercoder.solutions;
public class _313 {
public static class Solution1 {
public int nthSuperUglyNumber(int n, int[] primes) {
int[] ret = new int[n];
ret[0] = 1;
int[] indexes = new int[primes.length];
for (int i = 1; i < n; i++) {
ret[i] = Integer.MAX_VALUE;
for (int j = 0; j < primes.length; j++) {
ret[i] = Math.min(ret[i], primes[j] * ret[indexes[j]]);
}
for (int j = 0; j < indexes.length; j++) {
if (ret[i] == primes[j] * ret[indexes[j]]) {
indexes[j]++;
}
}
}
return ret[n - 1];
}
}
}
|
package org.eclipse.birt.report.engine.emitter.html;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IHTMLActionHandler;
import org.eclipse.birt.report.engine.api.IHTMLImageHandler;
import org.eclipse.birt.report.engine.api.IImage;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.InstanceID;
import org.eclipse.birt.report.engine.api.RenderOptionBase;
import org.eclipse.birt.report.engine.api.impl.Action;
import org.eclipse.birt.report.engine.api.impl.Image;
import org.eclipse.birt.report.engine.content.IBandContent;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IElement;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IGroupContent;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListBandContent;
import org.eclipse.birt.report.engine.content.IListGroupContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableBandContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITableGroupContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.content.impl.RowContent;
import org.eclipse.birt.report.engine.css.dom.CellMergedStyle;
import org.eclipse.birt.report.engine.css.engine.value.birt.BIRTConstants;
import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter;
import org.eclipse.birt.report.engine.emitter.IEmitterServices;
import org.eclipse.birt.report.engine.executor.ExecutionContext.ElementExceptionInfo;
import org.eclipse.birt.report.engine.executor.css.HTMLProcessor;
import org.eclipse.birt.report.engine.i18n.EngineResourceHandle;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.internal.util.HTMLUtil;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.EngineIRConstants;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.LabelItemDesign;
import org.eclipse.birt.report.engine.ir.ListItemDesign;
import org.eclipse.birt.report.engine.ir.MasterPageDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
import org.eclipse.birt.report.engine.ir.TableItemDesign;
import org.eclipse.birt.report.engine.ir.TemplateDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.eclipse.birt.report.engine.parser.TextParser;
import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.core.IModuleModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class HTMLReportEmitter extends ContentEmitterAdapter
{
/**
* the output format
*/
public static final String OUTPUT_FORMAT_HTML = "HTML"; //$NON-NLS-1$
/**
* the default target report file name
*/
public static final String REPORT_FILE = "report.html"; //$NON-NLS-1$
/**
* the default image folder
*/
public static final String IMAGE_FOLDER = "image"; //$NON-NLS-1$
/**
* output stream
*/
protected OutputStream out = null;
/**
* the report content
*/
protected IReportContent report;
/**
* the report runnable instance
*/
protected IReportRunnable runnable;
/**
* the render options
*/
protected IRenderOption renderOption;
/**
* should output the page header & footer
*/
protected boolean outputMasterPageContent = true;
/**
* specifies if the HTML output is embeddable
*/
protected boolean isEmbeddable = false;
/**
* the url encoding
*/
protected String urlEncoding = null;
/**
* should we output the report as Right To Left
*/
protected boolean htmlRtLFlag = false;
protected boolean pageFooterFloatFlag = true;
protected boolean enableMetadata = false;
protected boolean displayFilterIcon = false;
protected List ouputInstanceIDs = null;
/**
* specified the current page number, starting from 0
*/
protected int pageNo = 0;
/**
* the <code>HTMLWriter<code> object that is used to output HTML content
*/
protected HTMLWriter writer;
/**
* the image reder context
*/
protected Object renderContext;
/**
* indicates that the styled element is hidden or not
*/
protected Stack stack = new Stack( );
/**
* An Log object that <code>HTMLReportEmitter</code> use to log the error,
* debug, information messages.
*/
protected static Logger logger = Logger.getLogger( HTMLReportEmitter.class
.getName( ) );
/**
* html image handler
*/
protected IHTMLImageHandler imageHandler;
/**
* html action handler
*/
protected IHTMLActionHandler actionHandler;
/**
* emitter services
*/
protected IEmitterServices services;
/**
* The <code>tagStack</code> that stores the tag names to be closed in
* <code>endContainer()</code>.
*/
private Stack tagStack = new Stack( );
/**
* display type of Block
*/
protected static final int DISPLAY_BLOCK = 1;
/**
* display type of Inline
*/
protected static final int DISPLAY_INLINE = 2;
/**
* display type of Inline-Block
*/
protected static final int DISPLAY_INLINE_BLOCK = 4;
/**
* display type of none
*/
protected static final int DISPLAY_NONE = 8;
/**
* display flag which contains all display types
*/
protected static final int DISPLAY_FLAG_ALL = 0xffff;
/**
* content visitor that is used to handle page header/footer
*/
protected ContentEmitterVisitor contentVisitor;
private Stack detailRowStateStack = new Stack( );
/**
* the constructor
*/
public HTMLReportEmitter( )
{
contentVisitor = new ContentEmitterVisitor( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#initialize(org.eclipse.birt.report.engine.emitter.IEmitterServices)
*/
public void initialize( IEmitterServices services )
{
this.services = services;
Object fd = services.getOption( RenderOptionBase.OUTPUT_FILE_NAME );
File file = null;
try
{
if ( fd != null )
{
file = new File( fd.toString( ) );
File parent = file.getParentFile( );
if ( parent != null && !parent.exists( ) )
{
parent.mkdirs( );
}
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
}
catch ( FileNotFoundException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
if ( out == null )
{
Object value = services.getOption( RenderOptionBase.OUTPUT_STREAM );
if ( value != null && value instanceof OutputStream )
{
out = (OutputStream) value;
}
else
{
try
{
// FIXME
file = new File( REPORT_FILE );
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
catch ( FileNotFoundException e )
{
// FIXME
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
}
Object emitterConfig = services.getEmitterConfig( ).get( "html" ); //$NON-NLS-1$
if ( emitterConfig != null
&& emitterConfig instanceof HTMLEmitterConfig )
{
imageHandler = ( (HTMLEmitterConfig) emitterConfig )
.getImageHandler( );
actionHandler = ( (HTMLEmitterConfig) emitterConfig )
.getActionHandler( );
}
Object im = services.getOption( HTMLRenderOption.IMAGE_HANDLER );
if ( im != null && im instanceof IHTMLImageHandler )
{
imageHandler = (IHTMLImageHandler) im;
}
Object ac = services.getOption( HTMLRenderOption.ACTION_HANDLER );
if ( ac != null && ac instanceof IHTMLActionHandler )
{
actionHandler = (IHTMLActionHandler) ac;
}
if ( services.getRenderContext( ) instanceof Map )
{
renderContext = ( (Map) services.getRenderContext( ) )
.get( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT );
}
else
{
renderContext = services.getRenderContext( ); // Handle the
// old-style render
// context, follow
// the same code
// path as before.
}
renderOption = services.getRenderOption( );
runnable = services.getReportRunnable( );
if ( renderOption != null && renderOption instanceof HTMLRenderOption )
{
HTMLRenderOption htmlOption = (HTMLRenderOption) renderOption;
isEmbeddable = htmlOption.getEmbeddable( );
HashMap options = renderOption.getOutputSetting( );
if ( options != null )
{
urlEncoding = (String) options
.get( HTMLRenderOption.URL_ENCODING );
}
outputMasterPageContent = htmlOption.getMasterPageContent( );
IHTMLActionHandler actHandler = htmlOption.getActionHandle( );
if ( ac != null )
{
actionHandler = actHandler;
}
pageFooterFloatFlag = htmlOption.getPageFooterFloatFlag( );
htmlRtLFlag = htmlOption.getHtmlRtLFlag( );
enableMetadata = htmlOption.getEnableMetadata( );
displayFilterIcon = htmlOption.getDisplayFilterIcon( );
ouputInstanceIDs = htmlOption.getInstanceIDs( );
}
writer = new HTMLWriter( );
}
/**
* @return the <code>Report</code> object.
*/
public IReportContent getReport( )
{
return report;
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* to the style
*
* @param style
*/
public void push( IStyle style )
{
stack.push( new Boolean( peek( style ) ) );
}
/**
* Pops the element of the stack
*
* @return the boolean indicating whether or not the item is hidden
*/
public boolean pop( )
{
return ( (Boolean) stack.pop( ) ).booleanValue( );
}
/**
* Peeks the element of stack
*
* @param style
* @return the boolean indicating whether or not the item is hidden
*/
public boolean peek( IStyle style )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
String formats = style.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
isHidden = true;
}
}
return isHidden;
}
/**
* Checks if the current item is hidden
*
* @return a boolean value
*/
public boolean isHidden( )
{
return ( (Boolean) stack.peek( ) ).booleanValue( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#getOutputFormat()
*/
public String getOutputFormat( )
{
return OUTPUT_FORMAT_HTML;
}
protected void fixTransparentPNG( )
{
writer.writeCode( "<!--[if gte IE 5.5000]>" ); //$NON-NLS-1$
writer
.writeCode( " <script language=\"JavaScript\"> var ie55up = true </script>" ); //$NON-NLS-1$
writer.writeCode( "<![endif]-->" ); //$NON-NLS-1$
writer.writeCode( "<script language=\"JavaScript\">" ); //$NON-NLS-1$
writer
.writeCode( " function fixPNG(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher." ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer.writeCode( " if (window.ie55up)" ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer
.writeCode( " var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgTitle = (myImage.title) ? \"title='\" + myImage.title + \"' \" : \"title='\" + myImage.alt + \"' \"" ); //$NON-NLS-1$
writer
.writeCode( " var imgStyle = \"display:inline-block;\" + myImage.style.cssText" ); //$NON-NLS-1$
writer
.writeCode( " var strNewHTML = \"<span \" + imgID + imgClass + imgTitle" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \" style=\\\"\" + \"width:\" + myImage.width + \"px; height:\" + myImage.height + \"px;\" + imgStyle + \";\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"(src=\\'\" + myImage.src + \"\\', sizingMethod='scale');\\\"></span>\"" ); //$NON-NLS-1$
writer.writeCode( " myImage.outerHTML = strNewHTML" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( "</script>" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#start(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void start( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] Start emitter." ); //$NON-NLS-1$
this.report = report;
writer.open( out, "UTF-8" ); //$NON-NLS-1$
// If it is the body style and htmlRtLFlag has been set true,
// remove the text-align included in the style.
if ( htmlRtLFlag )
{
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
//style.removeProperty( "text-align" );
style.setTextAlign( "right" );
}
}
if ( isEmbeddable )
{
fixTransparentPNG( );
writer.openTag( HTMLTags.TAG_DIV );
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildStyle( styleBuffer, style, this, false );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
return;
}
writer.startWriter( );
writer.openTag( HTMLTags.TAG_HTML );
writer.openTag( HTMLTags.TAG_HEAD );
// write the title of the report in html.
Report reportDesign = null;
if ( report != null )
{
reportDesign = report.getDesign( );
ReportDesignHandle designHandle = reportDesign.getReportDesign( );
String title = designHandle.getStringProperty( IModuleModel.TITLE_PROP );
if ( title == null )
{
// set the default title
if ( renderOption != null && renderOption instanceof HTMLRenderOption )
{
HTMLRenderOption htmlOption = (HTMLRenderOption) renderOption;
title = htmlOption.getHtmlTitle( );
}
}
if ( title != null )
{
writer.openTag( HTMLTags.TAG_TITLE );
writer.text( title );
writer.closeTag( HTMLTags.TAG_TITLE );
}
}
writer.openTag( HTMLTags.TAG_META );
writer.attribute( HTMLTags.ATTR_HTTP_EQUIV, "Content-Type" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_CONTENT, "text/html; charset=UTF-8" ); //$NON-NLS-1$
writer.closeNoEndTag( );
writer.openTag( HTMLTags.TAG_STYLE );
writer.attribute( HTMLTags.ATTR_TYPE, "text/css" ); //$NON-NLS-1$
IStyle style;
StringBuffer styleBuffer = new StringBuffer( );
if ( report == null )
{
logger.log( Level.WARNING,
"[HTMLReportEmitter] Report object is null." ); //$NON-NLS-1$
}
else
{
for ( int n = 0; n < reportDesign.getStyleCount( ); n++ )
{
styleBuffer.delete( 0, styleBuffer.capacity( ) );
style = (IStyle) reportDesign.getStyle( n );
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
writer.style( Report.PREFIX_STYLE_NAME + n, styleBuffer
.toString( ), false );
}
}
writer.closeTag( HTMLTags.TAG_STYLE );
fixTransparentPNG( );
writer.closeTag( HTMLTags.TAG_HEAD );
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
writer.openTag( HTMLTags.TAG_BODY );
if ( reportStyleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, reportStyleName );
}
}
private void appendErrorMessage( int index, ElementExceptionInfo info )
{
EngineResourceHandle rc = EngineResourceHandle.getInstance( );
writer.writeCode( " <div>" );
writer.writeCode( " <div id=\"error_title\" style=\"text-decoration:underline\">" );
String name = info.getName( );
if ( name != null )
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE,
new Object[]{info.getType( ), name } ), false );
}
else
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE_WITH_ID,
new Object[]{info.getType( ), info.getID( ) } ), false );
}
writer.writeCode( "</div>" );//$NON-NLS-1$
ArrayList errorList = info.getErrorList( );
ArrayList countList = info.getCountList( );
for ( int i = 0; i < errorList.size( ); i++ )
{
String errorId = "document.getElementById('error_detail" + index + "_" + i + "')";
String errorIcon = "document.getElementById('error_icon" + index + "_" + i + "')";
String onClick = "if (" + errorId + ".style.display == 'none') { "
+ errorIcon + ".innerHTML = '- '; " + errorId
+ ".style.display = 'block'; }" + "else { " + errorIcon
+ ".innerHTML = '+ '; " + errorId + ".style.display = 'none'; }";
writer.writeCode("<div>");
BirtException ex = (BirtException) errorList.get( i );
writer.writeCode( "<span id=\"error_icon" + index + "_" + i
+ "\" style=\"cursor:pointer\" onclick=\"" + onClick
+ "\" > + </span>" );
writer.text( ex.getLocalizedMessage( ) );
writer.writeCode( " <pre id=\"error_detail" + index + "_" + i //$NON-NLS-1$
+ "\" style=\"display:none;\" >" );//$NON-NLS-1$
String messageTitle = rc.getMessage(
MessageConstants.REPORT_ERROR_ID, new Object[]{
ex.getErrorCode( ) ,
countList.get( i )} );
String detailTag = rc
.getMessage( MessageConstants.REPORT_ERROR_DETAIL );
String messageBody = getDetailMessage( ex );
boolean indent = writer.isIndent( );
writer.setIndent( false );
writer.text( messageTitle, false );
writer.writeCode( "\r\n" );//$NON-NLS-1$
writer.text( detailTag, false );
writer.text( messageBody, false );
writer.setIndent( indent );
writer.writeCode( " </pre>" ); //$NON-NLS-1$
writer.writeCode("</div>");
}
writer.writeCode( "</div>" ); //$NON-NLS-1$
writer.writeCode( "<br>" ); //$NON-NLS-1$
}
private String getDetailMessage( Throwable t )
{
StringWriter out = new StringWriter( );
PrintWriter print = new PrintWriter( out );
try
{
t.printStackTrace( print );
}
catch ( Throwable ex )
{
}
print.flush( );
return out.getBuffer( ).toString( );
}
protected boolean outputErrors( List errors )
{
// Outputs the error message at the end of the report
if ( errors != null && !errors.isEmpty( ) )
{
writer.writeCode( " <hr style=\"color:red\"/>" );
writer.writeCode( " <div style=\"color:red\">" );
writer.writeCode( " <div>" );
writer.text( EngineResourceHandle.getInstance( ).getMessage(
MessageConstants.ERRORS_ON_REPORT_PAGE ), false );
writer.writeCode( "</div>" );//$NON-NLS-1$
writer.writeCode( "<br>") ;//$NON-NLS-1$
Iterator it = errors.iterator( );
int index = 0;
while ( it.hasNext( ) )
{
appendErrorMessage( index++, (ElementExceptionInfo) it.next( ) );
}
writer.writeCode( "</div>" );
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#end(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void end( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End body." ); //$NON-NLS-1$
if ( report != null )
{
List errors = report.getErrors( );
if ( errors != null && !errors.isEmpty( ) )
{
outputErrors( errors );
}
}
if ( !isEmbeddable )
{
writer.closeTag( HTMLTags.TAG_BODY );
writer.closeTag( HTMLTags.TAG_HTML );
}
else
{
writer.closeTag( HTMLTags.TAG_DIV );
}
writer.endWriter( );
writer.close( );
if ( out != null )
{
try
{
out.close( );
}
catch ( IOException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
}
}
/***
* output the style of page header/footer/body.
* The background style will not be out put.
* @param styleName name of the style
* @param style style object
*/
public void handlePageStyle( String styleName, IStyle style )
{
StringBuffer styleBuffer = new StringBuffer( );
if ( isEmbeddable )
{
AttributeBuilder.buildPageStyle( styleBuffer, style, this );
}
else
{
IStyle classStyle = report.findStyle( styleName );
AttributeBuilder.buildPageStyle( styleBuffer, classStyle, this );
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void startPage( IPageContent page )
{
pageNo++;
if ( pageNo > 1 && outputMasterPageContent == false )
{
writer.openTag( "hr" );
writer.closeTag( "hr" );
}
// out put the page tag
writer.openTag( HTMLTags.TAG_DIV );
// out put the background
if ( page != null )
{
Object genBy = page.getGenerateBy( );
if ( genBy instanceof MasterPageDesign )
{
MasterPageDesign masterPage = (MasterPageDesign) genBy;
String masterPageStyleName = masterPage.getStyleName( );
IStyle classStyle = report.findStyle( masterPageStyleName );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildBackgroundStyle( styleBuffer, classStyle, this );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
}
if ( htmlRtLFlag )
{
writer.attribute( HTMLTags.ATTR_HTML_DIR, "RTL" );
}
if ( pageNo > 1 )
{
writer.attribute( HTMLTags.ATTR_STYLE, "page-break-before: always;" );
}
//output page header
if ( page != null )
{
if ( outputMasterPageContent )
{
// output DIV for page header
boolean showHeader = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowHeaderOnFirst( ) )
{
if ( page.getPageNumber( ) == 1 )
{
showHeader = false;
}
}
}
if ( showHeader )
{
writer.openTag( HTMLTags.TAG_DIV );
handlePageStyle( page.getPageHeader( ).getStyleClass( ),
page.getPageHeader( ).getStyle( ) );
contentVisitor.visitChildren( page.getPageHeader( ), null );
// close the page header
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// start output the page body , with the body style
writer.openTag( HTMLTags.TAG_DIV );
if ( page != null )
{
IContent pageBody = page.getPageBody( );
IStyle bodyStyle = pageBody.getStyle( );
String bodyStyleName = pageBody.getStyleClass( );
Object genBy = page.getGenerateBy( );
if ( genBy instanceof MasterPageDesign )
{
MasterPageDesign masterPage = (MasterPageDesign) genBy;
StringBuffer styleBuffer = new StringBuffer( );
if ( isEmbeddable )
{
AttributeBuilder.buildPageStyle( styleBuffer, bodyStyle, this );
}
else
{
IStyle classStyle = report.findStyle( bodyStyleName );
AttributeBuilder.buildPageStyle( styleBuffer, classStyle, this );
}
if( !pageFooterFloatFlag )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_HEIGHT,
masterPage.getPageHeight( ) );
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void endPage( IPageContent page )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End page." ); //$NON-NLS-1$
//close the page body (DIV)
writer.closeTag( HTMLTags.TAG_DIV );
//output page footer
if ( page != null )
{
if ( outputMasterPageContent )
{
boolean showFooter = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowFooterOnLast( ) )
{
long totalPage = page.getPageNumber( );
IReportContent report = page.getReportContent( );
if ( report != null )
{
totalPage = report.getTotalPage( );
}
if ( page.getPageNumber( ) == totalPage)
{
showFooter = false;
}
}
}
if ( showFooter )
{
// start output the page footer
writer.openTag( HTMLTags.TAG_DIV );
handlePageStyle( page.getPageFooter( ).getStyleClass( ),
page.getPageFooter( ).getStyle( ) );
contentVisitor.visitChildren( page.getPageFooter( ), null );
// close the page footer
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// close the page tag ( DIV )
writer.closeTag( HTMLTags.TAG_DIV );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void startTable( ITableContent table )
{
assert table != null;
IStyle mergedStyle = table.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start table" ); //$NON-NLS-1$
DimensionType x = table.getX( );
DimensionType y = table.getY( );
StringBuffer styleBuffer = new StringBuffer( );
addDefaultTableStyles( styleBuffer );
writer.openTag( HTMLTags.TAG_TABLE );
// style string
setStyleName( table.getStyleClass( ) );
int display = checkElementType( x, y, mergedStyle, styleBuffer );
setDisplayProperty( display, DISPLAY_INLINE, styleBuffer );
handleShrink( DISPLAY_BLOCK, mergedStyle, table.getHeight( ), table
.getWidth( ), styleBuffer );
handleStyle( table, styleBuffer );
// bookmark
String bookmark = table.getBookmark( );
if ( bookmark == null )
{
bookmark = generateUniqueID( );
table.setBookmark( bookmark );
}
setBookmark( null, bookmark );
// Add it to active id list, and output type iid to html
setActiveIDTypeIID(table);
// table caption
String caption = table.getCaption( );
if ( caption != null && caption.length( ) > 0 )
{
writer.openTag( HTMLTags.TAG_CAPTION );
writer.text( caption );
writer.closeTag( HTMLTags.TAG_CAPTION );
}
// include select handle table
if ( enableMetadata )
{
Object generateBy = table.getGenerateBy( );
DetailRowState state = null;
if ( generateBy instanceof TableItemDesign )
{
state = new DetailRowState( false, false, true );
}
else
{
state = new DetailRowState( false, false, false );
}
detailRowStateStack.push( state );
}
writeColumns( table );
}
protected void writeColumns( ITableContent table )
{
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
IColumn column = table.getColumn( i );
if ( isColumnHidden( column ) )
{
continue;
}
writer.openTag( HTMLTags.TAG_COL );
setStyleName( column.getStyleClass( ) );
// width
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH,
column.getWidth( ) );
if ( isEmbeddable )
{
// output in-line style
String styleName = column.getStyleClass( );
if ( styleName != null )
{
IStyle style = report.findStyle( styleName );
if ( style != null )
{
AttributeBuilder.buildStyle( styleBuffer, style, this );
}
}
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
// Instance ID
InstanceID iid = column.getInstanceID( );
if ( iid != null )
{
writer.attribute( "iid", iid.toString( ) );
}
writer.closeNoEndTag( );
}
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* @param hidden
*/
public void push( boolean hidden )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
isHidden = hidden;
}
stack.push( new Boolean( isHidden ) );
}
/**
* check whether to hide the column.
* @param column
* @return
*/
private boolean isColumnHidden( IColumn column )
{
String formats = column.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
return true;
}
return false;
}
/**
* get the new colspan of the cell
* by checking the relational columns.
* @param column
* @return
*/
private int getNewColSpan( ICellContent cell )
{
int columnNumber = cell.getColumn( );
int colSpan = cell.getColSpan( );
ITableContent table = getTableOfCell(cell);
if (table == null)
{
return colSpan;
}
int newColSpan = colSpan;
for ( int i = 0; i < colSpan; i++ )
{
IColumn column = table.getColumn( columnNumber + i );
if ( isColumnHidden( column ) )
{
newColSpan
}
}
return newColSpan;
}
private ITableContent getTableOfCell( ICellContent cell )
{
IElement parent = cell.getParent( );
while ( parent != null )
{
if ( parent instanceof ITableContent )
{
return (ITableContent) parent;
}
parent = parent.getParent( );
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void endTable( ITableContent table )
{
if ( pop( ) )
{
return;
}
// include select handle table
if ( enableMetadata )
{
detailRowStateStack.pop( );
}
writer.closeTag( HTMLTags.TAG_TABLE );
logger.log( Level.FINE, "[HTMLTableEmitter] End table" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TFOOT );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TFOOT );
}
boolean isRowInDetailBand(IRowContent row)
{
IElement parent = row.getParent( );
if ( !( parent instanceof IBandContent ) )
{
return false;
}
IBandContent band = (IBandContent)parent;
if (band.getBandType( ) == IBandContent.BAND_DETAIL)
{
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void startRow( IRowContent row )
{
assert row != null;
IStyle mergedStyle = row.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
if ( enableMetadata )
{
if ( isRowInDetailBand( row ) )
{
DetailRowState state = (DetailRowState) detailRowStateStack
.peek( );
if ( !state.hasOutput && !state.isStartOfDetail
&& state.isTable )
{
state.isStartOfDetail = true;
state.hasOutput = true;
}
}
}
writer.openTag( HTMLTags.TAG_TR );
setStyleName( row.getStyleClass( ) );
// bookmark
setBookmark( null, row.getBookmark( ) );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, row
.getHeight( ) ); //$NON-NLS-1$
outputRowMetaData( row );
handleStyle( row, styleBuffer );
}
protected IGroupContent getGroup(IBandContent bandContent)
{
IContent parent = (IContent)bandContent.getParent();
if (parent instanceof IGroupContent)
{
return (IGroupContent)parent;
}
return null;
}
protected void outputRowMetaData( IRowContent rowContent )
{
Object parent = rowContent.getParent( );
if ( parent instanceof ITableBandContent )
{
ITableBandContent bandContent = (ITableBandContent) parent;
IGroupContent group = rowContent.getGroup( );
String groupId = rowContent.getGroupId( );
if ( groupId != null )
{
writer.attribute( HTMLTags.ATTR_GOURP_ID, groupId );
}
String rowType = null;
String metaType = null;
int bandType = bandContent.getBandType( );
if ( bandType == ITableBandContent.BAND_HEADER )
{
metaType = "wrth";
rowType = "header";
}
else if ( bandType == ITableBandContent.BAND_FOOTER )
{
metaType = "wrtf";
rowType = "footer";
}
else if ( bandType == ITableBandContent.BAND_GROUP_HEADER )
{
rowType = "group-header";
if ( group != null )
{
metaType = "wrgh" + group.getGroupLevel( );
}
}
else if ( bandType == ITableBandContent.BAND_GROUP_FOOTER )
{
rowType = "group-footer";
if ( group != null )
{
metaType = "wrgf" + group.getGroupLevel( );
}
}
writer.attribute( HTMLTags.ATTR_TYPE, metaType );
writer.attribute( HTMLTags.ATTR_ROW_TYPE, rowType );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void endRow( IRowContent row )
{
if ( pop( ) )
{
return;
}
if ( enableMetadata )
{
DetailRowState state = (DetailRowState) detailRowStateStack.peek( );
if ( state.isStartOfDetail )
{
state.isStartOfDetail = false;
}
}
// assert currentData != null;
// currentData.adjustCols( );
writer.closeTag( HTMLTags.TAG_TR );
}
private boolean isCellInTableHead( ICellContent cell )
{
IElement row = cell.getParent( );
if ( row instanceof IRowContent )
{
IElement tableBand = row.getParent( );
if ( tableBand instanceof ITableBandContent )
{
int type = ( (ITableBandContent)tableBand ).getBandType( );
if ( type == ITableBandContent.BAND_HEADER )
{
return true;
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void startCell( ICellContent cell )
{
int colSpan = cell.getColSpan( );
push( false );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start cell." ); //$NON-NLS-1$
// output 'th' tag in table head, otherwise 'td' tag
boolean isInTableHead = isCellInTableHead( cell );
if ( isInTableHead )
{
writer.openTag( HTMLTags.TAG_TH ); //$NON-NLS-1$
}
else
{
writer.openTag( HTMLTags.TAG_TD ); //$NON-NLS-1$
}
// set the 'name' property
setStyleName( cell.getStyleClass( ) );
// colspan
if ( colSpan > 1 )
{
writer.attribute( HTMLTags.ATTR_COLSPAN, colSpan );
}
// rowspan
if ( ( cell.getRowSpan( ) ) > 1 )
{
writer.attribute( HTMLTags.ATTR_ROWSPAN, cell.getRowSpan( ) );
}
// vertical align can only be used with tabelCell/Inline Element
StringBuffer styleBuffer = new StringBuffer( );
handleColumnRelatedStyle( cell, styleBuffer );
handleVerticalAlign( cell, styleBuffer );
// set font weight to be normal if the cell use "th" tag while it is in table header.
if ( isInTableHead )
{
handleCellFont( cell, styleBuffer );
}
handleStyle( cell, styleBuffer );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
initializeCell( cell );
}
private void initializeCell( ICellContent cell )
{
if ( enableMetadata )
{
if ( needColumnFilter( cell ) || cell.isStartOfGroup( ) )
{
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_HEIGHT, "100%" );
writer.attribute( HTMLTags.ATTR_WIDTH, "100%" );
if ( cell.isStartOfGroup( ))
{
writer.openTag( HTMLTags.TAG_COL );
writer.attribute( "style", "width:" + getRowIndent( cell ) );
writer.closeNoEndTag( );
writer.openTag( HTMLTags.TAG_COL );
writer.closeNoEndTag( );
writer.openTag( HTMLTags.TAG_COL );
writer.closeNoEndTag( );
}
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
}
if ( cell.isStartOfGroup( ) )
{
// include select handle table
writer.attribute( HTMLTags.ATTR_STYLE, "vertical-align:top" + ";text-align:right" );
writer.openTag( HTMLTags.TAG_IMAGE );
writer.attribute( HTMLTags.ATTR_SRC,
"iv/images/collapsexpand.gif" );
writer.attribute( HTMLTags.ATTR_STYLE, "cursor:pointer" );
String bookmark = generateUniqueID( );
setBookmark( null, bookmark );
setActiveIDTypeIID( bookmark, "GROUP", null, -1 );
writer.closeTag( HTMLTags.TAG_IMAGE );
writer.closeTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
}
}
}
private String getRowIndent( ICellContent cell )
{
IRowContent row = ( RowContent )cell.getParent( );
int groupLevel = HTMLUtil.getGroupLevel( row );
if ( groupLevel >= 0 )
{
return String.valueOf( HTMLUtil.getGroupLevel( row ) * 16 ) + "px";
}
return "0px";
}
private void handleColumnRelatedStyle( ICellContent cell,
StringBuffer styleBuffer )
{
IStyle style = new CellMergedStyle( cell );
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void endCell( ICellContent cell )
{
if ( pop( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] End cell." ); //$NON-NLS-1$
if ( enableMetadata )
{
if ( needColumnFilter( cell ) )
{
// include select handle table
writer.closeTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( HTMLTags.ATTR_STYLE, "vertical-align:top" );
writer.openTag( HTMLTags.TAG_IMAGE );
writer
.attribute( HTMLTags.ATTR_SRC,
"iv/images/columnicon.gif" );
writer.attribute( HTMLTags.ATTR_ALT, HTMLUtil
.getColumnFilterText( cell ) );
writer.attribute( HTMLTags.ATTR_STYLE, "cursor:pointer" );
writer.attribute( HTMLTags.ATTR_COLUMN, cell
.getColumnInstance( ).getInstanceID( ).toString( ) );
String bookmark = generateUniqueID( );
setBookmark( null, bookmark );
setActiveIDTypeIID( bookmark, "COLOUMNINFO", null, -1 );
writer.closeTag( HTMLTags.TAG_IMAGE );
}
if ( needColumnFilter( cell ) || cell.isStartOfGroup( ) )
{
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
}
if ( isCellInTableHead( cell ) )
{
writer.closeTag( HTMLTags.TAG_TH );
}
else
{
writer.closeTag( HTMLTags.TAG_TD );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void startContainer( IContainerContent container )
{
IStyle mergedStyle = container.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start container" ); //$NON-NLS-1$
String tagName;
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = container.getX( );
DimensionType y = container.getY( );
DimensionType width = container.getWidth( );
DimensionType height = container.getHeight( );
int display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
tagStack.push( tagName );
// class
setStyleName( container.getStyleClass( ) );
// bookmark
String bookmark = container.getBookmark( );
if ( bookmark == null )
{
bookmark = generateUniqueID( );
container.setBookmark( bookmark );
}
setBookmark( tagName, bookmark );
setActiveIDTypeIID( container );
// output style
// if ( x == null && y == null )
// styleBuffer.append( "position: relative;" ); //$NON-NLS-1$
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
handleShrink( display, mergedStyle, height, width, styleBuffer );
handleStyle( container, styleBuffer );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void endContainer( IContainerContent container )
{
if ( pop( ) )
{
return;
}
writer.closeTag( (String) tagStack.pop( ) );
logger.log( Level.FINE, "[HTMLContainerEmitter] End container" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startText(org.eclipse.birt.report.engine.content.ITextContent)
*/
public void startText( ITextContent text )
{
IStyle mergedStyle = text.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start text" ); //$NON-NLS-1$
//Resize if the text generated by TemplateDesign
//resizeTemplateElement( text);
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = text.getX( );
DimensionType y = text.getY( );
DimensionType width = text.getWidth( );
DimensionType height = text.getHeight( );
String textValue = text.getText( );
if (textValue == null || textValue == "" ) //$NON-NLS-1$
{
textValue = " "; //$NON-NLS-1$
}
int display;
// If the item is multi-line, we should check if it can be inline-block
if ( textValue != null && textValue.indexOf( '\n' ) >= 0 )
{
display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
}
else
{
display = checkElementType( x, y, mergedStyle, styleBuffer );
}
// action
String tagName;
String selectHandleTag = null;
String url = validate( text.getHyperlinkAction( ) );
boolean needMetadata = enableMetadata
&& ( text.getGenerateBy( ) instanceof LabelItemDesign || text
.getGenerateBy( ) instanceof TemplateDesign );
if ( url != null )
{
//output select class
if ( needMetadata )
{
selectHandleTag = HTMLTags.TAG_SPAN;
writer.openTag( selectHandleTag );
writer.attribute( HTMLTags.ATTR_CLASS, "birt-label-design" ); //$NON-NLS-1$
setActiveIDTypeIID( text );
setBookmark( selectHandleTag, text.getBookmark( ) );
}
tagName = HTMLTags.TAG_A;
outputAction( text.getHyperlinkAction( ), url );
setDisplayProperty( display, DISPLAY_BLOCK | DISPLAY_INLINE_BLOCK,
styleBuffer );
AttributeBuilder.checkHyperlinkTextDecoration( mergedStyle,
styleBuffer );
}
else
{
if ( needMetadata )
{
selectHandleTag = getTagByType( display, DISPLAY_FLAG_ALL );
writer.openTag( selectHandleTag );
writer.attribute( HTMLTags.ATTR_CLASS, "birt-label-design" ); //$NON-NLS-1$
setActiveIDTypeIID( text );
setBookmark( selectHandleTag, text.getBookmark( ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
}
setStyleName( text.getStyleClass( ) );
// bookmark
if ( !needMetadata )
{
outputBookmark( text, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, text.getHelpText( ) ); //$NON-NLS-1$
/*if( isTalbeTemplateElement( text ) )
{
//set lines to dotted lines
mergedStyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_BOTTOM_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_FONT_FAMILY, IStyle.SANS_SERIF_VALUE );
}*/
// check 'can-shrink' property
handleShrink( display, mergedStyle, height, width, styleBuffer );
// export the text-align
String textAlign = text.getComputedStyle( ).getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
handleStyle( text, styleBuffer, false );
String verticalAlign = mergedStyle.getVerticalAlign( );
if ( !"baseline".equals( verticalAlign ) && height != null )
{
// implement vertical align.
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE, " width:100%; height:100%;" );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
StringBuffer textStyleBuffer = new StringBuffer( );
textStyleBuffer.append( " vertical-align:" );
textStyleBuffer.append( verticalAlign );
textStyleBuffer.append( ";" );
writer.attribute( HTMLTags.ATTR_STYLE, textStyleBuffer );
writer.text( textValue );
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
else
{
writer.text( textValue );
}
writer.closeTag( tagName );
if ( needMetadata )
{
writer.closeTag( selectHandleTag );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startForeign(org.eclipse.birt.report.engine.content.IForeignContent)
*/
public void startForeign( IForeignContent foreign )
{
IStyle mergedStyle = foreign.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start foreign" ); //$NON-NLS-1$
resizeTemplateElement( foreign);
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = foreign.getX( );
DimensionType y = foreign.getY( );
DimensionType width = foreign.getWidth( );
DimensionType height = foreign.getHeight( );
int display;
display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
// create default bookmark if we need output metadata
String designClassName = "birt-foreign-design";
if ( foreign.getGenerateBy( ) instanceof TemplateDesign )
{
//FIXME: actually, it should be birt-template-design
designClassName = "birt-label-design";
String bookmark = foreign.getBookmark( );
if ( bookmark == null )
{
bookmark = generateUniqueID( );
foreign.setBookmark( bookmark );
}
}
// action
String tagName;
String selectHandleTag = null;
String url = validate( foreign.getHyperlinkAction( ) );
if ( url != null )
{
if ( enableMetadata )
{
// output select class
selectHandleTag = HTMLTags.TAG_SPAN;
writer.openTag( selectHandleTag );
writer.attribute( HTMLTags.ATTR_CLASS, designClassName ); //$NON-NLS-1$
setActiveIDTypeIID( foreign );
setBookmark( selectHandleTag, foreign.getBookmark( ) );
}
tagName = HTMLTags.TAG_A;
outputAction( foreign.getHyperlinkAction( ), url );
setDisplayProperty( display, DISPLAY_BLOCK | DISPLAY_INLINE_BLOCK,
styleBuffer );
AttributeBuilder.checkHyperlinkTextDecoration( mergedStyle,
styleBuffer );
}
else
{
if ( enableMetadata )
{
selectHandleTag = getTagByType( display, DISPLAY_FLAG_ALL );
writer.openTag( selectHandleTag );
writer.attribute( HTMLTags.ATTR_CLASS, designClassName ); //$NON-NLS-1$
setActiveIDTypeIID( foreign );
setBookmark( selectHandleTag, foreign.getBookmark( ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
}
setStyleName( foreign.getStyleClass( ) );
// bookmark
if ( !enableMetadata )
{
outputBookmark( foreign, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, foreign.getHelpText( ) );
if( isTalbeTemplateElement( foreign ) )
{
//set lines to dotted lines
mergedStyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_BOTTOM_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_FONT_FAMILY, IStyle.SANS_SERIF_VALUE );
}
String textAlign = foreign.getComputedStyle( ).getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
// check 'can-shrink' property
handleShrink( display, mergedStyle, height, width, styleBuffer );
handleStyle( foreign, styleBuffer, false );
String rawType = foreign.getRawType( );
boolean isHtml = IForeignContent.HTML_TYPE.equalsIgnoreCase( rawType );
if ( isHtml )
{
String verticalAlign = mergedStyle.getVerticalAlign( );
if ( !"baseline".equals( verticalAlign ) && height != null )
{
// implement vertical align.
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE, " width:100%; height:100%;" );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
StringBuffer textStyleBuffer = new StringBuffer( );
textStyleBuffer.append( " vertical-align:" );
textStyleBuffer.append( verticalAlign );
textStyleBuffer.append( ";" );
writer.attribute( HTMLTags.ATTR_STYLE, textStyleBuffer );
outputHtmlText(foreign);
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
else
{
outputHtmlText( foreign);
}
}
// writer.text( text, !isHtml, !isHtml );
writer.closeTag( tagName );
if ( enableMetadata )
{
writer.closeTag( selectHandleTag );
}
}
private void outputHtmlText(IForeignContent foreign)
{
Object rawValue = foreign.getRawValue( );
String text = rawValue == null ? null : rawValue.toString( );
Document doc = new TextParser( ).parse( text,
TextParser.TEXT_TYPE_HTML );
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
HTMLProcessor htmlProcessor = new HTMLProcessor( design );
HashMap styleMap = new HashMap( );
Element body = null;
if ( doc != null )
{
NodeList bodys = doc.getElementsByTagName( "body" );
if ( bodys.getLength( ) > 0 )
{
body = (Element) bodys.item( 0 );
}
}
if ( body != null )
{
htmlProcessor.execute( body, styleMap );
processNodes( body, styleMap );
}
}
/**
* Visits the children nodes of the specific node
*
* @param visitor
* the ITextNodeVisitor instance
* @param ele
* the specific node
*/
private void processNodes( Element ele, HashMap cssStyles )
{
for ( Node node = ele.getFirstChild( ); node != null; node = node
.getNextSibling( ) )
{
// At present we only deal with the text and element nodes
if ( node.getNodeType( ) == Node.TEXT_NODE
|| node.getNodeType( ) == Node.ELEMENT_NODE )
{
if ( !node.getNodeName( ).equals( "#text" ) )
{
startNode( node, cssStyles );
}
if ( node.getNodeType( ) == Node.TEXT_NODE )
{
// bug132213 in text item should only deal with the escape special characters: < > &
// old code: writer.text( node.getNodeValue( ), false, true );
writer.textForHtmlItem( node.getNodeValue( ) );
}
else
{
processNodes( (Element) node, cssStyles );
}
if ( !node.getNodeName( ).equals( "#text" ) )
{
endNode( node );
}
}
}
}
public void startNode( Node node, HashMap cssStyles )
{
String nodeName = node.getNodeName( );
HashMap cssStyle = (HashMap) cssStyles.get( node );
writer.openTag( nodeName );
NamedNodeMap attributes = node.getAttributes( );
if ( attributes != null )
{
for ( int i = 0; i < attributes.getLength( ); i++ )
{
Node attribute = attributes.item( i );
String attrName = attribute.getNodeName( );
String attrValue = attribute.getNodeValue( );
if ( attrValue != null )
{
if ( "img".equalsIgnoreCase( nodeName )
&& "src".equalsIgnoreCase( attrName ) )
{
String attrValueTrue = handleStyleImage( attrValue );
if ( attrValueTrue != null )
{
attrValue = attrValueTrue;
}
}
writer.attribute( attrName, attrValue );
}
}
}
if ( cssStyle != null )
{
StringBuffer buffer = new StringBuffer( );
Iterator ite = cssStyle.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
Object keyObj = entry.getKey( );
Object valueObj = entry.getValue( );
if ( keyObj == null || valueObj == null )
{
continue;
}
String key = keyObj.toString( );
String value = valueObj.toString( );
buffer.append( key );
buffer.append( ":" );
if ( "background-image".equalsIgnoreCase( key ) )
{
String valueTrue = handleStyleImage( value );
if ( valueTrue != null )
{
value = valueTrue;
}
buffer.append( "url(" );
buffer.append( value );
buffer.append( ")" );
}
else
{
buffer.append( value.replaceAll( " ", "" ) );
}
buffer.append( ";" );
}
if ( buffer.length( ) != 0 )
{
writer.attribute( "style", buffer.toString( ) );
}
}
}
public void endNode( Node node )
{
writer.closeTag( node.getNodeName( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startLabel(org.eclipse.birt.report.engine.content.ILabelContent)
*/
public void startLabel( ILabelContent label )
{
String bookmark = label.getBookmark( );
if ( bookmark == null )
{
bookmark = generateUniqueID( );
label.setBookmark( bookmark );
}
startText( label );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startData(org.eclipse.birt.report.engine.content.IDataContent)
*/
public void startData( IDataContent data )
{
startText( data );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startImage(org.eclipse.birt.report.engine.content.IImageContent)
*/
public void startImage( IImageContent image )
{
assert image != null;
IStyle mergedStyle = image.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLImageEmitter] Start image" ); //$NON-NLS-1$
Object generateBy = image.getGenerateBy( );
StringBuffer styleBuffer = new StringBuffer( );
int display = checkElementType( image.getX( ), image.getY( ),
mergedStyle, styleBuffer );
boolean isSelectHandleTableChart = false;
if ( enableMetadata )
{
if ( generateBy instanceof ExtendedItemDesign )
{
startSelectHandle( display, DISPLAY_BLOCK, "birt-chart-design" ); //$NON-NLS-1$
isSelectHandleTableChart = true;
// If the image is a chart, add it to active id list, and output type iid to html
String bookmark = image.getBookmark( );
if ( bookmark == null )
{
bookmark = generateUniqueID( );
image.setBookmark( bookmark );
}
setActiveIDTypeIID(image);
setBookmark( HTMLTags.ATTR_IMAGE, bookmark ); //$NON-NLS-1$
}
}
String tag = openTagByType( display, DISPLAY_BLOCK );
// action
boolean hasAction = handleAction( image.getHyperlinkAction( ) );
String imgUri = getImageURI( image );
boolean useSVG = (( image.getMIMEType( ) != null )
&& image.getMIMEType( ).equalsIgnoreCase( "image/svg+xml" )) //$NON-NLS-1$
|| (( image.getExtension( ) != null )
&& image.getExtension( ).equalsIgnoreCase( ".svg" )) //$NON-NLS-1$
|| (( image.getURI( ) != null )
&& image.getURI( ).toLowerCase( ).endsWith( ".svg" )); //$NON-NLS-1$
if ( useSVG )
{ // use svg
writer.openTag( HTMLTags.TAG_EMBED );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
// onresize gives the SVG a change to change its content
writer.attribute( "onresize", bookmark+".reload()"); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_TYPE, "image/svg+xml" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
setStyleName( image.getStyleClass( ) );
setDisplayProperty( display, 0, styleBuffer );
// build size
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, image
.getWidth( ) ); //$NON-NLS-1$
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, image
.getHeight( ) ); //$NON-NLS-1$
// handle inline style
handleStyle( image, styleBuffer, false );
writer.closeNoEndTag( );
}
else
{ // use img
// write image map if necessary
Object imageMapObject = image.getImageMap( );
// use imgUri as the image ID. As we know only the CHART can have
// image maps and each chart
// will have differnt URI, so it is safe for CHART. (If the named
// image also support image
// map, then we must use another way to get the image ID.
String imageMapId = imgUri;
boolean hasImageMap = ( imageMapObject != null )
&& ( imageMapObject instanceof String )
&& ( ( (String) imageMapObject ).length( ) > 0 );
if ( hasImageMap )
{
writer.openTag( HTMLTags.TAG_MAP );
writer.attribute( HTMLTags.ATTR_NAME, imageMapId );
writer.text( (String) imageMapObject, true, false );
writer.closeTag( HTMLTags.TAG_MAP );
}
writer.openTag( HTMLTags.TAG_IMAGE ); //$NON-NLS-1$
setStyleName( image.getStyleClass( ) );
setDisplayProperty( display, 0, styleBuffer );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
String ext = image.getExtension( );
// FIXME special process, such as encoding etc
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
if ( hasImageMap )
{
// BUGZILLA 119245 request chart (without hyperlink) can't have
// borders, the BROWSER add blue-solid border to the image with
// maps.
if ( !hasAction )
{
// disable the border, if the user defines border with the
// image, it will be overided by the following style setting
IStyle style = image.getStyle( );
if ( style.getBorderTopStyle( ) == null )
{
// user doesn't define the border, remove it.
styleBuffer.append( "border-top-style:none;" );
}
else
{
// use define the border-style, but not define the
// border color, use the default
// color.
if ( style.getBorderTopColor( ) == null )
{
styleBuffer.append( "border-top-color:black" );
}
}
if ( style.getBorderBottomStyle( ) == null )
{
styleBuffer.append( "border-bottom-style:none;" );
}
else
{
if ( style.getBorderBottomColor( ) == null )
{
styleBuffer.append( "border-bottom-color:black" );
}
}
if ( style.getBorderLeftStyle( ) == null )
{
styleBuffer.append( "border-left-style:none;" );
}
else
{
if ( style.getBorderLeftColor( ) == null )
{
styleBuffer.append( "border-left-color:black" );
}
}
if ( style.getBorderRightStyle( ) == null )
{
styleBuffer.append( "border-right-style:none;" );
}
else
{
if ( style.getBorderRightColor( ) == null )
{
styleBuffer.append( "border-right-color:black" );
}
}
}
writer.attribute( HTMLTags.ATTR_USEMAP, "#" + imageMapId ); //$NON-NLS-1$ //$NON-NLS-2$
}
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
// help text
writer.attribute( HTMLTags.ATTR_TITLE, image.getHelpText( ) );
// image size
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, image
.getWidth( ) ); //$NON-NLS-1$
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT,
image.getHeight( ) ); //$NON-NLS-1$
// handle style
handleStyle( image, styleBuffer, false );
if ( ".PNG".equalsIgnoreCase( ext ) && imageHandler != null ) //$NON-NLS-1$
{
writer.attribute( HTMLTags.ATTR_ONLOAD, "fixPNG(this)" ); //$NON-NLS-1$
}
writer.closeNoEndTag( );
}
if ( hasAction )
{
writer.closeTag( HTMLTags.TAG_A );
}
writer.closeTag( tag );
// include select handle chart
if ( enableMetadata )
{
if ( generateBy instanceof ExtendedItemDesign )
{
endSelectHandle( display, DISPLAY_BLOCK);
}
}
}
private void startSelectHandle( int display, int blockType, String cssClass )
{
writer.openTag( getTagByType( display, blockType ) );
writer.attribute( HTMLTags.ATTR_CLASS, cssClass );
}
private void endSelectHandle( int display, int blockType )
{
writer.closeTag( getTagByType( display, blockType ) );
}
/**
* gets the image's URI
*
* @param image
* the image content
* @return image's URI
*/
protected String getImageURI( IImageContent image )
{
String imgUri = null;
if ( imageHandler != null )
{
Image img = new Image( image );
img.setRenderOption( renderOption );
img.setReportRunnable( runnable );
switch ( img.getSource( ) )
{
case IImage.DESIGN_IMAGE :
imgUri = imageHandler.onDesignImage( img, renderContext );
break;
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( img, renderContext );
break;
case IImage.REPORTDOC_IMAGE :
imgUri = imageHandler.onDocImage( img, renderContext );
break;
case IImage.CUSTOM_IMAGE :
imgUri = imageHandler.onCustomImage( img, renderContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( img, renderContext );
break;
case IImage.INVALID_IMAGE :
break;
}
}
return imgUri;
}
/**
* Sets the <code>'class'</code> property and stores the style to styleMap
* object.
*
* @param styleName
* the style name
*/
protected void setStyleName( String styleName )
{
if ( isEmbeddable )
{
return;
}
if ( styleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, styleName );
}
}
/**
* Checks the 'CanShrink' property and sets the width and height according
* to the table below:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>CanShrink</th>
* <th align=left>Element Type</th>
* <th align=left>Width</th>
* <th align=left>Height</th>
* </tr>
* <tr valign=middle>
* <td rowspan="2"><code>true(by default)</code></td>
* <td>in-line</td>
* <td>ignor</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>ignor</td>
* </tr>
* <tr valign=middle>
* <td rowspan="2" bgcolor="#eeeeff"><code>false</code></td>
* <td>in-line</td>
* <td>replaced by 'min-width' property</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>replaced by 'min-height' property</td>
* </tr>
* </table>
*
* @param type
* The display type of the element.
* @param style
* The style of an element.
* @param height
* The height property.
* @param width
* The width property.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return A <code>boolean</code> value indicating 'Can-Shrink' property
* is set to <code>true</code> or not.
*/
protected boolean handleShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style == null
|| !"false".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & DISPLAY_BLOCK ) > 0 )
{
AttributeBuilder
.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & DISPLAY_INLINE ) > 0 )
{
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT,
height );
if ( !canShrink )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
/**
* Outputs the 'bookmark' property. Destination anchors in HTML documents
* may be specified either by the A element (naming it with the 'name'
* attribute), or by any other elements (naming with the 'id' attribute).
*
* @param tagName
* The tag's name.
* @param bookmark
* The bookmark value.
*/
protected void setBookmark( String tagName, String bookmark )
{
if ( tagName == null || !HTMLTags.TAG_A.equalsIgnoreCase( tagName ) )
{
writer.attribute( HTMLTags.ATTR_ID, bookmark );
}
else
{
writer.attribute( HTMLTags.ATTR_ID, bookmark );
writer.attribute( HTMLTags.ATTR_NAME, bookmark );
}
}
protected void outputBookmark( IContent content, String tagName )
{
String bookmark = content.getBookmark( );
setBookmark( tagName, bookmark );
String type = getActiveIdType( content );
InstanceID iid = content.getInstanceID( );
long componentID = ( iid != null ) ? iid.getComponentID( ) : 0;
exportElementID( bookmark, type, componentID);
}
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return The display type of the element.
*/
protected int checkElementType( DimensionType x, DimensionType y,
IStyle style, StringBuffer styleBuffer )
{
return checkElementType( x, y, null, null, style, styleBuffer );
}
protected int checkElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style,
StringBuffer styleBuffer )
{
int type = 0;
String display = null;
if ( style != null )
{
display = style.getDisplay( );
}
if ( EngineIRConstants.DISPLAY_NONE.equalsIgnoreCase( display ) )
{
type |= DISPLAY_NONE;
}
if ( x != null || y != null )
{
styleBuffer.append( "position: absolute;" ); //$NON-NLS-1$
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_LEFT, x );
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_LEFT, y );
return type | DISPLAY_BLOCK;
}
else if ( EngineIRConstants.DISPLAY_INLINE.equalsIgnoreCase( display ) )
{
type |= DISPLAY_INLINE;
if ( width != null || height != null )
{
type |= DISPLAY_INLINE_BLOCK;
}
return type;
}
return type | DISPLAY_BLOCK;
}
/**
* Open a tag according to the display type of the element. Here is the
* mapping table:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>Display Type</th>
* <th align=left>Tag name</th>
* </tr>
* <tr valign=middle>
* <td>DISPLAY_BLOCK</td>
* <td>DIV</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td>DISPLAY_INLINE</td>
* <td>SPAN</td>
* </tr>
* </table>
*
* @param display
* The display type.
* @param mask
* The mask value.
* @return Tag name.
*/
protected String openTagByType( int display, int mask )
{
String tag = getTagByType( display, mask );
if ( tag != null)
{
writer.openTag( tag );
}
return tag;
}
private String getTagByType( int display, int mask )
{
int flag = display & mask;
String tag = null;
if ( ( flag & DISPLAY_BLOCK ) > 0 )
{
tag = HTMLTags.TAG_DIV;
}
if ( ( flag & DISPLAY_INLINE ) > 0 )
{
tag = HTMLTags.TAG_SPAN;
}
return tag;
}
/**
* Set the display property to style.
*
* @param display
* The display type.
* @param mask
* The mask.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
*/
protected void setDisplayProperty( int display, int mask,
StringBuffer styleBuffer )
{
int flag = display & mask;
if ( ( display & DISPLAY_NONE ) > 0 )
{
styleBuffer.append( "display: none;" ); //$NON-NLS-1$
}
else if ( flag > 0 )
{
if ( ( flag & DISPLAY_BLOCK ) > 0 )
{
styleBuffer.append( "display: block;" ); //$NON-NLS-1$
}
else if ( ( flag & DISPLAY_INLINE_BLOCK ) > 0 )
{
styleBuffer.append( "display: inline-block;" ); //$NON-NLS-1$
}
else if ( ( flag & DISPLAY_INLINE ) > 0 )
{
styleBuffer.append( "display: inline;" ); //$NON-NLS-1$
}
}
}
/**
* Checks the Action object and then output corresponding tag and property.
*
* @param action
* The <code>IHyperlinkAction</code> object.
* @return A <code>boolean</code> value indicating whether the Action
* object is valid or not.
*/
protected boolean handleAction( IHyperlinkAction action )
{
String url = validate( action );
if ( url != null )
{
outputAction( action, url );
}
return url != null;
}
/**
* Outputs an hyperlink action.
*
* @param action
* the hyperlink action.
*/
protected void outputAction( IHyperlinkAction action, String url )
{
writer.openTag( HTMLTags.TAG_A );
writer.attribute( HTMLTags.ATTR_HREF, url );
writer.attribute( HTMLTags.ATTR_TARGET, action.getTargetWindow( ) );
}
/**
* Judges if a hyperlink is valid.
*
* @param action
* the hyperlink action
* @return
*/
private String validate( IHyperlinkAction action )
{
if ( action == null )
{
return null;
}
String systemId = runnable == null ? null : runnable.getReportName( );
Action act = new Action( systemId, action );
if ( actionHandler == null )
{
return null;
}
String link = actionHandler.getURL( act, renderContext );
if ( link != null && !link.equals( "" ) )//$NON-NLS-1$
{
return link;
}
return null;
}
/**
* handle style image
*
* @param uri
* uri in style image
* @return
*/
public String handleStyleImage( String uri )
{
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
URL url = design.findResource( uri, IResourceLocator.IMAGE );
if ( url == null )
{
return uri;
}
uri = url.toExternalForm( );
Image image = new Image( uri );
image.setReportRunnable( runnable );
image.setRenderOption( renderOption );
String imgUri = null;
if ( imageHandler != null )
{
switch ( image.getSource( ) )
{
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( image, renderContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( image, renderContext );
break;
case IImage.INVALID_IMAGE :
break;
default :
assert ( false );
}
// imgUri = imgUri.replace( File.separatorChar, '/' );
}
return imgUri;
}
/**
* Handles the style of the styled element content
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleStyle( IContent element, StringBuffer styleBuffer,
boolean bContainer )
{
IStyle style;
if ( isEmbeddable )
{
style = element.getStyle( );
}
else
{
style = element.getInlineStyle( );
}
AttributeBuilder.buildStyle( styleBuffer, style, this, bContainer );
if ( !bContainer )
{
AttributeBuilder.buildComputedTextStyle( styleBuffer, element.getComputedStyle( ),this , bContainer );
}
// output in-line style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
protected void handleStyle( IContent element, StringBuffer styleBuffer )
{
IStyle style;
if ( isEmbeddable )
{
style = element.getStyle( );
}
else
{
style = element.getInlineStyle( );
}
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
// output in-line style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
/**
* Handles the Vertical-Align property of the element content
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleVerticalAlign( ICellContent element,
StringBuffer styleBuffer )
{
IStyle style = element.getComputedStyle( );
String verticalAlign = style.getVerticalAlign( );
if ( verticalAlign == null || verticalAlign.equals( "baseline" ) )
{
verticalAlign = "top";
}
if ( verticalAlign != null )
{
styleBuffer.append( "vertical-align: " );
styleBuffer.append( verticalAlign );
styleBuffer.append( ";" );
}
}
/**
* Handles the font-weight property of the cell content
* while the cell is in table header
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleCellFont( ICellContent element,
StringBuffer styleBuffer )
{
IStyle style = element.getInlineStyle( );
String fontWeight = style.getFontWeight( );
if ( fontWeight == null )
{
style = element.getComputedStyle( );
fontWeight = style.getFontWeight( );
if ( fontWeight == null )
{
fontWeight = "normal";
}
styleBuffer.append( "font-weight: " );
styleBuffer.append( fontWeight );
styleBuffer.append( ";" );
}
}
/**
* adds the default table styles
*
* @param styleBuffer
*/
protected void addDefaultTableStyles( StringBuffer styleBuffer )
{
styleBuffer
.append( "border-collapse: collapse; empty-cells: show;" ); //$NON-NLS-1$
}
protected void exportElementID( String bookmark,
String type, long componentID )
{
if ( ouputInstanceIDs != null )
{
if ( bookmark != null )
{
assert type != null;
String newBookmark = bookmark + "," + type + ","
+ new Long( componentID ).toString( );
ouputInstanceIDs.add( newBookmark );
}
}
}
protected int bookmarkId = 0;
protected String generateUniqueID( )
{
bookmarkId ++;
return "AUTOGENBOOKMARK_" + bookmarkId;
}
/**
* Add element to active ID list. Output type & iid to html.
*
* @param content
* the styled element content
*/
private void setActiveIDTypeIID( IContent content )
{
// If content is generated by LabelItemDesign or TemplateDesign,
// ExtendedItemDesign, TableItemDesign
// add it to active id list, and output type & iid to html
String type = getActiveIdType( content );
if (type != null)
{
// Instance ID
InstanceID iid = content.getInstanceID( );
long componentID = ( iid != null ) ? iid.getComponentID( ) : 0;
setActiveIDTypeIID( content.getBookmark( ), type, iid, componentID );
}
}
private String getActiveIdType( IContent content )
{
Object genBy = content.getGenerateBy( );
String type = null;
if (genBy instanceof LabelItemDesign)
{
type = "LABEL";
}
else if (genBy instanceof TemplateDesign)
{
type = "TEMPLATE";
}
else if( genBy instanceof ExtendedItemDesign )
{
type = "EXTENDED" ;
}
else if ( genBy instanceof TableItemDesign )
{
type = "TABLE";
}
else if (genBy instanceof ListItemDesign)
{
type = "LIST";
}
else if ( genBy instanceof TextItemDesign )
{
type = "TEXT";
}
return type;
}
private void setActiveIDTypeIID( String bookmark, String type,
InstanceID iid, long elementId )
{
exportElementID( bookmark, type, elementId );
// type
writer.attribute( "element_type", type );
if ( iid != null )
{
writer.attribute( "iid", iid.toString( ) );
}
}
/**
* Resize chart template and table template element.
*
* @param content
* the styled element content
*/
private void resizeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "ExtendedItem".equals(allowedType ) )
{
// Resize chart template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 3, DimensionType.UNITS_IN ) );
content.setHeight( new DimensionType( 3, DimensionType.UNITS_IN ) );
}
else if ( "Table".equals(allowedType) )
{
// Resize table template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 5, DimensionType.UNITS_IN ) );
}
}
}
/**
* judge the content is belong table template element or not.
*
* @param content
* the styled element content
*/
private boolean isTalbeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "Table".equals(allowedType) )
{
return true;
}
}
return false;
}
private boolean needColumnFilter( ICellContent cell )
{
DetailRowState state = ( DetailRowState ) detailRowStateStack.peek( );
if ( cell.getColumnInstance( ) == null )
{
return false;
}
return state.isStartOfDetail
&& cell.getColumnInstance( ).hasDataItemsInDetail( )
&& displayFilterIcon
&& HTMLUtil.getFilterConditions( cell ).size( ) > 0 ;
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void endGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void endListBand( IListBandContent listBand )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void endListGroup( IListGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void endTableGroup( ITableGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void startGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void startListBand( IListBandContent listBand )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void startListGroup( IListGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void startTableGroup( ITableGroupContent group )
{
}
}
class DetailRowState
{
public DetailRowState( boolean isStartOfDetail, boolean hasOutput,
boolean isTable )
{
this.isStartOfDetail = isStartOfDetail;
this.hasOutput = hasOutput;
this.isTable = isTable;
}
public boolean isStartOfDetail;
public boolean hasOutput;
public boolean isTable;
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 472. Concatenated Words
*
* Given a list of words, please write a program that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example:
Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Note:
The number of elements of the given array will not exceed 10,000
The length sum of elements in the given array will not exceed 600,000.
All the input string will only include lower case letters.
The returned elements order does not matter.
*/
public class _472 {
public static class Solution1 {
private TrieNode root;
private int maxWordLen;
public List<String> findAllConcatenatedWordsInADict(String[] words) {
ResultType result = buildTrie(words);
root = result.root;
maxWordLen = result.maxWordLen;
List<String> validConcatenatedWords = new ArrayList();
for (String word : words) {
if (word == null || word.length() == 0) {
continue;
}
remove(word, root);/** every word is comprised of every word itself, thus this word itself needs to be removed first for checking it*/
int n = word.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i && j <= maxWordLen; j++) {
if (!dp[i - j]) {
continue;
}
String subWord = word.substring(i - j, i);
if (contains(subWord, root)) {
dp[i] = true;
break;
}
}
}
if (dp[n]) {
validConcatenatedWords.add(word);
}
undoRemove(word, root);
}
return validConcatenatedWords;
}
public ResultType buildTrie(String[] words) {
ResultType result = new ResultType();
TrieNode root = new TrieNode();
int maxWordLen = 0;
for (String word : words) {
maxWordLen = Math.max(maxWordLen, word.length());
char[] chars = word.toCharArray();
TrieNode node = root;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isWord = true;
}
result.root = root;
result.maxWordLen = maxWordLen;
return result;
}
public class ResultType {
int maxWordLen;
TrieNode root;
}
// Returns true if the word is in the trie.
public boolean contains(String word, TrieNode root) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
if (node.children[word.charAt(i) - 'a'] == null) {
return false;
}
node = node.children[word.charAt(i) - 'a'];
}
return node.isWord;
}
// mark that word on
public void undoRemove(String word, TrieNode root) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
node = node.children[word.charAt(i) - 'a'];
}
node.isWord = true;
}
// mark that word off, we are not really deleting that word
public void remove(String word, TrieNode root) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
node = node.children[word.charAt(i) - 'a'];
}
node.isWord = false;
}
class TrieNode {
boolean isWord;
TrieNode[] children = new TrieNode[26];
public TrieNode() {
}
}
}
public static class Solution2 {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
List<String> result = new ArrayList<>();
Set<String> preWords = new HashSet<>();
/**Words could only be formed by other words that are shorter than itself, so we sort them based on their lengths first.*/
Arrays.sort(words, (s1, s2) -> s1.length() - s2.length());
for (int i = 0; i < words.length; i++) {
if (canForm(words[i], preWords)) {
result.add(words[i]);
}
preWords.add(words[i]);
}
return result;
}
boolean canForm(String word, Set<String> dict) {
if (dict.isEmpty()) {
return false;
}
boolean[] dp = new boolean[word.length() + 1];
dp[0] = true;
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.contains(word.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[word.length()];
}
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 637. Average of Levels in Binary Tree
*
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node's value is in the range of 32-bit signed integer.
*/
public class _637 {
public static class Solution1 {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
double sum = 0.0;
for (int i = 0; i < size; i++) {
TreeNode curr = queue.poll();
if (curr != null) {
sum += curr.val;
}
if (curr.left != null) {
queue.offer(curr.left);
}
if (curr.right != null) {
queue.offer(curr.right);
}
}
result.add(sum / size);
}
return result;
}
}
}
|
package com.fionapet.business.service;
import com.fionapet.business.entity.ItemCate;
import com.fionapet.business.entity.ItemType;
import com.fionapet.business.repository.ItemCateDao;
import com.fionapet.business.repository.ItemTypeDao;
import com.google.common.collect.ImmutableMap;
import org.dubbo.x.repository.DaoBase;
import org.dubbo.x.service.CURDServiceBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Transactional
public class ItemCateServiceImpl extends CURDServiceBase<ItemCate> implements ItemCateService {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemCateServiceImpl.class);
@Autowired
private ItemCateDao itemCateDao;
@Autowired
private ItemTypeDao itemTypeDao;
@Override
public DaoBase<ItemCate> getDao() {
return itemCateDao;
}
@Override
public Map<String, Collection> selects(Map<String, String> params) {
LOGGER.debug("selects params:{}", params);
Map<String, String> paramKeyToValue = new HashMap<String, String>();
for (Map.Entry<String, String> param:params.entrySet()){
paramKeyToValue.put(param.getValue(), param.getKey());
}
List<ItemCate> dictTypes = itemCateDao.findByCateNameIn(paramKeyToValue.keySet());
Map<String, Collection> result = new HashMap<String, Collection>();
for (ItemCate dictType: dictTypes){
result.put(paramKeyToValue.get(dictType.getCateName()), itemTypeDao.findByCateNo(dictType.getId()));
}
return result;
}
}
|
package com.fishercoder.solutions;
import java.util.LinkedList;
import java.util.Queue;
public class _649 {
public static class Solution1 {
public String predictPartyVictory(String senate) {
Queue<Integer> radiantQ = new LinkedList<>();
Queue<Integer> direQ = new LinkedList<>();
int len = senate.length();
for (int i = 0; i < len; i++) {
if (senate.charAt(i) == 'R') {
radiantQ.offer(i);
} else {
direQ.offer(i);
}
}
while (!radiantQ.isEmpty() && !direQ.isEmpty()) {
int radiantIndex = radiantQ.poll();
int direIndex = direQ.poll();
if (radiantIndex < direIndex) {
/**Radiant will ban Dire in this case, so we'll add radiant index back to the queue plus n*/
radiantQ.offer(radiantIndex + len);
} else {
direQ.offer(direIndex + len);
}
}
return radiantQ.isEmpty() ? "Dire" : "Radiant";
}
}
}
|
package javaUtilities;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
/**
* A reentrant read-write lock allowing at most one designated upgradable thread
* that can switch between reading and writing. Other readers can acquire the
* lock while the thread with the upgradable lock is downgraded. The upgradable
* thread blocks while upgrading if other threads hold read locks.
* <p>
* A thread can initially acquire the lock in any of three modes: read,
* upgradable, and write. A thread acquiring an upgradable lock starts in the
* downgraded state. All locks and unlocks are nested. This means that a thread
* cannot acquire a write lock, then a read lock, and then release the write
* lock without releasing the read lock. Calls to downgrade must be matched by
* calls to upgrade. Calls to upgrade and downgrade can be interleaved with
* calls to lock and unlock in any order, as long as the thread has an
* upgradable or write lock when upgrading or downgrading. A thread with only a
* read lock cannot acquire an upgradable or write lock. Any thread with an
* upgradable or write lock can acquire the lock again in any of the three
* modes. Acquiring a read lock after an upgradable or write lock has no effect,
* though it still must be released.
* <p>
* This class allows {@linkplain Condition condition} waits for threads that
* hold write locks or have upgraded.
* <p>
* This lock allows a running thread to acquire the lock without waiting in the
* queue, unless the thread is acquiring a read lock, and it detects a thread
* waiting to upgrade or acquire a write lock at the front of the queue.
* <p>
* This class is {@linkplain Serializable serializable}. It is always
* deserialized in the fully unlocked state.
*/
public final class UpgradableLock implements Serializable {
/*
* This class stores each thread's lock holds in a thread local variable. It
* uses a subclass of AbstractQueuedSynchronizer (mySync) to manage the queue
* and store the number of threads with each type of lock hold. For every call
* to a public method, this class first uses the thread local state to
* determine whether the state of mySync must change. Then it delegates to
* mySync and updates the thread local state on success.
*/
private static final long serialVersionUID = 0L;
private static final long MIN_TIMEOUT = -1L;
private static final long NO_WAIT = -2L;
private static final long NO_TIMEOUT = -3L;
private final Sync mySync = new Sync();
private final ThreadLocal<ThreadState> myThreadState = new ThreadLocal<ThreadState>() {
@Override
protected ThreadState initialValue() {
return ThreadState.newState();
}
};
/**
* The modes used to acquire the lock.
*/
public static enum Mode {
READ,
UPGRADABLE,
WRITE
}
/**
* Thrown when a thread attempts to acquire or upgrade the lock when the lock
* already has the maximum number of holds.
*/
public static final class TooManyHoldsException extends RuntimeException {
private static final long serialVersionUID = 0L;
TooManyHoldsException(String aMessage) {
super(aMessage);
}
}
/**
* Lock state that applies to the current thread. It stores the numbers
* and types of holds that the thread currently has.
*/
private static final class ThreadState {
private static final int NO_WRITE_HOLDS = -1;
private static final ThreadState NEW = new ThreadState(FirstHold.NONE, 0, 0, NO_WRITE_HOLDS);
private final FirstHold myFirstHold;
private final int myUpgradeCount;
private final int myHoldCount;
private final int myFirstWriteHold;
private static enum FirstHold {
NONE,
READ,
UPGRADABLE,
WRITE;
}
static ThreadState newState() {
// reuse instance for efficiency
return NEW;
}
private ThreadState(FirstHold aFirstHold, int aUpgrades, int aHolds, int aFirstWrite) {
myFirstHold = aFirstHold;
myUpgradeCount = aUpgrades;
myHoldCount = aHolds;
myFirstWriteHold = aFirstWrite;
}
Mode getFirstHold() {
switch (myFirstHold) {
case NONE: throw new IllegalArgumentException("No hold yet");
case READ: return Mode.READ;
case UPGRADABLE: return Mode.UPGRADABLE;
case WRITE: return Mode.WRITE;
default: throw new AssertionError();
}
}
boolean acquiredReadFirst() {
return myFirstHold == FirstHold.READ;
}
boolean isUnlocked() {
return myHoldCount == 0;
}
/**
* Returns {@code true} if the thread holds only a read lock or a downgraded
* upgradable lock.
*/
boolean canWrite() {
return myFirstHold == FirstHold.WRITE ||
myFirstHold == FirstHold.UPGRADABLE &&
(myUpgradeCount > 0 || myFirstWriteHold != NO_WRITE_HOLDS);
}
boolean isDowngraded() {
return myUpgradeCount == 0;
}
ThreadState incrementWrite() {
FirstHold mFirst = myFirstHold == FirstHold.NONE ? FirstHold.WRITE : myFirstHold;
int mNewHolds = incrementHolds();
int mFirstWrite = (myFirstWriteHold == NO_WRITE_HOLDS) ? mNewHolds : myFirstWriteHold;
return new ThreadState(mFirst, myUpgradeCount, mNewHolds, mFirstWrite);
}
ThreadState incrementUpgradable() {
FirstHold mFirst = myFirstHold == FirstHold.NONE ? FirstHold.UPGRADABLE : myFirstHold;
int mNewHolds = incrementHolds();
return new ThreadState(mFirst, myUpgradeCount, mNewHolds, myFirstWriteHold);
}
ThreadState incrementRead() {
FirstHold mFirst = myFirstHold == FirstHold.NONE ? FirstHold.READ : myFirstHold;
int mNewHolds = incrementHolds();
return new ThreadState(mFirst, myUpgradeCount, mNewHolds, myFirstWriteHold);
}
ThreadState decrementHolds() {
int mFirstWrite = (myFirstWriteHold == myHoldCount) ? NO_WRITE_HOLDS : myFirstWriteHold;
int mNewHolds = myHoldCount - 1;
return new ThreadState(myFirstHold, myUpgradeCount, mNewHolds, mFirstWrite);
}
ThreadState upgrade() {
if (myUpgradeCount == Integer.MAX_VALUE) {
throw new TooManyHoldsException("Too many upgrades");
}
return new ThreadState(myFirstHold, myUpgradeCount + 1, myHoldCount, myFirstWriteHold);
}
ThreadState downgrade() {
return new ThreadState(myFirstHold, myUpgradeCount - 1, myHoldCount, myFirstWriteHold);
}
private int incrementHolds() {
if (myHoldCount == Integer.MAX_VALUE) {
throw new TooManyHoldsException("Too many holds");
}
return myHoldCount + 1;
}
}
private static final class Sync extends AbstractQueuedSynchronizer {
/*
* This class uses its int state to maintain 3 counts:
*
* - threads with read locks
* - threads with downgraded upgradable locks
* - threads with write/upgraded locks
*
* It does not keep track of the number of holds per thread or which holds
* allow downgrading. The lowest bit stores the number of writer threads,
* the next bit stores the number of downgraded threads, and the rest of
* the state stores the number of reader threads.
*/
private static final int MAX_READ_HOLDS = Integer.MAX_VALUE >>> 2;
/* Arguments passed to methods of AbstractQueuedSynchronizer
*
* The value for acquiring and releasing a write lock must equal the lock
* state before releasing a write lock for conditions to work. All other
* constants should be different from allowed lock states to distinguish
* between releases caused by condition waits and other releases.
*/
private static final int WRITE_ARG = calcState(true, false, 0);
private static final int UPGRADABLE_ARG = calcState(true, true, 1);
private static final int READ_ARG = calcState(true, true, 2);
private static final int UPGRADE_DOWNGRADE_ARG = calcState(true, true, 3);
boolean lock(Mode aMode, boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
switch (aMode) {
case WRITE: return acquire(WRITE_ARG, aInterruptible, aTime, aUnit);
case UPGRADABLE: return acquireShared(UPGRADABLE_ARG, aInterruptible, aTime, aUnit);
case READ: return acquireShared(READ_ARG, aInterruptible, aTime, aUnit);
default: throw new AssertionError();
}
}
boolean upgrade(boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
return acquire(UPGRADE_DOWNGRADE_ARG, aInterruptible, aTime, aUnit);
}
private boolean acquire(int aArg, boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
if (aTime == NO_WAIT) {
return tryAcquire(aArg);
} else if (aTime == NO_TIMEOUT) {
if (aInterruptible) {
acquireInterruptibly(aArg);
} else acquire(aArg);
return true;
} else return tryAcquireNanos(aArg, aUnit.toNanos(aTime));
}
private boolean acquireShared(int aArg, boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
if (aTime == NO_WAIT) {
return tryAcquireShared(aArg) >= 0;
} else if (aTime == NO_TIMEOUT) {
if (aInterruptible) {
acquireSharedInterruptibly(aArg);
} else acquireShared(aArg);
return true;
} else return tryAcquireSharedNanos(aArg, aUnit.toNanos(aTime));
}
void unlock(Mode aMode) {
switch (aMode) {
case WRITE: release(WRITE_ARG); return;
case UPGRADABLE: releaseShared(UPGRADABLE_ARG); return;
case READ: releaseShared(READ_ARG); return;
default: throw new AssertionError();
}
}
void downgrade() {
release(UPGRADE_DOWNGRADE_ARG);
}
@Override
protected boolean tryAcquire(int aArg) {
assert aArg == UPGRADE_DOWNGRADE_ARG || aArg == WRITE_ARG;
int mState = getState();
if (hasWriteHold(mState) || getReadHolds(mState) > 0) return false;
boolean mIsUpgrade = aArg == UPGRADE_DOWNGRADE_ARG;
if (!mIsUpgrade && hasUpgradableHold(mState)) return false;
int mNewState = calcState(true, false, 0);
if (compareAndSetState(mState, mNewState)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int aArg) {
if (!isHeldExclusively()) return false;
assert aArg == UPGRADE_DOWNGRADE_ARG || aArg == WRITE_ARG;
setExclusiveOwnerThread(null);
boolean mIsDowngrade = aArg == UPGRADE_DOWNGRADE_ARG;
int mNewState = calcState(false, mIsDowngrade, 0);
setState(mNewState);
return true;
}
@Override
protected int tryAcquireShared(int aArg) {
assert aArg == READ_ARG || aArg == UPGRADABLE_ARG;
// prevent writer threads from starving
if (isFirstQueuedThreadExclusive()) return -1;
int mState = getState();
if (hasWriteHold(mState)) return -1;
boolean mIsUpgradable = aArg == UPGRADABLE_ARG;
int mNewState;
if (mIsUpgradable) {
if (hasUpgradableHold(mState)) return -1;
mNewState = setUpgradableHold(mState, true);
} else {
int mReadHolds = getReadHolds(mState);
if (mReadHolds == MAX_READ_HOLDS) throw new TooManyHoldsException("Too many holds");
mNewState = setReadHolds(mState, mReadHolds + 1);
}
return compareAndSetState(mState, mNewState) ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(int aArg) {
assert aArg == READ_ARG || aArg == UPGRADABLE_ARG;
int mState, mNewState;
do {
mState = getState();
boolean mIsUpgradable = aArg == UPGRADABLE_ARG;
if (mIsUpgradable) {
mNewState = setUpgradableHold(mState, false);
} else {
int mReadHolds = getReadHolds(mState);
mNewState = setReadHolds(mState, mReadHolds - 1);
}
} while (!compareAndSetState(mState, mNewState));
return true;
}
@Override
protected boolean isHeldExclusively() {
return Thread.currentThread().equals(getExclusiveOwnerThread());
}
private static boolean hasWriteHold(int aState) {
return (aState & 1) != 0;
}
private static boolean hasUpgradableHold(int aState) {
return (aState & 2) != 0;
}
private static int getReadHolds(int aState) {
return aState >>> 2;
}
private static int setUpgradableHold(int aState, boolean aUpgradable) {
return setBit(aState, 1, aUpgradable);
}
private static int setBit(int aValue, int aIndex, boolean aOn) {
return aOn ? aValue | (1 << aIndex) : aValue & ~(1 << aIndex);
}
private static int setReadHolds(int aState, int aReadHolds) {
return aReadHolds << 2 | aState & 3;
}
private static int calcState(boolean aWrite, boolean aUpgradable, int aRead) {
int mState = aRead << 2;
if (aUpgradable) mState |= 2;
if (aWrite) mState |= 1;
return mState;
}
private boolean isFirstQueuedThreadExclusive() {
Thread mFirst = getFirstQueuedThread();
return getExclusiveQueuedThreads().contains(mFirst);
}
@Override
public String toString() {
int mState = getState();
String mMessage;
if (hasWriteHold(mState)) {
mMessage = "1 write/upgraded thread";
} else {
boolean mUpgradableHold = hasUpgradableHold(mState);
int mReadHolds = getReadHolds(mState);
if (mReadHolds == 0 && !mUpgradableHold) mMessage = "unlocked";
else {
mMessage = "";
if (mUpgradableHold) mMessage += "1 downgraded thread";
if (mReadHolds > 0) {
if (mUpgradableHold) mMessage += ", ";
mMessage += mReadHolds + " read thread";
if (mReadHolds > 1) mMessage += "s";
}
}
}
return "[" + mMessage + "]";
}
}
public void lock(Mode aMode) {
try {
lockInternal(aMode, false, NO_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
/**
* Acquires the lock while allowing
* {@linkplain Thread#interrupt interruption}.
*
* @see UpgradableLock#lock(Mode)
* @throws InterruptedException
* if the thread is interrupted before or while waiting for the lock.
*/
public void lockInterruptibly(Mode aMode) throws InterruptedException {
lockInternal(aMode, true, NO_TIMEOUT, TimeUnit.SECONDS);
}
/**
* Acquires the lock only if it is currently
* available and returns {@code true} if it succeeds.
*
* @see UpgradableLock#lock(Mode)
*/
public boolean tryLock(Mode aMode) {
try {
return lockInternal(aMode, false, NO_WAIT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
/**
* Tries to acquire the lock within the given time limit and returns
* {@code true} if it succeeds.
*
* @see UpgradableLock#lock(Mode)
* @throws InterruptedException
* if the thread is interrupted before or while waiting for the lock.
*/
public boolean tryLock(Mode aMode, long aTime, TimeUnit aUnit) throws InterruptedException {
long mTime = boundTimeout(aTime);
return lockInternal(aMode, true, mTime, aUnit);
}
public void unlock() {
ThreadState mOld = myThreadState.get();
if (mOld.isUnlocked()) {
throw new IllegalMonitorStateException("Cannot unlock lock that was not held");
}
boolean mWasWrite = mOld.canWrite();
ThreadState mNew = mOld.decrementHolds();
if (mNew.isUnlocked()) {
Mode mToRelease = mWasWrite ? Mode.WRITE : mOld.getFirstHold();
mySync.unlock(mToRelease);
myThreadState.remove();
return;
} else if (mWasWrite && !mNew.canWrite()) {
mySync.downgrade();
}
myThreadState.set(mNew);
}
public void upgrade() {
try {
upgradeInternal(false, NO_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
/**
* Upgrades the thread's hold on the lock while allowing
* {@linkplain Thread#interrupt interruption}.
* @see UpgradableLock#upgrade()
* @throws InterruptedException
* if the thread is interrupted before or while waiting to upgrade.
*/
public void upgradeInterruptibly() throws InterruptedException {
upgradeInternal(true, NO_TIMEOUT, TimeUnit.SECONDS);
}
/**
* Upgrades the thread's hold on the lock only if there are no current readers
* and returns {@code true} if it succeeds.
* @see UpgradableLock#upgrade()
*/
public boolean tryUpgrade() {
try {
return upgradeInternal(false, NO_WAIT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
/**
* Tries to upgrade the thread's hold on the lock for the given amount of time
* and returns {@code true} if it succeeds.
*
* @see UpgradableLock#upgrade()
* @throws InterruptedException
* if the thread is interrupted before or while waiting to upgrade.
*/
public boolean tryUpgrade(long aTime, TimeUnit aUnit) throws InterruptedException {
long mTime = boundTimeout(aTime);
return upgradeInternal(true, mTime, aUnit);
}
public void downgrade() {
ThreadState mOld = myThreadState.get();
if (mOld.isUnlocked()) {
throw new IllegalMonitorStateException("Cannot downgrade without lock");
}
if (mOld.acquiredReadFirst()) {
throw new IllegalMonitorStateException("Cannot upgrade or downgrade from read");
}
if (mOld.isDowngraded()) {
throw new IllegalMonitorStateException("Cannot downgrade without upgrade");
}
ThreadState mNew = mOld.downgrade();
if (!mNew.canWrite()) {
mySync.downgrade();
}
myThreadState.set(mNew);
}
/**
* Returns a new {@link Condition} object which can be used for waiting and
* notifying other threads. {@linkplain Condition#await() await()} and
* {@linkplain Condition#signal() signal()} can only be called by a thread
* holding the lock associated with the condition in write or upgraded mode.
*/
public Condition newCondition() {
return mySync.new ConditionObject();
}
private boolean lockInternal(Mode aMode, boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
switch (aMode) {
case READ: return readLockInternal(aInterruptible, aTime, aUnit);
case UPGRADABLE: return upgradableLockInternal(aInterruptible, aTime, aUnit);
case WRITE: return writeLockInternal(aInterruptible, aTime, aUnit);
default: throw new AssertionError();
}
}
private boolean readLockInternal(boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
ThreadState mOld = myThreadState.get();
ThreadState mNew = mOld.incrementRead();
if (mOld.isUnlocked()) {
if (!mySync.lock(Mode.READ, aInterruptible, aTime, aUnit)) return false;
}
myThreadState.set(mNew);
return true;
}
private boolean writeLockInternal(boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
ThreadState mOld = myThreadState.get();
if (mOld.acquiredReadFirst()) {
throw new IllegalMonitorStateException("Cannot upgrade from read");
}
ThreadState mNew = mOld.incrementWrite();
if (mOld.isUnlocked()) {
if (!mySync.lock(Mode.WRITE, aInterruptible, aTime, aUnit)) return false;
} else if (!mOld.canWrite()) {
if (!mySync.upgrade(aInterruptible, aTime, aUnit)) return false;
}
myThreadState.set(mNew);
return true;
}
private boolean upgradableLockInternal(boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
ThreadState mOld = myThreadState.get();
if (mOld.acquiredReadFirst()) {
throw new IllegalMonitorStateException("Cannot upgrade from read");
}
ThreadState mNew = mOld.incrementUpgradable();
if (mOld.isUnlocked()) {
if (!mySync.lock(Mode.UPGRADABLE, aInterruptible, aTime, aUnit)) return false;
}
myThreadState.set(mNew);
return true;
}
private boolean upgradeInternal(boolean aInterruptible, long aTime, TimeUnit aUnit) throws InterruptedException {
ThreadState mOld = myThreadState.get();
if (mOld.isUnlocked()) {
throw new IllegalMonitorStateException("Cannot upgrade without lock");
}
if (mOld.acquiredReadFirst()) {
throw new IllegalMonitorStateException("Cannot upgrade from read");
}
ThreadState mNew = mOld.upgrade();
if (!mOld.canWrite()) {
if (!mySync.upgrade(aInterruptible, aTime, aUnit)) return false;
}
myThreadState.set(mNew);
return true;
}
private static long boundTimeout(long aTime) {
return aTime < 0 ? MIN_TIMEOUT : aTime;
}
@Override
public String toString() {
return "UpgradableLock" + mySync.toString();
}
private Object writeReplace() {
return new SerializationProxy();
}
private void readObject(ObjectInputStream aOis) throws InvalidObjectException {
throw new InvalidObjectException("Expecting serialization proxy");
}
/*
* A new upgradable lock must be created after deserialization to allow all
* fields to be final while avoiding serializing the thread local state. A
* serialization proxy makes this easier.
*/
private static final class SerializationProxy implements Serializable {
private static final long serialVersionUID = 0L;
private Object readResolve() {
return new UpgradableLock();
}
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class _890 {
public static class Solution1 {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
for (String word : words) {
Map<Character, Character> map = new HashMap<>();
Set<Character> set = new HashSet<>();
boolean match = true;
for (int i = 0; i < pattern.length(); i++) {
if (map.containsKey(pattern.charAt(i))) {
if (word.charAt(i) != map.get(pattern.charAt(i))) {
match = false;
break;
}
} else {
map.put(pattern.charAt(i), word.charAt(i));
if (!set.add(word.charAt(i))) {
match = false;
}
}
}
if (match) {
result.add(word);
}
}
return result;
}
}
public static class Solution2 {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
for (String word : words) {
if (matches(word, pattern)) {
result.add(word);
}
}
return result;
}
private boolean matches(String word, String pattern) {
Map<Character, Character> map1 = new HashMap<>();//word -> p
Map<Character, Character> map2 = new HashMap<>();//p -> word
for (int i = 0; i < pattern.length(); i++) {
if (!map1.containsKey(word.charAt(i))) {
map1.put(word.charAt(i), pattern.charAt(i));
}
if (map1.containsKey(word.charAt(i)) && map1.get(word.charAt(i)) != pattern.charAt(i)) {
return false;
}
if (!map2.containsKey(pattern.charAt(i))) {
map2.put(pattern.charAt(i), word.charAt(i));
}
if (map2.containsKey(pattern.charAt(i)) && map2.get(pattern.charAt(i)) != word.charAt(i)) {
return false;
}
}
return true;
}
}
}
|
package com.github.enanomapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.formats.RDFXMLDocumentFormat;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.AddOntologyAnnotation;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDeclarationAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.RemoveImport;
import org.semanticweb.owlapi.model.SetOntologyID;
import org.semanticweb.owlapi.search.EntitySearcher;
import org.semanticweb.owlapi.search.Searcher;
import org.semanticweb.owlapi.util.OWLEntityRemover;
import org.semanticweb.owlapi.util.OWLOntologyMerger;
import org.semanticweb.owlapi.util.SimpleIRIMapper;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
public class Slimmer {
private OWLOntologyManager man;
private OWLOntology onto;
public Slimmer(File owlFile, String mergedOntologyIRI) throws OWLOntologyCreationException, FileNotFoundException {
this(new FileInputStream(owlFile), mergedOntologyIRI);
}
public Slimmer(InputStream owlFile) throws OWLOntologyCreationException {
this(owlFile, null);
}
public Slimmer(InputStream owlFile, String mergedOntologyIRI) throws OWLOntologyCreationException {
man = OWLManager.createOWLOntologyManager();
if (System.getenv("WORKSPACE") != null) {
String root = System.getenv("WORKSPACE");
System.out.println("Adding mappings with root: " + root);
addMappings(man, root);
}
onto = man.loadOntologyFromOntologyDocument(owlFile);
if (mergedOntologyIRI != null) {
Set<OWLImportsDeclaration> importDeclarations = onto.getImportsDeclarations();
for (OWLImportsDeclaration declaration : importDeclarations) {
try {
man.loadOntology(declaration.getIRI());
System.out.println("Loaded imported ontology: " + declaration.getIRI());
} catch (Exception exception) {
System.out.println("Failed to load imported ontology: " + declaration.getIRI());
}
}
// Merge all of the loaded ontologies, specifying an IRI for the new ontology
OWLOntologyMerger merger = new OWLOntologyMerger(man);
onto = merger.createMergedOntology(man, IRI.create(mergedOntologyIRI));
for (OWLOntology ontology : man.getOntologies()) {
System.out.println(" Copying annotations from " + ontology.getOntologyID());
for (OWLAnnotation annotation : ontology.getAnnotations()) {
System.out.println(" copying annotation: " + annotation.getProperty() + " -> " + annotation.getValue());
AddOntologyAnnotation annotationAdd = new AddOntologyAnnotation(onto, annotation);
man.applyChange(annotationAdd);
}
}
}
}
public OWLOntology getOntology() {
return this.onto;
}
public static void main(String[] args) {
boolean allSucceeded = true;
String rootFolder = args[0];
System.out.println("Searching configuration files in " + rootFolder);
File dir = new File(rootFolder);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".props");
}
});
for (File file : files) {
try {
System.out.println("Slimming for " + file.getName());
// read the information about the ontology to process
Properties props = new Properties();
props.load(new FileReader(file));
String owlURL = props.getProperty("owl"); // for step 1
String owlFilename = owlURL;
if (owlFilename.contains("/")) {
owlFilename = owlFilename.substring(owlFilename.lastIndexOf('/')+1);
}
String iriFilename = props.getProperty("iris"); // for step 2,3
String slimmedURI = props.getProperty("slimmed"); // for step 5
String slimmedFilename = slimmedURI;
if (slimmedFilename.contains("/")) {
slimmedFilename = slimmedFilename.substring(slimmedFilename.lastIndexOf('/')+1);
}
// 1. read the original ontology
File owlFile = new File(owlFilename);
Slimmer slimmer = new Slimmer(owlFile, slimmedFilename);
OWLOntology onto = slimmer.getOntology();
System.out.println("Loaded axioms: " + onto.getAxiomCount());
// 2. read the configuration of what to keep/remove
File configFile = new File(rootFolder,iriFilename);
Configuration config = new Configuration();
try {
System.out.println("Reading config file: " + configFile);
config.read(configFile);
} catch (Exception exception) {
System.out.println("Error while reading the config file: " + exception.getMessage());
System.exit(-1);
}
// 3. remove everything except for what is defined by the instructions
Set<Instruction> irisToSave = config.getTreePartsToSave();
slimmer.removeAllExcept(irisToSave);
Set<Instruction> irisToRemove = config.getTreePartsToRemove();
slimmer.removeAll(irisToRemove);
// 4. remove owl:imports
Set<OWLImportsDeclaration> importDeclarations = onto.getImportsDeclarations();
for (OWLImportsDeclaration declaration : importDeclarations) {
System.out.println("Removing imports: " + declaration.getIRI());
RemoveImport removeImport = new RemoveImport(onto, declaration);
slimmer.man.applyChange(removeImport);
}
// 5. update descriptions and labels
Set<OWLClass> entities = onto.getClassesInSignature();
for (OWLClass clazz : entities) {
for (OWLAnnotation annot : EntitySearcher.getAnnotations(clazz, onto)) {
if (annot.getProperty().getIRI().toString().equals("http://purl.org/dc/elements/1.1/description")) {
System.out.println(" description: " + annot.getValue());
OWLDataFactory factory = slimmer.man.getOWLDataFactory();
OWLAnnotationProperty newDescription =
factory.getOWLAnnotationProperty(IRI.create("http://purl.obolibrary.org/obo/IAO_0000115"));
OWLAnnotation commentAnno = factory.getOWLAnnotation(
newDescription,
annot.getValue()
);
System.out.println(" new description: " + commentAnno);
OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(
clazz.getIRI(), commentAnno
);
slimmer.man.applyChange(new AddAxiom(onto, ax));
}
}
}
// 6. remove some nasty NPO properties
entities = onto.getClassesInSignature();
for (OWLClass clazz : entities) {
Set<OWLAnnotationAssertionAxiom> annots = onto.getAnnotationAssertionAxioms(clazz.getIRI());
Set<OWLAnnotationAssertionAxiom> toRemove = new HashSet<OWLAnnotationAssertionAxiom>();
for (OWLAnnotationAssertionAxiom axiom : annots) {
if (axiom.getProperty().getIRI().toString().equals("http://purl.bioontology.org/ontology/npo#FULL_SYN") ||
axiom.getProperty().getIRI().toString().equals("http://purl.bioontology.org/ontology/npo#defintion")) {
toRemove.add(axiom);
}
}
slimmer.man.removeAxioms(onto, toRemove);
}
// 7. save in OWL/XML format
SetOntologyID ontologyIDChange = new SetOntologyID(onto, IRI.create(slimmedURI));
slimmer.man.applyChange(ontologyIDChange);
File output = new File(slimmedFilename);
System.out.println("Saving to: " + output.getAbsolutePath());
slimmer.saveAs(output, owlURL);
} catch (Exception e) {
e.printStackTrace();
allSucceeded = false;
}
}
if (!allSucceeded) System.exit(-1);
}
public void saveAs(File output, String orinalOWL) throws OWLOntologyStorageException, FileNotFoundException {
saveAs(new FileOutputStream(output), orinalOWL);
}
public void saveAs(OutputStream output, String originalOWL) throws OWLOntologyStorageException {
// add provenance
OWLDataFactory dataFac = man.getOWLDataFactory();
// version info
OWLLiteral lit = dataFac.getOWLLiteral(
"This SLIM file was generated automatically by the eNanoMapper Slimmer "
+ "software library. For more information see "
+ "http://github.com/enanomapper/slimmer.");
OWLAnnotationProperty owlAnnotationProperty =
dataFac.getOWLAnnotationProperty(OWLRDFVocabulary.OWL_VERSION_INFO.getIRI());
OWLAnnotation anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
OWLAnnotationProperty pavImportedFrom = dataFac.getOWLAnnotationProperty(
IRI.create("http://purl.org/pav/importedFrom")
);
anno = dataFac.getOWLAnnotation(pavImportedFrom, dataFac.getOWLLiteral(originalOWL));
man.applyChange(new AddOntologyAnnotation(onto, anno));
// generation tool
lit = dataFac.getOWLLiteral("Slimmer");
owlAnnotationProperty = dataFac.getOWLAnnotationProperty(
IRI.create("http://www.geneontology.org/formats/oboInOwl#auto-generated-by")
);
anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
// generation date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
lit = dataFac.getOWLLiteral(dateFormat.format(date));
owlAnnotationProperty = dataFac.getOWLAnnotationProperty(
IRI.create("http://www.geneontology.org/formats/oboInOwl#date")
);
anno = dataFac.getOWLAnnotation(owlAnnotationProperty, lit);
man.applyChange(new AddOntologyAnnotation(onto, anno));
// save to file
RDFXMLDocumentFormat format = new RDFXMLDocumentFormat();
format.setPrefix("ncicp", "http://ncicb.nci.nih.gov/xml/owl/EVS/ComplexProperties.xsd
man.saveOntology(onto, format, output);
}
private Set<String> explode(Set<Instruction> instructions) {
Set<String> singleIRIs = new HashSet<String>();
for (Instruction instruction : instructions) {
String iri = instruction.getUriString();
if (instruction.getScope() == Instruction.Scope.UP) {
System.out.println("Extracting " + iri + "...");
Set<OWLEntity> entities = onto.getEntitiesInSignature(IRI.create(iri));
if (entities.size() > 0) {
OWLEntity entity = entities.iterator().next();
if (entity instanceof OWLClass) {
OWLClass clazz = (OWLClass)entity;
System.out.println("Class " + clazz);
Set<String> superClasses = allSuperClasses(clazz, onto);
for (String superClass : superClasses) {
System.out.println("Extracting " + superClass + "...");
singleIRIs.add(superClass);
}
}
}
singleIRIs.add(iri);
} else if (instruction.getScope() == Instruction.Scope.DOWN) {
System.out.println("Extracting " + iri + "...");
Set<OWLEntity> entities = onto.getEntitiesInSignature(IRI.create(iri));
if (entities.size() > 0) {
OWLEntity entity = entities.iterator().next();
if (entity instanceof OWLClass) {
OWLClass clazz = (OWLClass)entity;
System.out.println("Class " + clazz);
Set<String> subClasses = allSubClasses(clazz, onto);
for (String subClass : subClasses) {
System.out.println("Extracting " + subClass + "...");
singleIRIs.add(subClass);
}
}
}
singleIRIs.add(iri);
} else if (instruction.getScope() == Instruction.Scope.SINGLE) {
System.out.println("Extracting " + iri + "...");
singleIRIs.add(iri);
} else {
System.out.println("Cannot handle this instruction: " + instruction.getScope());
}
}
return singleIRIs;
}
public void removeAllExcept(Set<Instruction> irisToSave) {
Set<String> singleIRIs = explode(irisToSave);
Map<String,String> newSuperClasses = getNewSuperClasses(irisToSave);
System.out.println("" + singleIRIs);
// remove classes
OWLEntityRemover remover = new OWLEntityRemover(Collections.singleton(onto));
for (OWLClass ind : onto.getClassesInSignature()) {
String indIRI = ind.getIRI().toString();
System.out.println(indIRI);
if (!singleIRIs.contains(indIRI)) {
System.out.println("Remove: " + indIRI);
ind.accept(remover);
} else {
// OK, keep this one. But does it have a new super class?
if (newSuperClasses.containsKey(indIRI)) {
String newSuperClass = newSuperClasses.get(indIRI);
OWLDataFactory factory = man.getOWLDataFactory();
System.out.println("Super class: " + newSuperClass);
OWLClass superClass = factory.getOWLClass(IRI.create(newSuperClass));
OWLAxiom axiom = factory.getOWLSubClassOfAxiom(ind, superClass);
System.out.println("Adding super class axiom: " + axiom);
AddAxiom addAxiom = new AddAxiom(onto, axiom);
man.applyChange(addAxiom);
}
}
}
man.applyChanges(remover.getChanges());
// remove properties
Set<OWLAxiom> propsToRemove = new HashSet<OWLAxiom>();
for (OWLAxiom axiom : onto.getAxioms()) {
if (axiom instanceof OWLDeclarationAxiom) {
OWLEntity entity = ((OWLDeclarationAxiom)axiom).getEntity();
if (entity.isOWLObjectProperty() || entity.isOWLDataProperty()) {
String propIRI = entity.getIRI().toString();
if (!singleIRIs.contains(propIRI)) {
propsToRemove.add(axiom);
}
}
}
}
man.removeAxioms(onto, propsToRemove);
}
private Map<String, String> getNewSuperClasses(Set<Instruction> irisToSave) {
Map<String,String> newSuperClasses = new HashMap<String, String>();
for (Instruction instruction : irisToSave) {
if (instruction.getNewSuperClass() != null) {
newSuperClasses.put(instruction.getUriString(), instruction.getNewSuperClass());
}
}
return newSuperClasses;
}
public void removeAll(Set<Instruction> irisToRemove) {
Set<String> singleIRIs = explode(irisToRemove);
System.out.println("" + singleIRIs);
OWLEntityRemover remover = new OWLEntityRemover(Collections.singleton(onto));
for (OWLClass ind : onto.getClassesInSignature()) {
String indIRI = ind.getIRI().toString();
System.out.println(indIRI);
if (singleIRIs.contains(indIRI)) {
System.out.println("Remove: " + indIRI);
ind.accept(remover);
}
}
man.applyChanges(remover.getChanges());
}
private Set<String> allSuperClasses(OWLClass clazz,
OWLOntology onto) {
Set<String> allSuperClasses = new HashSet<String>();
Collection<OWLClassExpression> superClasses = Searcher.sup(onto.getSubClassAxiomsForSubClass(clazz));
for (OWLClassExpression superClass : superClasses) {
OWLClass superOwlClass = superClass.asOWLClass();
String superIri = superOwlClass.getIRI().toString();
allSuperClasses.add(superIri);
// recurse
allSuperClasses.addAll(allSuperClasses(superOwlClass, onto));
}
return allSuperClasses;
}
private Set<String> allSubClasses(OWLClass clazz,
OWLOntology onto) {
Set<String> allSubClasses = new HashSet<String>();
System.out.println("clazz: " + clazz);
Collection<OWLClassExpression> subClasses = Searcher.sub(onto.getSubClassAxiomsForSuperClass(clazz));
System.out.println("subclass count: " + subClasses.size());
for (OWLClassExpression subClass : subClasses) {
// skip itself
OWLClass subOwlClass = subClass.asOWLClass();
System.out.println("subclass: " + subOwlClass);
String subIri = subOwlClass.getIRI().toString();
allSubClasses.add(subIri);
// recurse
allSubClasses.addAll(allSubClasses(subOwlClass, onto));
}
return allSubClasses;
}
@SuppressWarnings("serial")
Map<String,String> mappings = new HashMap<String,String>() {{
put("http://purl.obolibrary.org/obo/oae/RO_dev_import", "RO_dev_import.owl");
}};
private void addMappings(OWLOntologyManager m, String root) {
if (!root.endsWith("/")) root = root + "/";
for (String ontoIRI : mappings.keySet()) {
String localPart = mappings.get(ontoIRI);
m.addIRIMapper(new SimpleIRIMapper(
IRI.create(ontoIRI), IRI.create("file://" + root + localPart)
));
System.out.println(" added: " + IRI.create("file://" + root + localPart));
}
}
}
|
package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.api.SourceFile;
import com.imcode.imcms.api.exception.FileAccessDeniedException;
import com.imcode.imcms.domain.dto.DocumentDTO;
import com.imcode.imcms.domain.dto.TemplateDTO;
import com.imcode.imcms.domain.exception.EmptyFileNameException;
import com.imcode.imcms.domain.service.DocumentService;
import com.imcode.imcms.domain.service.FileService;
import com.imcode.imcms.model.Template;
import com.imcode.imcms.model.TemplateGroup;
import com.imcode.imcms.persistence.entity.TemplateGroupJPA;
import com.imcode.imcms.persistence.entity.TemplateJPA;
import com.imcode.imcms.persistence.repository.TemplateGroupRepository;
import com.imcode.imcms.persistence.repository.TemplateRepository;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.uima.util.FileUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static com.imcode.imcms.api.SourceFile.FileType.DIRECTORY;
import static com.imcode.imcms.api.SourceFile.FileType.FILE;
import static ucar.httpservices.HTTPAuthStore.log;
@Service
public class DefaultFileService implements FileService {
private final DocumentService<DocumentDTO> documentService;
private final TemplateRepository templateRepository;
private final TemplateGroupRepository templateGroupRepository;
private final ModelMapper modelMapper;
@Value("#{'${FileAdminRootPaths}'.split(';')}")
private List<Path> rootPaths;
@Value(".")
private Path rootPath;
@Autowired
public DefaultFileService(DocumentService<DocumentDTO> documentService,
TemplateRepository templateRepository,
TemplateGroupRepository templateGroupRepository,
ModelMapper modelMapper) {
this.documentService = documentService;
this.templateRepository = templateRepository;
this.templateGroupRepository = templateGroupRepository;
this.modelMapper = modelMapper;
}
private boolean isAllowablePath(Path path) {
String normalizedPath = path.normalize().toString();
final String finalNormalize = StringUtils.isBlank(normalizedPath)
? rootPath.toString()
: normalizedPath;
long countMatches = 0;
for (Path pathRoot : rootPaths) {
try {
countMatches += Files.walk(pathRoot)
.filter(pathWalk -> Paths.get(finalNormalize).startsWith(pathWalk))
.count();
} catch (IOException e) {
e.getMessage();
continue;
}
}
if (countMatches > 0) {
return true;
} else {
log.error("File access denied ! Got path: " + path);
throw new FileAccessDeniedException("File access denied!");
}
}
private SourceFile toSourceFile(Path path) {
final SourceFile.FileType fileType = Files.isDirectory(path) ? DIRECTORY : FILE;
List<String> contents;
try {
contents = Files.readAllLines(path);
} catch (IOException e) {
log.info("File has not content!!!");
contents = null;
}
return new SourceFile(path.getFileName().toString(), path.toString(), fileType, contents);
}
private String getPathWithoutExtension(String fileName) {
return FilenameUtils.removeExtension(fileName);
}
@Override
public List<SourceFile> getRootFiles() {
return rootPaths.stream()
.filter(path -> Files.exists(Paths.get(path.toString())))
.map(this::toSourceFile)
.collect(Collectors.toList());
}
@Override
public List<SourceFile> getFiles(Path path) throws IOException {
List<Path> paths;
if (isAllowablePath(path) && Files.isDirectory(path)) {
paths = Files.list(path)
.collect(Collectors.toList());
} else {
paths = Collections.EMPTY_LIST;
}
return paths.stream()
.map(this::toSourceFile)
.collect(Collectors.toList());
}
@Override
public Path getFile(Path file) throws IOException {
if (isAllowablePath(file) && Files.exists(file)) {
return file;
} else {
log.error("File doesn't exist: " + file);
throw new NoSuchFileException("File is not exist!");
}
}
@Override
public List<DocumentDTO> getDocumentsByTemplatePath(Path template) throws IOException {
if (isAllowablePath(template) && Files.exists(template)) {
final String templateName = getPathWithoutExtension(template.getFileName().toString());
return documentService.getDocumentsByTemplateName(templateName);
} else {
log.error("Template file doesn't exist: " + template);
throw new NoSuchFileException("File is not exist!");
}
}
@Override
public void deleteFile(Path file) throws IOException {
if (isAllowablePath(file) && Files.isDirectory(file)) {
Files.list(file)
.map(Path::toFile)
.forEach(FileUtils::deleteRecursive);
Files.delete(file);
} else {
Files.delete(file);
}
}
@Override
public List<SourceFile> moveFile(List<Path> src, Path target) throws IOException {
final List<SourceFile> files = new ArrayList<>();
for (Path srcPath : src) {
if (isAllowablePath(srcPath) && isAllowablePath(target)) {
files.add(toSourceFile(
Files.move(srcPath, target.resolve(srcPath.getFileName()))
));
}
}
return files;
}
@Transactional
@Override
public SourceFile moveFile(Path src, Path target) throws IOException {
final String targetFileName = target.getFileName().toString();
final String srcFileName = src.getFileName().toString();
final String originalSrcName = getPathWithoutExtension(srcFileName);
final String originalTargetName = getPathWithoutExtension(targetFileName);
final Template receivedTemplate = templateRepository.findByName(originalSrcName);
if (isAllowablePath(src) && isAllowablePath(target) && StringUtils.isNotBlank(targetFileName)) {
if (null != receivedTemplate) {
TemplateGroup gotTemplateGroup = receivedTemplate.getTemplateGroup();
if (gotTemplateGroup != null)
gotTemplateGroup.setTemplates(Collections.EMPTY_SET); // in order to avoid recursive error
receivedTemplate.setId(receivedTemplate.getId());
receivedTemplate.setName(originalTargetName);
receivedTemplate.setHidden(receivedTemplate.isHidden());
receivedTemplate.setTemplateGroup(gotTemplateGroup);
templateRepository.saveAndFlush(modelMapper.map(receivedTemplate, TemplateJPA.class));
}
final Path path = Files.move(src, target);
return toSourceFile(path);
} else {
final String errorMessage = "File couldn't has empty Name !";
log.error(errorMessage);
throw new EmptyFileNameException(errorMessage);
}
}
@Override
public List<SourceFile> copyFile(List<Path> src, Path target) throws IOException {
final List<SourceFile> files = new ArrayList<>();
for (Path srcPath : src) {
if (isAllowablePath(srcPath) && isAllowablePath(target)) {
files.add(toSourceFile(
Files.copy(srcPath, target.resolve(srcPath.getFileName()))
));
}
}
return files;
}
@Override
public SourceFile saveFile(Path location, List<String> content, OpenOption writeMode) throws IOException {
Path writeFilePath = null;
if (isAllowablePath(location)) {
if (null == writeMode) {
writeFilePath = Files.write(location, content);
} else {
writeFilePath = Files.write(location, content, writeMode);
}
}
return toSourceFile(writeFilePath);
}
@Override
public SourceFile saveFile(Path location, byte[] content, OpenOption writeMode) throws IOException {
Path writeFilePath;
if (isAllowablePath(location)) {
if (null == writeMode) {
writeFilePath = Files.write(location, content);
} else {
writeFilePath = Files.write(location, content, writeMode);
}
return toSourceFile(writeFilePath);
} else {
final String errorMessage = "File name is empty! Can't save empty file name!";
log.error(errorMessage);
throw new EmptyFileNameException(errorMessage);
}
}
@Transactional
@Override
public Template saveTemplateInGroup(Path template, String templateGroupName) {
final String templateName = template.getFileName().normalize().toString();
final String originalTemplateName = getPathWithoutExtension(templateName);
if (isAllowablePath(template) && StringUtils.isNotBlank(templateName)) {
final TemplateJPA receivedTemplate = templateRepository.findByName(originalTemplateName);
final TemplateGroupJPA receivedTemplateGroup = templateGroupRepository.findByName(templateGroupName);
receivedTemplateGroup.setTemplates(Collections.EMPTY_SET);// in order to avoid recursive error
if (receivedTemplate != null) {
receivedTemplate.setTemplateGroup(receivedTemplateGroup);
return new TemplateDTO(templateRepository.save(receivedTemplate));
} else {
TemplateJPA newTemplateJPA = new TemplateJPA();
newTemplateJPA.setName(originalTemplateName);
newTemplateJPA.setHidden(false);
newTemplateJPA.setTemplateGroup(receivedTemplateGroup);
return new TemplateDTO(templateRepository.saveAndFlush(newTemplateJPA));
}
} else {
final String errorMessage = "File name is empty! Can't save empty file name template in group!";
log.error(errorMessage);
throw new EmptyFileNameException(errorMessage);
}
}
@Override
public SourceFile createFile(SourceFile file, boolean isDirectory) throws IOException {
final Path filePath = Paths.get(file.getFullPath());
final String fileName = FilenameUtils.removeExtension(filePath.getFileName().normalize().toString());
if (isAllowablePath(filePath) && StringUtils.isNotBlank(fileName)) {
Path newSrcFilePath;
if (isDirectory) {
newSrcFilePath = Files.createDirectory(filePath);
} else {
newSrcFilePath = Files.createFile(filePath);
}
return toSourceFile(newSrcFilePath);
} else {
final String errorMessage = "File name is empty! Can't create empty file name!";
log.error(errorMessage);
throw new EmptyFileNameException(errorMessage);
}
}
}
|
package org.eclipse.persistence.testing.tests.jpa21.advanced;
import static javax.persistence.ParameterMode.INOUT;
import static javax.persistence.ParameterMode.OUT;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.Query;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.StoredProcedureQuery;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.queries.ResultSetMappingQuery;
import org.eclipse.persistence.queries.SQLCall;
import org.eclipse.persistence.testing.models.jpa21.advanced.Address;
import org.eclipse.persistence.testing.models.jpa21.advanced.AdvancedTableCreator;
import org.eclipse.persistence.testing.models.jpa21.advanced.EmployeeDetails;
import org.eclipse.persistence.testing.models.jpa21.advanced.EmployeePopulator;
import org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject;
import org.eclipse.persistence.testing.models.jpa21.advanced.Project;
import org.eclipse.persistence.testing.models.jpa21.advanced.SmallProject;
import org.eclipse.persistence.testing.models.jpa21.advanced.Employee;
import org.eclipse.persistence.queries.ColumnResult;
import org.eclipse.persistence.queries.ConstructorResult;
import org.eclipse.persistence.queries.EntityResult;
import org.eclipse.persistence.queries.FieldResult;
import org.eclipse.persistence.queries.SQLResultSetMapping;
import org.eclipse.persistence.queries.StoredProcedureCall;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import junit.framework.TestSuite;
import junit.framework.Test;
public class NamedStoredProcedureQueryTestSuite extends JUnitTestCase {
protected boolean m_reset = false;
public NamedStoredProcedureQueryTestSuite() {}
public NamedStoredProcedureQueryTestSuite(String name) {
super(name);
}
public void setUp () {
m_reset = true;
super.setUp();
clearCache();
}
public void tearDown () {
if (m_reset) {
m_reset = false;
}
super.tearDown();
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("NamedStoredProcedureQueryTestSuite");
suite.addTest(new NamedStoredProcedureQueryTestSuite("testSetup"));
// These tests call stored procedures that return a result set.
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithMultipleResultsFromCode"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithMultipleResultsFromAnnotations"));
// These tests call stored procedures that write into OUT parameters.
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClassNamedFields"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultClassNumberedFields"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testQueryWithResultSetFieldMapping"));
// These tests call stored procedures from EM API
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithPositionalParameters"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithAliasedColumns"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureQueryWithSqlResultSetMapping"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureExecuteQuery1"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testEMCreateStoredProcedureExecuteQuery2"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteStoredProcedureQueryWithNamedCursors"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListStoredProcedureQueryWithNamedCursors"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteStoredProcedureQueryWithUnNamedCursor"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testStoredProcedureQuerySysCursor"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListOnUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetSingleResultOnUpdateQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetResultListOnDeleteQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testGetSingleResultOnDeleteQuery"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteUpdateOnSelectQueryWithResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testExecuteUpdateOnSelectQueryWithNoResultClass"));
suite.addTest(new NamedStoredProcedureQueryTestSuite("testClassCastExceptionOnExecuteWithNoOutputParameters"));
return suite;
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
new AdvancedTableCreator().replaceTables(JUnitTestCase.getServerSession());
EmployeePopulator employeePopulator = new EmployeePopulator();
employeePopulator.buildExamples();
employeePopulator.persistExample(getServerSession());
clearCache();
}
/**
* Tests a StoredProcedureQuery using only a procedure name though EM API
*/
public void testEMCreateStoredProcedureQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Edmonton");
address1.setPostalCode("T5B 4M9");
address1.setProvince("AB");
address1.setStreet("7424 118 Avenue");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
List addresses = query.setParameter("address_id_v", address1.getId()).getResultList();
assertTrue("Incorrect number of addresses returned", addresses.size() == 1);
Object[] addressContent = (Object[]) addresses.get(0);
assertTrue("Incorrect data content size", addressContent.length == 6);
assertTrue("Id content incorrect", addressContent[0].equals(new Long(address1.getId())));
assertTrue("Steet content incorrect", addressContent[1].equals(address1.getStreet()));
assertTrue("City content incorrect", addressContent[2].equals(address1.getCity()));
assertTrue("Country content incorrect", addressContent[3].equals(address1.getCountry()));
assertTrue("Province content incorrect", addressContent[4].equals(address1.getProvince()));
assertTrue("Postal Code content incorrect", addressContent[5].equals(address1.getPostalCode()));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testEMCreateStoredProcedureQueryWithPositionalParameters() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNumberedFieldResult").setParameter(1, address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-set-mapping using
* positional parameters (and more than the procedure expects).
*/
public void testEMCreateStoredProcedureQueryWithAliasedColumns() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K2J 0L7");
address1.setProvince("ON");
address1.setStreet("321 Main");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Numbered", "address-field-result-map-numbered");
query.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN);
List<Address> addresses = query.setParameter(1, address1.getId()).getResultList();
assertTrue("Too many addresses returned", addresses.size() == 1);
Address address2 = addresses.get(0);
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a class though EM API
*/
public void testEMCreateStoredProcedureQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Victoria");
address1.setPostalCode("V9A 6A9");
address1.setProvince("BC");
address1.setStreet("785 Lampson Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address", org.eclipse.persistence.testing.models.jpa21.advanced.Address.class);
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Address address2 = (Address) query.setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API
*/
public void testEMCreateStoredProcedureQueryWithSqlResultSetMapping() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", String.class, ParameterMode.IN);
Object[] values = (Object[]) query.setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertTrue("Address not found using stored procedure", address.getStreet().equals(values[1]));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testEMCreateStoredProcedureUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
beginTransaction(em);
int results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).executeUpdate();
commitTransaction(em);
assertTrue("Update count incorrect.", results == 2);
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using multiple names cursors.
*/
public void testExecuteStoredProcedureQueryWithNamedCursors() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingNamedRefCursors");
boolean returnVal = query.execute();
List<Employee> employees = (List<Employee>) query.getOutputParameterValue("CUR1");
assertFalse("No employees were returned", employees.isEmpty());
List<Address> addresses = (List<Address>) query.getOutputParameterValue("CUR2");
assertFalse("No addresses were returned", addresses.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery with an unnamed cursor.
*/
public void testExecuteStoredProcedureQueryWithUnNamedCursor() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingUnNamedRefCursor");
boolean returnVal = query.execute();
List<Employee> employees = (List<Employee>) query.getOutputParameterValue(1);
assertFalse("No employees were returned", employees.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery on Oracle using named ref cursors.
*/
public void testGetResultListStoredProcedureQueryWithNamedCursors() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadUsingNamedRefCursors");
// Calling get result list here on an oracle platform will
// will return false for no result set was returned. Users
// should be calling execute and getting results from the out
// parameters.
try {
query.getResultList();
} catch (IllegalStateException ise) {
// We expect the exception here, now check through the output parameters (as expected)
List<Employee> employees = (List<Employee>) query.getOutputParameterValue("CUR1");
assertFalse("No employees were returned", employees.isEmpty());
List<Address> addresses = (List<Address>) query.getOutputParameterValue("CUR2");
assertFalse("No addresses were returned", addresses.isEmpty());
assertFalse("The query had more results", query.hasMoreResults());
return;
}
fail("No IllegalStateException thrown on getResultList() to an Oracle stored procedure using ref cursors");
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a system cursor.
*/
public void testStoredProcedureQuerySysCursor() {
if (supportsStoredProcedures() && getPlatform().isOracle() ) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Using_Sys_Cursor", Employee.class);
query.registerStoredProcedureParameter("p_recordset", void.class, ParameterMode.REF_CURSOR);
boolean execute = query.execute();
assertFalse("Execute should have returned false.", execute);
// TODO: investigate .. the name parameter "p_recordset" can't be looked up here, must use ordinal, why?
List<Employee> employees = (List<Employee>) query.getOutputParameterValue(1);
assertFalse("No employees were returned", employees.isEmpty());
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testEMCreateStoredProcedureExecuteQuery1() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
boolean result = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).execute();
assertTrue("Result did not return true for a result set.", result);
List<Address> addressResults = query.getResultList();
assertTrue("The query didn't have any more results.", query.hasMoreResults());
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
// Get the update count.
int updateCount = query.getUpdateCount();
assertTrue("Update count incorrect: " + updateCount, updateCount == 2);
// Update count should return -1 now.
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(new Long(numberOfEmployes)));
} else if (outputParamValueFromName instanceof Integer) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(numberOfEmployes));
}
// TODO: else, don't worry about it for now ...
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Integer outputParamValueFromPosition = (Integer) query.getOutputParameterValue(3);
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition.equals(numberOfEmployes));
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
Address a3 = em.find(Address.class, address3.getId());
assertTrue("The postal code was not updated for address 3.", a3.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
// The open statement/connection will be closed here.
closeEntityManager(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
* This is the same test as above except different retrieval path.
*/
public void testEMCreateStoredProcedureExecuteQuery2() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
boolean result = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).execute();
assertTrue("Result did not return true for a result set.", result);
// This shouldn't affect where we are in the retrieval of the query.
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
List<Address> addressResults = query.getResultList();
// We know there should be more results so ask for them without checking for has more results.
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertNull("getResultList after no results did not return null", query.getResultList());
// Get the update count.
int updateCount = query.getUpdateCount();
assertTrue("Update count incorrect: " + updateCount, updateCount == 2);
// Update count should return -1 now.
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
assertTrue("Update count should be -1.", query.getUpdateCount() == -1);
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(new Long(numberOfEmployes)));
} else if (outputParamValueFromName instanceof Integer) {
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName.equals(numberOfEmployes));
}
// TODO: else, don't worry about it for now ...
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Integer outputParamValueFromPosition = (Integer) query.getOutputParameterValue(3);
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
assertTrue("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition.equals(numberOfEmployes));
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertTrue("The postal code was not updated for address 1.", a1.getPostalCode().equals(postalCodeCorrection));
Address a2 = em.find(Address.class, address2.getId());
assertTrue("The postal code was not updated for address 2.", a2.getPostalCode().equals(postalCodeCorrection));
Address a3 = em.find(Address.class, address3.getId());
assertTrue("The postal code was not updated for address 3.", a3.getPostalCode().equals(postalCodeCorrection));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
// The open statement/connection will be closed here.
closeEntityManager(em);
}
}
}
/**
* Test multiple result sets by setting the SQL results set mapping from code.
*/
public void testQueryWithMultipleResultsFromCode() throws Exception {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
// SQL result set mapping for employee.
SQLResultSetMapping employeeResultSetMapping = new SQLResultSetMapping("EmployeeResultSetMapping");
employeeResultSetMapping.addResult(new EntityResult(Employee.class));
// SQL result set mapping for address.
SQLResultSetMapping addressResultSetMapping = new SQLResultSetMapping("AddressResultSetMapping");
addressResultSetMapping.addResult(new EntityResult(Address.class));
// SQL result set mapping for project (using inheritance and more complex result)
SQLResultSetMapping projectResultSetMapping = new SQLResultSetMapping("ProjectResultSetMapping");
EntityResult projectEntityResult = new EntityResult(Project.class);
projectResultSetMapping.addResult(projectEntityResult);
projectEntityResult = new EntityResult(SmallProject.class);
projectEntityResult.addFieldResult(new FieldResult("id", "SMALL_ID"));
projectEntityResult.addFieldResult(new FieldResult("name", "SMALL_NAME"));
projectEntityResult.addFieldResult(new FieldResult("description", "SMALL_DESCRIPTION"));
projectEntityResult.addFieldResult(new FieldResult("teamLeader", "SMALL_TEAMLEAD"));
projectEntityResult.addFieldResult(new FieldResult("version", "SMALL_VERSION"));
projectEntityResult.setDiscriminatorColumn("SMALL_DESCRIM");
projectResultSetMapping.addResult(projectEntityResult);
projectResultSetMapping.addResult(new ColumnResult("BUDGET_SUM"));
// SQL result set mapping for employee using constructor results.
SQLResultSetMapping employeeConstrustorResultSetMapping = new SQLResultSetMapping("EmployeeConstructorResultSetMapping");
ConstructorResult constructorResult = new ConstructorResult(EmployeeDetails.class);
ColumnResult columnResult = new ColumnResult("EMP_ID");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("F_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("L_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("R_COUNT");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
employeeConstrustorResultSetMapping.addResult(constructorResult);
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("Read_Multiple_Result_Sets");
call.setHasMultipleResultSets(true);
call.setReturnMultipleResultSetCollections(true);
ResultSetMappingQuery query = new ResultSetMappingQuery(call);
query.addSQLResultSetMapping(employeeResultSetMapping);
query.addSQLResultSetMapping(addressResultSetMapping);
query.addSQLResultSetMapping(projectResultSetMapping);
query.addSQLResultSetMapping(employeeConstrustorResultSetMapping);
List allResults = (List)getServerSession().executeQuery(query);
assertNotNull("No results returned", allResults);
assertTrue("Incorrect number of results returned", allResults.size() == 4);
// Verify first result set mapping --> Employee
List results0 = (List) allResults.get(0);
assertNotNull("No Employee results returned", results0);
assertTrue("Empty Employee results returned", results0.size() > 0);
// Verify second result set mapping --> Address
List results1 = (List) allResults.get(1);
assertNotNull("No Address results returned", results1);
assertTrue("Empty Address results returned", results1.size() > 0);
// Verify third result set mapping --> Project
List results2 = (List) allResults.get(2);
assertNotNull("No Project results returned", results2);
assertTrue("Empty Project results returned", results2.size() > 0);
for (Object result2 : results2) {
Object[] result2Element = (Object[]) result2;
assertTrue("Failed to Return 3 items", (result2Element.length == 3));
// Using Number as Different db/drivers can return different types
// e.g. Oracle with ijdbc14.jar returns BigDecimal where as Derby
// with derbyclient.jar returns Double. NOTE: the order of checking
// here is valid and as defined by the spec.
assertTrue("Failed to return LargeProject", (result2Element[0] instanceof LargeProject));
assertTrue("Failed To Return SmallProject", (result2Element[1] instanceof SmallProject));
assertTrue("Failed to return column",(result2Element[2] instanceof Number));
assertFalse("Returned same data in both result elements",((SmallProject) result2Element[1]).getName().equals(((LargeProject) result2Element[0]).getName()));
}
// Verify fourth result set mapping --> Employee Constructor Result
List results3 = (List) allResults.get(3);
assertNotNull("No Employee constructor results returned", results3);
assertTrue("Empty Employee constructor results returned", results3.size() > 0);
}
}
/**
* Test multiple result sets by setting the SQL results set mapping from annotation.
*/
public void testQueryWithMultipleResultsFromAnnotations() throws Exception {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
StoredProcedureQuery multipleResultSetQuery = createEntityManager().createNamedStoredProcedureQuery("ReadUsingMultipleResultSetMappings");
// Verify first result set mapping --> Employee
List results = multipleResultSetQuery.getResultList();
assertNotNull("No Employee results returned", results);
assertTrue("Empty Employee results returned", results.size() > 0);
// Verify second result set mapping --> Address
assertTrue("Address results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Address results returned", results);
assertTrue("Empty Address results returned", results.size() > 0);
// Verify third result set mapping --> Project
assertTrue("Projects results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Project results returned", results);
assertTrue("Empty Project results returned", results.size() > 0);
for (Object result : results) {
Object[] resultElement = (Object[]) result;
assertTrue("Failed to Return 3 items", (resultElement.length == 3));
// Using Number as Different db/drivers can return different types
// e.g. Oracle with ijdbc14.jar returns BigDecimal where as Derby
// with derbyclient.jar returns Double. NOTE: the order of checking
// here is valid and as defined by the spec.
assertTrue("Failed to return LargeProject", (resultElement[0] instanceof LargeProject) );
assertTrue("Failed To Return SmallProject", (resultElement[1] instanceof SmallProject) );
assertTrue("Failed to return column",(resultElement[2] instanceof Number) );
assertFalse("Returned same data in both result elements",((SmallProject)resultElement[1]).getName().equals(((LargeProject)resultElement[0]).getName()));
}
// Verify fourth result set mapping --> Employee Constructor Result
assertTrue("Employee constructor results not available", multipleResultSetQuery.hasMoreResults());
results = multipleResultSetQuery.getResultList();
assertNotNull("No Employee constructor results returned", results);
assertTrue("Empty Employee constructor results returned", results.size() > 0);
// Verify there as no more results available
assertFalse("More results available", multipleResultSetQuery.hasMoreResults());
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressWithResultClass").setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-set mapping.
*/
public void testQueryWithResultClassNamedFields() {
// TODO: investigate if this test should work on Oracle as written.
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNamedFieldResult").setParameter("address_id_v", address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address not found using stored procedure", (address1.getId() == address2.getId()));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-class.
*/
public void testQueryWithResultClassNumberedFields() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K1G 6P3");
address1.setProvince("ON");
address1.setStreet("123 Street");
address1.setCountry("Canada");
em.persist(address1);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Address address2 = (Address) em.createNamedStoredProcedureQuery("ReadAddressMappedNumberedFieldResult").setParameter(1, address1.getId()).getSingleResult();
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertTrue("Address didn't build correctly using stored procedure", (address1.getStreet().equals(address2.getStreet())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getCountry().equals(address2.getCountry())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getProvince().equals(address2.getProvince())));
assertTrue("Address didn't build correctly using stored procedure", (address1.getPostalCode().equals(address2.getPostalCode())));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery annotation using a result-set mapping.
*/
public void testQueryWithResultSetFieldMapping() {
// TODO: investigate if this test should work on Oracle as written.
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Ottawa");
address.setPostalCode("K1G 6P3");
address.setProvince("ON");
address.setStreet("123 Street");
address.setCountry("Canada");
em.persist(address);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
Object[] values = (Object[]) em.createNamedStoredProcedureQuery("ReadAddressMappedNamedColumnResult").setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertTrue("Address not found using stored procedure", address.getStreet().equals(values[1]));
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
Object results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
Object results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Tests an execute update on a named stored procedure that does a select.
* NamedStoredProcedure defines a result class.
*/
public void testExecuteUpdateOnSelectQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createNamedStoredProcedureQuery("ReadAddressWithResultClass").setParameter("ADDRESS_ID", 1).executeUpdate();
commitTransaction(em);
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
return;
} finally {
closeEntityManager(em);
}
fail("Expected Illegal state exception was not thrown.");
}
}
/**
* Tests an execute update on a named stored procedure that does a select.
* NamedStoredProcedure defines a result class.
*/
public void testExecuteUpdateOnSelectQueryWithNoResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createNamedStoredProcedureQuery("ReadAllAddressesWithNoResultClass").executeUpdate();
commitTransaction(em);
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
return;
} finally {
closeEntityManager(em);
}
fail("Expected Illegal state exception was not thrown.");
}
}
/**
* Test a class cast exception.
*/
public void testClassCastExceptionOnExecuteWithNoOutputParameters() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_All_Employees");
boolean returnValue = query.execute();
assertTrue("Execute didn't return true", returnValue);
List<Employee> employees = query.getResultList();
assertFalse("No employees were returned", employees.isEmpty());
} catch (ClassCastException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("ClassCastException caught" + e);
} finally {
closeEntityManager(em);
}
}
}
}
|
package com.github.underscore.lodash;
import com.github.underscore.BinaryOperator;
import com.github.underscore.BiFunction;
import com.github.underscore.Consumer;
import com.github.underscore.Function;
import com.github.underscore.Function3;
import com.github.underscore.Predicate;
import com.github.underscore.PredicateIndexed;
import com.github.underscore.Tuple;
import com.github.underscore.Optional;
import java.util.*;
public class U<T> extends com.github.underscore.U<T> {
private static final int DEFAULT_TRUNC_LENGTH = 30;
private static final String DEFAULT_TRUNC_OMISSION = "...";
private static final String NULL = "null";
private static final String ELEMENT = "<element>";
private static final String CLOSED_ELEMENT = "</element>";
private static final String EMPTY_ELEMENT = ELEMENT + CLOSED_ELEMENT;
private static final String NULL_ELEMENT = ELEMENT + NULL + CLOSED_ELEMENT;
private static final java.util.regex.Pattern RE_LATIN_1 = java.util.regex.Pattern.compile(
"[\\xc0-\\xd6\\xd8-\\xde\\xdf-\\xf6\\xf8-\\xff]");
private static final java.util.regex.Pattern RE_PROP_NAME = java.util.regex.Pattern.compile(
"[^.\\[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\2)\\[^\\]|\\.)*?)\2)\\]|(?=(\\.|\\[\\])(?:\4|$))");
private static final Map<String, String> DEBURRED_LETTERS = new LinkedHashMap<String, String>() { {
put("\u00c0", "A"); put("\u00c1", "A"); put("\u00c2", "A"); put("\u00c3", "A");
put("\u00c4", "A"); put("\u00c5", "A");
put("\u00e0", "a"); put("\u00e1", "a"); put("\u00e2", "a"); put("\u00e3", "a");
put("\u00e4", "a"); put("\u00e5", "a");
put("\u00c7", "C"); put("\u00e7", "c");
put("\u00d0", "D"); put("\u00f0", "d");
put("\u00c8", "E"); put("\u00c9", "E"); put("\u00ca", "E"); put("\u00cb", "E");
put("\u00e8", "e"); put("\u00e9", "e"); put("\u00ea", "e"); put("\u00eb", "e");
put("\u00cC", "I"); put("\u00cd", "I"); put("\u00ce", "I"); put("\u00cf", "I");
put("\u00eC", "i"); put("\u00ed", "i"); put("\u00ee", "i"); put("\u00ef", "i");
put("\u00d1", "N"); put("\u00f1", "n");
put("\u00d2", "O"); put("\u00d3", "O"); put("\u00d4", "O"); put("\u00d5", "O");
put("\u00d6", "O"); put("\u00d8", "O");
put("\u00f2", "o"); put("\u00f3", "o"); put("\u00f4", "o"); put("\u00f5", "o");
put("\u00f6", "o"); put("\u00f8", "o");
put("\u00d9", "U"); put("\u00da", "U"); put("\u00db", "U"); put("\u00dc", "U");
put("\u00f9", "u"); put("\u00fa", "u"); put("\u00fb", "u"); put("\u00fc", "u");
put("\u00dd", "Y"); put("\u00fd", "y"); put("\u00ff", "y");
put("\u00c6", "Ae"); put("\u00e6", "ae");
put("\u00de", "Th"); put("\u00fe", "th");
put("\u00df", "ss");
} };
private static final Map<String, List<String>> DEFAULT_HEADER_FIELDS = new HashMap<String, List<String>>();
private static final Set<String> SUPPORTED_HTTP_METHODS = new HashSet<String>(
Arrays.asList("GET", "POST", "PUT", "DELETE"));
private static final int BUFFER_LENGTH_1024 = 1024;
private static final int RESPONSE_CODE_400 = 400;
private static String upper = "[A-Z\\xc0-\\xd6\\xd8-\\xde\\u0400-\\u04FF]";
private static String lower = "[a-z\\xdf-\\xf6\\xf8-\\xff]+";
private static java.util.regex.Pattern reWords = java.util.regex.Pattern.compile(
upper + "+(?=" + upper + lower + ")|" + upper + "?" + lower + "|" + upper + "+|[0-9]+");
static {
DEFAULT_HEADER_FIELDS.put("Content-Type", Arrays.asList("application/json", "charset=utf-8"));
}
public U(final Iterable<T> iterable) {
super(iterable);
}
public U(final String string) {
super(string);
}
public static class Chain<T> extends com.github.underscore.U.Chain<T> {
public Chain(final T item) {
super(item);
}
public Chain(final List<T> list) {
super(list);
}
public Chain<T> first() {
return new Chain<T>(U.first(value()));
}
public Chain<T> first(int n) {
return new Chain<T>(U.first(value(), n));
}
public Chain<T> firstOrNull() {
return new Chain<T>(U.firstOrNull(value()));
}
public Chain<T> firstOrNull(final Predicate<T> pred) {
return new Chain<T>(U.firstOrNull(value(), pred));
}
public Chain<T> initial() {
return new Chain<T>(U.initial(value()));
}
public Chain<T> initial(int n) {
return new Chain<T>(U.initial(value(), n));
}
public Chain<T> last() {
return new Chain<T>(U.last(value()));
}
public Chain<T> last(int n) {
return new Chain<T>(U.last(value(), n));
}
public Chain<T> lastOrNull() {
return new Chain<T>(U.lastOrNull(value()));
}
public Chain<T> lastOrNull(final Predicate<T> pred) {
return new Chain<T>(U.lastOrNull(value(), pred));
}
public Chain<T> rest() {
return new Chain<T>(U.rest(value()));
}
public Chain<T> rest(int n) {
return new Chain<T>(U.rest(value(), n));
}
public Chain<T> compact() {
return new Chain<T>(U.compact(value()));
}
public Chain<T> compact(final T falsyValue) {
return new Chain<T>(U.compact(value(), falsyValue));
}
@SuppressWarnings("unchecked")
public Chain flatten() {
return new Chain(U.flatten(value()));
}
public <F> Chain<F> map(final Function<? super T, F> func) {
return new Chain<F>(U.map(value(), func));
}
public <F> Chain<F> mapIndexed(final BiFunction<Integer, ? super T, F> func) {
return new Chain<F>(U.mapIndexed(value(), func));
}
public Chain<T> filter(final Predicate<T> pred) {
return new Chain<T>(U.filter(value(), pred));
}
public Chain<T> filterIndexed(final PredicateIndexed<T> pred) {
return new Chain<T>(U.filterIndexed(value(), pred));
}
public Chain<T> rejectIndexed(final PredicateIndexed<T> pred) {
return new Chain<T>(U.rejectIndexed(value(), pred));
}
public Chain<T> reject(final Predicate<T> pred) {
return new Chain<T>(U.reject(value(), pred));
}
public Chain<T> filterFalse(final Predicate<T> pred) {
return new Chain<T>(U.filterFalse(value(), pred));
}
public <F> Chain<F> reduce(final BiFunction<F, T, F> func, final F zeroElem) {
return new Chain<F>(U.reduce(value(), func, zeroElem));
}
public Chain<Optional<T>> reduce(final BinaryOperator<T> func) {
return new Chain<Optional<T>>(U.reduce(value(), func));
}
public <F> Chain<F> reduceRight(final BiFunction<F, T, F> func, final F zeroElem) {
return new Chain<F>(U.reduceRight(value(), func, zeroElem));
}
public Chain<Optional<T>> reduceRight(final BinaryOperator<T> func) {
return new Chain<Optional<T>>(U.reduceRight(value(), func));
}
public Chain<Optional<T>> find(final Predicate<T> pred) {
return new Chain<Optional<T>>(U.find(value(), pred));
}
public Chain<Optional<T>> findLast(final Predicate<T> pred) {
return new Chain<Optional<T>>(U.findLast(value(), pred));
}
@SuppressWarnings("unchecked")
public Chain<Comparable> max() {
return new Chain<Comparable>(U.max((Collection) value()));
}
public <F extends Comparable<? super F>> Chain<T> max(final Function<T, F> func) {
return new Chain<T>(U.max(value(), func));
}
@SuppressWarnings("unchecked")
public Chain<Comparable> min() {
return new Chain<Comparable>(U.min((Collection) value()));
}
public <F extends Comparable<? super F>> Chain<T> min(final Function<T, F> func) {
return new Chain<T>(U.min(value(), func));
}
@SuppressWarnings("unchecked")
public Chain<Comparable> sort() {
return new Chain<Comparable>(U.sort((List<Comparable>) value()));
}
@SuppressWarnings("unchecked")
public <F extends Comparable<? super F>> Chain<F> sortWith(final Comparator<F> comparator) {
return new Chain<F>(U.sortWith((List<F>) value(), comparator));
}
public <F extends Comparable<? super F>> Chain<T> sortBy(final Function<T, F> func) {
return new Chain<T>(U.sortBy(value(), func));
}
@SuppressWarnings("unchecked")
public <K> Chain<Map<K, Comparable>> sortBy(final K key) {
return new Chain<Map<K, Comparable>>(U.sortBy((List<Map<K, Comparable>>) value(), key));
}
public <F> Chain<Map<F, List<T>>> groupBy(final Function<T, F> func) {
return new Chain<Map<F, List<T>>>(U.groupBy(value(), func));
}
public <F> Chain<Map<F, Optional<T>>> groupBy(final Function<T, F> func,
final BinaryOperator<T> binaryOperator) {
return new Chain<Map<F, Optional<T>>>(U.groupBy(value(), func, binaryOperator));
}
public Chain<Map<Object, List<T>>> indexBy(final String property) {
return new Chain<Map<Object, List<T>>>(U.indexBy(value(), property));
}
public <F> Chain<Map<F, Integer>> countBy(final Function<T, F> func) {
return new Chain<Map<F, Integer>>(U.countBy(value(), func));
}
public Chain<T> shuffle() {
return new Chain<T>(U.shuffle(value()));
}
public Chain<T> sample() {
return new Chain<T>(U.sample(value()));
}
public Chain<T> sample(final int howMany) {
return new Chain<T>(U.newArrayList(U.sample(value(), howMany)));
}
public Chain<T> tap(final Consumer<T> func) {
U.tap(value(), func);
return new Chain<T>(value());
}
public Chain<T> forEach(final Consumer<T> func) {
U.forEach(value(), func);
return new Chain<T>(value());
}
public Chain<T> forEachRight(final Consumer<T> func) {
U.forEachRight(value(), func);
return new Chain<T>(value());
}
public Chain<Boolean> every(final Predicate<T> pred) {
return new Chain<Boolean>(U.every(value(), pred));
}
public Chain<Boolean> some(final Predicate<T> pred) {
return new Chain<Boolean>(U.some(value(), pred));
}
public Chain<Boolean> contains(final T elem) {
return new Chain<Boolean>(U.contains(value(), elem));
}
public Chain<T> invoke(final String methodName, final List<Object> args) {
return new Chain<T>(U.invoke(value(), methodName, args));
}
public Chain<T> invoke(final String methodName) {
return new Chain<T>(U.invoke(value(), methodName));
}
public Chain<Object> pluck(final String propertyName) {
return new Chain<Object>(U.pluck(value(), propertyName));
}
public <E> Chain<T> where(final List<Tuple<String, E>> properties) {
return new Chain<T>(U.where(value(), properties));
}
public <E> Chain<Optional<T>> findWhere(final List<Tuple<String, E>> properties) {
return new Chain<Optional<T>>(U.findWhere(value(), properties));
}
public Chain<T> uniq() {
return new Chain<T>(U.uniq(value()));
}
@SuppressWarnings("unchecked")
public <F> Chain<T> uniq(final Function<T, F> func) {
return new Chain<T>(U.newArrayList(U.uniq(value(), func)));
}
public Chain<T> distinct() {
return new Chain<T>(U.uniq(value()));
}
@SuppressWarnings("unchecked")
public <F> Chain<F> distinctBy(final Function<T, F> func) {
return new Chain<F>(U.newArrayList((Iterable<F>) U.uniq(value(), func)));
}
@SuppressWarnings("unchecked")
public Chain<T> union(final List<T> ... lists) {
return new Chain<T>(U.union(value(), lists));
}
@SuppressWarnings("unchecked")
public Chain<T> intersection(final List<T> ... lists) {
return new Chain<T>(U.intersection(value(), lists));
}
@SuppressWarnings("unchecked")
public Chain<T> difference(final List<T> ... lists) {
return new Chain<T>(U.difference(value(), lists));
}
public Chain<Integer> range(final int stop) {
return new Chain<Integer>(newIntegerList(U.range(stop)));
}
public Chain<Integer> range(final int start, final int stop) {
return new Chain<Integer>(newIntegerList(U.range(start, stop)));
}
public Chain<Integer> range(final int start, final int stop, final int step) {
return new Chain<Integer>(newIntegerList(U.range(start, stop, step)));
}
public Chain<List<T>> chunk(final int size) {
return new Chain<List<T>>(U.chunk(value(), size));
}
@SuppressWarnings("unchecked")
public Chain<T> concat(final List<T> ... lists) {
return new Chain<T>(U.concat(value(), lists));
}
public Chain<T> slice(final int start) {
return new Chain<T>(U.slice(value(), start));
}
public Chain<T> slice(final int start, final int end) {
return new Chain<T>(U.slice(value(), start, end));
}
public Chain<T> reverse() {
return new Chain<T>(U.reverse(value()));
}
public Chain<String> join() {
return new Chain<String>(U.join(value()));
}
public Chain<String> join(final String separator) {
return new Chain<String>(U.join(value(), separator));
}
public Chain<T> skip(final int numberToSkip) {
return new Chain<T>(value().subList(numberToSkip, value().size()));
}
public Chain<T> limit(final int size) {
return new Chain<T>(value().subList(0, size));
}
@SuppressWarnings("unchecked")
public <K, V> Chain<Map<K, V>> toMap() {
return new Chain<Map<K, V>>(U.toMap((Iterable<Map.Entry<K, V>>) value()));
}
public Chain<T> drop() {
return new Chain<T>(U.drop(value()));
}
public Chain<T> drop(final Integer n) {
return new Chain<T>(U.drop(value(), n));
}
public Chain<T> dropRight() {
return new Chain<T>(U.dropRight(value()));
}
public Chain<T> dropRight(final Integer n) {
return new Chain<T>(U.dropRight(value(), n));
}
public Chain<T> dropWhile(final Predicate<T> pred) {
return new Chain<T>(U.dropWhile(value(), pred));
}
public Chain<T> dropRightWhile(final Predicate<T> pred) {
return new Chain<T>(U.dropRightWhile(value(), pred));
}
@SuppressWarnings("unchecked")
public Chain<Object> fill(final Object value) {
return new Chain<Object>(U.fill((List<Object>) value(), value));
}
@SuppressWarnings("unchecked")
public Chain<Object> fill(final Object value, final Integer start, final Integer end) {
return new Chain<Object>(U.fill((List<Object>) value(), value, start, end));
}
public Chain<Object> flattenDeep() {
return new Chain<Object>(U.flattenDeep(value()));
}
@SuppressWarnings("unchecked")
public Chain<Object> pull(final Object ... values) {
return new Chain<Object>(U.pull((List<Object>) value(), values));
}
@SuppressWarnings("unchecked")
public Chain<Object> pullAt(final Integer ... indexes) {
return new Chain<Object>(U.pullAt((List<Object>) value(), indexes));
}
public Chain<T> remove(final Predicate<T> pred) {
return new Chain<T>(U.remove(value(), pred));
}
public Chain<T> take() {
return new Chain<T>(U.take(value()));
}
public Chain<T> takeRight() {
return new Chain<T>(U.takeRight(value()));
}
public Chain<T> take(final Integer n) {
return new Chain<T>(U.take(value(), n));
}
public Chain<T> takeRight(final Integer n) {
return new Chain<T>(U.takeRight(value(), n));
}
public Chain<T> takeWhile(final Predicate<T> pred) {
return new Chain<T>(U.takeWhile(value(), pred));
}
public Chain<T> takeRightWhile(final Predicate<T> pred) {
return new Chain<T>(U.takeRightWhile(value(), pred));
}
@SuppressWarnings("unchecked")
public Chain<T> xor(final List<T> list) {
return new Chain<T>(U.xor(value(), list));
}
public Chain<T> at(final Integer ... indexes) {
return new Chain<T>(U.at(value(), indexes));
}
@SuppressWarnings("unchecked")
public <F extends Number> Chain<F> sum() {
return new Chain<F>(U.sum((List<F>) value()));
}
public <F extends Number> Chain<F> sum(final Function<T, F> func) {
return new Chain<F>(U.sum(value(), func));
}
@SuppressWarnings("unchecked")
public Chain<Double> mean() {
return new Chain<Double>(U.mean((List<Number>) value()));
}
@SuppressWarnings("unchecked")
public Chain<Double> median() {
return new Chain<Double>(U.median((List<Number>) value()));
}
public Chain<String> camelCase() {
return new Chain<String>(U.camelCase((String) item()));
}
public Chain<String> lowerFirst() {
return new Chain<String>(U.lowerFirst((String) item()));
}
public Chain<String> upperFirst() {
return new Chain<String>(U.upperFirst((String) item()));
}
public Chain<String> capitalize() {
return new Chain<String>(U.capitalize((String) item()));
}
public Chain<String> deburr() {
return new Chain<String>(U.deburr((String) item()));
}
public Chain<Boolean> endsWith(final String target) {
return new Chain<Boolean>(U.endsWith((String) item(), target));
}
public Chain<Boolean> endsWith(final String target, final Integer position) {
return new Chain<Boolean>(U.endsWith((String) item(), target, position));
}
public Chain<String> kebabCase() {
return new Chain<String>(U.kebabCase((String) item()));
}
public Chain<String> repeat(final int length) {
return new Chain<String>(U.repeat((String) item(), length));
}
public Chain<String> pad(final int length) {
return new Chain<String>(U.pad((String) item(), length));
}
public Chain<String> pad(final int length, final String chars) {
return new Chain<String>(U.pad((String) item(), length, chars));
}
public Chain<String> padStart(final int length) {
return new Chain<String>(U.padStart((String) item(), length));
}
public Chain<String> padStart(final int length, final String chars) {
return new Chain<String>(U.padStart((String) item(), length, chars));
}
public Chain<String> padEnd(final int length) {
return new Chain<String>(U.padEnd((String) item(), length));
}
public Chain<String> padEnd(final int length, final String chars) {
return new Chain<String>(U.padEnd((String) item(), length, chars));
}
public Chain<String> snakeCase() {
return new Chain<String>(U.snakeCase((String) item()));
}
public Chain<String> startCase() {
return new Chain<String>(U.startCase((String) item()));
}
public Chain<Boolean> startsWith(final String target) {
return new Chain<Boolean>(U.startsWith((String) item(), target));
}
public Chain<Boolean> startsWith(final String target, final Integer position) {
return new Chain<Boolean>(U.startsWith((String) item(), target, position));
}
public Chain<String> trim() {
return new Chain<String>(U.trim((String) item()));
}
public Chain<String> trim(final String chars) {
return new Chain<String>(U.trim((String) item(), chars));
}
public Chain<String> trimStart() {
return new Chain<String>(U.trimStart((String) item()));
}
public Chain<String> trimStart(final String chars) {
return new Chain<String>(U.trimStart((String) item(), chars));
}
public Chain<String> trimEnd() {
return new Chain<String>(U.trimEnd((String) item()));
}
public Chain<String> trunc() {
return new Chain<String>(U.trunc((String) item()));
}
public Chain<String> trunc(final int length) {
return new Chain<String>(U.trunc((String) item(), length));
}
public Chain<String> trimEnd(final String chars) {
return new Chain<String>(U.trimEnd((String) item(), chars));
}
public Chain<String> uncapitalize() {
return new Chain<String>(U.uncapitalize((String) item()));
}
public Chain<String> words() {
return new Chain<String>(U.words((String) item()));
}
public Chain<String> toJson() {
return new Chain<String>(U.toJson((Collection) value()));
}
public Chain<Object> fromJson() {
return new Chain<Object>(U.fromJson((String) item()));
}
public Chain<String> toXml() {
return new Chain<String>(U.toXml((Collection) value()));
}
public Chain<Object> fromXml() {
return new Chain<Object>(U.fromXml((String) item()));
}
public Chain<String> fetch() {
return new Chain<String>(U.fetch((String) item()).text());
}
public Chain<String> fetch(final String method, final String body) {
return new Chain<String>(U.fetch((String) item(), method, body).text());
}
@SuppressWarnings("unchecked")
public Chain<List<T>> createPermutationWithRepetition(final int permutationLength) {
return new Chain<List<T>>(U.createPermutationWithRepetition((List<T>) value(), permutationLength));
}
public Chain<String> toJsonJavaString() {
return new Chain<String>(U.toJsonJavaString((Collection) value()));
}
}
public static Chain<String> chain(final String item) {
return new U.Chain<String>(item);
}
public static <T> Chain<T> chain(final List<T> list) {
return new U.Chain<T>(list);
}
public static <T> Chain<T> chain(final Iterable<T> iterable) {
return new U.Chain<T>(newArrayList(iterable));
}
public static <T> Chain<T> chain(final Iterable<T> iterable, int size) {
return new U.Chain<T>(newArrayList(iterable, size));
}
@SuppressWarnings("unchecked")
public static <T> Chain<T> chain(final T ... list) {
return new U.Chain<T>(Arrays.asList(list));
}
public static Chain<Integer> chain(final int[] array) {
return new U.Chain<Integer>(newIntegerList(array));
}
public Chain<T> chain() {
return new U.Chain<T>(newArrayList(value()));
}
public static <T> List<T> drop(final Iterable<T> iterable) {
return rest(newArrayList(iterable));
}
public List<T> drop() {
return drop(getIterable());
}
public static <T> List<T> drop(final Iterable<T> iterable, final Integer n) {
return rest(newArrayList(iterable), n);
}
public List<T> drop(final Integer n) {
return drop(getIterable(), n);
}
public static <T> List<T> dropRight(final Iterable<T> iterable) {
return initial(newArrayList(iterable));
}
public List<T> dropRight() {
return dropRight(getIterable());
}
public static <T> List<T> dropRight(final Iterable<T> iterable, final Integer n) {
return initial(newArrayList(iterable), n);
}
public List<T> dropRight(final Integer n) {
return dropRight(getIterable(), n);
}
public static <T> List<T> dropWhile(final Iterable<T> iterable, final Predicate<T> pred) {
return rest(newArrayList(iterable), findIndex(newArrayList(iterable), negate(pred)));
}
public List<T> dropWhile(final Predicate<T> pred) {
return dropWhile(getIterable(), pred);
}
public static <T> List<T> dropRightWhile(final Iterable<T> iterable, final Predicate<T> pred) {
return reverse(dropWhile(reverse(iterable), pred));
}
public List<T> dropRightWhile(final Predicate<T> pred) {
return dropRightWhile(getIterable(), pred);
}
public static List<Object> fill(final List<Object> list, Object value) {
for (int index = 0; index < list.size(); index += 1) {
list.set(index, value);
}
return list;
}
@SuppressWarnings("unchecked")
public List<Object> fill(Object value) {
return fill((List<Object>) getIterable(), value);
}
public static List<Object> fill(final List<Object> list, Object value, Integer start, Integer end) {
for (int index = start; index < end; index += 1) {
list.set(index, value);
}
return list;
}
@SuppressWarnings("unchecked")
public List<Object> fill(Object value, Integer start, Integer end) {
return fill((List<Object>) getIterable(), value, start, end);
}
public static <E> List<E> flattenDeep(final List<?> list) {
return flatten(list, false);
}
public List<T> flattenDeep() {
return flattenDeep((List<?>) getIterable());
}
public static List<Object> pull(final List<Object> list, Object ... values) {
final List<Object> valuesList = Arrays.asList(values);
for (final Iterator<Object> iterator = list.iterator(); iterator.hasNext(); ) {
final Object object = iterator.next();
if (valuesList.contains(object)) {
iterator.remove();
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Object> pull(Object ... values) {
return pull((List<Object>) getIterable(), values);
}
public static List<Object> pullAt(final List<Object> list, final Integer ... indexes) {
final List<Object> result = newArrayList();
final List<Integer> indexesList = Arrays.asList(indexes);
int index = 0;
for (final Iterator<Object> iterator = list.iterator(); iterator.hasNext(); ) {
final Object object = iterator.next();
if (indexesList.contains(index)) {
result.add(object);
iterator.remove();
}
index += 1;
}
return result;
}
@SuppressWarnings("unchecked")
public List<Object> pullAt(final Integer ... indexes) {
return pullAt((List<Object>) getIterable(), indexes);
}
public static <T> List<T> remove(final List<T> list, final Predicate<T> pred) {
final List<T> result = newArrayList();
for (final Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {
final T object = iterator.next();
if (pred.test(object)) {
result.add(object);
iterator.remove();
}
}
return result;
}
public List<T> remove(final Predicate<T> pred) {
return remove((List<T>) getIterable(), pred);
}
public static <T> List<T> take(final Iterable<T> iterable) {
return first(newArrayList(iterable), 1);
}
public List<T> take() {
return take(getIterable());
}
public static <T> List<T> takeRight(final Iterable<T> iterable) {
return last(newArrayList(iterable), 1);
}
public List<T> takeRight() {
return takeRight(getIterable());
}
public static <T> List<T> take(final Iterable<T> iterable, final Integer n) {
return first(newArrayList(iterable), n);
}
public List<T> take(final Integer n) {
return take(getIterable(), n);
}
public static <T> List<T> takeRight(final Iterable<T> iterable, final Integer n) {
return last(newArrayList(iterable), n);
}
public List<T> takeRight(final Integer n) {
return takeRight(getIterable(), n);
}
public static <T> List<T> takeWhile(final Iterable<T> iterable, final Predicate<T> pred) {
return first(newArrayList(iterable), findIndex(newArrayList(iterable), negate(pred)));
}
public List<T> takeWhile(final Predicate<T> pred) {
return takeWhile(getIterable(), pred);
}
public static <T> List<T> takeRightWhile(final Iterable<T> iterable, final Predicate<T> pred) {
return reverse(takeWhile(reverse(iterable), pred));
}
public List<T> takeRightWhile(final Predicate<T> pred) {
return takeRightWhile(getIterable(), pred);
}
@SuppressWarnings("unchecked")
public static <T> List<T> xor(final List<T> ... lists) {
int index = -1;
int length = lists.length;
List<T> result = null;
while (++index < length) {
final List<T> array = lists[index];
result = result == null ? array : concat(difference(result, array), difference(array, result));
}
return uniq(result);
}
@SuppressWarnings("unchecked")
public List<T> xor(final List<T> list) {
return xor((List<T>) getIterable(), list);
}
public static <T> List<T> at(final List<T> list, final Integer ... indexes) {
final List<T> result = newArrayList();
final List<Integer> indexesList = Arrays.asList(indexes);
int index = 0;
for (final Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {
final T object = iterator.next();
if (indexesList.contains(index)) {
result.add(object);
}
index += 1;
}
return result;
}
public List<T> at(final Integer ... indexes) {
return at((List<T>) getIterable(), indexes);
}
public static <T extends Number> T sum(final Iterable<T> iterable) {
T result = null;
for (final T item : iterable) {
result = add(result, item);
}
return result;
}
public static <E, F extends Number> F sum(final Iterable<E> iterable, final Function<E, F> func) {
F result = null;
for (final E item : iterable) {
result = add(result, func.apply(item));
}
return result;
}
@SuppressWarnings("unchecked")
public <F extends Number> F sum() {
return sum((List<F>) getIterable());
}
@SuppressWarnings("unchecked")
public <E, F extends Number> F sum(final Function<E, F> func) {
return sum((List<E>) getIterable(), func);
}
@SuppressWarnings("unchecked")
public static <T extends Number> T add(final T first, final T second) {
if (first == null) {
return second;
} else if (second == null) {
return first;
} else if (first instanceof java.math.BigDecimal) {
return (T) sum((java.math.BigDecimal) first, (java.math.BigDecimal) second);
} else if (second instanceof java.math.BigInteger) {
return (T) sum((java.math.BigInteger) first, (java.math.BigInteger) second);
} else if (first instanceof Byte) {
return (T) sum((Byte) first, (Byte) second);
} else if (first instanceof Double) {
return (T) sum((Double) first, (Double) second);
} else if (first instanceof Float) {
return (T) sum((Float) first, (Float) second);
} else if (first instanceof Integer) {
return (T) sum((Integer) first, (Integer) second);
} else if (first instanceof Long) {
return (T) sum((Long) first, (Long) second);
} else if (first instanceof Short) {
return (T) sum((Short) first, (Short) second);
} else {
throw new UnsupportedOperationException("Sum only supports official subclasses of Number");
}
}
private static java.math.BigDecimal sum(java.math.BigDecimal first, java.math.BigDecimal second) {
return first.add(second);
}
private static java.math.BigInteger sum(java.math.BigInteger first, java.math.BigInteger second) {
return first.add(second);
}
private static Byte sum(Byte first, Byte second) {
return (byte) (first + second);
}
private static Double sum(Double first, Double second) {
return first + second;
}
private static Float sum(Float first, Float second) {
return first + second;
}
private static Integer sum(Integer first, Integer second) {
return first + second;
}
private static Long sum(Long first, Long second) {
return first + second;
}
private static Short sum(Short first, Short second) {
return (short) (first + second);
}
public static <T extends Number> double mean(final Iterable<T> iterable) {
T result = null;
int count = 0;
for (final T item : iterable) {
result = add(result, item);
count += 1;
}
if (result == null) {
return 0d;
}
return result.doubleValue() / count;
}
@SuppressWarnings("unchecked")
public double mean() {
return mean((Iterable<Number>) getIterable());
}
@SuppressWarnings("unchecked")
public static <T extends Number> double median(final Iterable<T> iterable) {
final List<T> result = newArrayList((Collection) iterable);
final int size = size(iterable);
if (size == 0) {
throw new IllegalArgumentException("Iterable cannot be empty");
}
if (size % 2 != 0) {
return result.get(size / 2).doubleValue();
}
return (result.get(size / 2 - 1).doubleValue() + result.get(size / 2).doubleValue()) / 2;
}
@SuppressWarnings("unchecked")
public double median() {
return median((Iterable<Number>) getIterable());
}
public static String camelCase(final String string) {
return createCompounder(new Function3<String, String, Integer, String>() {
public String apply(final String result, final String word, final Integer index) {
final String localWord = word.toLowerCase(Locale.getDefault());
return result + (index > 0 ? word.substring(0, 1).toUpperCase(Locale.getDefault())
+ word.substring(1) : localWord);
}
}).apply(string);
}
public static String lowerFirst(final String string) {
return createCaseFirst("toLowerCase").apply(string);
}
public static String upperFirst(final String string) {
return createCaseFirst("toUpperCase").apply(string);
}
public static String capitalize(final String string) {
return upperFirst(baseToString(string).toLowerCase());
}
public static String uncapitalize(final String string) {
return lowerFirst(baseToString(string).toLowerCase());
}
private static String baseToString(String value) {
return value == null ? "" : value;
}
public static String deburr(final String string) {
final String localString = baseToString(string);
final StringBuilder sb = new StringBuilder();
for (final String str : localString.split("")) {
if (RE_LATIN_1.matcher(str).matches()) {
sb.append(DEBURRED_LETTERS.get(str));
} else {
sb.append(str);
}
}
return sb.toString();
}
public static List<String> words(final String string) {
final String localString = baseToString(string);
final List<String> result = new ArrayList<String>();
final java.util.regex.Matcher matcher = reWords.matcher(localString);
while (matcher.find()) {
result.add(matcher.group());
}
return result;
}
private static Function<String, String> createCompounder(
final Function3<String, String, Integer, String> callback) {
return new Function<String, String>() {
public String apply(final String string) {
int index = -1;
List<String> array = words(deburr(string));
int length = array.size();
String result = "";
while (++index < length) {
result = callback.apply(result, array.get(index), index);
}
return result;
}
};
}
private static Function<String, String> createCaseFirst(final String methodName) {
return new Function<String, String>() {
public String apply(final String string) {
final String localString = baseToString(string);
final String chr = localString.isEmpty() ? "" : localString.substring(0, 1);
final String trailing = localString.length() > 1 ? localString.substring(1) : "";
return U.invoke(Arrays.asList(chr), methodName).get(0) + trailing;
}
};
}
public static boolean endsWith(final String string, final String target) {
return endsWith(string, target, null);
}
public static boolean endsWith(final String string, final String target, final Integer position) {
if (string == null || target == null) {
return false;
}
final String localString = baseToString(string);
final int length = localString.length();
final int localPosition = position == null ? length
: Math.min(position < 0 ? 0 : position, length);
final int localPosition2 = localPosition - target.length();
return localPosition2 >= 0 && localString.indexOf(target, localPosition2) == localPosition2;
}
public static String kebabCase(final String string) {
return createCompounder(new Function3<String, String, Integer, String>() {
public String apply(final String result, final String word, final Integer index) {
return result + (index > 0 ? "-" : "") + word.toLowerCase(Locale.getDefault());
}
}).apply(string);
}
public static String repeat(final String string, final int length) {
final StringBuilder result = new StringBuilder();
final StringBuilder localString = new StringBuilder(baseToString(string));
if (length < 1 || string == null) {
return result.toString();
}
int n = length;
do {
if (n % 2 != 0) {
result.append(localString);
}
n = (int) Math.floor(n / (double) 2);
localString.append(localString.toString());
} while (n > 0);
return result.toString();
}
private static String createPadding(final String string, final int length, final String chars) {
final int strLength = string.length();
final int padLength = length - strLength;
final String localChars = chars == null ? " " : chars;
return repeat(localChars, (int) Math.ceil(padLength / (double) localChars.length())).substring(0, padLength);
}
public static String pad(final String string, final int length) {
return pad(string, length, null);
}
public static String pad(final String string, final int length, final String chars) {
final String localString = baseToString(string);
final int strLength = localString.length();
if (strLength >= length) {
return localString;
}
final double mid = (length - strLength) / (double) 2;
final int leftLength = (int) Math.floor(mid);
final int rightLength = (int) Math.ceil(mid);
final String localChars = createPadding("", rightLength, chars);
return localChars.substring(0, leftLength) + localString + localChars;
}
private static Function3<String, Integer, String, String> createPadDir(final boolean fromRight) {
return new Function3<String, Integer, String, String>() {
public String apply(String string, Integer length, String chars) {
final String localString = baseToString(string);
return (fromRight ? localString : "") + createPadding(localString, length, chars)
+ (fromRight ? "" : localString);
}
};
}
public static String padStart(final String string, final Integer length) {
return createPadDir(false).apply(string, length, null);
}
public static String padStart(final String string, final Integer length, final String chars) {
return createPadDir(false).apply(string, length, chars);
}
public static String padEnd(final String string, final Integer length) {
return createPadDir(true).apply(string, length, null);
}
public static String padEnd(final String string, final Integer length, final String chars) {
return createPadDir(true).apply(string, length, chars);
}
public static String snakeCase(final String string) {
return createCompounder(new Function3<String, String, Integer, String>() {
public String apply(final String result, final String word, final Integer index) {
return result + (index > 0 ? "_" : "") + word.toLowerCase(Locale.getDefault());
}
}).apply(string);
}
public static String startCase(final String string) {
return createCompounder(new Function3<String, String, Integer, String>() {
public String apply(final String result, final String word, final Integer index) {
return result + (index > 0 ? " " : "") + word.substring(0, 1).toUpperCase(Locale.getDefault())
+ word.substring(1);
}
}).apply(string);
}
public static boolean startsWith(final String string, final String target) {
return startsWith(string, target, null);
}
public static boolean startsWith(final String string, final String target, final Integer position) {
if (string == null || target == null) {
return false;
}
final String localString = baseToString(string);
final int length = localString.length();
final int localPosition = position == null ? 0
: Math.min(position < 0 ? 0 : position, length);
return localString.lastIndexOf(target, localPosition) == localPosition;
}
private static int charsLeftIndex(final String string, final String chars) {
int index = 0;
final int length = string.length();
while (index < length && chars.indexOf(string.charAt(index)) > -1) {
index += 1;
}
return index == length ? -1 : index;
}
private static int charsRightIndex(final String string, final String chars) {
int index = string.length() - 1;
while (index >= 0 && chars.indexOf(string.charAt(index)) > -1) {
index -= 1;
}
return index;
}
public static String trim(final String string) {
return trim(string, null);
}
public static String trim(final String string, final String chars) {
final String localString = baseToString(string);
if (localString.isEmpty()) {
return localString;
}
final String localChars;
if (chars == null) {
localChars = " ";
} else {
localChars = chars;
}
final int leftIndex = charsLeftIndex(localString, localChars);
final int rightIndex = charsRightIndex(localString, localChars);
return leftIndex > -1 ? localString.substring(leftIndex, rightIndex + 1) : localString;
}
public static String trimStart(final String string) {
return trimStart(string, null);
}
public static String trimStart(final String string, final String chars) {
final String localString = baseToString(string);
if (localString.isEmpty()) {
return localString;
}
final String localChars;
if (chars == null) {
localChars = " ";
} else {
localChars = chars;
}
final int leftIndex = charsLeftIndex(localString, localChars);
return leftIndex > -1 ? localString.substring(leftIndex, localString.length()) : localString;
}
public static String trimEnd(final String string) {
return trimEnd(string, null);
}
public static String trimEnd(final String string, final String chars) {
final String localString = baseToString(string);
if (localString.isEmpty()) {
return localString;
}
final String localChars;
if (chars == null) {
localChars = " ";
} else {
localChars = chars;
}
final int rightIndex = charsRightIndex(localString, localChars);
return rightIndex > -1 ? localString.substring(0, rightIndex + 1) : localString;
}
public static String trunc(final String string) {
return trunc(string, DEFAULT_TRUNC_LENGTH);
}
public static String trunc(final String string, final Integer length) {
final String localString = baseToString(string);
final String omission = DEFAULT_TRUNC_OMISSION;
if (length >= localString.length()) {
return localString;
}
final int end = length - omission.length();
final String result = localString.substring(0, end);
return result + omission;
}
public static List<String> stringToPath(final String string) {
final List<String> result = new ArrayList<String>();
final java.util.regex.Matcher matcher = RE_PROP_NAME.matcher(baseToString(string));
while (matcher.find()) {
result.add(matcher.group(1) == null ? matcher.group(0) : matcher.group(1));
}
return result;
}
@SuppressWarnings("unchecked")
private static <T> T baseGet(final Map<String, Object> object, final String path) {
final List<String> paths = stringToPath(path);
int index = 0;
final int length = paths.size();
Object localObject = object;
while (localObject != null && index < length) {
if (localObject instanceof Map) {
localObject = ((Map) localObject).get(paths.get(index));
} else if (localObject instanceof List) {
localObject = ((List) localObject).get(Integer.parseInt(paths.get(index)));
} else {
break;
}
index += 1;
}
if (index > 0 && index == length) {
return (T) localObject;
}
return null;
}
public static <T> T get(final Map<String, Object> object, final String path) {
return baseGet(object, path);
}
public static class JsonStringBuilder {
private final StringBuilder builder;
private int ident;
public JsonStringBuilder() {
builder = new StringBuilder();
}
public JsonStringBuilder append(final char character) {
builder.append(character);
return this;
}
public JsonStringBuilder append(final String string) {
builder.append(string);
return this;
}
public JsonStringBuilder fillSpaces() {
for (int index = 0; index < ident; index += 1) {
builder.append(' ');
}
return this;
}
public JsonStringBuilder incIdent() {
ident += 2;
return this;
}
public JsonStringBuilder decIdent() {
ident -= 2;
return this;
}
public JsonStringBuilder newLine() {
builder.append("\n");
return this;
}
public String toString() {
return builder.toString();
}
}
public static class JsonArray {
public static void writeJson(Collection collection, JsonStringBuilder builder) {
if (collection == null) {
builder.append(NULL);
return;
}
Iterator iter = collection.iterator();
builder.append('[').incIdent().newLine();
while (iter.hasNext()) {
Object value = iter.next();
if (value == null) {
builder.fillSpaces().append(NULL);
continue;
}
builder.fillSpaces();
JsonValue.writeJson(value, builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIdent().fillSpaces().append(']');
}
public static void writeJson(byte[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(short[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(int[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(long[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(float[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(double[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(boolean[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(char[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append('\"').append(String.valueOf(array[0])).append('\"');
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append('\"').append(String.valueOf(array[i])).append('\"');
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(Object[] array, JsonStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').newLine().incIdent().fillSpaces();
JsonValue.writeJson(array[0], builder);
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
JsonValue.writeJson(array[i], builder);
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
}
public static class JsonObject {
public static void writeJson(Map map, JsonStringBuilder builder) {
if (map == null) {
builder.append(NULL);
return;
}
Iterator iter = map.entrySet().iterator();
builder.append('{').incIdent();
if (!map.isEmpty()) {
builder.newLine();
}
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
builder.fillSpaces().append('\"');
builder.append(JsonValue.unescapeName(String.valueOf(entry.getKey())));
builder.append('\"');
builder.append(':').append(' ');
JsonValue.writeJson(entry.getValue(), builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIdent().fillSpaces().append('}');
}
}
public static class JsonValue {
public static void writeJson(Object value, JsonStringBuilder builder) {
if (value == null) {
builder.append(NULL);
} else if (value instanceof String) {
builder.append('"').append(escape((String) value)).append('"');
} else if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Number) {
builder.append(value.toString());
} else if (value instanceof Boolean) {
builder.append(value.toString());
} else if (value instanceof Map) {
JsonObject.writeJson((Map) value, builder);
} else if (value instanceof Collection) {
JsonArray.writeJson((Collection) value, builder);
} else if (value instanceof byte[]) {
JsonArray.writeJson((byte[]) value, builder);
} else if (value instanceof short[]) {
JsonArray.writeJson((short[]) value, builder);
} else if (value instanceof int[]) {
JsonArray.writeJson((int[]) value, builder);
} else if (value instanceof long[]) {
JsonArray.writeJson((long[]) value, builder);
} else if (value instanceof float[]) {
JsonArray.writeJson((float[]) value, builder);
} else if (value instanceof double[]) {
JsonArray.writeJson((double[]) value, builder);
} else if (value instanceof boolean[]) {
JsonArray.writeJson((boolean[]) value, builder);
} else if (value instanceof char[]) {
JsonArray.writeJson((char[]) value, builder);
} else if (value instanceof Object[]) {
JsonArray.writeJson((Object[]) value, builder);
} else {
builder.append(value.toString());
}
}
public static String unescapeName(final String name) {
final int length = name.length();
if (length == 0 || "__EE__EMPTY__EE__".equals(name)) {
return "";
}
if ("-__EE__EMPTY__EE__".equals(name)) {
return "-";
}
StringBuilder result = new StringBuilder();
int underlineCount = 0;
StringBuilder lastChars = new StringBuilder();
outer:
for (int i = 0; i < length; ++i) {
char ch = name.charAt(i);
if (ch == '_') {
lastChars.append(ch);
} else {
if (lastChars.length() == 2) {
StringBuilder nameToDecode = new StringBuilder();
for (int j = i; j < length; ++j) {
if (name.charAt(j) == '_') {
underlineCount += 1;
if (underlineCount == 2) {
result.append(Base32.decode(nameToDecode.toString()));
i = j;
underlineCount = 0;
lastChars.setLength(0);
continue outer;
}
} else {
nameToDecode.append(name.charAt(j));
underlineCount = 0;
}
}
}
result.append(lastChars).append(ch);
lastChars.setLength(0);
}
}
return result.append(lastChars).toString();
}
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
}
private static void escape(String s, StringBuilder sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch <= '\u001F' || ch >= '\u007F' && ch <= '\u009F'
|| ch >= '\u2000' && ch <= '\u20FF') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
break;
}
}
}
}
public static String toJson(Collection collection) {
final JsonStringBuilder builder = new JsonStringBuilder();
JsonArray.writeJson(collection, builder);
return builder.toString();
}
public String toJson() {
return toJson((Collection) getIterable());
}
public static String toJson(Map map) {
final JsonStringBuilder builder = new JsonStringBuilder();
JsonObject.writeJson(map, builder);
return builder.toString();
}
public static class XmlStringBuilder {
protected final StringBuilder builder;
private int ident;
public XmlStringBuilder() {
builder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n");
ident = 2;
}
public XmlStringBuilder(StringBuilder builder, int ident) {
this.builder = builder;
this.ident = ident;
}
public XmlStringBuilder append(final String string) {
builder.append(string);
return this;
}
public XmlStringBuilder fillSpaces() {
for (int index = 0; index < ident; index += 1) {
builder.append(' ');
}
return this;
}
public XmlStringBuilder incIdent() {
ident += 2;
return this;
}
public XmlStringBuilder decIdent() {
ident -= 2;
return this;
}
public XmlStringBuilder newLine() {
builder.append("\n");
return this;
}
public int getIdent() {
return ident;
}
public String toString() {
return builder.toString() + "\n</root>";
}
}
public static class XmlStringBuilderWithoutRoot extends XmlStringBuilder {
public XmlStringBuilderWithoutRoot() {
super(new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"), 0);
}
public String toString() {
return builder.toString();
}
}
public static class XmlStringBuilderWithoutHeader extends XmlStringBuilder {
public XmlStringBuilderWithoutHeader(int ident) {
super(new StringBuilder(""), ident);
}
public String toString() {
return builder.toString();
}
}
public static class XmlArray {
public static void writeXml(Collection collection, String name, XmlStringBuilder builder,
boolean parentTextFound) {
if (collection == null) {
builder.append(NULL);
return;
}
if (name != null) {
builder.fillSpaces().append("<").append(name).append(">").incIdent();
if (!collection.isEmpty()) {
builder.newLine();
}
}
writeXml(collection, builder, name, parentTextFound);
if (name != null) {
builder.decIdent().newLine().fillSpaces().append("</").append(name).append(">");
}
}
private static void writeXml(Collection collection, XmlStringBuilder builder, String name,
boolean parentTextFound) {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
Object value = iter.next();
if (value == null) {
builder.fillSpaces().append("<" + (name == null ? "element" : name) + ">"
+ NULL + "</" + (name == null ? "element" : name) + ">");
} else {
XmlValue.writeXml(value, name == null ? "element" : name, builder, parentTextFound);
parentTextFound = false;
}
if (iter.hasNext()) {
builder.newLine();
}
}
}
public static void writeXml(byte[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(short[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(int[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(long[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(float[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(double[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(boolean[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(char[] array, XmlStringBuilder builder) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
builder.fillSpaces().append(ELEMENT);
builder.append(String.valueOf(array[i]));
builder.append(CLOSED_ELEMENT);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
public static void writeXml(Object[] array, String name, XmlStringBuilder builder, boolean parentTextFound) {
if (array == null) {
builder.fillSpaces().append(NULL_ELEMENT);
} else if (array.length == 0) {
builder.fillSpaces().append(EMPTY_ELEMENT);
} else {
for (int i = 0; i < array.length; i++) {
XmlValue.writeXml(array[i], name == null ? "element" : name, builder, parentTextFound);
if (i != array.length - 1) {
builder.newLine();
}
}
}
}
}
public static class XmlObject {
@SuppressWarnings("unchecked")
public static void writeXml(Map map, String name, XmlStringBuilder builder, boolean parentTextFound) {
if (map == null) {
XmlValue.writeXml(NULL, name, builder, false);
return;
}
List<XmlStringBuilder> elems = newArrayList();
List<XmlStringBuilder> textElems = newArrayList();
List<String> attrs = newArrayList();
int ident = builder.getIdent() + (name == null ? 0 : 2);
boolean textFoundSave = false;
List<Map.Entry> entries = newArrayList(map.entrySet());
for (int index = 0; index < entries.size(); index += 1) {
Map.Entry entry = entries.get(index);
final boolean addNewLine = index < entries.size() - 1
&& !"#text".equals(String.valueOf(entries.get(index + 1).getKey()));
if (String.valueOf(entry.getKey()).startsWith("-") && !(entry.getValue() instanceof Map)
&& !(entry.getValue() instanceof List)) {
attrs.add(" " + XmlValue.escapeName(String.valueOf(entry.getKey()).substring(1))
+ "=\"" + escape(String.valueOf(entry.getValue())) + "\"");
} else if ("#text".equals(escape(String.valueOf(entry.getKey())))) {
if (elems.isEmpty()) {
textFoundSave = true;
}
if (entry.getValue() instanceof List) {
for (Object value : (List) entry.getValue()) {
textElems.add(new XmlStringBuilderWithoutHeader(ident).append(escape((String) value)));
}
} else {
textElems.add(new XmlStringBuilderWithoutHeader(ident).append(
escape((String) entry.getValue())));
}
} else if ("#comment".equals(escape(String.valueOf(entry.getKey())))) {
addComment(entry, ident, addNewLine, elems, "");
} else if ("#cdata-section".equals(escape(String.valueOf(entry.getKey())))) {
addComment(entry, ident, addNewLine, elems, "<![CDATA[", "]]>");
} else if (entry.getValue() instanceof List && !((List) entry.getValue()).isEmpty()) {
XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(ident);
XmlArray.writeXml((List) entry.getValue(), localBuilder,
XmlValue.escapeName(String.valueOf(entry.getKey())), !textElems.isEmpty());
if (addNewLine) {
localBuilder.newLine();
}
if (!textElems.isEmpty()) {
elems.add(textElems.remove(0));
}
elems.add(localBuilder);
} else {
XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(ident);
XmlValue.writeXml(entry.getValue(),
XmlValue.escapeName(String.valueOf(entry.getKey())), localBuilder, !textElems.isEmpty());
if (!textElems.isEmpty()) {
elems.add(textElems.remove(0));
}
if (addNewLine && textElems.isEmpty()) {
localBuilder.newLine();
}
elems.add(localBuilder);
}
}
for (XmlStringBuilder localBuilder : textElems) {
elems.add(localBuilder);
}
if (name != null) {
if (!parentTextFound) {
builder.fillSpaces();
}
builder.append("<").append(name).append(U.join(attrs, "")).append(">").incIdent();
if (!textFoundSave && !elems.isEmpty()) {
builder.newLine();
}
}
for (XmlStringBuilder localBuilder : elems) {
builder.append(localBuilder.toString());
}
if (name != null) {
builder.decIdent();
if (textElems.isEmpty()) {
builder.newLine().fillSpaces();
}
builder.append("</").append(name).append(">");
}
}
private static void addComment(Map.Entry entry, int ident, boolean addNewLine,
List<XmlStringBuilder> elems, String openElement, String closeElement) {
if (entry.getValue() instanceof List) {
for (Iterator iterator = ((List) entry.getValue()).iterator(); iterator.hasNext(); ) {
addCommentValue(ident, (String) iterator.next(),
iterator.hasNext() || addNewLine, elems, openElement, closeElement);
}
} else {
addCommentValue(ident, (String) entry.getValue(), addNewLine, elems,
openElement, closeElement);
}
}
private static void addCommentValue(int ident, String value, boolean addNewLine,
List<XmlStringBuilder> elems, String openElement, String closeElement) {
XmlStringBuilder localBuilder = new XmlStringBuilderWithoutHeader(ident)
.fillSpaces().append(openElement).append(value).append(closeElement);
if (addNewLine) {
localBuilder.newLine();
}
elems.add(localBuilder);
}
}
public static class XmlValue {
public static void writeXml(Object value, String name, XmlStringBuilder builder, boolean parentTextFound) {
if (value instanceof Map) {
XmlObject.writeXml((Map) value, name, builder, parentTextFound);
return;
}
if (value instanceof Collection) {
XmlArray.writeXml((Collection) value, name, builder, parentTextFound);
return;
}
if (!parentTextFound) {
builder.fillSpaces();
}
builder.append("<" + name + ">");
if (value == null) {
builder.append(NULL);
} else if (value instanceof String) {
builder.append(escape((String) value));
} else if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Number) {
builder.append(value.toString());
} else if (value instanceof Boolean) {
builder.append(value.toString());
} else if (value instanceof byte[]) {
builder.newLine().incIdent();
XmlArray.writeXml((byte[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof short[]) {
builder.newLine().incIdent();
XmlArray.writeXml((short[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof int[]) {
builder.newLine().incIdent();
XmlArray.writeXml((int[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof long[]) {
builder.newLine().incIdent();
XmlArray.writeXml((long[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof float[]) {
builder.newLine().incIdent();
XmlArray.writeXml((float[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof double[]) {
builder.newLine().incIdent();
XmlArray.writeXml((double[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof boolean[]) {
builder.newLine().incIdent();
XmlArray.writeXml((boolean[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof char[]) {
builder.newLine().incIdent();
XmlArray.writeXml((char[]) value, builder);
builder.decIdent().newLine().fillSpaces();
} else if (value instanceof Object[]) {
builder.newLine().incIdent();
XmlArray.writeXml((Object[]) value, name, builder, parentTextFound);
builder.decIdent().newLine().fillSpaces();
} else {
builder.append(value.toString());
}
builder.append("</" + name + ">");
}
public static String escapeName(String name) {
final int length = name.length();
if (length == 0) {
return "__EE__EMPTY__EE__";
}
final StringBuilder result = new StringBuilder();
char ch = name.charAt(0);
if (com.sun.org.apache.xerces.internal.util.XMLChar.isNameStart(ch)) {
result.append(ch);
} else {
result.append("__").append(Base32.encode(Character.toString(ch))).append("__");
}
for (int i = 1; i < length; ++i) {
ch = name.charAt(i);
if (com.sun.org.apache.xerces.internal.util.XMLChar.isName(ch)) {
result.append(ch);
} else {
result.append("__").append(Base32.encode(Character.toString(ch))).append("__");
}
}
return result.toString();
}
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
}
private static void escape(String s, StringBuilder sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (ch <= '\u001F' || ch >= '\u007F' && ch <= '\u009F'
|| ch >= '\u2000' && ch <= '\u20FF') {
String ss = Integer.toHexString(ch);
sb.append("&
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase()).append(";");
} else {
sb.append(ch);
}
break;
}
}
}
}
public static String toXml(Collection collection) {
final XmlStringBuilder builder = new XmlStringBuilder();
XmlArray.writeXml(collection, null, builder, false);
return builder.toString();
}
public String toXml() {
return toXml((Collection) getIterable());
}
public static String toXml(Map map) {
final XmlStringBuilder builder = new XmlStringBuilderWithoutRoot();
if (map == null || map.size() != 1
|| ((String) ((Map.Entry) map.entrySet().iterator().next()).getKey()).startsWith("-")
|| ((Map.Entry) map.entrySet().iterator().next()).getValue() instanceof List) {
XmlObject.writeXml(map, "root", builder, false);
} else {
XmlObject.writeXml(map, null, builder, false);
}
return builder.toString();
}
public static class ParseException extends RuntimeException {
private final int offset;
private final int line;
private final int column;
public ParseException(String message, int offset, int line, int column) {
super(message + " at " + line + ":" + column);
this.offset = offset;
this.line = line;
this.column = column;
}
public int getOffset() {
return offset;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
}
public static class JsonParser {
private final String json;
private int index;
private int line;
private int lineOffset;
private int current;
private StringBuilder captureBuffer;
private int captureStart;
public JsonParser(String string) {
this.json = string;
line = 1;
captureStart = -1;
}
public Object parse() {
read();
skipWhiteSpace();
final Object result = readValue();
skipWhiteSpace();
if (!isEndOfText()) {
throw error("Unexpected character");
}
return result;
}
private Object readValue() {
switch (current) {
case 'n':
return readNull();
case 't':
return readTrue();
case 'f':
return readFalse();
case '"':
return readString();
case '[':
return readArray();
case '{':
return readObject();
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return readNumber();
default:
throw expected("value");
}
}
private List<Object> readArray() {
read();
List<Object> array = newArrayList();
skipWhiteSpace();
if (readChar(']')) {
return array;
}
do {
skipWhiteSpace();
array.add(readValue());
skipWhiteSpace();
} while (readChar(','));
if (!readChar(']')) {
throw expected("',' or ']'");
}
return array;
}
private Map<String, Object> readObject() {
read();
Map<String, Object> object = newLinkedHashMap();
skipWhiteSpace();
if (readChar('}')) {
return object;
}
do {
skipWhiteSpace();
String name = readName();
skipWhiteSpace();
if (!readChar(':')) {
throw expected("':'");
}
skipWhiteSpace();
object.put(name, readValue());
skipWhiteSpace();
} while (readChar(','));
if (!readChar('}')) {
throw expected("',' or '}'");
}
return object;
}
private String readName() {
if (current != '"') {
throw expected("name");
}
return readString();
}
private String readNull() {
read();
readRequiredChar('u');
readRequiredChar('l');
readRequiredChar('l');
return null;
}
private Boolean readTrue() {
read();
readRequiredChar('r');
readRequiredChar('u');
readRequiredChar('e');
return Boolean.TRUE;
}
private Boolean readFalse() {
read();
readRequiredChar('a');
readRequiredChar('l');
readRequiredChar('s');
readRequiredChar('e');
return Boolean.FALSE;
}
private void readRequiredChar(char ch) {
if (!readChar(ch)) {
throw expected("'" + ch + "'");
}
}
private String readString() {
read();
startCapture();
while (current != '"') {
if (current == '\\') {
pauseCapture();
readEscape();
startCapture();
} else if (current < 0x20) {
throw expected("valid string character");
} else {
read();
}
}
String string = endCapture();
read();
return string;
}
private void readEscape() {
read();
switch (current) {
case '"':
case '/':
case '\\':
captureBuffer.append((char) current);
break;
case 'b':
captureBuffer.append('\b');
break;
case 'f':
captureBuffer.append('\f');
break;
case 'n':
captureBuffer.append('\n');
break;
case 'r':
captureBuffer.append('\r');
break;
case 't':
captureBuffer.append('\t');
break;
case 'u':
char[] hexChars = new char[4];
boolean isHexCharsDigits = true;
for (int i = 0; i < 4; i++) {
read();
if (!isHexDigit()) {
isHexCharsDigits = false;
}
hexChars[i] = (char) current;
}
if (isHexCharsDigits) {
captureBuffer.append((char) Integer.parseInt(new String(hexChars), 16));
} else {
captureBuffer.append("\\u").append(hexChars[0]).append(hexChars[1]).append(hexChars[2])
.append(hexChars[3]);
}
break;
default:
throw expected("valid escape sequence");
}
read();
}
private Number readNumber() {
startCapture();
readChar('-');
int firstDigit = current;
if (!readDigit()) {
throw expected("digit");
}
if (firstDigit != '0') {
while (readDigit()) {
}
}
readFraction();
readExponent();
final String number = endCapture();
if (number.contains(".") || number.contains("e") || number.contains("E")) {
return Double.valueOf(number);
} else {
return Long.valueOf(number);
}
}
private boolean readFraction() {
if (!readChar('.')) {
return false;
}
if (!readDigit()) {
throw expected("digit");
}
while (readDigit()) {
}
return true;
}
private boolean readExponent() {
if (!readChar('e') && !readChar('E')) {
return false;
}
if (!readChar('+')) {
readChar('-');
}
if (!readDigit()) {
throw expected("digit");
}
while (readDigit()) {
}
return true;
}
private boolean readChar(char ch) {
if (current != ch) {
return false;
}
read();
return true;
}
private boolean readDigit() {
if (!isDigit()) {
return false;
}
read();
return true;
}
private void skipWhiteSpace() {
while (isWhiteSpace()) {
read();
}
}
private void read() {
if (index == json.length()) {
current = -1;
return;
}
if (current == '\n') {
line++;
lineOffset = index;
}
current = json.charAt(index++);
}
private void startCapture() {
if (captureBuffer == null) {
captureBuffer = new StringBuilder();
}
captureStart = index - 1;
}
private void pauseCapture() {
captureBuffer.append(json.substring(captureStart, index - 1));
captureStart = -1;
}
private String endCapture() {
int end = current == -1 ? index : index - 1;
String captured;
if (captureBuffer.length() > 0) {
captureBuffer.append(json.substring(captureStart, end));
captured = captureBuffer.toString();
captureBuffer.setLength(0);
} else {
captured = json.substring(captureStart, end);
}
captureStart = -1;
return captured;
}
private ParseException expected(String expected) {
if (isEndOfText()) {
return error("Unexpected end of input");
}
return error("Expected " + expected);
}
private ParseException error(String message) {
int absIndex = index;
int column = absIndex - lineOffset;
int offset = isEndOfText() ? absIndex : absIndex - 1;
return new ParseException(message, offset, line, column - 1);
}
private boolean isWhiteSpace() {
return current == ' ' || current == '\t' || current == '\n' || current == '\r';
}
private boolean isDigit() {
return current >= '0' && current <= '9';
}
private boolean isHexDigit() {
return isDigit() || current >= 'a' && current <= 'f' || current >= 'A'
&& current <= 'F';
}
private boolean isEndOfText() {
return current == -1;
}
}
public static Object fromJson(String string) {
return new JsonParser(string).parse();
}
public Object fromJson() {
return fromJson(getString().get());
}
@SuppressWarnings("unchecked")
private static Object getValue(final Object value) {
if (value instanceof Map && ((Map<String, Object>) value).entrySet().size() == 1) {
final Map.Entry<String, Object> entry = ((Map<String, Object>) value).entrySet().iterator().next();
if (entry.getKey().equals("#text") || entry.getKey().equals("element")) {
return entry.getValue();
}
}
return value;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> createMap(final org.w3c.dom.Node node,
final Function<Object, Object> nodeMapper, Map<String, Object> attrMap) {
final Map<String, Object> map = newLinkedHashMap();
map.putAll(attrMap);
final org.w3c.dom.NodeList nodeList = node.getChildNodes();
for (int index = 0; index < nodeList.getLength(); index++) {
final org.w3c.dom.Node currentNode = nodeList.item(index);
final String name = currentNode.getNodeName();
final Object value;
final int attributesLength = currentNode.getAttributes() == null
? 0 : currentNode.getAttributes().getLength();
if (currentNode.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
final Map<String, Object> attrMapLocal = newLinkedHashMap();
for (int indexAttr = 0; indexAttr < attributesLength; indexAttr += 1) {
final org.w3c.dom.Node currentNodeAttr = currentNode.getAttributes().item(indexAttr);
addNodeValue(attrMapLocal, '-' + currentNodeAttr.getNodeName(),
currentNodeAttr.getTextContent(), nodeMapper);
}
value = createMap(currentNode, nodeMapper, attrMapLocal);
} else {
value = currentNode.getTextContent();
}
if ("#text".equals(name) && value.toString().trim().isEmpty()) {
continue;
}
addNodeValue(map, name, value, nodeMapper);
}
return map;
}
@SuppressWarnings("unchecked")
private static void addNodeValue(final Map<String, Object> map, final String name, final Object value,
final Function<Object, Object> nodeMapper) {
if (map.containsKey(name)) {
final Object object = map.get(name);
if (object instanceof List) {
((List<Object>) object).add(getValue(value));
} else {
final List<Object> objects = newArrayList();
objects.add(object);
objects.add(getValue(value));
map.put(name, objects);
}
} else {
map.put(name, nodeMapper.apply(getValue(value)));
}
}
@SuppressWarnings("unchecked")
public static Object fromXml(final String xml) {
if (xml == null) {
return null;
}
try {
final java.io.InputStream stream = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8"));
final javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final org.w3c.dom.Document document = factory.newDocumentBuilder().parse(stream);
final Object result = createMap(document, new Function<Object, Object>() {
public Object apply(Object object) {
return object;
}
}, Collections.<String, Object>emptyMap());
if (((Map.Entry) ((Map) result).entrySet().iterator().next()).getKey().equals("root")
&& (((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue() instanceof List
|| ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue() instanceof Map)) {
return ((Map.Entry) ((Map) result).entrySet().iterator().next()).getValue();
}
return result;
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
public static Object fromXmlMakeArrays(final String xml) {
try {
final java.io.InputStream stream = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8"));
final javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final org.w3c.dom.Document document = factory.newDocumentBuilder().parse(stream);
return createMap(document, new Function<Object, Object>() {
public Object apply(Object object) {
return object instanceof List ? object : newArrayList(Arrays.asList(object));
}
}, Collections.<String, Object>emptyMap());
} catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
public Object fromXml() {
return fromXml(getString().get());
}
public static class JsonJavaStringBuilder {
private final StringBuilder builder;
private int ident;
public JsonJavaStringBuilder() {
builder = new StringBuilder("\"");
}
public JsonJavaStringBuilder append(final char character) {
builder.append(character);
return this;
}
public JsonJavaStringBuilder append(final String string) {
builder.append(string);
return this;
}
public JsonJavaStringBuilder fillSpaces() {
for (int index = 0; index < ident; index += 1) {
builder.append(' ');
}
return this;
}
public JsonJavaStringBuilder incIdent() {
ident += 2;
return this;
}
public JsonJavaStringBuilder decIdent() {
ident -= 2;
return this;
}
public JsonJavaStringBuilder newLine() {
builder.append("\\n\"\n + \"");
return this;
}
public String toString() {
return builder.toString() + "\";";
}
}
public static class JsonJavaArray {
public static void writeJson(Collection collection, JsonJavaStringBuilder builder) {
if (collection == null) {
builder.append(NULL);
return;
}
Iterator iter = collection.iterator();
builder.append('[').incIdent().newLine();
while (iter.hasNext()) {
Object value = iter.next();
if (value == null) {
builder.fillSpaces().append(NULL);
continue;
}
builder.fillSpaces();
JsonJavaValue.writeJson(value, builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIdent().fillSpaces().append(']');
}
public static void writeJson(byte[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(short[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(int[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(long[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(float[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(double[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(boolean[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append(String.valueOf(array[i]));
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(char[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').incIdent().newLine();
builder.fillSpaces().append('\"').append(String.valueOf(array[0])).append('\"');
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
builder.append('\"').append(String.valueOf(array[i])).append('\"');
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
public static void writeJson(Object[] array, JsonJavaStringBuilder builder) {
if (array == null) {
builder.append(NULL);
} else if (array.length == 0) {
builder.append("[]");
} else {
builder.append('[').newLine().incIdent().fillSpaces();
JsonJavaValue.writeJson(array[0], builder);
for (int i = 1; i < array.length; i++) {
builder.append(',').newLine().fillSpaces();
JsonJavaValue.writeJson(array[i], builder);
}
builder.newLine().decIdent().fillSpaces().append(']');
}
}
}
public static class JsonJavaObject {
public static void writeJson(Map map, JsonJavaStringBuilder builder) {
if (map == null) {
builder.append(NULL);
return;
}
Iterator iter = map.entrySet().iterator();
builder.append('{').newLine().incIdent();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
builder.fillSpaces().append("\\\"");
builder.append(escape(String.valueOf(entry.getKey())));
builder.append("\\\"");
builder.append(':').append(' ');
JsonJavaValue.writeJson(entry.getValue(), builder);
if (iter.hasNext()) {
builder.append(',').newLine();
}
}
builder.newLine().decIdent().fillSpaces().append('}');
}
}
public static class JsonJavaValue {
public static void writeJson(Object value, JsonJavaStringBuilder builder) {
if (value == null) {
builder.append(NULL);
} else if (value instanceof String) {
builder.append("\\\"").append(escape((String) value)).append("\\\"");
} else if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
builder.append(NULL);
} else {
builder.append(value.toString());
}
} else if (value instanceof Number) {
builder.append(value.toString());
} else if (value instanceof Boolean) {
builder.append(value.toString());
} else if (value instanceof Map) {
JsonJavaObject.writeJson((Map) value, builder);
} else if (value instanceof Collection) {
JsonJavaArray.writeJson((Collection) value, builder);
} else if (value instanceof byte[]) {
JsonJavaArray.writeJson((byte[]) value, builder);
} else if (value instanceof short[]) {
JsonJavaArray.writeJson((short[]) value, builder);
} else if (value instanceof int[]) {
JsonJavaArray.writeJson((int[]) value, builder);
} else if (value instanceof long[]) {
JsonJavaArray.writeJson((long[]) value, builder);
} else if (value instanceof float[]) {
JsonJavaArray.writeJson((float[]) value, builder);
} else if (value instanceof double[]) {
JsonJavaArray.writeJson((double[]) value, builder);
} else if (value instanceof boolean[]) {
JsonJavaArray.writeJson((boolean[]) value, builder);
} else if (value instanceof char[]) {
JsonJavaArray.writeJson((char[]) value, builder);
} else if (value instanceof Object[]) {
JsonJavaArray.writeJson((Object[]) value, builder);
} else {
builder.append(value.toString());
}
}
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
}
private static void escape(String s, StringBuilder sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch <= '\u001F' || ch >= '\u007F' && ch <= '\u009F'
|| ch >= '\u2000' && ch <= '\u20FF') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
break;
}
}
}
}
public static String toJsonJavaString(Collection collection) {
final JsonJavaStringBuilder builder = new JsonJavaStringBuilder();
JsonJavaArray.writeJson(collection, builder);
return builder.toString();
}
public String toJsonJavaString() {
return toJsonJavaString((Collection) getIterable());
}
public static String toJsonJavaString(Map map) {
final JsonJavaStringBuilder builder = new JsonJavaStringBuilder();
JsonJavaObject.writeJson(map, builder);
return builder.toString();
}
public static class FetchResponse {
private final boolean ok;
private final int status;
private final Map<String, List<String>> headerFields;
private final java.io.ByteArrayOutputStream stream;
public FetchResponse(final boolean ok, final int status, final Map<String, List<String>> headerFields,
final java.io.ByteArrayOutputStream stream) {
this.ok = ok;
this.status = status;
this.stream = stream;
this.headerFields = headerFields;
}
public boolean isOk() {
return ok;
}
public int getStatus() {
return status;
}
public Map<String, List<String>> getHeaderFields() {
return headerFields;
}
public byte[] blob() {
return stream.toByteArray();
}
public String text() {
try {
return stream.toString("UTF-8");
} catch (java.io.UnsupportedEncodingException ex) {
throw new UnsupportedOperationException(ex);
}
}
public Object json() {
return U.fromJson(text());
}
public Object xml() {
return U.fromXml(text());
}
}
public static FetchResponse fetch(final String url) {
return fetch(url, null, null, DEFAULT_HEADER_FIELDS, null, null);
}
public static FetchResponse fetch(final String url, final Integer connectTimeout, final Integer readTimeout) {
return fetch(url, null, null, DEFAULT_HEADER_FIELDS, connectTimeout, readTimeout);
}
public static FetchResponse fetch(final String url, final String method, final String body) {
return fetch(url, method, body, DEFAULT_HEADER_FIELDS, null, null);
}
private static class BaseHttpSSLSocketFactory extends javax.net.ssl.SSLSocketFactory {
private javax.net.ssl.SSLContext getSSLContext() {
return createEasySSLContext();
}
@Override
public java.net.Socket createSocket(java.net.InetAddress arg0, int arg1, java.net.InetAddress arg2,
int arg3) throws java.io.IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}
@Override
public java.net.Socket createSocket(String arg0, int arg1, java.net.InetAddress arg2, int arg3)
throws java.io.IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}
@Override
public java.net.Socket createSocket(java.net.InetAddress arg0, int arg1) throws java.io.IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}
@Override
public java.net.Socket createSocket(String arg0, int arg1) throws java.io.IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}
@Override
public String[] getSupportedCipherSuites() {
return null;
}
@Override
public String[] getDefaultCipherSuites() {
return null;
}
@Override
public java.net.Socket createSocket(java.net.Socket arg0, String arg1, int arg2, boolean arg3)
throws java.io.IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}
private javax.net.ssl.SSLContext createEasySSLContext() {
try {
javax.net.ssl.SSLContext context = javax.net.ssl.SSLContext.getInstance("SSL");
context.init(null, new javax.net.ssl.TrustManager[] { MyX509TrustManager.manger }, null);
return context;
} catch (Exception ex) {
throw new UnsupportedOperationException(ex);
}
}
public static class MyX509TrustManager implements javax.net.ssl.X509TrustManager {
static MyX509TrustManager manger = new MyX509TrustManager();
public MyX509TrustManager() {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
}
}
static class NoHostnameVerifier implements javax.net.ssl.HostnameVerifier {
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return true;
}
}
private static void setupConnection(final java.net.HttpURLConnection connection, final String method,
final Map<String, List<String>> headerFields, final Integer connectTimeout, final Integer readTimeout)
throws java.io.IOException {
final String localMethod;
if (SUPPORTED_HTTP_METHODS.contains(method)) {
localMethod = method;
} else {
localMethod = "GET";
}
connection.setRequestMethod(localMethod);
if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
}
if (readTimeout != null) {
connection.setReadTimeout(readTimeout);
}
if (connection instanceof javax.net.ssl.HttpsURLConnection) {
((javax.net.ssl.HttpsURLConnection) connection).setSSLSocketFactory(new BaseHttpSSLSocketFactory());
((javax.net.ssl.HttpsURLConnection) connection).setHostnameVerifier(new NoHostnameVerifier());
}
if (headerFields != null) {
for (final Map.Entry<String, List<String>> header : headerFields.entrySet()) {
connection.setRequestProperty(header.getKey(), join(header.getValue(), ";"));
}
}
}
public static FetchResponse fetch(final String url, final String method, final String body,
final Map<String, List<String>> headerFields, final Integer connectTimeout, final Integer readTimeout) {
try {
final java.net.URL localUrl = new java.net.URL(url);
final java.net.HttpURLConnection connection = (java.net.HttpURLConnection) localUrl.openConnection();
setupConnection(connection, method, headerFields, connectTimeout, readTimeout);
if (body != null) {
connection.setDoOutput(true);
final java.io.DataOutputStream outputStream =
new java.io.DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(body);
outputStream.close();
}
final int responseCode = connection.getResponseCode();
final java.io.InputStream inputStream;
if (responseCode < RESPONSE_CODE_400) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
final java.io.ByteArrayOutputStream result = new java.io.ByteArrayOutputStream();
final byte[] buffer = new byte[BUFFER_LENGTH_1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
inputStream.close();
return new FetchResponse(responseCode < RESPONSE_CODE_400, responseCode, connection.getHeaderFields(),
result);
} catch (java.io.IOException ex) {
throw new UnsupportedOperationException(ex);
}
}
public String camelCase() {
return camelCase(getString().get());
}
public String lowerFirst() {
return lowerFirst(getString().get());
}
public String upperFirst() {
return upperFirst(getString().get());
}
public String capitalize() {
return capitalize(getString().get());
}
public String deburr() {
return deburr(getString().get());
}
public boolean endsWith(final String target) {
return endsWith(getString().get(), target);
}
public boolean endsWith(final String target, final Integer position) {
return endsWith(getString().get(), target, position);
}
public String kebabCase() {
return kebabCase(getString().get());
}
public String repeat(final int length) {
return repeat(getString().get(), length);
}
public String pad(final int length) {
return pad(getString().get(), length);
}
public String pad(final int length, final String chars) {
return pad(getString().get(), length, chars);
}
public String padStart(final int length) {
return padStart(getString().get(), length);
}
public String padStart(final int length, final String chars) {
return padStart(getString().get(), length, chars);
}
public String padEnd(final int length) {
return padEnd(getString().get(), length);
}
public String padEnd(final int length, final String chars) {
return padEnd(getString().get(), length, chars);
}
public String snakeCase() {
return snakeCase(getString().get());
}
public String startCase() {
return startCase(getString().get());
}
public boolean startsWith(final String target) {
return startsWith(getString().get(), target);
}
public boolean startsWith(final String target, final Integer position) {
return startsWith(getString().get(), target, position);
}
public String trim() {
return trim(getString().get());
}
public String trimWith(final String chars) {
return trim(getString().get(), chars);
}
public String trimStart() {
return trimStart(getString().get());
}
public String trimStartWith(final String chars) {
return trimStart(getString().get(), chars);
}
public String trimEnd() {
return trimEnd(getString().get());
}
public String trimEndWith(final String chars) {
return trimEnd(getString().get(), chars);
}
public String trunc() {
return trunc(getString().get());
}
public String trunc(final int length) {
return trunc(getString().get(), length);
}
public String uncapitalize() {
return uncapitalize(getString().get());
}
public List<String> words() {
return words(getString().get());
}
public static class LRUCache<K, V> {
private static final boolean SORT_BY_ACCESS = true;
private static final float LOAD_FACTOR = 0.75F;
private final Map<K, V> lruCacheMap;
private final int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
this.lruCacheMap = new LinkedHashMap<K, V>(capacity, LOAD_FACTOR, SORT_BY_ACCESS);
}
public V get(K key) {
return lruCacheMap.get(key);
}
public void put(K key, V value) {
if (lruCacheMap.containsKey(key)) {
lruCacheMap.remove(key);
} else if (lruCacheMap.size() >= capacity) {
lruCacheMap.remove(lruCacheMap.keySet().iterator().next());
}
lruCacheMap.put(key, value);
}
}
public static <K, V> LRUCache<K, V> createLRUCache(final int capacity) {
return new LRUCache<K, V>(capacity);
}
public static <T> List<List<T>> createPermutationWithRepetition(final List<T> list, final int permutationLength) {
final long resultSize = (long) Math.pow(list.size(), permutationLength);
final List<List<T>> result = new ArrayList<List<T>>((int) resultSize);
final int[] bitVector = new int[permutationLength];
for (int index = 0; index < resultSize; index += 1) {
List<T> result2 = new ArrayList<T>(permutationLength);
for (int index2 = 0; index2 < permutationLength; index2 += 1) {
result2.add(list.get(bitVector[index2]));
}
int index3 = 0;
while (index3 < permutationLength && bitVector[index3] == list.size() - 1) {
bitVector[index3] = 0;
index3 += 1;
}
if (index3 < permutationLength) {
bitVector[index3] += 1;
}
result.add(result2);
}
return result;
}
@SuppressWarnings("unchecked")
public List<List<T>> createPermutationWithRepetition(final int permutationLength) {
return createPermutationWithRepetition((List<T>) value(), permutationLength);
}
@SuppressWarnings("unchecked")
public static String jsonToXml(String json) {
Object result = fromJson(json);
if (result instanceof Map) {
return toXml((Map) result);
}
return toXml((List) result);
}
@SuppressWarnings("unchecked")
public static String xmlToJson(String xml) {
Object result = fromXml(xml);
if (result instanceof Map) {
return toJson((Map) result);
}
return toJson((List) result);
}
}
|
package com.insidecoding.opium.rest.api;
import java.io.IOException;
import javax.validation.constraints.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.insidecoding.opium.entity.OpiumCallResponse;
import com.insidecoding.opium.rest.api.service.RemoteExecutionService;
@Controller
public class DeviceHandleController {
private static final Logger LOG = LoggerFactory.getLogger(DeviceHandleController.class);
@Autowired
private RemoteExecutionService remoteExec;
@CrossOrigin
@RequestMapping(value = "/execute", method = RequestMethod.DELETE, consumes = "application/json")
public ResponseEntity<String> stop(@RequestBody @Validated OpiumCommand opiumCmd) {
LOG.info("Got command: " + opiumCmd);
ResponseEntity<String> response = null;
try {
OpiumCallResponse opiumResp = this.remoteExec.stop(opiumCmd.ip, opiumCmd.command);
response = new ResponseEntity<String>(opiumResp.getResponseBody(), opiumResp.getStatusCode());
} catch (IOException e) {
LOG.error("Command not executed: " + opiumCmd, e);
response = new ResponseEntity<String>("Error while stopping appium: " + e.getMessage(),
HttpStatus.BAD_REQUEST);
}
return response;
}
@CrossOrigin
@RequestMapping(value = "/execute", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<String> execute(@RequestBody @Validated OpiumCommand opiumCmd) {
LOG.info("Got command: " + opiumCmd);
ResponseEntity<String> response = null;
try {
OpiumCallResponse opiumResp = this.remoteExec.start(opiumCmd.ip, opiumCmd.command);
response = new ResponseEntity<String>(opiumResp.getResponseBody(), opiumResp.getStatusCode());
} catch (IOException e) {
LOG.error("Command not executed: " + opiumCmd, e);
response = new ResponseEntity<String>("Error while starting appium: " + e.getMessage(),
HttpStatus.BAD_REQUEST);
}
return response;
}
static class OpiumCommand {
@Pattern(regexp = "[\\w.]+")
private String ip;
@Pattern(regexp = "[\\w]+")
private String deviceHash;
@Pattern(regexp = "[\\w\\-\\w ]+")
private String command;
@JsonCreator
public OpiumCommand(@JsonProperty("ip") String ip,
@JsonProperty("deviceHash") String deviceHash, @JsonProperty("command") String command) {
this.ip = ip;
this.deviceHash = deviceHash;
this.command = command;
}
@Override
public String toString() {
return "OpiumCommand [ip=" + ip + ", deviceHash=" + deviceHash + ", command=" + command + "]";
}
}
}
|
package org.safehaus.subutai.plugin.cassandra.impl;
import java.util.HashSet;
import java.util.Set;
import org.safehaus.subutai.common.enums.OutputRedirection;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.settings.Common;
import org.safehaus.subutai.common.util.AgentUtil;
import org.safehaus.subutai.core.command.api.command.AgentRequestBuilder;
import org.safehaus.subutai.core.command.api.command.Command;
import org.safehaus.subutai.core.command.api.command.CommandRunnerBase;
import org.safehaus.subutai.core.command.api.command.RequestBuilder;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
public class Commands
{
public static final String PACKAGE_NAME = Common.PACKAGE_PREFIX + "cassandra";
private final CommandRunnerBase commandRunner;
public Commands( CommandRunnerBase commandRunner )
{
Preconditions.checkNotNull( commandRunner, "Command Runner is null" );
this.commandRunner = commandRunner;
}
public Command getInstallCommand( Set<Agent> agents )
{
return commandRunner.createCommand(
new RequestBuilder( "apt-get --force-yes --assume-yes install " + PACKAGE_NAME ).withTimeout( 360 )
.withStdOutRedirection(
OutputRedirection.NO ),
agents );
}
public Command getStartCommand( Set<Agent> agents )
{
return commandRunner.createCommand( new RequestBuilder( "service cassandra start" ), agents );
}
public Command getStopCommand( Set<Agent> agents )
{
return commandRunner.createCommand( new RequestBuilder( "service cassandra stop" ), agents );
}
public Command getStatusCommand( Set<Agent> agents )
{
return commandRunner.createCommand( new RequestBuilder( "service cassandra status" ), agents );
}
public Command getStatusCommand( Agent agent )
{
return commandRunner
.createCommand( new RequestBuilder( "/etc/init.d/cassandra status" ), Sets.newHashSet( agent ) );
}
public Command getConfigureCommand( Set<Agent> agents, String param )
{
return commandRunner.createCommand( new RequestBuilder(
String.format( ". /etc/profile && $CASSANDRA_HOME/bin/cassandra-conf.sh %s", param ) ),
agents );
}
public Command getConfigureRpcAndListenAddressesCommand( Set<Agent> agents, String param )
{
Set<AgentRequestBuilder> sarb = new HashSet<AgentRequestBuilder>();
for ( Agent agent : agents )
{
AgentRequestBuilder arb = new AgentRequestBuilder( agent,
String.format( ". /etc/profile && $CASSANDRA_HOME/bin/cassandra-conf.sh %s %s", param,
AgentUtil.getAgentIpByMask( agent, Common.IP_MASK ) ) );
sarb.add( arb );
}
return commandRunner.createCommand( sarb );
}
}
|
package com.lassekoskela.maven.buildevents;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.time.Duration;
class BuildEventLogReport {
private final Logger logger;
private final List<BuildStep> steps;
public BuildEventLogReport(Logger logger) {
this(logger, new ArrayList<BuildStep>());
}
public BuildEventLogReport(Logger logger, List<BuildStep> steps) {
this.logger = logger;
this.steps = steps;
}
public void report() {
String currentPhase = "";
long totalDuration = totalDuration();
logger.info("
for (BuildStep buildStep : steps) {
reportBuildStep(currentPhase, buildStep, totalDuration);
currentPhase = buildStep.phase;
}
}
private void reportBuildStep(String currentPhase, BuildStep buildStep,
long totalDuration) {
String phase = buildStep.phase;
long phaseDuration = totalDurationOfPhase(phase);
long percentageOfPhase = (long) buildStep.duration().percentageOf(
phaseDuration);
if (phase != null && !phase.equals(currentPhase)) {
reportPhaseStatistics(phase, totalDuration, phaseDuration);
}
reportGoalStatistics(buildStep, percentageOfPhase);
}
private void reportGoalStatistics(BuildStep buildStep, long percentage) {
String goal = buildStep.artifactId + ":" + buildStep.goal;
double seconds = buildStep.duration().inSeconds();
logger.info(format(" %-48s %7.1fs %3s%% ", goal, seconds, percentage));
}
private void reportPhaseStatistics(String phase, long totalDuration,
long totalDurationOfPhase) {
Duration phaseDuration = new Duration(totalDurationOfPhase);
long percentage = (long) phaseDuration.percentageOf(totalDuration);
double seconds = phaseDuration.inSeconds();
logger.info(format("%-50s %7.1fs %3s%%]", "[" + phase, seconds,
percentage));
}
public long totalDurationOfPhase(String phase) {
long total = 0;
for (BuildStep e : steps) {
if (phase != null && phase.equals(e.phase)) {
total += e.duration().inMillis();
}
}
return total;
}
public long totalDuration() {
long totalDuration = 0;
for (BuildStep e : steps) {
totalDuration += e.duration().inMillis();
}
return totalDuration;
}
public void add(List<BuildStep> steps) {
this.steps.addAll(steps);
}
}
|
package com.jaamsim.BasicObjects;
import java.util.ArrayList;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.Samples.SampleConstant;
import com.jaamsim.Samples.SampleExpInput;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.datatypes.DoubleVector;
import com.jaamsim.events.EventHandle;
import com.jaamsim.events.EventManager;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.TimeUnit;
public class Queue extends LinkedComponent {
@Keyword(description = "The priority for positioning the received entity in the queue.\n" +
"Priority is integer valued and a lower numerical value indicates a higher priority.\n" +
"For example, priority 3 is higher than 4, and priorities 3, 3.2, and 3.8 are equivalent.",
example = "Queue1 Priority { this.obj.Attrib1 }")
private final SampleExpInput priority;
@Keyword(description = "An expression that returns a dimensionless integer value that can be used to "
+ "match entities in separate queues. The expression is evaluated when the entity "
+ "first arrives at the queue. Since Match is integer valued, a value of 3.2 for one "
+ "queue and 3.6 for another queue are considered to be equal.",
example = "Queue1 Match { this.obj.Attrib1 }")
private final SampleExpInput match;
@Keyword(description = "Determines the order in which entities are placed in the queue (FIFO or LIFO):\n" +
"TRUE = first in first out (FIFO) order (the default setting)," +
"FALSE = last in first out (LIFO) order.",
example = "Queue1 FIFO { FALSE }")
private final BooleanInput fifo;
@Keyword(description = "The amount of graphical space shown between DisplayEntity objects in the queue.",
example = "Queue1 Spacing { 1 m }")
private final ValueInput spacing;
@Keyword(description = "The number of queuing entities in each row.",
example = "Queue1 MaxPerLine { 4 }")
protected final IntegerInput maxPerLine; // maximum items per sub line-up of queue
protected ArrayList<QueueEntry> itemList;
private final ArrayList<QueueUser> userList; // other objects that use this queue
// Statistics
protected double timeOfLastUpdate; // time at which the statistics were last updated
protected double startOfStatisticsCollection; // time at which statistics collection was started
protected int minElements; // minimum observed number of entities in the queue
protected int maxElements; // maximum observed number of entities in the queue
protected double elementSeconds; // total time that entities have spent in the queue
protected double squaredElementSeconds; // total time for the square of the number of elements in the queue
protected DoubleVector queueLengthDist; // entry at position n is the total time the queue has had length n
{
testEntity.setHidden(true);
nextComponent.setHidden(true);
priority = new SampleExpInput("Priority", "Key Inputs", new SampleConstant(0));
priority.setUnitType(DimensionlessUnit.class);
priority.setEntity(this);
priority.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(priority);
match = new SampleExpInput("Match", "Key Inputs", new SampleConstant(0));
match.setUnitType(DimensionlessUnit.class);
match.setEntity(this);
this.addInput(match);
fifo = new BooleanInput("FIFO", "Key Inputs", true);
this.addInput(fifo);
spacing = new ValueInput("Spacing", "Key Inputs", 0.0d);
spacing.setUnitType(DistanceUnit.class);
spacing.setValidRange(0.0d, Double.POSITIVE_INFINITY);
this.addInput(spacing);
maxPerLine = new IntegerInput("MaxPerLine", "Key Inputs", Integer.MAX_VALUE);
maxPerLine.setValidRange(1, Integer.MAX_VALUE);
this.addInput(maxPerLine);
}
@Override
public void validate() {
super.validate();
priority.validate();
}
public Queue() {
itemList = new ArrayList<>();
queueLengthDist = new DoubleVector(10,10);
userList = new ArrayList<>();
}
@Override
public void earlyInit() {
super.earlyInit();
// Clear the entries in the queue
itemList.clear();
// Clear statistics
this.clearStatistics();
// Identify the objects that use this queue
userList.clear();
for (Entity each : Entity.getAll()) {
if (each instanceof QueueUser) {
QueueUser u = (QueueUser)each;
if (u.getQueues().contains(this))
userList.add(u);
}
}
}
private static class QueueEntry {
DisplayEntity entity;
double timeAdded;
int priority;
int match;
}
private final DoQueueChanged userUpdate = new DoQueueChanged(this);
private final EventHandle userUpdateHandle = new EventHandle();
private static class DoQueueChanged extends ProcessTarget {
private final Queue queue;
public DoQueueChanged(Queue q) {
queue = q;
}
@Override
public void process() {
for (QueueUser each : queue.userList)
each.queueChanged();
}
@Override
public String getDescription() {
return queue.getName() + ".UpdateAllQueueUsers";
}
}
// QUEUE HANDLING METHODS
@Override
public void addEntity(DisplayEntity ent) {
super.addEntity(ent);
// Determine the entity's priority and match values
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
// Insert the entity in the correct position in the queue
// FIFO ordering
int pos = 0;
if (fifo.getValue()) {
for (int i=itemList.size()-1; i>=0; i
if (itemList.get(i).priority <= pri) {
pos = i+1;
break;
}
}
}
// LIFO ordering
else {
pos = itemList.size();
for (int i=0; i<itemList.size(); i++) {
if (itemList.get(i).priority >= pri) {
pos = i;
break;
}
}
}
this.add(pos, ent, pri, mtch);
// Notify the users of this queue
if (!userUpdateHandle.isScheduled())
EventManager.scheduleTicks(0, 2, false, userUpdate, userUpdateHandle);
}
/**
* Inserts the specified element at the specified position in this Queue.
* Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
*/
private void add(int i, DisplayEntity ent, int pri, int mtch) {
int queueSize = itemList.size(); // present number of entities in the queue
this.updateStatistics(queueSize, queueSize+1);
QueueEntry entry = new QueueEntry();
entry.entity = ent;
entry.timeAdded = this.getSimTime();
entry.priority = pri;
entry.match = mtch;
itemList.add(i, entry);
}
public void add(int i, DisplayEntity ent) {
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
this.add(i, ent, pri, mtch);
}
/**
* Add an entity to the end of the queue
*/
public void addLast(DisplayEntity ent) {
int pri = (int) priority.getValue().getNextSample(getSimTime());
int mtch = (int) match.getValue().getNextSample(getSimTime());
this.add(itemList.size(), ent, pri, mtch);
}
/**
* Removes the entity at the specified position in the queue
*/
public DisplayEntity remove(int i) {
if (i >= itemList.size() || i < 0)
error("Index: %d is beyond the end of the queue.", i);
int queueSize = itemList.size(); // present number of entities in the queue
this.updateStatistics(queueSize, queueSize-1);
QueueEntry entry = itemList.remove(i);
DisplayEntity ent = entry.entity;
this.incrementNumberProcessed();
return ent;
}
/**
* Removes the first entity from the queue
*/
public DisplayEntity removeFirst() {
return this.remove(0);
}
/**
* Returns the first entity in the queue.
* @return first entity in the queue.
*/
public DisplayEntity getFirst() {
return itemList.get(0).entity;
}
/**
* Number of entities in the queue
*/
public int getCount() {
return itemList.size();
}
/**
* Returns the number of seconds spent by the first object in the queue
*/
public double getQueueTime() {
return this.getSimTime() - itemList.get(0).timeAdded;
}
/**
* Update the position of all entities in the queue. ASSUME that entities
* will line up according to the orientation of the queue.
*/
@Override
public void updateGraphics(double simTime) {
Vec3d queueOrientation = getOrientation();
Vec3d qSize = this.getSize();
Vec3d tmp = new Vec3d();
double distanceX = 0.5d * qSize.x;
double distanceY = 0;
double maxWidth = 0;
// find widest vessel
if (itemList.size() > maxPerLine.getValue()){
for (QueueEntry entry : itemList) {
maxWidth = Math.max(maxWidth, entry.entity.getSize().y);
}
}
// update item locations
for (int i = 0; i < itemList.size(); i++) {
// if new row is required, set reset distanceX and move distanceY up one row
if( i > 0 && i % maxPerLine.getValue() == 0 ){
distanceX = 0.5d * qSize.x;
distanceY += spacing.getValue() + maxWidth;
}
DisplayEntity item = itemList.get(i).entity;
// Rotate each transporter about its center so it points to the right direction
item.setOrientation(queueOrientation);
Vec3d itemSize = item.getSize();
distanceX += spacing.getValue() + 0.5d * itemSize.x;
tmp.set3(-distanceX / qSize.x, distanceY/qSize.y, 0.0d);
// increment total distance
distanceX += 0.5d * itemSize.x;
// Set Position
Vec3d itemCenter = this.getGlobalPositionForAlignment(tmp);
item.setGlobalPositionForAlignment(new Vec3d(), itemCenter);
}
}
// STATISTICS
/**
* Clear queue statistics
*/
@Override
public void clearStatistics() {
double simTime = this.getSimTime();
startOfStatisticsCollection = simTime;
timeOfLastUpdate = simTime;
minElements = itemList.size();
maxElements = itemList.size();
elementSeconds = 0.0;
squaredElementSeconds = 0.0;
queueLengthDist.clear();
}
private void updateStatistics(int oldValue, int newValue) {
minElements = Math.min(newValue, minElements);
maxElements = Math.max(newValue, maxElements);
// Add the necessary number of additional bins to the queue length distribution
int n = newValue + 1 - queueLengthDist.size();
for (int i = 0; i < n; i++) {
queueLengthDist.add(0.0);
}
double simTime = this.getSimTime();
double dt = simTime - timeOfLastUpdate;
if (dt > 0.0) {
elementSeconds += dt * oldValue;
squaredElementSeconds += dt * oldValue * oldValue;
queueLengthDist.addAt(dt,oldValue); // add dt to the entry at index queueSize
timeOfLastUpdate = simTime;
}
}
// OUTPUT METHODS
@Output(name = "QueueLength",
description = "The present number of entities in the queue.",
unitType = DimensionlessUnit.class)
public double getQueueLength(double simTime) {
return itemList.size();
}
@Output(name = "QueueLengthAverage",
description = "The average number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthAverage(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
return (elementSeconds + dt*queueSize)/totalTime;
}
return 0.0;
}
@Output(name = "QueueLengthStandardDeviation",
description = "The standard deviation of the number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public double getQueueLengthStandardDeviation(double simTime) {
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double mean = this.getQueueLengthAverage(simTime);
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
return Math.sqrt( (squaredElementSeconds + dt*queueSize*queueSize)/totalTime - mean*mean );
}
return 0.0;
}
@Output(name = "QueueLengthMinimum",
description = "The minimum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMinimum(double simTime) {
return minElements;
}
@Output(name = "QueueLengthMaximum",
description = "The maximum number of entities in the queue.",
unitType = DimensionlessUnit.class,
reportable = true)
public Integer getQueueLengthMaximum(double simTime) {
// An entity that is added to an empty queue and removed immediately
// does not count as a non-zero queue length
if (maxElements == 1 && queueLengthDist.get(1) == 0.0)
return 0;
return maxElements;
}
@Output(name = "QueueLengthDistribution",
description = "The fraction of time that the queue has length 0, 1, 2, etc.",
unitType = DimensionlessUnit.class,
reportable = true)
public DoubleVector getQueueLengthDistribution(double simTime) {
DoubleVector ret = new DoubleVector(queueLengthDist);
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
double totalTime = simTime - startOfStatisticsCollection;
if (totalTime > 0.0) {
if (ret.size() == 0)
ret.add(0.0);
ret.addAt(dt, queueSize); // adds dt to the entry at index queueSize
for (int i = 0; i < ret.size(); i++) {
ret.set(i, ret.get(i)/totalTime);
}
}
else {
ret.clear();
}
return ret;
}
@Output(name = "AverageQueueTime",
description = "The average time each entity waits in the queue. Calculated as total queue time to date divided " +
"by the total number of entities added to the queue.",
unitType = TimeUnit.class,
reportable = true)
public double getAverageQueueTime(double simTime) {
int n = this.getNumberAdded();
if (n == 0)
return 0.0;
double dt = simTime - timeOfLastUpdate;
int queueSize = itemList.size();
return (elementSeconds + dt*queueSize)/n;
}
}
|
package com.nhn.pinpoint.testweb.controller;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ArcusClient;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import perftest.LevelManager;
import com.nhn.pinpoint.testweb.service.MemberService;
import com.nhn.pinpoint.testweb.util.HttpConnectorOptions;
import com.nhn.pinpoint.testweb.util.HttpInvoker;
import com.nhncorp.lucy.net.invoker.InvocationFuture;
import com.nhncorp.lucy.npc.connector.NpcHessianConnector;
@Controller
public class AllInOneController implements DisposableBean {
private final ArcusClient arcus;
private final MemcachedClient memcached;
private final LevelManager levelManager;
public AllInOneController() throws IOException {
arcus = ArcusClient.createArcusClient("dev.arcuscloud.nhncorp.com:17288", "dev", new ConnectionFactoryBuilder());
memcached = new MemcachedClient(AddrUtil.getAddresses("10.25.149.80:11244,10.25.149.80:11211,10.25.149.79:11211"));
levelManager = new LevelManager();
}
@Autowired
private MemberService service;
private void arcus() {
int rand = new Random().nextInt(100);
String key = "pinpoint:testkey-" + rand;
Future<Object> getFuture = null;
try {
getFuture = arcus.asyncGet(key);
getFuture.get(1000L, TimeUnit.MILLISECONDS);
} catch (Exception e) {
if (getFuture != null)
getFuture.cancel(true);
}
}
private void memcached() {
int rand = new Random().nextInt(100);
String key = "pinpoint:testkey-" + rand;
Future<Object> getFuture = null;
try {
getFuture = memcached.asyncGet(key);
getFuture.get(1000L, TimeUnit.MILLISECONDS);
} catch (Exception e) {
if (getFuture != null)
getFuture.cancel(true);
}
}
private void mysql() {
service.list();
}
private void npc() {
try {
InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1", 5000);
NpcHessianConnector connector = new NpcHessianConnector(serverAddress, true);
Map<String, Object> params = new HashMap<String, Object>();
params.put("message", "hello pinpoint");
InvocationFuture future = connector.invoke("welcome/com.nhncorp.lucy.bloc.welcome.EchoBO", "execute", params);
future.await();
Object result = future.get();
System.out.println("npc result=" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
private void nested() {
HttpInvoker client2 = new HttpInvoker(new HttpConnectorOptions());
client2.execute("http://localhost:8080/donothing.pinpoint", new HashMap<String, Object>());
}
private void unknown() {
try {
HttpInvoker client = new HttpInvoker(new HttpConnectorOptions());
client.execute("http:
client.execute("http:
client.execute("http://very.very.very.long.long.url/", new HashMap<String, Object>());
client.execute("http://url1/", new HashMap<String, Object>());
client.execute("http://url2/", new HashMap<String, Object>());
client.execute("http://url2/", new HashMap<String, Object>());
client.execute("http://url3/", new HashMap<String, Object>());
client.execute("http://url3/", new HashMap<String, Object>());
client.execute("http://url3/", new HashMap<String, Object>());
} catch (Exception e) {
}
}
@RequestMapping(value = "/allInOne2")
public String allInOne2(Model model,
@RequestParam(value = "arcus2", required = false, defaultValue = "true") boolean arcus2,
@RequestParam(value = "memcached2", required = false, defaultValue = "false") boolean memcached2,
@RequestParam(value = "mysql2", required = false, defaultValue = "false") boolean mysql2,
@RequestParam(value = "npc2", required = false, defaultValue = "false") boolean npc2,
@RequestParam(value = "unknown2", required = false, defaultValue = "false") boolean unknown2) {
if (arcus2) arcus();
if (memcached2) memcached();
if (mysql2) mysql();
if (npc2) npc();
if (unknown2) unknown();
return "remotecombination";
}
@RequestMapping(value = "/allInOne")
public String allInOne(Model model,
@RequestParam(value = "arcus", required = false, defaultValue = "true") boolean arcus,
@RequestParam(value = "memcached", required = false, defaultValue = "false") boolean memcached,
@RequestParam(value = "mysql", required = false, defaultValue = "false") boolean mysql,
@RequestParam(value = "npc", required = false, defaultValue = "false") boolean npc,
@RequestParam(value = "unknown", required = false, defaultValue = "false") boolean unknown,
@RequestParam(value = "nested", required = false, defaultValue = "true") boolean nested,
@RequestParam(value = "arcus2", required = false, defaultValue = "true") boolean arcus2,
@RequestParam(value = "memcached2", required = false, defaultValue = "true") boolean memcached2,
@RequestParam(value = "mysql2", required = false, defaultValue = "true") boolean mysql2,
@RequestParam(value = "npc2", required = false, defaultValue = "true") boolean npc2,
@RequestParam(value = "unknown2", required = false, defaultValue = "true") boolean unknown2,
@RequestParam(value = "remote", required = false, defaultValue = "true") boolean remote,
@RequestParam(value = "randomRemotePort", required = false, defaultValue = "false") boolean randomRemotePort) {
if (arcus) arcus();
if (memcached) memcached();
if (mysql) mysql();
if (npc) npc();
if (unknown) unknown();
if (nested) nested();
if (remote) {
String[] ports = new String[] { "9080", "10080", "11080" };
Random random = new Random();
String port = (randomRemotePort) ? ports[random.nextInt(3)] : ports[0];
HttpInvoker client = new HttpInvoker(new HttpConnectorOptions());
StringBuilder params = new StringBuilder();
params.append("arcus2=").append(arcus2).append("&");
params.append("memcached2=").append(memcached2).append("&");
params.append("mysql2=").append(mysql2).append("&");
params.append("npc2=").append(npc2).append("&");
params.append("unknown2=").append(unknown2).append("&");
client.execute("http://localhost:" + port + "/allInOne2.pinpoint?" + params.toString(), new HashMap<String, Object>());
}
return "remotecombination";
}
@Override
public void destroy() throws Exception {
arcus.shutdown();
memcached.shutdown();
}
}
|
package polyglot.types;
import java.io.File;
import polyglot.frontend.*;
import polyglot.frontend.Compiler;
import polyglot.frontend.goals.Goal;
import polyglot.main.Report;
import polyglot.types.reflect.*;
import polyglot.util.InternalCompilerError;
/**
* Loads class information from source files, class files, or serialized
* class infomation from within class files. An outline of the steps is
* given below.
*
* <ol>
* <li> When the polyglot translator looks for a class by the name
* "foo.bar.Quux" it first searches for that class in any file given
* on the command line. If the class is found one of these files, then
* this definition is used and the remainder of the steps are
* skipped.
*
* <li>If none of these files contain the desired class, then the source
* path is searched next. For example, if the source extension is
* ".jl" and the source path is "mydir:." then the translator looks
* for files "mydir/foo/bar/Quux.jl" and "./foo/bar/Quux.jl".
*
* <li> Regardless of whether or not a source file is found, the translator
* searches the classpath (defined as normal through the environment
* and command-line options to the interpreter) for the desired class.
*
* <li>If no source file exists, and no class is found then an error is
* reported (skipping the rest of the steps below).
*
* <li>If a source file is found, but no class, then the source file is
* parsed. If it contains the desired class definition (which it
* should) then that definition is used and the remainder of the steps
* are skipped. (If it does not contain this definition, an error is
* reported and the remainder of the steps are skipped.
*
* <li>If a class is found but no source file, then the class is examined
* for jlc class type information. If the class contains no class type
* information (this is the case if the class file was compiled from
* raw Java source rather than jlc translated output) then this class
* is used as the desired class definition (skipping all steps below).
*
* <li>(class, but no still no source) If the class does contain jlc class
* type information, then the version number of translator used to
* translate the source which created the given class file is compared
* against the version of the current instantiation of the translator.
* If the versions are compatible, then the jlc class type information
* is used as the desired definiton. If the versions are incompatible
* (see the documentation in Compiler.java) then an error is reported.
* In either case, all remaining steps are skipped.
*
* <li>If both a suitable source file and class are found then we have a
* choice. If the class definition does not contain jlc class type
* information then the source file is parsed as the definition found
* in this file is used as desired definiton and we stop here. If the
* class does contain jlc class type information, then continue.
*
* <li>(source and class with jlc info) Next the last modification date of
* the source file is compared to the last modification date of the
* source file used to generate the class file. If the source file is
* more recent, the it is parsed as used as the desired definition and
* all remaining steps are skipped.
*
* <li>(source and class with jlc info) Next the jlc version of the class
* and of the current translator are compared (as in 7.). If the
* verisions are incompatible, then we use the definition from the
* parsed source file. If the versions are compatible, then we use
* the definition given by the jlc class type information.
* </ol>
* Finally, if at any point an error occurs while reading jlc class type
* information (e.g. if this information exists but is corrupted), then
* an error is reported.
*/
public class SourceClassResolver extends LoadedClassResolver
{
protected Compiler compiler;
protected ExtensionInfo ext;
protected boolean compileCommandLineOnly;
protected boolean ignoreModTimes;
/**
* Create a loaded class resolver.
* @param compiler The compiler.
* @param ext The extension to load sources for.
* @param classpath The class path.
* @param loader The class file loader to use.
* @param allowRawClasses True if vanilla Java class files without
* Polyglot-embedded type information should be
* allowed.
* @param compileCommandLineOnly TODO
* @param ignoreModTimes TODO
*/
public SourceClassResolver(Compiler compiler, ExtensionInfo ext,
String classpath, ClassFileLoader loader,
boolean allowRawClasses,
boolean compileCommandLineOnly, boolean ignoreModTimes)
{
super(ext.typeSystem(), classpath, loader, ext.version(), allowRawClasses);
this.compiler = compiler;
this.ext = ext;
this.compileCommandLineOnly = compileCommandLineOnly;
this.ignoreModTimes = ignoreModTimes;
}
public boolean packageExists(String name) {
if (super.packageExists(name)) {
return true;
}
/*
if (ext.sourceLoader().packageExists(name)) {
return true;
}
*/
return false;
}
/**
* Find a type by name.
*/
public Named find(String name) throws SemanticException {
if (Report.should_report(report_topics, 3))
Report.report(3, "SourceCR.find(" + name + ")");
ClassFile clazz = null;
ClassFile encodedClazz = null;
FileSource source = null;
// First try the class file.
clazz = loadFile(name);
if (clazz != null) {
// Check for encoded type information.
if (clazz.encodedClassType(version.name()) != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Class " + name + " has encoded type info");
encodedClazz = clazz;
}
if (encodedClazz != null &&
!name.replace(".", File.separator).equals(encodedClazz.name())) {
if (Report.should_report(report_topics, 3))
Report.report(3, "Not using " + encodedClazz.name() + "(case-insensitive filesystem?)");
encodedClazz = null;
clazz = null;
}
}
// Now, try and find the source file.
source = ext.sourceLoader().classSource(name);
// Check if a job for the source already exists.
if (ext.scheduler().sourceHasJob(source)) {
// the source has already been compiled; what are we doing here?
return getTypeFromSource(source, name);
}
if (Report.should_report(report_topics, 4)) {
if (source == null)
Report.report(4, "Class " + name + " not found in source file");
else
Report.report(4, "Class " + name + " found in source " + source);
}
// Don't use the raw class if the source or encoded class is available.
if (encodedClazz != null || source != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Not using raw class file for " + name);
clazz = null;
}
// If both the source and encoded class are available, we decide which to
// use based on compiler compatibility and modification times.
if (encodedClazz != null && source != null) {
long classModTime = encodedClazz.sourceLastModified(version.name());
long sourceModTime = source.lastModified().getTime();
int comp = checkCompilerVersion(encodedClazz.compilerVersion(version.name()));
if (! ignoreModTimes && classModTime < sourceModTime) {
if (Report.should_report(report_topics, 3))
Report.report(3, "Source file version is newer than compiled for " +
name + ".");
encodedClazz = null;
}
else if (comp != COMPATIBLE) {
// Incompatible or older version, so go with the source.
if (Report.should_report(report_topics, 3))
Report.report(3, "Incompatible source file version for " + name + ".");
encodedClazz = null;
}
}
Named result = null;
if (encodedClazz != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using encoded class type for " + name);
try {
result = getEncodedType(encodedClazz, name);
}
catch (BadSerializationException e) {
throw e;
}
catch (SemanticException e) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Could not load encoded class " + name);
encodedClazz = null;
}
}
// At this point, at most one of clazz and source should be set.
if (result == null && clazz != null && this.allowRawClasses) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using raw class file for " + name);
result = ts.classFileLazyClassInitializer(clazz).type();
}
if (result == null && source != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using source file for " + name);
result = getTypeFromSource(source, name);
}
// Verify that the type we loaded has the right name. This prevents,
// for example, requesting a type through its mangled (class file) name.
if (result != null) {
return result;
// if (name.equals(result.fullName())) {
// return result;
// if (result instanceof ClassType && name.equals(ts.getTransformedClassName((ClassType) result))) {
// return result;
}
if (clazz != null && !this.allowRawClasses) {
// We have a raw class only. We do not have the source code,
// or encoded class information.
throw new SemanticException("Class \"" + name + "\" not found."
+ " A class file was found at " + clazz.getClassFileLocation()
+ ", but it did not contain appropriate"
+ " information for the Polyglot-based compiler " +
ext.compilerName() + ". Try using " + ext.compilerName()
+ " to recompile the source code.");
}
throw new NoClassException(name);
}
/**
* Get a type from a source file.
*/
protected Named getTypeFromSource(FileSource source, String name)
throws SemanticException
{
Scheduler scheduler = ext.scheduler();
Job job = scheduler.loadSource(source, ! compileCommandLineOnly);
if (Report.should_report("sourceloader", 3))
new Exception("loaded " + source).printStackTrace();
if (job != null) {
Named n = ts.systemResolver().check(name);
if (n != null) {
return n;
}
Goal g = scheduler.TypesInitialized(job);
if (! scheduler.reached(g)) {
throw new MissingDependencyException(g);
}
}
// The source has already been compiled, but the type was not created there.
throw new NoClassException(name, "Could not find \"" + name + "\" in " + source + ".");
}
}
|
package com.bbn.bue.common.collections;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.util.Comparator;
import java.util.Map;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Guava's {@link com.google.common.collect.ImmutableMap.Builder} disallows adding the same key
* twice, even with the same value. In many situations this is inconvenient, so this interface
* is the parent of builders which relax this constraint in various ways.
* See
* {@link MapUtils#immutableMapBuilderAllowingSameEntryTwice()},
* {@link MapUtils#immutableMapBuilderIgnoringDuplicates()}, and
* {@link MapUtils#immutableMapBuilderResolvingDuplicatesBy(Comparator)}.
*
*
* You might think that this is unnecessary because you can simply build your map using e.g.
* a {@link java.util.HashMap} and then call {@link ImmutableMap#copyOf(Iterable)}, but that loses
* {@link ImmutableMap.Builder}'s very nice determinism guarantees.
*
* These builders are generally less efficient than {@link ImmutableMap.Builder}, so
* be cautious using them in performance-sensitive code.
*/
public interface LaxImmutableMapBuilder<K,V> {
LaxImmutableMapBuilder<K,V> put(K key, V value);
LaxImmutableMapBuilder<K,V> putAll(Map<? extends K, ? extends V> map);
LaxImmutableMapBuilder<K, V> putAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries);
/**
* See {@link ImmutableMap.Builder#orderEntriesByValue(Comparator)}
*/
LaxImmutableMapBuilder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator);
ImmutableMap<K,V> build();
}
/**
* Implementation for {@link LaxImmutableMapBuilder}s which never need to change their mind.
*/
final class MonotonicLaxImmutableMapBuilder<K,V> implements LaxImmutableMapBuilder<K,V> {
private final Map<K, V> mappingsSeen = Maps.newHashMap();
private final ImmutableMap.Builder<K, V> innerBuilder = ImmutableMap.builder();
private final boolean keepFirst;
MonotonicLaxImmutableMapBuilder(final boolean keepFirst) {
this.keepFirst = keepFirst;
}
public LaxImmutableMapBuilder<K, V> put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
final V existingMapping = mappingsSeen.get(key);
if (null == existingMapping) {
mappingsSeen.put(key, value);
innerBuilder.put(key, value);
} else if (existingMapping.equals(value)) {
// do nothing
} else if (keepFirst) {
// do nothing, we have been requested to silently keep the first value
} else {
throw new IllegalArgumentException("Refusing to add two mappings for the key "
+ key + ": " + existingMapping + " and " + value);
}
return this;
}
public LaxImmutableMapBuilder<K,V> putAll(Map<? extends K, ? extends V> map) {
for (final Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
return this;
}
public LaxImmutableMapBuilder<K, V> putAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
for (final Map.Entry<? extends K, ? extends V> e : entries) {
put(e.getKey(), e.getValue());
}
return this;
}
/**
* See {@link ImmutableMap.Builder#orderEntriesByValue(Comparator)}
*/
public LaxImmutableMapBuilder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
innerBuilder.orderEntriesByValue(valueComparator);
return this;
}
public ImmutableMap<K,V> build() {
return innerBuilder.build();
}
}
/**
* Implementation for {@link LaxImmutableMapBuilder}s which do need to change their mind.
*/
final class NonMonotonicLaxImmutableMapBuilder<K,V> implements LaxImmutableMapBuilder<K,V> {
private final ImmutableSet.Builder<K> orderKeysSeenIn = ImmutableSet.builder();
private final Map<K,V> mappingsSeen = Maps.newHashMap();
private final Ordering<? super V> conflictComparator;
private @Nullable Comparator<? super V> immutableMapEntryOrdering = null;
NonMonotonicLaxImmutableMapBuilder(final Ordering<? super V> conflictComparator) {
this.conflictComparator = checkNotNull(conflictComparator);
}
public LaxImmutableMapBuilder<K,V> put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
final V existingMapping = mappingsSeen.get(key);
if (null == existingMapping) {
mappingsSeen.put(key, value);
orderKeysSeenIn.add(key);
} else if (existingMapping.equals(value)) {
// do nothing
} else {
// add only if new value is larger by the provided comparator
if (conflictComparator.max(existingMapping, value).equals(value)) {
mappingsSeen.put(key, value);
}
}
return this;
}
public LaxImmutableMapBuilder<K,V> putAll(Map<? extends K, ? extends V> map) {
for (final Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
return this;
}
public LaxImmutableMapBuilder<K, V> putAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) {
for (final Map.Entry<? extends K, ? extends V> e : entries) {
put(e.getKey(), e.getValue());
}
return this;
}
/**
* See {@link ImmutableMap.Builder#orderEntriesByValue(Comparator)}
*/
public LaxImmutableMapBuilder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
this.immutableMapEntryOrdering = checkNotNull(valueComparator);
return this;
}
public ImmutableMap<K,V> build() {
final ImmutableMap.Builder<K, V> ret = ImmutableMap.builder();
if (immutableMapEntryOrdering != null) {
ret.orderEntriesByValue(immutableMapEntryOrdering);
}
for (final K key : orderKeysSeenIn.build()) {
ret.put(key, mappingsSeen.get(key));
}
return ret.build();
}
}
|
package com.jcabi.log;
import com.jcabi.aspects.Immutable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
@Immutable
@ToString
@EqualsAndHashCode(callSuper = false)
@SuppressWarnings("PMD.NonStaticInitializer")
public final class MulticolorLayout extends PatternLayout {
/**
* Control sequence indicator.
*/
private static final String CSI = "\u001b[";
/**
* Colors with names.
*/
private static final ConcurrentMap<String, String> COLORS =
new ConcurrentHashMap<String, String>() {
private static final long serialVersionUID = 0x7526EF78EEDFE465L;
{
this.put("black", "30");
this.put("blue", "34");
this.put("cyan", "36");
this.put("green", "32");
this.put("magenta", "35");
this.put("red", "31");
this.put("yellow", "33");
this.put("white", "37");
}
};
/**
* Colors of levels.
*/
private static final ConcurrentMap<Level, String> LEVELS =
new ConcurrentHashMap<Level, String>() {
private static final long serialVersionUID = 0x7526FF78EEDFC465L;
{
this.put(Level.TRACE, "2;33");
this.put(Level.DEBUG, "2;37");
this.put(Level.INFO, "0;37");
this.put(Level.WARN, "0;33");
this.put(Level.ERROR, "0;31");
this.put(Level.FATAL, "0;35");
}
};
/**
* Regular expression for all matches.
*/
private static final Pattern METAS = Pattern.compile(
"%color(?:-([a-z]+|[0-9]{1,3};[0-9]{1,3};[0-9]{1,3}))?\\{(.*?)\\}"
);
/**
* {@inheritDoc}
*/
@Override
public void setConversionPattern(final String pattern) {
final Matcher matcher = MulticolorLayout.METAS.matcher(pattern);
final StringBuffer buf = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buf, "");
buf.append(MulticolorLayout.CSI)
.append(this.ansi(matcher.group(1)))
.append('m')
.append(matcher.group(2))
.append(MulticolorLayout.CSI)
.append('m');
}
matcher.appendTail(buf);
super.setConversionPattern(buf.toString());
}
/**
* {@inheritDoc}
*/
@Override
public String format(final LoggingEvent event) {
return super.format(event).replace(
String.format("%s?m", MulticolorLayout.CSI),
String.format(
"%s%sm",
MulticolorLayout.CSI,
MulticolorLayout.LEVELS.get(event.getLevel())
)
);
}
/**
* Convert our text to ANSI color.
* @param meta Meta text
* @return ANSI color
*/
private String ansi(final String meta) {
String ansi;
if (meta == null) {
ansi = "?";
} else if (meta.matches("[a-z]+")) {
ansi = MulticolorLayout.COLORS.get(meta);
if (ansi == null) {
throw new IllegalArgumentException(
String.format("unknown color '%s'", meta)
);
}
} else {
ansi = meta;
}
return ansi;
}
}
|
package com.samovich.cop2800.chapter7.assignment;
import javax.swing.JOptionPane;
public class PasswordInput {
/**
* Main method
* @param args
*/
public static void main(String[] args) {
// declare fields
String password;
// prompt a user to type password
password = JOptionPane.showInputDialog(
null,
"Please enter your password",
"Password",
JOptionPane.QUESTION_MESSAGE);
// validate the password
if (PasswordChecker.checkPassword(password)) {
// display valid message
JOptionPane.showMessageDialog(
null,
"Password is valid!",
"Password Check Result",
JOptionPane.INFORMATION_MESSAGE);
} else {
// display error message
JOptionPane.showMessageDialog(
null,
"Password is invalid!\n" +
"Password must contain a uppercase letter, \n" +
"a lowercase letter, a number, a special character,\n" +
"and be 8 characters or longer with no spaces.",
"Password Check Result",
JOptionPane.ERROR_MESSAGE);
}
}
}
|
package net.katsuster.semu;
import java.util.*;
/**
* ARMv5TE CPU
*
* : ARM Second Edition
* ARM DDI0100DJ
*
* ARM DDI0100HJ, ARM DDI0100I
*
* T Thumb
* E DSP
*
*
* @author katsuhiro
*/
public class ARMv5 extends CPU {
private int[] regs;
private int[] regs_svc;
private int[] regs_abt;
private int[] regs_und;
private int[] regs_irq;
private int[] regs_fiq;
private int cpsr;
private CoProc[] coProcs;
private MMUv5 mmu;
private INTC intcIRQ;
private INTC intcFIQ;
private boolean exceptions[];
private String exceptionReasons[];
private boolean raised;
private boolean jumped;
private boolean highVector;
public ARMv5() {
CoProcVFPv2 cpVfps;
CoProcStdv5 cpStd;
cpVfps = new CoProcVFPv2(10, this);
cpStd = new CoProcStdv5(15, this);
regs = new int[17];
regs_svc = new int[17];
regs_abt = new int[17];
regs_und = new int[17];
regs_irq = new int[17];
regs_fiq = new int[17];
coProcs = new CoProc[16];
coProcs[10] = cpVfps;
coProcs[15] = cpStd;
mmu = new MMUv5(this, cpStd);
intcIRQ = new NullINTC();
intcFIQ = new NullINTC();
exceptions = new boolean[7];
exceptionReasons = new String[7];
raised = false;
jumped = false;
highVector = false;
}
@Override
public void printDisasm(Instruction inst, String operation, String operand) {
if (!isPrintDisasm()) {
return;
}
System.out.printf("%08x: %08x %-7s %s\n",
getPC() - 8, inst.getInst(), operation, operand);
}
@Override
public void printPC() {
System.out.printf("pc:%08x\n", getPC() - 8);
}
@Override
public void printRegs() {
if (!isPrintRegs()) {
return;
}
for (int i = 0; i < 16; i += 4) {
System.out.printf(" r%-2d: %08x, r%-2d: %08x, r%-2d: %08x, r%-2d: %08x, \n",
i, getRegRaw(i), i + 1, getRegRaw(i + 1),
i + 2, getRegRaw(i + 2), i + 3, getRegRaw(i + 3));
}
System.out.printf(" cpsr:%08x(%s), spsr:%08x(%s)\n",
getCPSR(), getPSRName(getCPSR()),
getSPSR(), getPSRName(getSPSR()));
}
/**
* Rn
*
* r15 +8
*
* @param n 0 1516 SPSR
* @return
*/
public int getRegRaw(int n) {
switch (getCPSR_Mode()) {
case MODE_USR:
case MODE_SYS:
return regs[n];
case MODE_SVC:
if ((13 <= n && n <= 14) || n == 16) {
return regs_svc[n];
} else {
return regs[n];
}
case MODE_ABT:
if ((13 <= n && n <= 14) || n == 16) {
return regs_abt[n];
} else {
return regs[n];
}
case MODE_UND:
if ((13 <= n && n <= 14) || n == 16) {
return regs_und[n];
} else {
return regs[n];
}
case MODE_IRQ:
if ((13 <= n && n <= 14) || n == 16) {
return regs_irq[n];
} else {
return regs[n];
}
case MODE_FIQ:
if ((8 <= n && n <= 14) || n == 16) {
return regs_fiq[n];
} else {
return regs[n];
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Illegal mode " +
String.format("mode:0x%x.", getCPSR_Mode()));
}
/**
* Rn
*
* r15
*
* @param n 0 1516 SPSR
* @param val
*/
public void setRegRaw(int n, int val) {
switch (getCPSR_Mode()) {
case MODE_USR:
case MODE_SYS:
regs[n] = val;
return;
case MODE_SVC:
if ((13 <= n && n <= 14) || n == 16) {
regs_svc[n] = val;
return;
} else {
regs[n] = val;
return;
}
case MODE_ABT:
if ((13 <= n && n <= 14) || n == 16) {
regs_abt[n] = val;
return;
} else {
regs[n] = val;
return;
}
case MODE_UND:
if ((13 <= n && n <= 14) || n == 16) {
regs_und[n] = val;
return;
} else {
regs[n] = val;
return;
}
case MODE_IRQ:
if ((13 <= n && n <= 14) || n == 16) {
regs_irq[n] = val;
return;
} else {
regs[n] = val;
return;
}
case MODE_FIQ:
if ((8 <= n && n <= 14) || n == 16) {
regs_fiq[n] = val;
return;
} else {
regs[n] = val;
return;
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Illegal mode " +
String.format("mode:0x%x.", getCPSR_Mode()));
}
/**
* Rn
*
* @param n 0 15
* @return
*/
public int getReg(int n) {
if (n == 15) {
return getRegRaw(n) + 8;
} else {
return getRegRaw(n);
}
}
/**
* Rn
*
* @param n 0 15
* @param val
*/
public void setReg(int n, int val) {
if (n == 15) {
setJumped(true);
}
setRegRaw(n, val);
}
/**
* Rn
*
* @param n 0 15
* @return
*/
public static String getRegName(int n) {
return String.format("r%d", n);
}
/**
* Pn
*
* @param cpnum
* @return
*/
public CoProc getCoproc(int cpnum) {
return coProcs[cpnum];
}
/**
* CRn
*
* @param cpnum
* @param n 0 7
* @return
*/
public static String getCoprocRegName(int cpnum, int n) {
return String.format("cr%d", n);
}
/**
* Cp15
*
* @return
*/
public CoProcStdv5 getCoProcStd() {
return (CoProcStdv5)coProcs[15];
}
/**
* MMU
*
* @return MMU
*/
public MMUv5 getMMU() {
return mmu;
}
/**
* PC
*
*
* getReg(15)
*
* @return PC
*/
public int getPC() {
return getReg(15);
}
/**
* PC
*
*
* setReg(15, val)
*
* @param val PC
*/
public void setPC(int val) {
setReg(15, val);
}
public void nextPC() {
if (isJumped()) {
setJumped(false);
} else {
regs[15] += 4;
}
}
/**
*
*
* PC +8+
* PC
*
* PC 4
*
*
* @param val
*/
public void jumpRel(int val) {
setPC(getPC() + val);
setJumped(true);
}
public static final int PSR_BIT_N = 31;
public static final int PSR_BIT_Z = 30;
public static final int PSR_BIT_C = 29;
public static final int PSR_BIT_V = 28;
public static final int PSR_BIT_I = 7;
public static final int PSR_BIT_F = 6;
public static final int PSR_BIT_T = 5;
/**
* CPSR
*
* @return CPSR
*/
public int getCPSR() {
return cpsr;
}
/**
* CPSR
*
* @param val CPSR
*/
public void setCPSR(int val) {
cpsr = val;
}
/**
* SPSR
*
* @return SPSR
*/
public int getSPSR() {
return getReg(16);
}
/**
* SPSR
*
* @param val SPSR
*/
public void setSPSR(int val) {
setReg(16, val);
}
/**
* APSR
*
* @return APSR
*/
public int getAPSR() {
return getCPSR() & 0xf80f0000;
}
/**
* APSR
*
* @param val APSR
*/
public void setAPSR(int val) {
int r;
//N, Z, C, V, Q, GE
r = getCPSR();
r &= ~0xf80f0000;
r |= val & 0xf80f0000;
setCPSR(r);
}
public static final int MODE_USR = 0x10;
public static final int MODE_FIQ = 0x11;
public static final int MODE_IRQ = 0x12;
public static final int MODE_SVC = 0x13;
public static final int MODE_ABT = 0x17;
public static final int MODE_UND = 0x1b;
public static final int MODE_SYS = 0x1f;
/**
* PSR M
* [4:0]
*
* @param val PSR
* @return M
*/
public static int getPSR_Mode(int val) {
return val & 0x1f;
}
/**
* PSR M
* [4:0]
*
* @param val PSR
* @param mod
* @return PSR
*/
public static int setPSR_Mode(int val, int mod) {
int mask = 0x1f;
val &= ~mask;
val |= mod & mask;
return val;
}
/**
*
*
* @param mode
* @return
*/
public static String getPSR_ModeName(int mode) {
switch (mode) {
case 0x10:
return "usr";
case 0x11:
return "fiq";
case 0x12:
return "irq";
case 0x13:
return "svc";
case 0x17:
return "abt";
case 0x1b:
return "und";
case 0x1f:
return "sys";
default:
return "???";
}
}
/**
* PSR
*
* @param val PSR
* @return PSR
*/
public static String getPSRName(int val) {
return String.format("%s%s%s%s_%s%s%s%5s",
BitOp.getBit32(val, PSR_BIT_N) ? "N" : "n",
BitOp.getBit32(val, PSR_BIT_Z) ? "Z" : "z",
BitOp.getBit32(val, PSR_BIT_C) ? "C" : "c",
BitOp.getBit32(val, PSR_BIT_V) ? "V" : "v",
BitOp.getBit32(val, PSR_BIT_I) ? "I" : "i",
BitOp.getBit32(val, PSR_BIT_F) ? "F" : "f",
BitOp.getBit32(val, PSR_BIT_T) ? "T" : "t",
getPSR_ModeName(getPSR_Mode(val)));
}
/**
* CPSR
* N 31
*
* N 31 1
* 2
* N=0 N=1
*
* @return N true, false
*/
public boolean getCPSR_N() {
return BitOp.getBit32(getCPSR(), PSR_BIT_N);
}
/**
* CPSR
* N 31
*
* N 31 1
* 2
* N=0 N=1
*
* @param nv N true, false
*/
public void setCPSR_N(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_N, nv));
}
/**
* CPSR
* Z 30
*
* Z 0
* 0 Z=00 Z=1
*
* @return Z true, false
*/
public boolean getCPSR_Z() {
return BitOp.getBit32(getCPSR(), PSR_BIT_Z);
}
/**
* CPSR
* Z 30
*
* Z 0
* 0 Z=00 Z=1
*
* @param nv Z true, false
*/
public void setCPSR_Z(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_Z, nv));
}
/**
* CPSR
* C 29
*
* C
*
*
*
* -
* C=0
* C=1
* -
* C=0
* C=1
* - 0 C=0
* 1 C=1
*
* @return C true, false
*/
public boolean getCPSR_C() {
return BitOp.getBit32(getCPSR(), PSR_BIT_C);
}
/**
* CPSR
* C 29
*
* C
*
*
*
* -
* C=0
* C=1
* -
* C=0
* C=1
* - 0 C=0
* 1 C=1
*
* @param nv C true, false
*/
public void setCPSR_C(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_C, nv));
}
/**
* CPSR
* V 28
*
* V
*
* -
* V=0
* V=1
*
* @return V true, false
*/
public boolean getCPSR_V() {
return BitOp.getBit32(getCPSR(), PSR_BIT_V);
}
/**
* CPSR
* V 28
*
* V
*
* -
* V=0
* V=1
*
* @param nv V true, false
*/
public void setCPSR_V(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_V, nv));
}
/**
* CPSR
* I 7
*
* I=0 IRQ
* I=1 IRQ
*
* @return I true, false
*/
public boolean getCPSR_I() {
return BitOp.getBit32(getCPSR(), PSR_BIT_I);
}
/**
* CPSR
* I 7
*
* I=0 IRQ
* I=1 IRQ
*
* @param nv I true, false
*/
public void setCPSR_I(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_I, nv));
}
/**
* CPSR
* F 6
*
* F=0 FIQ
* F=1 FIQ
*
* @return F true, false
*/
public boolean getCPSR_F() {
return BitOp.getBit32(getCPSR(), PSR_BIT_F);
}
/**
* CPSR
* F 6
*
* F=0 FIQ
* F=1 FIQ
*
* @param nv F true, false
*/
public void setCPSR_F(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_F, nv));
}
/**
* CPSR
* T 5
*
* T=0 ARM
* T=1 Thumb
*
* ARMv5 T Thumb
* T=1
*
* @return T true, false
*/
public boolean getCPSR_T() {
return BitOp.getBit32(getCPSR(), PSR_BIT_T);
}
/**
* CPSR
* T 5
*
* T=0 ARM
* T=1 Thumb
*
* ARMv5 T Thumb
* T=1
*
* @param nv T true, false
*/
public void setCPSR_T(boolean nv) {
setCPSR(BitOp.setBit32(getCPSR(), PSR_BIT_T, nv));
}
/**
*
*
* CPSR M [4:0]
*
* @return
*/
public int getCPSR_Mode() {
return getPSR_Mode(getCPSR());
}
/**
*
*
* CPSR M [4:0]
*
* @param mod
*/
public void setCPSR_Mode(int mod) {
setCPSR(setPSR_Mode(getCPSR(), mod));
}
/**
*
*
* @return true false
*/
public boolean isPrivMode() {
return getCPSR_Mode() != MODE_USR;
}
/**
* 1 -
*
* @param inst ARM
* @return
*/
public int getShifterOperand(Instruction inst) {
boolean i = inst.getIBit();
boolean b7 = inst.getBit(7);
boolean b4 = inst.getBit(4);
if (i) {
//32bits
return getShifterOperandImm(inst);
} else if (!b4) {
return getShifterOperandImmShift(inst);
} else if (b4 && !b7) {
return getShifterOperandRegShift(inst);
} else {
throw new IllegalArgumentException("Unknown shifter_operand " +
String.format("0x%08x, I:%b, b7:%b, b4:%b.",
inst.getInst(), i, b7, b4));
}
}
/**
* 1 -
* 32
*
* :
* I [25]: 1
*
* rotate_imm: [11:8]
* immed_8: [7:0]
* imm32
*
* imm32 = rotateRight(immed_8, rotate_imm * 2)
*
* @param inst ARM
* @return
*/
public int getShifterOperandImm(Instruction inst) {
int rotR = inst.getField(8, 4);
int imm8 = inst.getField(0, 8);
return Integer.rotateRight(imm8, rotR * 2);
}
/**
* 1 -
*
*
* :
* I [25]: 0
* [4]: 0
*
* :
* [6:4]
* 0b000: -
* 0b000: -
* 0b010: -
* 0b100: -
* 0b110: -
* 0b110: -
*
* @param inst ARM
* @return
*/
public int getShifterOperandImmShift(Instruction inst) {
int shift_imm = inst.getField(7, 5);
int shift = inst.getField(5, 2);
int rm = inst.getRmField();
switch (shift) {
case 0:
if (shift_imm == 0) {
return getReg(rm);
} else {
return getReg(rm) << shift_imm;
}
case 1:
if (shift_imm == 0) {
return 0;
} else {
return getReg(rm) >>> shift_imm;
}
case 2:
if (shift_imm == 0) {
if (BitOp.getBit32(getReg(rm), 31)) {
return 0xffffffff;
} else {
return 0;
}
} else {
return getReg(rm) >> shift_imm;
}
case 3:
if (shift_imm == 0) {
if (getCPSR_C()) {
return (1 << 31) | (getReg(rm) >>> 1);
} else {
return getReg(rm) >>> 1;
}
} else {
return Integer.rotateRight(getReg(rm), shift_imm);
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Imm Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
public int getShifterOperandRegShift(Instruction inst) {
int shift = inst.getField(5, 2);
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int valRs, valRsLow;
//Rs[7:0]
valRs = getReg(rs) & 0xff;
//Rs[4:0]
valRsLow = getReg(rs) & 0x1f;
switch (shift) {
case 0:
if (valRs == 0) {
return getReg(rm);
} else if (valRs < 32) {
return getReg(rm) << valRs;
} else {
return 0;
}
case 1:
if (valRs == 0) {
return getReg(rm);
} else if (valRs < 32) {
return getReg(rm) >>> valRs;
} else {
return 0;
}
case 2:
if (valRs == 0) {
return getReg(rm);
} else if (valRs < 32) {
return getReg(rm) >> valRs;
} else {
if (BitOp.getBit32(getReg(rm), 31)) {
return 0xffffffff;
} else {
return 0;
}
}
case 3:
if (valRs == 0) {
return getReg(rm);
} else if (valRsLow == 0) {
return getReg(rm);
} else {
return Integer.rotateRight(getReg(rm), valRsLow);
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Reg Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
/**
* 1 -
*
* @param inst ARM
* @return true false
*/
public boolean getShifterCarry(Instruction inst) {
boolean i = inst.getIBit();
boolean b7 = inst.getBit(7);
boolean b4 = inst.getBit(4);
if (i) {
//32bits
return getShifterCarryImm(inst);
} else if (!b4) {
return getShifterCarryImmShift(inst);
} else if (b4 && !b7) {
return getShifterCarryRegShift(inst);
} else {
throw new IllegalArgumentException("Unknown shifter_operand " +
String.format("0x%08x, I:%b, b7:%b, b4:%b.",
inst.getInst(), i, b7, b4));
}
}
/**
* 1 -
* 32
*
* @param inst ARM
* @return true false
*/
public boolean getShifterCarryImm(Instruction inst) {
int rotR = inst.getField(8, 4);
if (rotR == 0) {
return getCPSR_C();
} else {
return BitOp.getBit32(getShifterOperandImm(inst), 31);
}
}
/**
* 1 -
*
*
* :
* I [25]: 0
* [4]: 0
*
* :
* [6:4]
* 0b000: -
* 0b000: -
* 0b010: -
* 0b100: -
* 0b110: -
* 0b110: -
*
* @param inst ARM
* @return true false
*/
public boolean getShifterCarryImmShift(Instruction inst) {
int shift_imm = inst.getField(7, 5);
int shift = inst.getField(5, 2);
int rm = inst.getRmField();
switch (shift) {
case 0:
if (shift_imm == 0) {
return getCPSR_C();
} else {
return BitOp.getBit32(getReg(rm), 32 - shift_imm);
}
case 1:
if (shift_imm == 0) {
return BitOp.getBit32(getReg(rm), 31);
} else {
return BitOp.getBit32(getReg(rm), shift_imm - 1);
}
case 2:
if (shift_imm == 0) {
return BitOp.getBit32(getReg(rm), 31);
} else {
return BitOp.getBit32(getReg(rm), shift_imm - 1);
}
case 3:
if (shift_imm == 0) {
return BitOp.getBit32(getReg(rm), 0);
} else {
return BitOp.getBit32(getReg(rm), shift_imm - 1);
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Imm Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
public boolean getShifterCarryRegShift(Instruction inst) {
int shift = inst.getField(5, 2);
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int valRs, valRsLow;
//Rs[7:0]
valRs = getReg(rs) & 0xff;
//Rs[4:0]
valRsLow = getReg(rs) & 0x1f;
switch (shift) {
case 0:
if (valRs == 0) {
return getCPSR_C();
} else if (valRs <= 32) {
return BitOp.getBit32(getReg(rm), 32 - valRs);
} else {
return false;
}
case 1:
if (valRs == 0) {
return getCPSR_C();
} else if (valRs <= 32) {
return BitOp.getBit32(getReg(rm), valRs - 1);
} else {
return false;
}
case 2:
if (valRs == 0) {
return getCPSR_C();
} else if (valRs <= 32) {
return BitOp.getBit32(getReg(rm), valRs - 1);
} else {
return BitOp.getBit32(getReg(rm), 31);
}
case 3:
if (valRs == 0) {
return getCPSR_C();
} else if (valRsLow == 0) {
return BitOp.getBit32(getReg(rm), 31);
} else {
return BitOp.getBit32(getReg(rm), valRsLow - 1);
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Reg Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
/**
* 1 -
*
* @param inst ARM
* @return
*/
public String getShifterOperandName(Instruction inst) {
boolean i = inst.getIBit();
boolean b7 = inst.getBit(7);
boolean b4 = inst.getBit(4);
if (i) {
//32bits
return getShifterOperandImm32Name(inst);
} else if (!b4) {
return getShifterOperandImmShiftName(inst);
} else if (b4 && !b7) {
return getShifterOperandRegShiftName(inst);
} else {
throw new IllegalArgumentException("Unknown shifter_operand " +
String.format("0x%08x, I:%b, b7:%b, b4:%b.",
inst.getInst(), i, b7, b4));
}
}
/**
* 1 -
* 32
*
* @param inst
* @return
*/
public String getShifterOperandImm32Name(Instruction inst) {
int imm32 = getShifterOperandImm(inst);
return String.format("#%d ; 0x%x", imm32, imm32);
}
/**
* 1 -
*
*
* :
* I [25]: 0
* [4]: 0
*
* :
* [6:4]
* 0b000: -
* 0b000: -
* 0b010: -
* 0b100: -
* 0b110: -
* 0b110: -
*
* @param inst ARM
* @return
*/
public String getShifterOperandImmShiftName(Instruction inst) {
int shift_imm = inst.getField(7, 5);
int shift = inst.getField(5, 2);
int rm = inst.getRmField();
switch (shift) {
case 0:
if (shift_imm == 0) {
return getRegName(rm);
} else {
return String.format("%s, lsl
getRegName(rm), shift_imm);
}
case 1:
return String.format("%s, lsr
getRegName(rm), shift_imm);
case 2:
return String.format("%s, asr
getRegName(rm), shift_imm);
case 3:
if (shift_imm == 0) {
return String.format("%s, rrx",
getRegName(rm));
} else {
return String.format("%s, ror
getRegName(rm), shift_imm);
}
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Imm Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
public String getShifterOperandRegShiftName(Instruction inst) {
int shift = inst.getField(5, 2);
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
switch (shift) {
case 0:
return String.format("%s, lsl %s",
getRegName(rm), getRegName(rs));
case 1:
return String.format("%s, lsr %s",
getRegName(rm), getRegName(rs));
case 2:
return String.format("%s, asr %s",
getRegName(rm), getRegName(rs));
case 3:
return String.format("%s, ror %s",
getRegName(rm), getRegName(rs));
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Reg Shift " +
String.format("0x%08x, shift:%d.",
inst.getInst(), shift));
}
/**
* 2 - /
*
*
* I
* I=0
* I=1
*
*
*
*
*
*
*
* @param inst ARM
* @return
*/
public int getOffsetAddress(Instruction inst) {
boolean i = inst.getIBit();
boolean u = inst.getBit(23);
int rn = inst.getRnField();
int shift_imm = inst.getField(7, 5);
int shift = inst.getField(5, 2);
int offset;
if (!i) {
//12bits
offset = getOffsetAddressImm(inst);
} else if (shift_imm == 0 && shift == 0) {
offset = getOffsetAddressReg(inst);
} else {
offset = getOffsetAddressScaled(inst);
}
if (!u) {
offset = -offset;
}
return getReg(rn) + offset;
}
/**
* 2 - /
* 12bits
*
* @param inst ARM
* @return
*/
public int getOffsetAddressImm(Instruction inst) {
int offset12 = inst.getField(0, 12);
return offset12;
}
/**
* 2 - /
*
*
* 1 -
* shifter_operand
*
* @param inst ARM
* @return
*/
public int getOffsetAddressReg(Instruction inst) {
return getShifterOperandImmShift(inst);
}
/**
* 2 - /
*
*
* 1 -
* shifter_operand
*
* @param inst ARM
* @return
*/
public int getOffsetAddressScaled(Instruction inst) {
return getShifterOperandImmShift(inst);
}
/**
* 2 - /
*
*
* I
* I=0
* I=1
*
* @param inst ARM
* @return
*/
public String getOffsetAddressName(Instruction inst) {
boolean i = inst.getIBit();
boolean p = inst.getBit(24);
boolean u = inst.getBit(23);
boolean b = inst.getBit(22);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int shift_imm = inst.getField(7, 5);
int shift = inst.getField(5, 2);
int rm = inst.getRmField();
String strOffset;
if (!i) {
//12bits
return getOffsetAddressImmName(inst);
} else if (shift_imm == 0 && shift == 0) {
strOffset = getOffsetAddressRegName(inst);
} else {
strOffset = getOffsetAddressScaledName(inst);
}
if (p && !w) {
return String.format("[%s, %s%s]",
getRegName(rn), (u) ? "" : "-",
strOffset);
} else if (p && w) {
return String.format("[%s, %s%s]!",
getRegName(rn), (u) ? "" : "-",
strOffset);
} else if (!p) {
return String.format("[%s], %s%s",
getRegName(rn), (u) ? "" : "-",
strOffset);
} else {
throw new IllegalArgumentException("Illegal P,W bits " +
String.format("p:%b, w:%b.", p, w));
}
}
/**
* 2 - /
* 12bits
*
*
*
* #
* 16
*
* @param inst ARM
* @return
*/
public String getOffsetAddressImmName(Instruction inst) {
boolean p = inst.getBit(24);
boolean u = inst.getBit(23);
boolean b = inst.getBit(22);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int offset12 = inst.getField(0, 12);
if (p && !w) {
return String.format("[%s, #%s%d] ; 0x%x",
getRegName(rn), (u) ? "" : "-",
offset12, offset12);
} else if (p && w) {
return String.format("[%s, #%s%d]! ; 0x%x",
getRegName(rn), (u) ? "" : "-",
offset12, offset12);
} else if (!p) {
return String.format("[%s], #%s%d ; 0x%x",
getRegName(rn), (u) ? "" : "-",
offset12, offset12);
} else {
throw new IllegalArgumentException("Illegal P,W bits " +
String.format("p:%b, w:%b.", p, w));
}
}
/**
* 2 - /
*
*
* 1 -
* shifter_operand
*
* @param inst ARM
* @return
*/
public String getOffsetAddressRegName(Instruction inst) {
return getShifterOperandImmShiftName(inst);
}
/**
* 2 - /
*
*
* 1 -
* shifter_operand
*
* @param inst ARM
* @return
*/
public String getOffsetAddressScaledName(Instruction inst) {
return getShifterOperandImmShiftName(inst);
}
/**
* 3 - /
*
*
* @param inst ARM
* @return
*/
public int getOffsetHalf(Instruction inst) {
boolean u = inst.getBit(23);
boolean b = inst.getBit(22);
int rn = inst.getRnField();
int offset;
if (b) {
offset = getOffsetHalfImm(inst);
} else {
offset = getOffsetHalfReg(inst);
}
if (!u) {
offset = -offset;
}
return getReg(rn) + offset;
}
/**
* 3 - /
* /
*
* @param inst ARM
* @return
*/
public int getOffsetHalfImm(Instruction inst) {
int immh = inst.getField(8, 4);
int imml = inst.getField(0, 4);
return (immh << 4) | imml;
}
/**
* 3 - /
* /
*
* @param inst ARM
* @return
*/
public int getOffsetHalfReg(Instruction inst) {
int rm = inst.getRmField();
return getReg(rm);
}
/**
* 3 - /
*
*
* @param inst ARM
* @return
*/
public String getOffsetHalfName(Instruction inst) {
boolean b = inst.getBit(22);
if (b) {
return getOffsetHalfImmName(inst);
} else {
return getOffsetHalfRegName(inst);
}
}
/**
* 3 - /
* /
*
* @param inst ARM
* @return
*/
public String getOffsetHalfImmName(Instruction inst) {
boolean p = inst.getBit(24);
boolean u = inst.getBit(23);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int imm8 = getOffsetHalfImm(inst);
if (p && !w) {
return String.format("[%s, #%s%d] ; 0x%x",
getRegName(rn), (u) ? "" : "-",
imm8, imm8);
} else if (p && w) {
return String.format("[%s, #%s%d]! ; 0x%x",
getRegName(rn), (u) ? "" : "-",
imm8, imm8);
} else if (!p) {
return String.format("[%s], #%s%d ; 0x%x",
getRegName(rn), (u) ? "" : "-",
imm8, imm8);
} else {
throw new IllegalArgumentException("Illegal P,W bits " +
String.format("p:%b, w:%b.", p, w));
}
}
/**
* 3 - /
* /
*
* @param inst ARM
* @return
*/
public String getOffsetHalfRegName(Instruction inst) {
boolean p = inst.getBit(24);
boolean u = inst.getBit(23);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rm = inst.getRmField();
if (p && !w) {
return String.format("[%s, %s%s]",
getRegName(rn), (u) ? "" : "-",
getRegName(rm));
} else if (p && w) {
return String.format("[%s, %s%s]!",
getRegName(rn), (u) ? "" : "-",
getRegName(rm));
} else if (!p) {
return String.format("[%s], %s%s",
getRegName(rn), (u) ? "" : "-",
getRegName(rm));
} else {
throw new IllegalArgumentException("Illegal P,W bits " +
String.format("p:%b, w:%b.", p, w));
}
}
/**
* 4 - /
*
*
* @param pu P, U
* @param rn
* @param rlist
* @return
*/
public int getRegistersStartAddress(int pu, int rn, int rlist) {
switch (pu) {
case Instruction.PU_ADDR4_IA:
return getReg(rn);
case Instruction.PU_ADDR4_IB:
return getReg(rn) + 4;
case Instruction.PU_ADDR4_DA:
return getReg(rn) - (Integer.bitCount(rlist) * 4) + 4;
case Instruction.PU_ADDR4_DB:
return getReg(rn) - (Integer.bitCount(rlist) * 4);
default:
//do nothing
break;
}
throw new IllegalArgumentException("Illegal PU field " +
pu + ".");
}
/**
* 4 - /
*
*
* @param pu P, U
* @param rlist
* @return
*/
public int getRegistersLength(int pu, int rlist) {
switch (pu) {
case Instruction.PU_ADDR4_IA:
case Instruction.PU_ADDR4_IB:
return Integer.bitCount(rlist) * 4;
case Instruction.PU_ADDR4_DA:
case Instruction.PU_ADDR4_DB:
return -(Integer.bitCount(rlist) * 4);
default:
//do nothing
break;
}
throw new IllegalArgumentException("Illegal PU field " +
pu + ".");
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeMrs(Instruction inst, boolean exec) {
boolean r = inst.getBit(22);
int sbo = inst.getField(16, 4);
int rd = inst.getRdField();
int dest;
if (!exec) {
disasmInst(inst,
String.format("mrs%s", inst.getCondFieldName()),
String.format("%s, %s",
getRegName(rd), (r) ? "spsr" : "cpsr"));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (sbo != 0xf) {
System.out.println("Warning: Illegal instruction, " +
String.format("mrs SBO[19:16](0x%01x) != 0xf.", sbo));
}
if (r) {
dest = getSPSR();
} else {
dest = getCPSR();
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeMsr(Instruction inst, boolean exec) {
boolean i = inst.getIBit();
boolean r = inst.getBit(22);
boolean mask_f = inst.getBit(19);
boolean mask_s = inst.getBit(18);
boolean mask_x = inst.getBit(17);
boolean mask_c = inst.getBit(16);
int sbo = inst.getField(12, 4);
int opr = getShifterOperand(inst);
int dest, m = 0;
if (!exec) {
disasmInst(inst,
String.format("msr%s", inst.getCondFieldName()),
String.format("%s_%s%s%s%s, %s",
(r) ? "SPSR" : "CPSR",
(mask_f) ? "f" : "",
(mask_s) ? "s" : "",
(mask_x) ? "x" : "",
(mask_c) ? "c" : "",
getShifterOperandName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (sbo != 0xf) {
System.out.println("Warning: Illegal instruction, " +
String.format("msr SBO[15:12](0x%01x) != 0xf.", sbo));
}
if (!r) {
dest = getCPSR();
} else {
dest = getSPSR();
}
if (mask_c) {
m |= 0x000000ff;
}
if (mask_x) {
m |= 0x0000ff00;
}
if (mask_s) {
m |= 0x00ff0000;
}
if (mask_f) {
m |= 0xff000000;
}
dest &= ~m;
dest |= opr & m;
if (!r) {
setCPSR(dest);
} else {
setSPSR(dest);
}
}
/**
*
*
*
* and, eor, sub, rsb,
* add, adc, sbc, rsc,
* tst, teq, cmp, cmn,
* orr, mov, bic, mvn,
*
* @param inst ARM
* @param exec true false
* @param id S ID
*/
public void executeALU(Instruction inst, boolean exec, int id) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
String strInst, strOperand;
if (!exec) {
switch (id) {
case Instruction.OPCODE_S_ADC:
case Instruction.OPCODE_S_ADD:
case Instruction.OPCODE_S_AND:
case Instruction.OPCODE_S_BIC:
case Instruction.OPCODE_S_EOR:
case Instruction.OPCODE_S_ORR:
case Instruction.OPCODE_S_RSB:
case Instruction.OPCODE_S_RSC:
case Instruction.OPCODE_S_SBC:
case Instruction.OPCODE_S_SUB:
//with S bit
strInst = String.format("%s%s%s", inst.getOpcodeFieldName(),
inst.getCondFieldName(),
(s) ? "s" : "");
//rd, rn, shifter_operand
strOperand = String.format("%s, %s, %s", getRegName(rd),
getRegName(rn), getShifterOperandName(inst));
break;
case Instruction.OPCODE_S_MOV:
case Instruction.OPCODE_S_MVN:
//with S bit
strInst = String.format("%s%s%s", inst.getOpcodeFieldName(),
inst.getCondFieldName(),
(s) ? "s" : "");
//rd, shifter_operand
strOperand = String.format("%s, %s", getRegName(rd),
getShifterOperandName(inst));
break;
case Instruction.OPCODE_S_CMN:
case Instruction.OPCODE_S_CMP:
case Instruction.OPCODE_S_TEQ:
case Instruction.OPCODE_S_TST:
//S bit is 1
strInst = String.format("%s%s", inst.getOpcodeFieldName(),
inst.getCondFieldName());
//rn, shifter_operand
strOperand = String.format("%s, %s", getRegName(rn),
getShifterOperandName(inst));
break;
default:
throw new IllegalArgumentException("Unknown opcode S-bit ID " +
String.format("%d.", id));
}
disasmInst(inst, strInst, strOperand);
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
switch (id) {
case Instruction.OPCODE_S_AND:
executeALUAnd(inst, exec);
break;
case Instruction.OPCODE_S_EOR:
executeALUEor(inst, exec);
break;
case Instruction.OPCODE_S_SUB:
executeALUSub(inst, exec);
break;
case Instruction.OPCODE_S_RSB:
executeALURsb(inst, exec);
break;
case Instruction.OPCODE_S_ADD:
executeALUAdd(inst, exec);
break;
case Instruction.OPCODE_S_ADC:
executeALUAdc(inst, exec);
break;
case Instruction.OPCODE_S_SBC:
executeALUSbc(inst, exec);
break;
case Instruction.OPCODE_S_RSC:
executeALURsc(inst, exec);
break;
case Instruction.OPCODE_S_TST:
executeALUTst(inst, exec);
break;
case Instruction.OPCODE_S_TEQ:
executeALUTeq(inst, exec);
break;
case Instruction.OPCODE_S_CMP:
executeALUCmp(inst, exec);
break;
case Instruction.OPCODE_S_CMN:
executeALUCmn(inst, exec);
break;
case Instruction.OPCODE_S_ORR:
executeALUOrr(inst, exec);
break;
case Instruction.OPCODE_S_MOV:
executeALUMov(inst, exec);
break;
case Instruction.OPCODE_S_BIC:
executeALUBic(inst, exec);
break;
case Instruction.OPCODE_S_MVN:
executeALUMvn(inst, exec);
break;
default:
throw new IllegalArgumentException("Unknown opcode S-bit ID " +
String.format("%d.", id));
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUAnd(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left & right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUEor(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left ^ right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUSub(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left - right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(!borrowFrom32(left, right));
setCPSR_V(overflowFrom32(left, right, false));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALURsb(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = opr;
right = getReg(rn);
dest = left - right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(!borrowFrom32(left, right));
setCPSR_V(overflowFrom32(left, right, false));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUAdd(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left + right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(carryFrom32(left, right));
setCPSR_V(overflowFrom32(left, right, true));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUAdc(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, center, right, dest;
left = getReg(rn);
center = opr;
right = BitOp.toInt(getCPSR_C());
dest = left + center + right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
int left_center = left + center;
boolean lc_c = carryFrom32(left, center);
boolean lc_v = overflowFrom32(left, center, true);
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(lc_c || carryFrom32(left_center, right));
setCPSR_V(lc_v || overflowFrom32(left_center, right, true));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUSbc(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, center, right, dest;
left = getReg(rn);
center = opr;
right = BitOp.toInt(!getCPSR_C());
dest = left - center - right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
int left_center = left + center;
boolean lc_c = !borrowFrom32(left, center);
boolean lc_v = overflowFrom32(left, center, false);
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(lc_c || !borrowFrom32(left_center, right));
setCPSR_V(lc_v || overflowFrom32(left_center, right, false));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALURsc(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, center, right, dest;
left = opr;
center = getReg(rn);
right = BitOp.toInt(!getCPSR_C());
dest = left - center - right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
int left_center = left + center;
boolean lc_c = !borrowFrom32(left, center);
boolean lc_v = overflowFrom32(left, center, false);
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(lc_c || !borrowFrom32(left_center, right));
setCPSR_V(lc_v || overflowFrom32(left_center, right, false));
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUTst(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int sbz = inst.getField(12, 4);
int opr = getShifterOperand(inst);
int left, right, dest;
if (sbz != 0x0) {
System.out.println("Warning: Illegal instruction, " +
String.format("tst SBZ[15:12](0x%01x) != 0x0.", sbz));
}
left = getReg(rn);
right = opr;
dest = left & right;
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUTeq(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int sbz = inst.getField(12, 4);
int opr = getShifterOperand(inst);
int left, right, dest;
if (sbz != 0x0) {
System.out.println("Warning: Illegal instruction, " +
String.format("teq SBZ[15:12](0x%01x) != 0x0.", sbz));
}
left = getReg(rn);
right = opr;
dest = left ^ right;
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUCmp(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int sbz = inst.getField(12, 4);
int opr = getShifterOperand(inst);
int left, right, dest;
if (sbz != 0x0) {
System.out.println("Warning: Illegal instruction, " +
String.format("cmp SBZ[15:12](0x%01x) != 0x0.", sbz));
}
left = getReg(rn);
right = opr;
dest = left - right;
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(!borrowFrom32(left, right));
setCPSR_V(overflowFrom32(left, right, false));
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUCmn(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int sbz = inst.getField(12, 4);
int opr = getShifterOperand(inst);
int left, right, dest;
if (sbz != 0x0) {
System.out.println("Warning: Illegal instruction, " +
String.format("cmp SBZ[15:12](0x%01x) != 0x0.", sbz));
}
left = getReg(rn);
right = opr;
dest = left + right;
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(carryFrom32(left, right));
setCPSR_V(overflowFrom32(left, right, true));
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUOrr(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left | right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUMov(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int sbz = inst.getField(16, 4);
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int right, dest;
if (sbz != 0x0) {
System.out.println("Warning: Illegal instruction, " +
String.format("mov SBZ[19:16](0x%01x) != 0x0.", sbz));
}
right = opr;
dest = right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUBic(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rn = inst.getRnField();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
left = getReg(rn);
right = opr;
dest = left & ~right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeALUMvn(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rd = inst.getRdField();
int opr = getShifterOperand(inst);
int left, right, dest;
right = opr;
dest = ~right;
if (s && rd == 15) {
setCPSR(getSPSR());
} else if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
setCPSR_C(getShifterCarry(inst));
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeMla(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rd = inst.getField(16, 4);
int rn = inst.getField(12, 4);
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int left, center, right, dest;
if (!exec) {
disasmInst(inst,
String.format("mla%s%s", inst.getCondFieldName(),
(s) ? "s" : ""),
String.format("%s, %s, %s, %s",
getRegName(rd), getRegName(rm),
getRegName(rs), getRegName(rn)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
center = getReg(rs);
right = getReg(rn);
dest = left * center + right;
if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
//C flag is unaffected
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeMul(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rd = inst.getField(16, 4);
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int left, right, dest;
if (!exec) {
disasmInst(inst,
String.format("mul%s%s", inst.getCondFieldName(),
(s) ? "s" : ""),
String.format("%s, %s, %s",
getRegName(rd), getRegName(rm),
getRegName(rs)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
right = getReg(rs);
dest = left * right;
if (s) {
setCPSR_N(BitOp.getBit32(dest, 31));
setCPSR_Z(dest == 0);
//C flag is unaffected
//V flag is unaffected
}
setReg(rd, dest);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeSmlal(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rdhi = inst.getField(16, 4);
int rdlo = inst.getRdField();
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int left, right, desthi, destlo;
long dest;
if (!exec) {
disasmInst(inst,
String.format("smlal%s%s", inst.getCondFieldName(),
(s) ? "s" : ""),
String.format("%s, %s, %s, %s",
getRegName(rdlo), getRegName(rdhi),
getRegName(rm), getRegName(rs)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
right = getReg(rs);
dest = ((long)getReg(rdhi) << 32) + (getReg(rdlo) & 0xffffffffL);
dest += (long)left * (long)right;
desthi = (int)(dest >>> 32);
destlo = (int)dest;
if (s) {
setCPSR_N(BitOp.getBit32(desthi, 31));
setCPSR_Z(dest == 0);
//C flag is unaffected
//V flag is unaffected
}
setReg(rdhi, desthi);
setReg(rdlo, destlo);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeUmlal(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rdhi = inst.getField(16, 4);
int rdlo = inst.getRdField();
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int left, right, desthi, destlo;
long dest;
if (!exec) {
disasmInst(inst,
String.format("umlal%s%s", inst.getCondFieldName(),
(s) ? "s" : ""),
String.format("%s, %s, %s, %s",
getRegName(rdlo), getRegName(rdhi),
getRegName(rm), getRegName(rs)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
right = getReg(rs);
dest = ((long)getReg(rdhi) << 32) + (getReg(rdlo) & 0xffffffffL);
dest += (left & 0xffffffffL) * (right & 0xffffffffL);
desthi = (int)(dest >>> 32);
destlo = (int)dest;
if (s) {
setCPSR_N(BitOp.getBit32(desthi, 31));
setCPSR_Z(dest == 0);
//C flag is unaffected
//V flag is unaffected
}
setReg(rdhi, desthi);
setReg(rdlo, destlo);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeUmull(Instruction inst, boolean exec) {
boolean s = inst.getSBit();
int rdhi = inst.getField(16, 4);
int rdlo = inst.getRdField();
int rs = inst.getField(8, 4);
int rm = inst.getRmField();
int left, right, desthi, destlo;
long dest;
if (!exec) {
disasmInst(inst,
String.format("umull%s%s", inst.getCondFieldName(),
(s) ? "s" : ""),
String.format("%s, %s, %s, %s",
getRegName(rdlo), getRegName(rdhi),
getRegName(rm), getRegName(rs)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
right = getReg(rs);
dest = (left & 0xffffffffL) * (right & 0xffffffffL);
desthi = (int)(dest >>> 32);
destlo = (int)dest;
if (s) {
setCPSR_N(BitOp.getBit32(desthi, 31));
setCPSR_Z(dest == 0);
//C flag is unaffected
//V flag is unaffected
}
setReg(rdhi, desthi);
setReg(rdlo, destlo);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeSwp(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int rd = inst.getRdField();
int rm = inst.getRmField();
int left, right, rot;
int vaddr, paddr;
if (!exec) {
disasmInst(inst,
String.format("swp%s", inst.getCondFieldName()),
String.format("%s, %s, [%s]",
getRegName(rd), getRegName(rm), getRegName(rn)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
left = getReg(rm);
rot = getReg(rn) & 0x3;
vaddr = getReg(rn);
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr) || !tryWrite(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("swp [%08x]", paddr));
return;
}
right = read32(paddr);
switch (rot) {
case 0:
//do nothing
break;
case 1:
right = Integer.rotateRight(right, 8);
break;
case 2:
right = Integer.rotateRight(right, 16);
break;
case 3:
right = Integer.rotateRight(right, 24);
break;
default:
throw new IllegalArgumentException("Illegal address " +
String.format("inst:0x%08x, rn:%d, rot:%d.",
inst.getInst(), rn, rot));
}
write32(paddr, left);
setReg(rd, right);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrt(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr, rot, value;
if (!exec) {
disasmInst(inst,
String.format("ldrt%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
//P 0
vaddr = getReg(rn);
rot = vaddr & 0x3;
paddr = getMMU().translate(vaddr, 4, false, false, true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrt [%08x]", paddr));
return;
}
value = read32(paddr);
switch (rot) {
case 0:
//do nothing
break;
case 1:
value = Integer.rotateRight(value, 8);
break;
case 2:
value = Integer.rotateRight(value, 16);
break;
case 3:
value = Integer.rotateRight(value, 24);
break;
default:
throw new IllegalArgumentException("Illegal address " +
String.format("inst:0x%08x, rot:%d.",
inst.getInst(), rot));
}
if (rd == 15) {
setPC(value & 0xfffffffe);
setCPSR_T(BitOp.getBit32(value, 0));
} else {
setReg(rd, value);
}
//W 1
setReg(rn, offset);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrbt(Instruction inst, boolean exec) {
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr, value;
if (!exec) {
disasmInst(inst,
String.format("ldrbt%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
//P 0
vaddr = getReg(rn);
paddr = getMMU().translate(vaddr, 1, false, false, true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrbt [%08x]", paddr));
return;
}
value = (int)(read8(paddr)) & 0xff;
setReg(rd, value);
//W 1
setReg(rn, offset);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrb(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr, value;
if (!exec) {
disasmInst(inst,
String.format("ldrb%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 1, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrb [%08x]", paddr));
return;
}
value = (int)(read8(paddr)) & 0xff;
setReg(rd, value);
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdr(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr, rot, value;
if (!exec) {
disasmInst(inst,
String.format("ldr%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
rot = vaddr & 0x3;
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldr [%08x]", paddr));
return;
}
value = read32(paddr);
switch (rot) {
case 0:
//do nothing
break;
case 1:
value = Integer.rotateRight(value, 8);
break;
case 2:
value = Integer.rotateRight(value, 16);
break;
case 3:
value = Integer.rotateRight(value, 24);
break;
default:
throw new IllegalArgumentException("Illegal address " +
String.format("inst:0x%08x, rot:%d.",
inst.getInst(), rot));
}
if (rd == 15) {
setPC(value & 0xfffffffe);
setCPSR_T(BitOp.getBit32(value, 0));
} else {
setReg(rd, value);
}
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrh(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr, value;
if (!exec) {
disasmInst(inst,
String.format("ldrh%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 2, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrh [%08x]", paddr));
return;
}
value = read16(paddr) & 0xffff;
setReg(rd, value);
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrsb(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr, value;
if (!exec) {
disasmInst(inst,
String.format("ldrsb%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 1, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrsb [%08x]", paddr));
return;
}
value = read8(paddr);
setReg(rd, value);
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrsh(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr, value;
if (!exec) {
disasmInst(inst,
String.format("ldrsh%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 2, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrsh [%08x]", paddr));
return;
}
value = read16(paddr);
setReg(rd, value);
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdrd(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr, value1, value2;
if (!exec) {
disasmInst(inst,
String.format("ldrd%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr) || !tryRead(paddr + 4)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldrd [%08x]", paddr));
return;
}
value1 = read32(paddr);
value2 = read32(paddr + 4);
setReg(rd, value1);
setReg(rd + 1, value2);
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
public void executePld(Instruction inst, boolean exec) {
boolean r = inst.getBit(22);
if (!exec) {
disasmInst(inst,
String.format("pld%s", (r) ? "" : "w"),
String.format("%s", getOffsetAddressName(inst)));
return;
}
//pld cond NV
//do noting
}
public void executeStrt(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
public void executeStrbt(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeStrb(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr;
if (!exec) {
disasmInst(inst,
String.format("strb%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 1, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryWrite(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("strb [%08x]", paddr));
return;
}
write8(paddr, (byte) getReg(rd));
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeStr(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetAddress(inst);
int vaddr, paddr;
if (!exec) {
disasmInst(inst,
String.format("str%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetAddressName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryWrite(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("str [%08x]", paddr));
return;
}
write32(paddr, getReg(rd));
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeStrh(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr;
if (!exec) {
disasmInst(inst,
String.format("strh%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 2, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryWrite(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("strh [%08x]", paddr));
return;
}
write16(paddr, (short) getReg(rd));
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeStrd(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rd = inst.getRdField();
int offset = getOffsetHalf(inst);
int vaddr, paddr;
if (!exec) {
disasmInst(inst,
String.format("strd%s", inst.getCondFieldName()),
String.format("%s, %s", getRegName(rd),
getOffsetHalfName(inst)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (p) {
vaddr = offset;
} else {
vaddr = getReg(rn);
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryWrite(paddr) || !tryWrite(paddr + 4)) {
raiseException(EXCEPT_ABT_DATA,
String.format("strd [%08x]", paddr));
return;
}
write32(paddr, getReg(rd));
write32(paddr + 4, getReg(rd + 1));
if (!p || w) {
// !(p && !w) P, W
setReg(rn, offset);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeLdm1(Instruction inst, boolean exec) {
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rlist = inst.getRegListField();
int vaddr, paddr, len;
if (!exec) {
disasmInst(inst,
String.format("ldm%s%s",
inst.getCondFieldName(),
inst.getPUFieldName()),
String.format("%s%s, {%s}",
getRegName(rn), (w) ? "!" : "",
inst.getRegListFieldName()));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
//r15
vaddr = getRegistersStartAddress(inst.getPUField(), rn, rlist);
len = getRegistersLength(inst.getPUField(), rlist);
for (int i = 0; i < 15; i++) {
if ((rlist & (1 << i)) == 0) {
continue;
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldm(1) [%08x]", paddr));
return;
}
setReg(i, read32(paddr));
vaddr += 4;
}
//r15
if (BitOp.getBit32(rlist, 15)) {
int v;
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldm(1) [%08x]", paddr));
return;
}
v = read32(paddr);
setPC(v & 0xfffffffe);
setCPSR_T(BitOp.getBit32(v, 0));
vaddr += 4;
}
if (w) {
setReg(rn, getReg(rn) + len);
}
}
public void executeLdm2(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
public void executeLdm3(Instruction inst, boolean exec) {
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rlist = inst.getRegListField();
int vaddr, paddr, len, v;
if (!exec) {
disasmInst(inst,
String.format("ldm%s%s",
inst.getCondFieldName(),
inst.getPUFieldName()),
String.format("%s%s, {%s}^",
getRegName(rn), (w) ? "!" : "",
inst.getRegListFieldName()));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
//r15
vaddr = getRegistersStartAddress(inst.getPUField(), rn, rlist);
len = getRegistersLength(inst.getPUField(), rlist);
for (int i = 0; i < 15; i++) {
if ((rlist & (1 << i)) == 0) {
continue;
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldm(3) [%08x]", paddr));
return;
}
setReg(i, read32(paddr));
vaddr += 4;
}
//CPSR SPSR
setCPSR(getSPSR());
//r15
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("ldm(3) [%08x]", paddr));
return;
}
v = read32(paddr);
setPC(v & 0xfffffffe);
setCPSR_T(BitOp.getBit32(v, 0));
vaddr += 4;
if (w) {
setReg(rn, getReg(rn) + len);
}
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeStm1(Instruction inst, boolean exec) {
int pu = inst.getPUField();
boolean w = inst.getBit(21);
int rn = inst.getRnField();
int rlist = inst.getRegListField();
int vaddr, paddr, len;
if (!exec) {
disasmInst(inst,
String.format("stm%s%s",
inst.getCondFieldName(),
inst.getPUFieldName()),
String.format("%s%s, {%s}",
getRegName(rn), (w) ? "!" : "",
inst.getRegListFieldName()));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
vaddr = getRegistersStartAddress(pu, rn, rlist);
len = getRegistersLength(pu, rlist);
for (int i = 0; i < 16; i++) {
if ((rlist & (1 << i)) == 0) {
continue;
}
paddr = getMMU().translate(vaddr, 4, false, isPrivMode(), false);
if (getMMU().isFault()) {
getMMU().clearFault();
return;
}
if (!tryWrite(paddr)) {
raiseException(EXCEPT_ABT_DATA,
String.format("stm(1) [%08x]", paddr));
return;
}
write32(paddr, getReg(i));
vaddr += 4;
}
if (w) {
setReg(rn, getReg(rn) + len);
}
}
public void executeStm2(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeBl(Instruction inst, boolean exec) {
boolean l = inst.getBit(24);
int imm24 = inst.getField(0, 24);
int simm24 = (int) signExt64(imm24, 24) << 2;
if (!exec) {
disasmInst(inst,
String.format("b%s%s",
(l) ? "l" : "", inst.getCondFieldName()),
String.format("%08x", getPC() + simm24));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
if (l) {
setReg(14, getPC() - 4);
}
jumpRel(simm24);
}
public void executeBlx1(Instruction inst, boolean exec) {
boolean h = inst.getBit(24);
int vh = BitOp.toInt(h) << 1;
int imm24 = inst.getField(0, 24);
int simm24 = (int) signExt64(imm24, 24) << 2;
if (!exec) {
disasmInst(inst,
String.format("blx"),
String.format("%08x", getPC() + simm24 + vh));
return;
}
//blx cond NV
setReg(14, getPC() - 4);
setCPSR_T(true);
jumpRel(simm24 + vh);
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
public void executeBlx2(Instruction inst, boolean exec) {
int rm = inst.getRmField();
int dest;
if (!exec) {
disasmInst(inst,
String.format("blx"),
String.format("%s", getRegName(rm)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
dest = getReg(rm);
setReg(14, getPC() - 4);
setCPSR_T(BitOp.getBit32(dest, 0));
setPC(dest & 0xfffffffe);
}
/**
*
*
* Thumb
*
* @param inst ARM
* @param exec true false
*/
public void executeBx(Instruction inst, boolean exec) {
int rm = inst.getRmField();
int dest;
if (!exec) {
disasmInst(inst,
String.format("bx%s", inst.getCondFieldName()),
String.format("%s", getRegName(rm)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
dest = getReg(rm);
setCPSR_T((dest & 0x1) == 1);
setPC(dest & 0xfffffffe);
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeClz(Instruction inst, boolean exec) {
int rd = inst.getRdField();
int rm = inst.getRmField();
int dest;
if (!exec) {
disasmInst(inst,
String.format("clz%s", inst.getCondFieldName()),
String.format("%s, %s",
getRegName(rd), getRegName(rm)));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
dest = Integer.numberOfLeadingZeros(getReg(rm));
setReg(rd, dest);
}
public void executeCdp(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
* ARM
*
* @param inst ARM
* @param exec true false
*/
public void executeMcr(Instruction inst, boolean exec) {
int opcode1 = inst.getField(21, 3);
int crn = inst.getField(16, 4);
int rd = inst.getRdField();
int cpnum = inst.getField(8, 4);
int opcode2 = inst.getField(5, 3);
int crm = inst.getField(0, 4);
CoProc cp;
int crid;
if (!exec) {
disasmInst(inst,
String.format("mcr%s", inst.getCondFieldName()),
String.format("%s, %d, %s, %s, %s, {%d}",
getCoproc(cpnum).toString(), opcode1,
getRegName(rd), getCoprocRegName(cpnum, crn),
getCoprocRegName(cpnum, crm), opcode2));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
cp = getCoproc(cpnum);
if (cp == null) {
//TODO: for debug, will be removed
throw new IllegalArgumentException(String.format(
"Unimplemented coprocessor, p%d selected.", cpnum));
//raiseException(EXCEPT_UND, "Unimplemented coprocessor, " +
// String.format("p%d selected.", cpnum));
//return;
}
crid = CoProc.getCRegID(crn, opcode1, crm, opcode2);
if (!cp.validCRegNumber(crid)) {
//TODO: for debug, will be removed
throw new IllegalArgumentException("Unimplemented coprocessor register, " +
String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.",
cpnum, crid, crn, opcode1, crm, opcode2));
//raiseException(EXCEPT_UND, "Unimplemented coprocessor register, " +
// String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.",
// cpnum, crid, crn, opcode1, crm, opcode2));
//return;
}
cp.setCReg(crid, getReg(rd));
}
/**
* ARM
*
* @param inst ARM
* @param exec true false
*/
public void executeMrc(Instruction inst, boolean exec) {
int opcode1 = inst.getField(21, 3);
int crn = inst.getField(16, 4);
int rd = inst.getRdField();
int cpnum = inst.getField(8, 4);
int opcode2 = inst.getField(5, 3);
int crm = inst.getField(0, 4);
CoProc cp;
int crid, crval, rval;
if (!exec) {
disasmInst(inst,
String.format("mrc%s", inst.getCondFieldName()),
String.format("p%d, %d, %s, %s, %s, {%d}",
cpnum, opcode1,
getRegName(rd), getCoprocRegName(cpnum, crn),
getCoprocRegName(cpnum, crm), opcode2));
return;
}
if (!inst.satisfiesCond(getCPSR())) {
return;
}
cp = getCoproc(cpnum);
if (cp == null) {
//TODO: for debug, will be removed
throw new IllegalArgumentException(String.format(
"Unimplemented coprocessor, p%d selected.", cpnum));
//raiseException(EXCEPT_UND, "Unimplemented coprocessor, " +
// String.format("p%d selected.", cpnum));
//return;
}
crid = CoProc.getCRegID(crn, opcode1, crm, opcode2);
if (!cp.validCRegNumber(crid)) {
//TODO: for debug, will be removed
throw new IllegalArgumentException("Unimplemented coprocessor register, " +
String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.",
cpnum, crid, crn, opcode1, crm, opcode2));
//raiseException(EXCEPT_UND, "Unimplemented coprocessor register, " +
// String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.",
// cpnum, crid, crn, opcode1, crm, opcode2));
//return;
}
crval = cp.getCReg(crid);
if (rd == 15) {
//r15 r15 APSR N, Z, C, V
rval = getSPSR();
rval &= ~0xf0000000;
rval |= crval & 0xf0000000;
setAPSR(rval);
} else {
setReg(rd, crval);
}
}
public void executeSwi(Instruction inst, boolean exec) {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
* @param inst ARM
* @param exec true false
*/
public void executeUnd(Instruction inst, boolean exec) {
if (!exec) {
disasmInst(inst,
String.format("und%s", inst.getCondFieldName()),
"");
return;
}
raiseException(EXCEPT_ABT_INST, "Warning: Undefined instruction " +
String.format("inst:0x%08x.", inst.getInst()));
}
/**
*
*
* @return inst ARM
*/
public Instruction fetch() {
Instruction inst;
int v, vaddr, paddr;
vaddr = getPC() - 8;
paddr = getMMU().translate(vaddr, 4, true, isPrivMode(), true);
if (getMMU().isFault()) {
getMMU().clearFault();
return null;
}
if (!tryRead(paddr)) {
raiseException(EXCEPT_ABT_INST,
String.format("exec [%08x]", paddr));
return null;
}
v = read32(paddr);
inst = new Instruction(v);
return inst;
}
/**
*
*
* @param inst ARM
*/
public void disasm(Instruction inst) {
executeInst(inst, false);
}
/**
*
*
* @param inst ARM
* @param operation
* @param operand
*/
public void disasmInst(Instruction inst, String operation, String operand) {
printDisasm(inst, operation, operand);
printRegs();
}
/**
*
*
* @param inst ARM
*/
public void execute(Instruction inst) {
executeInst(inst, true);
}
/**
*
*
* @param inst ARM
* @param exec true
* false
*/
public void executeInst(Instruction inst, boolean exec) {
int cond = inst.getCondField();
int subcode = inst.getSubCodeField();
switch (subcode) {
case Instruction.SUBCODE_USEALU:
executeSubALU(inst, exec);
return;
case Instruction.SUBCODE_LDRSTR:
executeSubLdrStr(inst, exec);
return;
case Instruction.SUBCODE_LDMSTM:
executeSubLdmStm(inst, exec);
return;
case Instruction.SUBCODE_COPSWI:
executeSubCopSwi(inst, exec);
return;
default:
//do nothing
break;
}
throw new IllegalArgumentException("Unknown Subcode" +
String.format("(%d).", subcode));
}
/**
*
*
* subcode = 0b00
*
* @param inst ARM
* @param exec true false
*/
public void executeSubALU(Instruction inst, boolean exec) {
boolean i = inst.getIBit();
boolean b7 = inst.getBit(7);
boolean b4 = inst.getBit(4);
if (!i) {
//b7, b4
// 0, 0:
// 1, 0:
// 0, 1:
// 1, 1:
if (!b4) {
executeSubALUShiftImm(inst, exec);
} else if (!b7 && b4) {
executeSubALUShiftReg(inst, exec);
} else {
int cond = inst.getCondField();
boolean p = inst.getBit(24);
int op = inst.getField(5, 2);
if (cond != Instruction.COND_NV && !p && op == 0) {
executeSubExtALU(inst, exec);
} else {
executeSubExtLdrStr(inst, exec);
}
}
} else {
executeSubALUImm(inst, exec);
}
}
/**
*
*
*
* @param inst ARM
* @param exec true false
*/
public void executeSubALUShiftImm(Instruction inst, boolean exec) {
int id = inst.getOpcodeSBitShiftID();
switch (id) {
case Instruction.OPCODE_S_OTH:
executeSubALUOther(inst, exec);
break;
default:
executeALU(inst, exec, id);
break;
}
}
/**
*
*
*
* @param inst ARM
* @param exec true false
*/
public void executeSubALUShiftReg(Instruction inst, boolean exec) {
int id = inst.getOpcodeSBitShiftID();
switch (id) {
case Instruction.OPCODE_S_OTH:
executeSubALUOther(inst, exec);
break;
default:
executeALU(inst, exec, id);
break;
}
}
/**
*
*
*
* cond != NV
* bit[27:24] = 0b0000
* bit[7:4] = 0b1001
*
* @param inst ARM
* @param exec true false
*/
public void executeSubExtALU(Instruction inst, boolean exec) {
//U, B, W [23:21]
int ubw = inst.getField(21, 3);
switch (ubw) {
case 1:
//mla
executeMla(inst, exec);
break;
case 0:
//mul
executeMul(inst, exec);
break;
case 7:
//smlal
executeSmlal(inst, exec);
break;
case 6:
//smull
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
//break;
case 5:
//umlal
executeUmlal(inst, exec);
break;
case 4:
//umull
executeUmull(inst, exec);
break;
default:
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
}
public void executeSubExtLdrStr(Instruction inst, boolean exec) {
boolean p = inst.getBit(24);
//U, B, W [23:21]
int ubw = inst.getField(21, 3);
boolean l = inst.getBit(20);
int op = inst.getField(5, 2);
if (p && op == 0) {
switch (ubw) {
case 0:
//swp
executeSwp(inst, exec);
break;
case 1:
//swpb
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
//break;
default:
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
} else if (op == 1) {
if (l) {
//ldrh
executeLdrh(inst, exec);
} else {
//strh
executeStrh(inst, exec);
}
} else if (op == 2) {
if (l) {
//ldrsb
executeLdrsb(inst, exec);
} else {
//ldrd
executeLdrd(inst, exec);
}
} else if (op == 3) {
if (l) {
//ldrsh
executeLdrsh(inst, exec);
} else {
//strd
executeStrd(inst, exec);
}
} else {
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
}
/**
*
*
*
*
*
*
* @param inst ARM
* @param exec true false
*/
public void executeSubALUImm(Instruction inst, boolean exec) {
int id = inst.getOpcodeSBitImmID();
switch (id) {
case Instruction.OPCODE_S_MSR:
executeMsr(inst, exec);
break;
case Instruction.OPCODE_S_UND:
executeUnd(inst, exec);
break;
default:
executeALU(inst, exec, id);
break;
}
}
public void executeSubALUOther(Instruction inst, boolean exec) {
int cond = inst.getCondField();
boolean b22 = inst.getBit(22);
boolean b21 = inst.getBit(21);
int type = inst.getField(4, 4);
switch (type) {
case 0x0:
if (!b21) {
//mrs
executeMrs(inst, exec);
} else {
//msr
executeMsr(inst, exec);
}
break;
case 0x1:
if (!b22 && b21) {
executeBx(inst, exec);
} else if (b22 && b21) {
//clz
executeClz(inst, exec);
} else {
executeUnd(inst, exec);
}
break;
case 0x3:
if (!b22 && b21) {
//blx(2)
executeBlx2(inst, exec);
} else {
executeUnd(inst, exec);
}
break;
case 0x7:
if (cond == Instruction.COND_AL && !b22 && b21) {
//bkpt
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
} else {
executeUnd(inst, exec);
}
break;
default:
//executeUnd(inst, exec);
//break;
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
}
public void executeSubLdrStr(Instruction inst, boolean exec) {
int cond = inst.getCondField();
boolean i = inst.getBit(25);
boolean p = inst.getBit(24);
boolean b = inst.getBit(22);
boolean w = inst.getBit(21);
boolean l = inst.getLBit();
int rd = inst.getRdField();
boolean b4 = inst.getBit(4);
if (i && b4) {
executeUnd(inst, exec);
} else if (l) {
if (!p && !b && w) {
//ldrt
executeLdrt(inst, exec);
} else if (!p && b && w) {
//ldrbt
executeLdrbt(inst, exec);
} else if (b) {
if (cond == inst.COND_NV && p && !w && rd == 15) {
//pld
executePld(inst, exec);
} else {
//ldrb
executeLdrb(inst, exec);
}
} else if (!b) {
//ldr
executeLdr(inst, exec);
} else {
throw new IllegalArgumentException("Illegal P,B,W bits " +
String.format("p:%b, b:%b, w:%b.", p, b, w));
}
} else if (!l) {
if (!p && !b && w) {
//strt
executeStrt(inst, exec);
} else if (!p && b && w) {
//strbt
executeStrbt(inst, exec);
} else if (b) {
//strb
executeStrb(inst, exec);
} else if (!b) {
//str
executeStr(inst, exec);
} else {
throw new IllegalArgumentException("Illegal P,B,W bits " +
String.format("p:%b, b:%b, w:%b.", p, b, w));
}
} else {
throw new IllegalArgumentException("Illegal P,B,W,L bits " +
String.format("p:%b, b:%b, w:%b, l:%b.", p, b, w, l));
}
}
/**
*
*
* subcode = 0b10
*
* @param inst ARM
* @param exec true false
*/
public void executeSubLdmStm(Instruction inst, boolean exec) {
int cond = inst.getCondField();
boolean b25 = inst.getBit(25);
boolean l = inst.getLBit();
if (!b25) {
if (cond == Instruction.COND_NV) {
executeUnd(inst, exec);
} else {
if (l) {
//ldm(1), ldm(2), ldm(3)
executeSubLdm(inst, exec);
} else {
//stm(1), stm(2)
executeSubStm(inst, exec);
}
}
} else {
if (cond == Instruction.COND_NV) {
//blx
executeBlx1(inst, exec);
} else {
//b, bl
executeBl(inst, exec);
}
}
}
/**
*
*
* subcode = 0b10
*
* @param inst ARM
* @param exec true false
*/
public void executeSubLdm(Instruction inst, boolean exec) {
boolean s = inst.getBit(22);
boolean b15 = inst.getBit(15);
if (!s) {
//ldm(1)
executeLdm1(inst, exec);
} else {
if (!b15) {
//ldm(2)
executeLdm2(inst, exec);
} else {
//ldm(3)
executeLdm3(inst, exec);
}
}
}
/**
*
*
* subcode = 0b10
*
* @param inst ARM
* @param exec true false
*/
public void executeSubStm(Instruction inst, boolean exec) {
boolean s = inst.getBit(22);
boolean w = inst.getBit(21);
if (!s) {
//stm(1)
executeStm1(inst, exec);
} else {
if (!w) {
//stm(2)
executeStm2(inst, exec);
} else {
executeUnd(inst, exec);
}
}
}
/**
*
*
* subcode = 0b11
*
* @param inst ARM
* @param exec true false
*/
public void executeSubCopSwi(Instruction inst, boolean exec) {
int cond = inst.getCondField();
int subsub = inst.getField(24, 2);
boolean b20 = inst.getBit(20);
boolean b4 = inst.getBit(4);
switch (subsub) {
case 0:
case 1:
if (b20) {
//ldc
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
} else {
//stc
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
//break;
case 2:
if (!b4) {
//cdp
executeCdp(inst, exec);
} else {
if (!b20) {
//mcr
executeMcr(inst, exec);
} else {
//mrc
executeMrc(inst, exec);
}
}
return;
case 3:
if (cond == Instruction.COND_NV) {
executeUnd(inst, exec);
} else {
//swi
executeSwi(inst, exec);
}
return;
default:
//do nothing
break;
}
throw new IllegalArgumentException("Illegal b25, b24 bits " +
String.format("b25b24:%d.", subsub));
}
public static final int EXCEPT_RST = 0;
public static final int EXCEPT_ABT_DATA = 1;
public static final int EXCEPT_FIQ = 2;
public static final int EXCEPT_IRQ = 3;
public static final int EXCEPT_ABT_INST = 4;
public static final int EXCEPT_UND = 5;
public static final int EXCEPT_SVC = 6;
/**
*
*
* @param num EXCEPT_xxxx
* @param dbgmsg
*/
public void raiseException(int num, String dbgmsg) {
if (num < 0 || exceptions.length <= num) {
throw new IllegalArgumentException("Illegal exception number " + num);
}
if (isRaised()) {
throw new IllegalStateException("Except status not cleared.");
}
exceptions[num] = true;
exceptionReasons[num] = dbgmsg;
setRaised(true);
}
public void doImportantException() {
boolean found = false;
int i;
for (i = 0; i < exceptions.length; i++) {
if (exceptions[i]) {
exceptions[i] = false;
found = true;
break;
}
}
if (!found) {
return;
}
switch (i) {
case EXCEPT_RST:
doExceptionReset(exceptionReasons[i]);
break;
case EXCEPT_UND:
doExceptionUndefined(exceptionReasons[i]);
break;
case EXCEPT_SVC:
doExceptionSoftware(exceptionReasons[i]);
break;
case EXCEPT_ABT_INST:
doExceptionPrefetch(exceptionReasons[i]);
break;
case EXCEPT_ABT_DATA:
doExceptionData(exceptionReasons[i]);
break;
case EXCEPT_IRQ:
doExceptionIRQ(exceptionReasons[i]);
break;
case EXCEPT_FIQ:
doExceptionFIQ(exceptionReasons[i]);
break;
default:
throw new IllegalArgumentException("Illegal exception number " + i);
}
}
/**
*
*
* @param dbgmsg
*/
public void doExceptionReset(String dbgmsg) {
int spsrOrg;
System.out.printf("Exception: Reset by '%s'.\n",
dbgmsg);
//cpsr
spsrOrg = getCPSR();
//ARM
setCPSR_Mode(MODE_SVC);
setCPSR_T(false);
setCPSR_F(true);
setCPSR_I(true);
//spsr cpsr
setSPSR(spsrOrg);
if (isHighVector()) {
setPC(0xffff0000);
} else {
setPC(0x00000000);
}
}
/**
*
*
*
*
*
* @param dbgmsg
*/
public void doExceptionUndefined(String dbgmsg) {
int pcOrg, spsrOrg;
System.out.printf("Exception: Undefined instruction by '%s'.\n",
dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//ARM
setCPSR_Mode(MODE_UND);
setCPSR_T(false);
//F flag is not affected
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
if (isHighVector()) {
setPC(0xffff0004);
} else {
setPC(0x00000004);
}
//tentative...
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
* swi
*
* @param dbgmsg
*/
public void doExceptionSoftware(String dbgmsg) {
int pcOrg, spsrOrg;
System.out.printf("Exception: Software interrupt by '%s'.\n",
dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//ARM
setCPSR_Mode(MODE_SVC);
setCPSR_T(false);
//F flag is not affected
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
if (isHighVector()) {
setPC(0xffff0008);
} else {
setPC(0x00000008);
}
//tentative...
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
*
*
* @param dbgmsg
*/
public void doExceptionPrefetch(String dbgmsg) {
int pcOrg, spsrOrg;
System.out.printf("Exception: Prefetch abort by '%s'.\n",
dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//ARM
setCPSR_Mode(MODE_ABT);
setCPSR_T(false);
//F flag is not affected
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
if (isHighVector()) {
setPC(0xffff000c);
} else {
setPC(0x0000000c);
}
//tentative...
//TODO: Not implemented
throw new IllegalArgumentException("Sorry, not implemented.");
}
/**
*
*
*
*
* @param dbgmsg
*/
public void doExceptionData(String dbgmsg) {
int pcOrg, spsrOrg;
System.out.printf("Exception: Data abort by '%s'.\n",
dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//ARM
setCPSR_Mode(MODE_ABT);
setCPSR_T(false);
//F flag is not affected
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
if (isHighVector()) {
setPC(0xffff0010);
} else {
setPC(0x00000010);
}
}
/**
*
*
* IRQ
*
* @param dbgmsg
*/
public void doExceptionIRQ(String dbgmsg) {
int pcOrg, spsrOrg;
//System.out.printf("Exception: IRQ by '%s'.\n",
// dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//IRQ ARM
setCPSR_Mode(MODE_IRQ);
setCPSR_T(false);
//F flag is not affected
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
//IRQ
if (isHighVector()) {
setPC(0xffff0018);
} else {
setPC(0x00000018);
}
}
/**
*
*
* FIQ
*
* @param dbgmsg
*/
public void doExceptionFIQ(String dbgmsg) {
int pcOrg, spsrOrg;
System.out.printf("Exception: FIQ by '%s'.\n",
dbgmsg);
//pc, cpsr
pcOrg = getPC() - 4;
spsrOrg = getCPSR();
//FIQ ARM
setCPSR_Mode(MODE_FIQ);
setCPSR_T(false);
setCPSR_F(true);
setCPSR_I(true);
//lr, spsr pc, cpsr
setReg(14, pcOrg);
setSPSR(spsrOrg);
//FIQ
if (isHighVector()) {
setPC(0xffff001c);
} else {
setPC(0x0000001c);
}
}
/**
*
*
* setINTC()
* NullINTC
*
* @return
*/
public INTC getINTCForIRQ() {
return intcIRQ;
}
/**
*
*
* CPU
*
* @param c
*/
public void setINTCForIRQ(INTC c) {
intcIRQ = c;
}
/**
*
*
* setINTC()
* NullINTC
*
* @return
*/
public INTC getINTCForFIQ() {
return intcFIQ;
}
/**
*
*
* CPU
*
* @param c
*/
public void setINTCForFIQ(INTC c) {
intcFIQ = c;
}
/**
*
* IRQ
*/
public void acceptIRQ() {
INTC cnt;
Iterator<INTC> it;
String msg;
if (getCPSR_I()) {
//I 1 IRQ
return;
}
if (!getINTCForIRQ().isAssert()) {
return;
}
msg = String.format("accept IRQ from '%s'",
getINTCForIRQ().getIRQMessage());
raiseException(EXCEPT_IRQ, msg);
}
/**
*
* FIQ
*/
public void acceptFIQ() {
String msg;
if (getCPSR_F()) {
//F 1 FIQ
return;
}
if (!getINTCForFIQ().isAssert()) {
return;
}
msg = String.format("accept FIQ from '%s'",
getINTCForFIQ().getIRQMessage());
raiseException(EXCEPT_FIQ, msg);
}
/**
*
* CPU
*
* @return CPU true false
*/
public boolean isRaised() {
return raised;
}
/**
* CPU
*
* @param m CPU true false
*/
public void setRaised(boolean m) {
raised = m;
}
/**
* CPU
*/
public void clearRaised() {
setRaised(false);
}
/**
*
*
* @return true false
*/
public boolean isJumped() {
return jumped;
}
/**
*
*
* @param b true false
*/
public void setJumped(boolean b) {
jumped = b;
}
/**
* 0xffff00000xffff001c
* 0x000000000x0000001c
*
* @return true
* false
*/
public boolean isHighVector() {
return highVector;
}
/**
* 0xffff00000xffff001c
* 0x000000000x0000001c
*
* @param m true
* false
*/
public void setHighVector(boolean m) {
highVector = m;
}
@Override
public void step() {
Instruction inst;
//for debug
int target_address1 = 0;//0xc036aee8; //<versatile_init_irq>
int target_address2 = 0;//0xc036aee8; //<versatile_init_irq>
doImportantException();
//IRQ
acceptIRQ();
if (isRaised()) {
clearRaised();
return;
}
inst = fetch();
if (isRaised()) {
clearRaised();
return;
}
//for debug,
if (getPC() - 8 == target_address1) {
setDisasmMode(true);
setPrintDisasm(true);
}
if (getPC() - 8 == target_address2) {
setPrintRegs(true);
}
if (isDisasmMode()) {
disasm(inst);
}
//for debug,
if (isPrintRegs()) {
int a = 0;
}
execute(inst);
nextPC();
if (isRaised()) {
clearRaised();
return;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.