answer
stringlengths
17
10.2M
package com.namelessmc.plugin.velocity; import com.google.inject.Inject; import com.namelessmc.plugin.common.*; import com.namelessmc.plugin.common.command.AbstractScheduler; import com.namelessmc.plugin.common.command.CommonCommand; import com.velocitypowered.api.command.Command; import com.velocitypowered.api.command.SimpleCommand; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; import net.kyori.adventure.platform.AudienceProvider; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.MappingNode; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @Plugin(id = "nameless-plugin", name = "Nameless Plugin", version = "@project.version@", url = "https://plugin.namelessmc.com/", description = "Integration with NamelessMC websites", authors = {"Derkades"}) public class NamelessPlugin implements CommonObjectsProvider { private final AbstractScheduler scheduler; @Override public AbstractScheduler getScheduler() { return this.scheduler; } private LanguageHandler language; @Override public LanguageHandler getLanguage() { return this.language; } private ApiProvider apiProvider; @Override public ApiProvider getApiProvider() { return this.apiProvider; } private AudienceProvider adventure; @Override public AudienceProvider adventure() { return this.adventure; } private ExceptionLogger exceptionLogger; @Override public ExceptionLogger getExceptionLogger() { return this.exceptionLogger; } private AbstractYamlFile commandsConfig; @Override public AbstractYamlFile getCommandsConfig() { return this.commandsConfig; } private final @NotNull Yaml yaml = new Yaml(); private MappingNode mainConfig; private final ArrayList<String> registeredCommands = new ArrayList<>(); private final @NotNull ProxyServer server; private final @NotNull Logger logger; private final @NotNull Path dataDirectory; @Inject public NamelessPlugin(final @NotNull ProxyServer server, final @NotNull Logger logger, final @NotNull @DataDirectory Path dataDirectory) { this.server = server; this.logger = logger; this.dataDirectory = dataDirectory; this.scheduler = new AbstractScheduler() { @Override public void runAsync(final Runnable runnable) { NamelessPlugin.this.server.getScheduler().buildTask(NamelessPlugin.this, runnable).schedule(); } @Override public void runSync(final Runnable runnable) { // Velocity has no "main thread", we can just run it in the current thread runnable.run(); } }; } @Subscribe public void onProxyInitialization(ProxyInitializeEvent event) { this.reload(); } private MappingNode copyFromJarAndLoad(String name) throws IOException { Path path = this.dataDirectory.resolve(name); if (!Files.isRegularFile(path)) { try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(name)) { Files.copy(in, path); } } try (Reader reader = Files.newBufferedReader(path)) { return (MappingNode) yaml.compose(reader); } } private void reload() { try { this.mainConfig = copyFromJarAndLoad("config.yml"); this.commandsConfig = new YamlFileImpl(copyFromJarAndLoad("commands.yml")); } catch (IOException e) { throw new RuntimeException(e); } this.registerCommands(); } private void registerCommands() { for (String registeredName : registeredCommands) { this.server.getCommandManager().unregister(registeredName); } registeredCommands.clear(); CommonCommand.getEnabledCommands(this).forEach(command -> { final String permission = command.getPermission().toString(); Command velocityCommand = new SimpleCommand() { @Override public void execute(Invocation invocation) { command.execute(new VelocityCommandSender(invocation.source()), invocation.arguments()); } @Override public boolean hasPermission(final Invocation invocation) { return invocation.source().hasPermission(permission); } }; String name = command.getActualName(); this.server.getCommandManager().register(name, velocityCommand); this.registeredCommands.add(name); }); this.registeredCommands.trimToSize(); } }
package com.oux.photocaption; import android.support.v4.view.PagerAdapter; import android.provider.MediaStore; import android.content.Context; import java.nio.charset.CharsetEncoder; import java.nio.charset.Charset; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.LayoutInflater; import android.view.View; import android.util.Log; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.widget.TextView; import android.widget.ImageView; import android.view.WindowManager; import android.view.Display; import android.graphics.Point; import com.android.gallery3d.exif.ExifInterface; import com.android.gallery3d.exif.ExifTag; import com.android.gallery3d.exif.IfdId; import uk.co.senab.photoview.PhotoView; import android.webkit.MimeTypeMap; class PhotoCaptionPagerAdapter extends PagerAdapter { private PhotoCaptionView mContext; private int layoutResourceId; private Cursor externalCursor; private Uri externalContentUri; private int externalColumnIndex; static final String TAG = "photoCaptionPagerAdapter"; private Uri mImageUriForced; Point mSize; public void setContext(PhotoCaptionView context) { mContext = context; WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); mSize = new Point(); display.getSize(mSize); //Do the query externalContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String[] projection = {MediaStore.Images.Media._ID}; String selection = MediaStore.Files.FileColumns.MIME_TYPE + "=?"; String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpeg"); String [] selectionArgs = new String[]{ mimeType }; externalCursor = mContext.getContentResolver().query( externalContentUri,projection, selection,selectionArgs, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC, " + MediaStore.Images.ImageColumns._ID + " DESC"); externalColumnIndex = externalCursor.getColumnIndex(MediaStore.Images.Media._ID); } public void forceUri(Uri imageUri) { mImageUriForced = imageUri; notifyDataSetChanged(); } public Uri getUri(int position) { externalCursor.moveToPosition(position); int imageID = externalCursor.getInt( externalColumnIndex ); return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,Integer.toString(imageID)); } public int getPosition(long id) { try { externalCursor.moveToFirst(); while (externalCursor.getInt(externalColumnIndex) != id) { externalCursor.moveToNext(); } return externalCursor.getPosition(); } catch (Exception e) { return -1; } } public int getPosition(String filePath) { String[] projection = {MediaStore.Images.Media._ID}; String selection = MediaStore.Images.ImageColumns.DATA + " LIKE ?"; String [] selectionArgs = {filePath}; Cursor cursor = mContext.getContentResolver().query( externalContentUri,projection, selection,selectionArgs, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); try { long Id = cursor.getLong(columnIndex); Log.d(TAG,"Photo ID is " + Id); cursor.close(); return getPosition(Id); } catch (Exception e) { return -1; } } @Override public int getCount() { if (mImageUriForced == null) return externalCursor.getCount(); else return 1; } @Override public View instantiateItem(ViewGroup container, int position) { Log.i(TAG,"VIEW:" + position + ", container:" + container + ", context:" + container.getContext() + ", mContext:" + mContext); LayoutInflater inflater = (LayoutInflater) container.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.view, null); PhotoView photoView = (PhotoView) view.findViewById(R.id.ImageView); TextView descriptionView = (TextView) view.findViewById(R.id.Description); ExifInterface exifInterface = new ExifInterface(); Bitmap preview_bitmap = null; Uri imageUri = null; if (mImageUriForced == null) { externalCursor.moveToPosition(position); int imageID = externalCursor.getInt( externalColumnIndex ); Log.d(TAG,"Id:" + imageID); imageUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,Integer.toString(imageID)); } else { imageUri = mImageUriForced; } Log.d(TAG,"imageUri:" + imageUri); try { exifInterface.readExif(mContext.getContentResolver().openInputStream(imageUri)); } catch (Exception e) { e.printStackTrace(); } ExifTag tag = exifInterface.getTag(ExifInterface.TAG_USER_COMMENT); String description = null; if (tag != null) { description = tag.getValueAsString(); CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder(); if (! encoder.canEncode(description)) { description="<BINARY DATA>"; } } try { String image; if (imageUri.getScheme().equals("content")) { Log.i(TAG,"Content"); image = getRealPathFromURI(imageUri); } else image = imageUri.getPath(); BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds=true; BitmapFactory.decodeFile(image ,options); int h=(int) Math.ceil(options.outHeight/(float)mSize.y); int w=(int) Math.ceil(options.outWidth/(float)mSize.x); if(h>1 || w>1){ if(h>w){ options.inSampleSize=h; }else{ options.inSampleSize=w; } } options.inJustDecodeBounds=false; preview_bitmap=BitmapFactory.decodeFile(image ,options); photoView.setImageBitmap(preview_bitmap); if (description != "" && description != null && description.length() != 0) { Log.i(TAG,"setText: <"+description + ">("+description.length()+")"); descriptionView.setText(description); } else { Log.i(TAG,"Hidding"); descriptionView.setVisibility(View.INVISIBLE); } // Now just add PhotoView to ViewPager and return it container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } catch (Exception e) { e.printStackTrace(); } return view; } public String getRealPathFromURI(Uri uri) { Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); String ret = cursor.getString(idx); cursor.close(); return ret; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }
package com.ra4king.circuitsim.gui.peers.wiring; import java.util.ArrayList; import java.util.List; import com.ra4king.circuitsim.gui.ComponentManager.ComponentManagerInterface; import com.ra4king.circuitsim.gui.ComponentPeer; import com.ra4king.circuitsim.gui.Connection.PortConnection; import com.ra4king.circuitsim.gui.GuiUtils; import com.ra4king.circuitsim.gui.Properties; import com.ra4king.circuitsim.gui.Properties.Direction; import com.ra4king.Circuitsim.gui.Properties.Base; import com.ra4king.circuitsim.gui.Properties.Property; import com.ra4king.circuitsim.simulator.CircuitState; import com.ra4king.circuitsim.simulator.Component; import com.ra4king.circuitsim.simulator.Port; import com.ra4king.circuitsim.simulator.WireValue; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.util.Pair; /** * @author Roi Atalla */ public class Probe extends ComponentPeer<Component> { public static void installComponent(ComponentManagerInterface manager) { manager.addComponent(new Pair<>("Wiring", "Probe"), new Image(Probe.class.getResourceAsStream("/resources/Probe.png")), new Properties(new Property<>(Properties.DIRECTION, Direction.SOUTH))); } public Probe(Properties props, int x, int y) { super(x, y, 0, 0); Properties properties = new Properties(); properties.ensureProperty(Properties.LABEL); properties.ensureProperty(Properties.LABEL_LOCATION); properties.ensureProperty(Properties.DIRECTION); properties.ensureProperty(Properties.BITSIZE); properties.ensureProperty(Properties.BASE); properties.mergeIfExists(props); int bitSize = properties.getValue(Properties.BITSIZE); Component probe = new Component(properties.getValue(Properties.LABEL), new int[] { bitSize }) { @Override public void valueChanged(CircuitState state, WireValue value, int portIndex) {} }; switch(properties.getValue(Properties.BASE)) { case BINARY: setWidth(Math.max(2, Math.min(8, bitSize))); setHeight((int)Math.round((1 + (bitSize - 1) / 8) * 1.5)); break; case HEXADECIMAL: setWidth(Math.max(2, (int) (bitSize / 4))); setHeight(2); break; } List<PortConnection> connections = new ArrayList<>(); switch(properties.getValue(Properties.DIRECTION)) { case EAST: connections.add(new PortConnection(this, probe.getPort(0), getWidth(), getHeight() / 2)); break; case WEST: connections.add(new PortConnection(this, probe.getPort(0), 0, getHeight() / 2)); break; case NORTH: connections.add(new PortConnection(this, probe.getPort(0), getWidth() / 2, 0)); break; case SOUTH: connections.add(new PortConnection(this, probe.getPort(0), getWidth() / 2, getHeight())); break; } init(probe, properties, connections); } @Override public void paint(GraphicsContext graphics, CircuitState circuitState) { GuiUtils.drawName(graphics, this, getProperties().getValue(Properties.LABEL_LOCATION)); graphics.setFont(GuiUtils.getFont(16)); Port port = getComponent().getPort(0); WireValue value = circuitState.getLastReceived(port); String valStr; switch(getProperties().getValue(Properties.BASE)) { case BINARY: valStr = value.toString(); break; case HEXADECIMAL: valStr = value.toHexString(); break; } if(circuitState.isShortCircuited(port.getLink())) { graphics.setFill(Color.RED); } else { graphics.setFill(Color.LIGHTGRAY); } graphics.setStroke(Color.WHITE); graphics.fillRoundRect(getScreenX(), getScreenY(), getScreenWidth(), getScreenHeight(), 20, 20); graphics.strokeRoundRect(getScreenX(), getScreenY(), getScreenWidth(), getScreenHeight(), 20, 20); graphics.setFill(Color.BLACK); GuiUtils.drawValue(graphics, valStr, getScreenX(), getScreenY(), getScreenWidth()); } }
package com.valkryst.generator; import lombok.NonNull; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public final class CombinatorialGenerator extends NameGenerator { /** The name-beginnings. */ private final String[] beginnings; /** The name-middles. */ private final String[] middles; /** The name-endings. */ private final String[] endings; /** * Constructs a new CombinatorialGenerator. * * @param beginnings * The name-beginnings. * * @param endings * The name-endings. */ public CombinatorialGenerator(final List<String> beginnings, final List<String> endings) { this(beginnings, null, endings); } public CombinatorialGenerator(final List<String> beginnings, List<String> middles, final List<String> endings) { if (middles == null) { middles = Collections.emptyList(); } // Ensure lists aren't empty: if (beginnings == null || beginnings.size() == 0) { throw new IllegalArgumentException("The list of beginnings is empty or null."); } if (endings == null || endings.size() == 0) { throw new IllegalArgumentException("The list of endings is empty or null."); } this.beginnings = beginnings.toArray(new String[0]); this.middles = middles.toArray(new String[0]); this.endings = endings.toArray(new String[0]); } @Override public String generateName(int length) { if (length == 0) { length = 2; } final StringBuilder sb = new StringBuilder(); // Construct Name: sb.append(beginnings[ThreadLocalRandom.current().nextInt(beginnings.length)]); if (middles.length > 0) { while (sb.length() < length) { sb.append(middles[ThreadLocalRandom.current().nextInt(middles.length)]); } } sb.append(endings[ThreadLocalRandom.current().nextInt(endings.length)]); return super.capitalizeFirstCharacter(sb.toString()); } }
package com.valkryst.generator; import lombok.NonNull; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public final class CombinatorialGenerator extends NameGenerator { /** The name-beginnings. */ private final String[] beginnings; /** The name-middles. */ private final String[] middles; /** The name-endings. */ private final String[] endings; /** * Constructs a new CombinatorialGenerator. * * @param beginnings * The name-beginnings. * * @param endings * The name-endings. */ public CombinatorialGenerator(final List<String> beginnings, final List<String> endings) { this(beginnings, null, endings); } public CombinatorialGenerator(List<String> beginnings, List<String> middles, List<String> endings) { if (middles == null) { middles = Collections.emptyList(); } // Ensure lists aren't empty: if (beginnings == null || beginnings.size() == 0) { throw new IllegalArgumentException("The list of beginnings is empty or null."); } if (endings == null || endings.size() == 0) { throw new IllegalArgumentException("The list of endings is empty or null."); } this.beginnings = beginnings.toArray(new String[0]); this.middles = middles.toArray(new String[0]); this.endings = endings.toArray(new String[0]); } @Override public String generateName(int length) { if (length == 0) { length = 2; } final StringBuilder sb = new StringBuilder(); // Construct Name: sb.append(chooseRandomElementFrom(beginnings)); if (middles.length > 0) { while (sb.length() < length) { sb.append(chooseRandomElementFrom(middles)); } } sb.append(chooseRandomElementFrom(endings)); return super.capitalizeFirstCharacter(sb.toString()); } /** * Chooses a random String from an array. * * @param arr * The array. * * @return * A random String from the array. * * @throws NullPointerException * If the array is null. */ private String chooseRandomElementFrom(final @NonNull String[] arr) { final int index = ThreadLocalRandom.current().nextInt(arr.length); return arr[index]; } }
package com.vectrace.MercurialEclipse.model; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.vectrace.MercurialEclipse.HgRevision; import com.vectrace.MercurialEclipse.storage.HgRepositoryLocation; public class ChangeSet implements Comparable<ChangeSet> { public static enum Direction { INCOMING, OUTGOING, LOCAL; } private int changesetIndex; private String changeset; private String tag; private String user; private String date; private FileStatus[] changedFiles; private String description; private String ageDate; private String nodeShort; private String[] parents; private Date realDate; private File bundleFile; private HgRepositoryLocation repository; private Direction direction; private String summary; public ChangeSet() { super(); } public ChangeSet(int changesetIndex, String changeSet, String tag, String user, String date, String description, String[] parents) { this.changesetIndex = changesetIndex; this.changeset = changeSet; this.tag = tag; this.user = user; this.date = date; setDescription(description); setParents(parents); try { if (date != null) { this.realDate = new SimpleDateFormat("yyyy-MM-dd hh:mm Z") .parse(date); } } catch (Exception e) { this.realDate = null; } } public ChangeSet(int changesetIndex, String changeSet, String user, String date) { this(changesetIndex, changeSet, null, user, date, null, null); } public int getChangesetIndex() { return changesetIndex; } public String getChangeset() { return changeset; } public String getTag() { if (tag != null && tag.equals("tip") && bundleFile != null) { tag = tag.concat(" [ ").concat(repository.toString()).concat(" ]"); } return tag; } public String getUser() { return user; } public String getDate() { return date; } public String getDescription() { return description; } public HgRevision getRevision() { return new HgRevision(changeset, changesetIndex); } @Override public String toString() { if (nodeShort != null) { return this.changesetIndex + ":" + this.nodeShort; } return this.changesetIndex + ":" + this.changeset; } /** * @return the changedFiles */ public FileStatus[] getChangedFiles() { if( changedFiles != null) { // Don't let clients manipulate the array in-place return changedFiles.clone(); } return new FileStatus[0]; } /** * @param changedFiles * the changedFiles to set */ public void setChangedFiles(FileStatus[] changedFiles) { this.changedFiles = changedFiles; } /** * @return the ageDate */ public String getAgeDate() { return ageDate; } /** * @param ageDate * the ageDate to set */ public void setAgeDate(String ageDate) { this.ageDate = ageDate; } /** * @return the nodeShort */ public String getNodeShort() { return nodeShort; } /** * @param nodeShort * the nodeShort to set */ public void setNodeShort(String nodeShort) { this.nodeShort = nodeShort; } public int compareTo(ChangeSet o) { if (o.getChangeset().equals(this.getChangeset())) { return 0; } if (realDate != null && o.getRealDate() != null) { int dateCompare = this.getRealDate().compareTo(o.getRealDate()); if (dateCompare != 0) { return dateCompare; } } return this.getChangesetIndex() - o.getChangesetIndex(); } @Override public boolean equals(Object obj) { if (obj != null && obj instanceof ChangeSet) { return this.compareTo((ChangeSet) obj) == 0; } return false; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((changeset == null) ? 0 : changeset.hashCode()); return result; } public Date getRealDate() { return this.realDate; } /** * @return the bundleFile */ public File getBundleFile() { return bundleFile; } /** * @param bundleFile * the bundleFile to set */ public void setBundleFile(File bundleFile) { this.bundleFile = bundleFile; } public String[] getParents() { return parents; } public void setParents(String[] parents) { // filter null parents (hg uses -1 to signify a null parent) List<String> temp = new ArrayList<String>(parents.length); for (int i = 0; i < parents.length; i++) { String parent = parents[i]; if (parent.charAt(0) != '-') { temp.add(parent); } } this.parents = temp.toArray(new String[temp.size()]); } public void setChangesetIndex(int changesetIndex) { this.changesetIndex = changesetIndex; } public void setChangeset(String changeset) { this.changeset = changeset; } public void setTag(String tag) { this.tag = tag; } public void setUser(String user) { this.user = user; } public void setDate(String date) { this.date = date; } public void setDescription(String description) { if (description != null) { int i = description.indexOf('\n'); if (i > 0) { this.summary = description.substring(0, i >= 0 ? i : description.length()); this.description = description; } else { this.summary = description; } } } public void setRealDate(Date realDate) { this.realDate = realDate; } public String getSummary() { return summary; } /** * @return the repository */ public HgRepositoryLocation getRepository() { return repository; } /** * @param repositoryLocation * the repository to set */ public void setRepository(HgRepositoryLocation repositoryLocation) { this.repository = repositoryLocation; } /** * @return the direction */ public Direction getDirection() { return direction; } /** * @param direction * the direction to set */ public void setDirection(Direction direction) { this.direction = direction; } }
package com.vectrace.MercurialEclipse.views; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Set; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareUI; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.team.ui.TeamUI; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.ViewPart; import com.vectrace.MercurialEclipse.MercurialEclipsePlugin; import com.vectrace.MercurialEclipse.commands.HgParentClient; import com.vectrace.MercurialEclipse.commands.HgResolveClient; import com.vectrace.MercurialEclipse.commands.HgStatusClient; import com.vectrace.MercurialEclipse.compare.HgCompareEditorInput; import com.vectrace.MercurialEclipse.compare.RevisionNode; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.menu.CommitMergeHandler; import com.vectrace.MercurialEclipse.menu.UpdateHandler; import com.vectrace.MercurialEclipse.model.FlaggedAdaptable; import com.vectrace.MercurialEclipse.model.HgRoot; import com.vectrace.MercurialEclipse.team.MercurialRevisionStorage; import com.vectrace.MercurialEclipse.team.MercurialTeamProvider; import com.vectrace.MercurialEclipse.team.ResourceProperties; import com.vectrace.MercurialEclipse.team.cache.MercurialStatusCache; import com.vectrace.MercurialEclipse.utils.ResourceUtils; public class MergeView extends ViewPart implements ISelectionListener, Observer { public final static String ID = MergeView.class.getName(); private Label statusLabel; private Table table; private Action abortAction; private Action markResolvedAction; private Action markUnresolvedAction; private HgRoot hgRoot; @Override public void createPartControl(final Composite parent) { parent.setLayout(new GridLayout(1, false)); statusLabel = new Label(parent, SWT.NONE); statusLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); table = new Table(parent, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL); table.setLinesVisible(true); table.setHeaderVisible(true); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.heightHint = 200; table.setLayoutData(data); table.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent event) { TableItem item = (TableItem) event.item; openMergeEditor(item); } }); String[] titles = { Messages.getString("MergeView.column.status"), Messages.getString("MergeView.column.file") }; //$NON-NLS-1$ //$NON-NLS-2$ int[] widths = { 100, 400 }; for (int i = 0; i < titles.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(titles[i]); column.setWidth(widths[i]); } createToolBar(); getSite().getPage().addSelectionListener(this); MercurialStatusCache.getInstance().addObserver(this); } private void createToolBar() { IToolBarManager mgr = getViewSite().getActionBars().getToolBarManager(); abortAction = new Action(Messages.getString("MergeView.abort")) { //$NON-NLS-1$ @Override public void run() { try { UpdateHandler update = new UpdateHandler(); update.setCleanEnabled(true); update.setRevision("."); update.setShell(table.getShell()); update.run(hgRoot); } catch (HgException e) { MercurialEclipsePlugin.logError(e); statusLabel.setText(e.getLocalizedMessage()); } } }; abortAction.setEnabled(false); abortAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_ELCL_STOP)); mgr.add(abortAction); markResolvedAction = new Action(Messages.getString("MergeView.markResolved")) { //$NON-NLS-1$ @Override public void run() { try { IFile file = getSelection(); if (file != null) { HgResolveClient.markResolved(file); populateView(true); } } catch (Exception e) { MercurialEclipsePlugin.logError(e); statusLabel.setText(e.getLocalizedMessage()); } } }; markResolvedAction.setEnabled(false); markUnresolvedAction = new Action(Messages.getString("MergeView.markUnresolved")) { //$NON-NLS-1$ @Override public void run() { try { IFile file = getSelection(); if (file != null) { HgResolveClient.markUnresolved(file); populateView(true); } } catch (Exception e) { MercurialEclipsePlugin.logError(e); statusLabel.setText(e.getLocalizedMessage()); } } }; markUnresolvedAction.setEnabled(false); final Action openMergeEditorAction = new Action("Open in Merge Editor") { @Override public void run() { TableItem[] selection = table.getSelection(); if (selection != null && selection.length > 0) { openMergeEditor(selection[0]); } } }; final Action openEditorAction = new Action("Open in Default Editor") { @Override public void run() { IFile file = getSelection(); if(file == null){ return; } try { IDE.openEditor(getSite().getPage(), file); } catch (PartInitException e) { MercurialEclipsePlugin.logError(e); } } }; final Action actionShowHistory = new Action("Show History") { @Override public void run() { IFile file = getSelection(); if(file == null){ return; } TeamUI.getHistoryView().showHistoryFor(file); } }; actionShowHistory.setImageDescriptor(MercurialEclipsePlugin.getImageDescriptor("history.gif")); // Contribute actions to popup menu final MenuManager menuMgr = new MenuManager(); Menu menu = menuMgr.createContextMenu(table); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr1) { menuMgr1.add(openMergeEditorAction); menuMgr1.add(openEditorAction); menuMgr1.add(new Separator()); menuMgr1.add(actionShowHistory); menuMgr1.add(new Separator()); menuMgr1.add(markResolvedAction); menuMgr1.add(markUnresolvedAction); menuMgr1.add(new Separator()); menuMgr1.add(abortAction); } }); menuMgr.setRemoveAllWhenShown(true); table.setMenu(menu); } private void populateView(boolean attemptToCommit) throws HgException { String mergeNodeId = HgStatusClient.getMergeChangesetId(hgRoot); if(mergeNodeId != null) { statusLabel.setText("Merging " + hgRoot.getName() + " with " + mergeNodeId); } else { statusLabel.setText("Merging " + hgRoot.getName()); } List<FlaggedAdaptable> status = null; status = HgResolveClient.list(hgRoot); table.removeAll(); for (FlaggedAdaptable flagged : status) { TableItem row = new TableItem(table, SWT.NONE); row.setText(0, flagged.getStatus()); IFile iFile = ((IFile) flagged.getAdapter(IFile.class)); row.setText(1, iFile.getProjectRelativePath().toString()); row.setData(flagged); if (flagged.getFlag() == MercurialStatusCache.CHAR_UNRESOLVED) { row.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT)); } } abortAction.setEnabled(true); markResolvedAction.setEnabled(true); markUnresolvedAction.setEnabled(true); if(attemptToCommit) { attemptToCommitMerge(); } } private void attemptToCommitMerge() { try { String mergeNode = HgStatusClient.getMergeChangesetId(hgRoot); // offer commit of merge exactly once if no conflicts // are found boolean allResolved = areAllResolved(); if (allResolved) { String message = hgRoot.getName() + Messages.getString("MergeView.PleaseCommitMerge") + " " + mergeNode; statusLabel.setText(message); IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); if (wsRoot.getSessionProperty(ResourceProperties.MERGE_COMMIT_OFFERED) == null) { new CommitMergeHandler().commitMergeWithCommitDialog(hgRoot, getSite().getShell()); ResourcesPlugin.getWorkspace().getRoot().setSessionProperty(ResourceProperties.MERGE_COMMIT_OFFERED, "true"); } } } catch (Exception e) { MercurialEclipsePlugin.logError(e); } } public void clearView() { statusLabel.setText(""); //$NON-NLS-1$ table.removeAll(); abortAction.setEnabled(false); markResolvedAction.setEnabled(false); markUnresolvedAction.setEnabled(false); hgRoot = null; } public void setCurrentRoot(HgRoot newRoot) { if(newRoot == null) { clearView(); return; } if ((hgRoot == null) || !newRoot.equals(hgRoot)) { // TODO should schedule a job here... try { if (HgStatusClient.isMergeInProgress(newRoot)) { this.hgRoot = newRoot; populateView(false); } else { clearView(); } } catch (HgException e) { MercurialEclipsePlugin.logError(e); } } } private boolean areAllResolved() { boolean allResolved = true; if (table.getItems() != null && table.getItems().length > 0) { for (TableItem item : table.getItems()) { FlaggedAdaptable fa = (FlaggedAdaptable) item.getData(); allResolved &= fa.getFlag() == MercurialStatusCache.CHAR_RESOLVED; } } return allResolved; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { // TODO do not react on any changes if the view is hidden... if (selection instanceof IStructuredSelection && !selection.isEmpty()) { IStructuredSelection structured = (IStructuredSelection) selection; IResource resource = MercurialEclipsePlugin.getAdapter(structured.getFirstElement(), IResource.class); if (resource != null) { setCurrentRoot(MercurialTeamProvider.getHgRoot(resource.getProject())); } } } @Override public void setFocus() { table.setFocus(); } @Override public void dispose() { getSite().getPage().removeSelectionListener(this); MercurialStatusCache.getInstance().deleteObserver(this); super.dispose(); } private IFile getSelection() { TableItem[] selection = table.getSelection(); if (selection != null && selection.length > 0) { FlaggedAdaptable fa = (FlaggedAdaptable) selection[0].getData(); IFile iFile = ((IFile) fa.getAdapter(IFile.class)); return iFile; } return null; } public void update(Observable o, Object arg) { if(hgRoot == null || !(arg instanceof Set<?>)){ return; } Set<?> set = (Set<?>) arg; Set<IProject> projects = ResourceUtils.getProjects(hgRoot); // create intersection of the root projects with the updated set projects.retainAll(set); // if the intersection contains common projects, we need update the view if(!projects.isEmpty()) { Display.getDefault().asyncExec(new Runnable() { public void run() { HgRoot backup = hgRoot; clearView(); setCurrentRoot(backup); } }); } } private void openMergeEditor(TableItem item) { try { FlaggedAdaptable flagged = (FlaggedAdaptable) item.getData(); IFile file = (IFile) flagged.getAdapter(IFile.class); String mergeNodeId = HgStatusClient.getMergeChangesetId(hgRoot); String[] parents = HgParentClient.getParentNodeIds(hgRoot); int ancestor = HgParentClient .findCommonAncestor(hgRoot, parents[0], parents[1]); RevisionNode mergeNode = new RevisionNode( new MercurialRevisionStorage(file, mergeNodeId)); RevisionNode ancestorNode = new RevisionNode( new MercurialRevisionStorage(file, ancestor)); HgCompareEditorInput compareInput = new HgCompareEditorInput( new CompareConfiguration(), file, ancestorNode, mergeNode, true); CompareUI.openCompareEditor(compareInput); } catch (CoreException e) { MercurialEclipsePlugin.logError(e); MercurialEclipsePlugin.showError(e); } } }
package au.edu.unimelb.boldapp; import java.io.IOException; import java.io.StringWriter; import java.util.UUID; import java.util.Date; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.util.Log; import android.content.Intent; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Activity that offers the user the ability to enter text in a text box and * press a button that then subsequently creates a corresponding user. * * @author Oliver Adams <oliver.adams@gmail.com> * @author Florian Hanke <florian.hanke@gmail.com> * */ public class SaveActivity extends Activity { /** * Constant to represent the request code for the LanguageFilterList calls. */ static final int SELECT_LANGUAGE = 0; /** * The language to save the recording as */ private Language language; /** * UUID of the file being saved. */ private UUID uuid; /** * The UUID of the original audio if the file to be saved is a respeaking; * null if the file to be save isn't a respeaking. */ private UUID originalUUID; /** * Initializes when the activity is started. * * @param savedInstanceState Bundle containing data most recently * supplied to onSaveInstanceState(Bundle). */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.save); if (GlobalState.getCurrentUser().getLanguages().size() >= 1) { setLanguage(GlobalState.getCurrentUser().getLanguages().get(0)); } else { setLanguage(new Language("English", "eng")); } Intent intent = getIntent(); if (intent.getExtras().containsKey("originalUUID")) { originalUUID = (UUID) intent.getExtras().get("originalUUID"); String originalName = intent.getStringExtra("originalName"); EditText recordingNameEditText = (EditText) findViewById(R.id.edit_recording_name); Log.i("issue1", recordingNameEditText + " "); Log.i("issue1", originalName + " "); recordingNameEditText.setText( "Respeaking of " + originalName, TextView.BufferType.EDITABLE); } uuid = (UUID) intent.getExtras().get("UUID"); } /** * Takes the user to the language filter to choose the language */ public void goToLanguageFilter(View view) { Intent intent = new Intent(this, LanguageFilterList.class); startActivityForResult(intent, SELECT_LANGUAGE); } private void setLanguage(Language language) { Button languageButton = (Button) findViewById(R.id.language_button); languageButton.setText(language.toString()); this.language = language; } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == SELECT_LANGUAGE) { if (resultCode == RESULT_OK) { setLanguage((Language) intent.getParcelableExtra("language")); Log.i("selectLanguage", " " + resultCode); } } } /** * Creates a new user with the name specified in the EditText view. * * The user is given a UUID and the user data is written to file. * * @param view The create user button that was clicked. */ public void save(View view) { //Get the username from the EditText view. EditText editText = (EditText) findViewById(R.id.edit_recording_name); String recordingName = editText.getText().toString(); User currentUser = GlobalState.getCurrentUser(); Recording recording; if (originalUUID == null) { recording = new Recording(uuid, currentUser.getUUID(), recordingName, new Date(), language); } else { recording = new Recording(uuid, currentUser.getUUID(), recordingName, new Date(), language, originalUUID); } try { FileIO.writeRecording(recording); Toast.makeText(this, recordingName + " saved", Toast.LENGTH_LONG).show(); this.finish(); } catch (IOException e) { Toast.makeText(this, "Failed writing " + recordingName, Toast.LENGTH_LONG).show(); } this.finish(); } /** * Go back to the record Activity * @param view the button pressed. */ /* public void back(View view) { this.finish(); } */ }
package edu.grinnell.csc207.username.hello; public class HelloWorld { public static void main (String[] args) { System.out.println ("Hello again, GitHub."); System.out.println ("Goodbye again, GitHub!"); } // main(String[]) }
/* 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.DigitalInput; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Timer; /** * 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 BloomFIRSTBot extends SimpleRobot { /* Drive train: this is what makes it move */ RobotDrive drivetrain = new RobotDrive(4, 3); private DigitalInput frontSwitch = new DigitalInput(1); private DigitalInput backSwitch = new DigitalInput(2); /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { /* This code will run once the referees start the match */ //Turn safety off since we won't be feeding the watchdog drivetrain.setSafetyEnabled(false); double speed = 0.2; while (isEnabled() && isAutonomous()) { //If we are driving forward AND the front switch is pressed //drive backwards if (speed > 0 && !frontSwitch.get()) { speed = -0.2; //Set reverse } else if (speed < 0 && !backSwitch.get()) { speed = 0.2; } drivetrain.drive(speed, 0); } } public double getDistance() { return rangefinder.getVoltage() * 1000 / 0.977; } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { } /** * This function is called once each time the robot enters test mode. */ public void test() { } }
/* 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.Compressor; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; public class RobotTemplate extends SimpleRobot { JoyStickCustom driveStick; JoyStickCustom secondStick; Talon frontLeft; Talon rearLeft; Talon frontRight; Talon rearRight; Compressor compress; RobotDrive mainDrive; final double DEADZONE=.08; Solenoid pistup; Solenoid pistdown; Pneumatics armJoint; Pneumatics handJoint; //Counter for teleOp loops int count=0; public void robotInit(){ driveStick= new JoyStickCustom(1, DEADZONE); secondStick=new JoyStickCustom(2, DEADZONE); frontLeft= new Talon(1); rearLeft= new Talon(2); frontRight= new Talon(3); rearRight= new Talon(4); mainDrive=new RobotDrive(frontLeft,rearLeft,frontRight,rearRight); compress=new Compressor(1,1); pistup=new Solenoid(1); pistdown=new Solenoid(2); armJoint=new Pneumatics(1,2); } public void autonomous() { } public void operatorControl() { while(isOperatorControl()&&isEnabled()){ driveStick.update(); secondStick.update(); compress.start(); //Cartesian Drive with Deadzones and Turning mainDrive.mecanumDrive_Cartesian( driveStick.getDeadAxisX(), driveStick.getDeadAxisY(), driveStick.getDeadTwist(),0); moveArm(); //logger /*if(count%500==0){System.out.println(count+": "+ frontLeft.getSpeed()+", "+ rearLeft.getSpeed()+", "+ frontRight.getSpeed()+", "+ rearRight.getSpeed()); }*/ //Increase number of teleop cycles count++; } } public void moveArm(){ if (secondStick.getButtonPressed(6)&&!secondStick.getButtonPressed(7)) { /*pistup.set(true); pistdown.set(false);*/ armJoint.up(); } else if (!secondStick.getButtonPressed(6)&&secondStick.getButtonPressed(7)) { /*pistdown.set(true); pistup.set(false);*/ armJoint.down(); } else { /*pistdown.set(false); pistup.set(false); */ armJoint.stay(); } } public void moveHand(){ if (secondStick.getButtonPressed(11)&&!secondStick.getButtonPressed(10)) { /*pistup.set(true); pistdown.set(false);*/ handJoint.up(); } else if (!secondStick.getButtonPressed(11)&&secondStick.getButtonPressed(10)) { /*pistdown.set(true); pistup.set(false);*/ handJoint.down(); } else { /*pistdown.set(false); pistup.set(false); */ handJoint.stay(); } } public void disabled(){ mainDrive.mecanumDrive_Cartesian(0, 0, 0, 0); armJoint.stay(); pistup.set(false); pistdown.set(false); } }
package emergencylanding.k.library.lwjgl; import java.awt.Frame; import java.awt.Toolkit; import java.lang.instrument.IllegalClassFormatException; import k.core.util.classes.StackTraceInfo; import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.opengl.ContextAttribs; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.PixelFormat; import de.matthiasmann.twl.renderer.Renderer; import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer; import emergencylanding.k.exst.mods.Mods; import emergencylanding.k.library.debug.FPS; import emergencylanding.k.library.lwjgl.control.Keys; import emergencylanding.k.library.lwjgl.control.MouseHelp; import emergencylanding.k.library.lwjgl.render.GLData; import emergencylanding.k.library.lwjgl.tex.ELTexture; import emergencylanding.k.library.main.KMain; import emergencylanding.k.library.util.LUtils; public class DisplayLayer { public static String VERSION = "1.2"; static { LUtils.init(); } private static String reqTitle = ""; private static boolean wasResizable; private static LWJGLRenderer renderer; private static boolean init = false; /** * Initializes the display and KMain instance. Parameter notes are found on * the longest argument version. * * @param fullscreen * - is fullscreen on at start? * @param width * - initial width of screen * @param height * - initial height of screen * @param title * - title of screen * @param resizable * - is the screen resizeable? * @param args * - main() args * @throws Exception * any exceptions will be thrown */ public static void initDisplay(boolean fullscreen, int width, int height, String title, boolean resizable, String[] args) throws Exception { DisplayLayer.initDisplay(fullscreen, width, height, title, resizable, true, args); } /** * Initializes the display and KMain instance. Parameter notes are found on * the longest argument version. * * @param fullscreen * - is fullscreen on at start? * @param width * - initial width of screen * @param height * - initial height of screen * @param title * - title of screen * @param resizable * - is the screen resizeable? * @param args * - main() args * @param vsync * - overrides default vsync option, true * @throws Exception * any exceptions will be thrown */ public static void initDisplay(boolean fullscreen, int width, int height, String title, boolean resizable, boolean vsync, String[] args) throws Exception { try { DisplayLayer.initDisplay( fullscreen, width, height, title, resizable, vsync, args, Class.forName( LUtils.getFirstEntryNotThis(DisplayLayer.class .getName())).asSubclass(KMain.class)); } catch (ClassCastException cce) { if (cce.getStackTrace()[StackTraceInfo.CLIENT_CODE_STACK_INDEX] .getClassName().equals(DisplayLayer.class.getName())) { throw new IllegalClassFormatException("Class " + Class.forName(StackTraceInfo.getInvokingClassName()) + " not implementing KMain!"); } else { throw cce; } } } /** * Initializes the display and KMain instance. Parameter notes are found on * the longest argument version. * * @param fullscreen * - is fullscreen on at start? * @param width * - initial width of screen * @param height * - initial height of screen * @param title * - title of screen * @param resizable * - is the screen resizeable? * @param args * - main() args * @param vsync * - is vsync enabled? * @param cls * - overrides the default class for KMain, which is the class * that called the method * @throws Exception * any exceptions will be thrown */ public static void initDisplay(boolean fullscreen, int width, int height, String title, boolean resizable, boolean vsync, String[] args, Class<? extends KMain> cls) throws Exception { KMain main = cls.newInstance(); DisplayLayer.initDisplay(fullscreen, width, height, title, resizable, vsync, args, main); } public static void initDisplay(boolean fullscreen, int width, int height, String title, boolean resizable, boolean vsync, String[] args, KMain main) throws Exception { LUtils.print("Using LWJGL v" + Sys.getVersion()); DisplayMode dm = LUtils.getDisplayMode(width, height, fullscreen); if (!dm.isFullscreenCapable() && fullscreen) { LUtils.print("Warning! Fullscreen is not supported with width " + width + " and height " + height); fullscreen = false; } DisplayLayer.reqTitle = title.toString(); Display.setDisplayMode(dm); if (!fullscreen) { Display.setTitle(DisplayLayer.reqTitle); } PixelFormat pixelFormat = new PixelFormat(); ContextAttribs contextAtrributes = new ContextAttribs(3, 0); System.err.println("Using contexAttributes " + contextAtrributes); Display.create(pixelFormat, contextAtrributes); Display.setFullscreen(fullscreen); Display.setResizable(resizable && !fullscreen); Display.setVSyncEnabled(vsync); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); KMain.setDisplayThread(Thread.currentThread()); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); KMain.setInst(main); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); Mods.findAndLoad(); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); GLData.initOpenGL(); FPS.init(0); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); FPS.setTitle(DisplayLayer.reqTitle); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); main.init(args); GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); LUtils.print("Using OpenGL v" + LUtils.getGLVer()); init = true; } public static void loop(int dfps) throws LWJGLException { Display.sync(dfps); int delta = FPS.update(0); if (Display.wasResized()) { GLData.resizedRefresh(); } GLData.clearAndLoad(); ELTexture.doBindings(); KMain.getInst().onDisplayUpdate(delta); MouseHelp.onDisplayUpdate(); GLData.unload(); Display.update(false); OrgLWJGLOpenGLPackageAccess.updateImplementation(); } public static void readDevices() { OrgLWJGLOpenGLPackageAccess.pollDevices(); Keys.read(); MouseHelp.read(); } public static void intoFull() throws LWJGLException { Display.setFullscreen(true); DisplayLayer.wasResizable = Display.isResizable(); Display.setResizable(false); } public static void outOfFull() throws LWJGLException { Display.setResizable(DisplayLayer.wasResizable); Display.setFullscreen(false); } public static void destroy() { if (init) { Display.destroy(); } Frame[] frms = Frame.getFrames(); for (Frame frm : frms) { if (frm.isVisible()) { frm.setVisible(false); frm.dispose(); System.err .println("CrashCourse has closed a JFrame called " + frm.getTitle() + ", which would have stalled the application's closing state. Please fix this!"); } } } public static void toggleFull() { try { if (Display.isFullscreen()) { DisplayLayer.outOfFull(); } else { DisplayLayer.intoFull(); } } catch (LWJGLException e) { } } /** * @param width * @param height * @param fullscreen * @return if the aspect ratio matches with the current screen * @deprecated Not useful anymore, calls should go to * {@link DisplayMode#isFullscreenCapable()} */ @Deprecated public static boolean compatibleWithFullscreen(int width, int height, boolean fullscreen) { int dw, dh; dw = Toolkit.getDefaultToolkit().getScreenSize().width; dh = Toolkit.getDefaultToolkit().getScreenSize().height; float aspect_requested = (float) width / (float) height; float aspect_required = (float) dw / (float) dh; return aspect_requested == aspect_required; } public static Renderer getLWJGLRenderer() { try { return DisplayLayer.renderer != null ? DisplayLayer.renderer : (DisplayLayer.renderer = new LWJGLRenderer()); } catch (LWJGLException e) { e.printStackTrace(); } return null; } }
package jkind.translation; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.ExprMapVisitor; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.VarDecl; import jkind.util.Util; public class InlineNodeCalls extends ExprMapVisitor { public static Node program(Program program) { InlineNodeCalls inliner = new InlineNodeCalls(Util.getNodeTable(program.nodes)); Node main = program.getMainNode(); List<Expr> assertions = inliner.visitAssertions(main.assertions); List<Equation> equations = inliner.visitEquations(main.equations); List<VarDecl> locals = new ArrayList<>(main.locals); locals.addAll(inliner.newLocals); List<String> properties = new ArrayList<>(main.properties); properties.addAll(inliner.newProperties); return new Node(main.location, main.id, main.inputs, main.outputs, locals, equations, properties, assertions); } private final Map<String, Node> nodeTable; private final List<VarDecl> newLocals = new ArrayList<>(); private final List<String> newProperties = new ArrayList<>(); private final Map<String, Integer> usedPrefixes = new HashMap<>(); private final Queue<Equation> queue = new ArrayDeque<>(); private InlineNodeCalls(Map<String, Node> nodeTable) { this.nodeTable = nodeTable; } private List<Expr> visitAssertions(List<Expr> assertions) { List<Expr> result = new ArrayList<>(); for (Expr assertion : assertions) { result.add(assertion.accept(this)); } return result; } private List<Equation> visitEquations(List<Equation> equations) { queue.addAll(equations); List<Equation> result = new ArrayList<>(); while (!queue.isEmpty()) { Equation eq = queue.poll(); if (eq.lhs.size() == 1) { result.add(new Equation(eq.location, eq.lhs, eq.expr.accept(this))); } else { List<IdExpr> outputs = visitNodeCallExpr((NodeCallExpr) eq.expr); for (int i = 0; i < eq.lhs.size(); i++) { result.add(new Equation(eq.lhs.get(i), outputs.get(i))); } } } return result; } @Override public Expr visit(NodeCallExpr e) { List<IdExpr> result = visitNodeCallExpr(e); if (result.size() == 1) { return result.get(0); } else { throw new IllegalArgumentException("Multi-return node calls should already be inlined"); } } public List<IdExpr> visitNodeCallExpr(NodeCallExpr e) { String prefix = newPrefix(e.node); Node node = getNode(e.node); Map<String, IdExpr> translation = getTranslation(prefix, node); createInputEquations(node.inputs, e.args, translation); createAssignmentEquations(prefix, node.equations, translation); accumulateProperties(node.properties, translation); List<IdExpr> result = new ArrayList<>(); for (VarDecl decl : node.outputs) { result.add(translation.get(decl.id)); } return result; } private Node getNode(String id) { if (id.contains(".")) { int index = id.lastIndexOf('.'); return nodeTable.get(id.substring(index + 1)); } else { return nodeTable.get(id); } } private Map<String, IdExpr> getTranslation(String prefix, Node node) { Map<String, IdExpr> translation = new HashMap<>(); for (VarDecl decl : Util.getVarDecls(node)) { String id = prefix + decl.id; newLocals.add(new VarDecl(id, decl.type)); translation.put(decl.id, new IdExpr(id)); } return translation; } private void createInputEquations(List<VarDecl> inputs, List<Expr> args, Map<String, IdExpr> translation) { for (int i = 0; i < inputs.size(); i++) { IdExpr idExpr = translation.get(inputs.get(i).id); Expr arg = args.get(i); queue.add(new Equation(idExpr, arg)); } } private void createAssignmentEquations(final String prefix, List<Equation> equations, Map<String, IdExpr> translation) { SubstitutionVisitor substitution = new SubstitutionVisitor(translation) { @Override public Expr visit(NodeCallExpr e) { return new NodeCallExpr(e.location, prefix + e.node, visitAll(e.args)); } }; for (Equation eq : equations) { List<IdExpr> lhs = new ArrayList<>(); for (IdExpr idExpr : eq.lhs) { lhs.add(translation.get(idExpr.id)); } Expr expr = eq.expr.accept(substitution); queue.add(new Equation(eq.location, lhs, expr)); } } private String newPrefix(String prefix) { int i = 0; if (usedPrefixes.containsKey(prefix)) { i = usedPrefixes.get(prefix); } usedPrefixes.put(prefix, i + 1); return prefix + "~" + i + "."; } private void accumulateProperties(List<String> properties, Map<String, IdExpr> translation) { for (String property : properties) { newProperties.add(translation.get(property).id); } } }
package experimentalcode.marisa.index.xtree; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import de.lmu.ifi.dbs.elki.algorithm.AbortException; import de.lmu.ifi.dbs.elki.data.DoubleVector; import de.lmu.ifi.dbs.elki.data.KNNList; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.database.DistanceResultPair; import de.lmu.ifi.dbs.elki.distance.Distance; import de.lmu.ifi.dbs.elki.distance.DoubleDistance; import de.lmu.ifi.dbs.elki.index.tree.DistanceEntry; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexHeader; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexPath; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexPathComponent; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialDistanceFunction; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialLeafEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.AbstractRStarTree; import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.NonFlatRStarTree; import de.lmu.ifi.dbs.elki.persistent.LRUCache; import de.lmu.ifi.dbs.elki.persistent.PersistentPageFile; import de.lmu.ifi.dbs.elki.utilities.HyperBoundingBox; import de.lmu.ifi.dbs.elki.utilities.ModifiableHyperBoundingBox; import de.lmu.ifi.dbs.elki.utilities.heap.DefaultIdentifiable; import de.lmu.ifi.dbs.elki.utilities.optionhandling.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.PatternParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.UnusedParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.EqualStringConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint.IntervalBoundary; import experimentalcode.marisa.index.xtree.util.SplitHistory; import experimentalcode.marisa.index.xtree.util.SquareEuclideanDistanceFunction; import experimentalcode.marisa.index.xtree.util.XSplitter; import experimentalcode.marisa.utils.MyKNNList; import experimentalcode.marisa.utils.PQ; import experimentalcode.marisa.utils.PriorityQueue; /** * Base class for XTree implementations and other extensions; derived from * {@link NonFlatRStarTree}. * * @author Marisa Thoma * * @param <O> Object type * @param <N> Node type * @param <E> Entry type */ public abstract class XTreeBase<O extends NumberVector<O, ?>, N extends XNode<E, N>, E extends SpatialEntry> extends AbstractRStarTree<O, N, E> { /** * If <code>true</code>, the expensive call of * {@link #calculateOverlapIncrease(List, SpatialEntry, HyperBoundingBox)} is * omitted for supernodes. This may lead to longer query times, however, is * necessary for enabling the construction of the tree for some * parameterizations. * */ public boolean OMIT_OVERLAP_INCREASE_4_SUPERNODES = true; /** * Mapping id to supernode. Supernodes are appended to the end of the index * file when calling #commit(); */ protected Map<Long, N> supernodes = new HashMap<Long, N>(); /** * Minimum size to be allowed for page sizes after a split in case of a * minimum overlap split. */ protected int min_fanout; /** Fraction of pages to be re-inserted instead of trying a split. */ protected float reinsert_fraction = .3f; /** Maximum overlap for a split partition. */ protected float max_overlap = .2f; /** Dimensionality of the {@link NumberVector}s stored in this tree. */ protected int dimensionality; /** Number of elements (of type <O>) currently contained in this tree. */ protected long num_elements = 0; /** * The maximum overlap is calculated as the ratio of total data objects in the * overlapping region. */ public static final int DATA_OVERLAP = 0; /** * The maximum overlap is calculated as the fraction of the overlapping region * of the two original mbrs: * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> */ public static final int VOLUME_OVERLAP = 1; /** * Type of overlap to be used for testing on maximum overlap. Must be one of * {@link #DATA_OVERLAP} and {@link #VOLUME_OVERLAP}. */ protected int overlap_type = DATA_OVERLAP; /** * OptionID for {@link #MIN_ENTRIES_PARAMETER} */ public static final OptionID MIN_ENTRIES_ID = OptionID.getOrCreateOptionID("xtree.min_entry_fraction", "The fraction (in [0,1]) of maximally allowed page entries which is to be be used as minimum number of page entries"); /** * OptionID for {@link #MIN_FANOUT_PARAMETER} */ public static final OptionID MIN_FANOUT_ID = OptionID.getOrCreateOptionID("xtree.min_fanout_fraction", "The fraction (in [0,1]) of maximally allowed directory page entries which is to be tolerated as minimum number of directory page entries for minimum overlap splits"); /** * OptionID for {@link #REINSERT_PARAMETER} */ public static final OptionID REINSERT_ID = OptionID.getOrCreateOptionID("xtree.reinsert_fraction", "The fraction (in [0,1]) of entries to be reinserted instead of performing a split"); /** * OptionID for {@link #MAX_OVERLAP_PARAMETER} */ public static final OptionID MAX_OVERLAP_ID = OptionID.getOrCreateOptionID("xtree.max_overlap_fraction", "The fraction (in [0,1]) of allowed entry overlaps. Overlap type specified in xtree.overlap_type"); /** * OptionID for {@link #OVERLAP_TYPE_PARAMETER} */ public static final OptionID OVERLAP_TYPE_ID = OptionID.getOrCreateOptionID("xtree.overlap_type", "How to calculate the maximum overlap? Options: \"DataOverlap\" = {ratio of data objects in the overlapping region}, \"VolumeOverlap\" = {(overlap volume) / (volume 1 + volume 2)}"); /** * Parameter for minimum number of entries per page; defaults to * <code>.4</code> times the number of maximum entries. */ private final DoubleParameter MIN_ENTRIES_PARAMETER = new DoubleParameter(MIN_ENTRIES_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.OPEN), 0.4); /** * Parameter for minimum number of entries per directory page when going for a * minimum overlap split; defaults to <code>.3</code> times the number of * maximum entries. */ private final DoubleParameter MIN_FANOUT_PARAMETER = new DoubleParameter(MIN_FANOUT_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.CLOSE), 0.3); /** * Parameter for the number of re-insertions to be performed instead of doing * a split; defaults to <code>.3</code> times the number of maximum entries. */ private final DoubleParameter REINSERT_PARAMETER = new DoubleParameter(REINSERT_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.OPEN), 0.3); /** * Parameter for the maximally allowed overlap. Defaults to <code>.2</code>. */ private final DoubleParameter MAX_OVERLAP_PARAMETER = new DoubleParameter(MAX_OVERLAP_ID, new IntervalConstraint(0, IntervalBoundary.OPEN, 1, IntervalBoundary.CLOSE), 0.2); /** * Parameter for defining the overlap type to be used for the maximum overlap * test. Available options: * <dl> * <dt><code>DataOverlap</code></dt> * <dd>The overlap is the ratio of total data objects in the overlapping * region.</dd> * <dt><code>VolumeOverlap</code></dt> * <dd>The overlap is the fraction of the overlapping region of the two * original mbrs:<br> * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> * <br> * This option is faster than <code>DataOverlap</code>, however, it may result * in a tree structure which is not optimally adapted to the indexed data.</dd> * </dl> * Defaults to <code>VolumeOverlap</code>. */ private final PatternParameter OVERLAP_TYPE_PARAMETER = new PatternParameter(OVERLAP_TYPE_ID, new EqualStringConstraint(new String[] { "DataOverlap", "VolumeOverlap" }), "VolumeOverlap"); public static final int QUEUE_INIT = 50; /* * Creates a new RTree. */ public XTreeBase() { super(); addOption(MIN_ENTRIES_PARAMETER); addOption(MIN_FANOUT_PARAMETER); addOption(REINSERT_PARAMETER); addOption(MAX_OVERLAP_PARAMETER); addOption(OVERLAP_TYPE_PARAMETER); } /** * Returns true if in the specified node an overflow occurred, false * otherwise. * * @param node the node to be tested for overflow * @return true if in the specified node an overflow occurred, false otherwise */ @Override protected boolean hasOverflow(N node) { if(node.isLeaf()) { return node.getNumEntries() == leafCapacity; } else { if(node.isSuperNode()) // supernode capacity differs from normal capacity return node.getNumEntries() == node.getCapacity(); return node.getNumEntries() == dirCapacity; } } /** * Returns true if in the specified node an underflow occurred, false * otherwise. If <code>node</code> is a supernode, never returns * <code>true</code>, as this method automatically shortens the node's * capacity by one page size in case of an underflow. If this leads to a * normal page size, the node is converted into a normal (non-super) node an * it is removed from {@link #supernodes}. * * @param node the node to be tested for underflow * @return true if in the specified node an underflow occurred, false * otherwise */ @Override protected boolean hasUnderflow(N node) { if(node.isLeaf()) { return node.getNumEntries() < leafMinimum; } else { if(node.isSuperNode()) { if(node.getCapacity() - node.getNumEntries() >= dirCapacity) { int newCapacity = node.shrinkSuperNode(dirCapacity); if(newCapacity == dirCapacity) { assert !node.isSuperNode(); // convert into a normal node (and insert into the index file) if(node.isSuperNode()) { throw new IllegalStateException("This node should not be a supernode anymore"); } N n = supernodes.remove(new Long(node.getID())); assert (n != null); // update the old reference in the file file.writePage(node); } } return false; } return node.getNumEntries() < dirMinimum; } } /** * Computes the height of this XTree. Is called by the constructor. and should * be overwritten by subclasses if necessary. * * @return the height of this XTree */ @Override protected int computeHeight() { N node = getRoot(); int tHeight = 1; // compute height while(!node.isLeaf() && node.getNumEntries() != 0) { E entry = node.getEntry(0); node = getNode(entry.getID()); tHeight++; } return tHeight; } /** * Returns the node with the specified id. Note that supernodes are kept in * main memory (in {@link #supernodes}, thus, their listing has to be tested * first. * * @param nodeID the page id of the node to be returned * @return the node with the specified id */ @Override public N getNode(int nodeID) { N nID = supernodes.get(new Long(nodeID)); if(nID != null) { return nID; } N n = super.getNode(nodeID); assert !n.isSuperNode(); // we should have them ALL in #supernodes return n; } @Override protected void createEmptyRoot(@SuppressWarnings("unused") O object) { N root = createNewLeafNode(leafCapacity); file.writePage(root); setHeight(1); } /** * TODO: This does not work at all for supernodes! * * Performs a bulk load on this XTree with the specified data. Is called by * the constructor and should be overwritten by subclasses if necessary. * * @param objects the data objects to be indexed */ @Override protected void bulkLoad(List<O> objects) { throw new UnsupportedOperationException("Bulk Load not supported for XTree"); } /** * Get the main memory supernode map for this tree. If it is empty, there are * no supernodes in this tree. * * @return the supernodes of this tree */ public Map<Long, N> getSupernodes() { return supernodes; } /** * Get the overlap type used for this XTree. * * @return One of * <dl> * <dt><code>{@link #DATA_OVERLAP}</code></dt> * <dd>The overlap is the ratio of total data objects in the * overlapping region.</dd> * <dt><code>{@link #VOLUME_OVERLAP}</code></dt> * <dd>The overlap is the fraction of the overlapping region of the * two original mbrs: * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> * </dd> * </dl> */ public int get_overlap_type() { return overlap_type; } /** @return the maximally allowed overlap for this XTree. */ public float get_max_overlap() { return max_overlap; } /** @return the minimum directory capacity after a minimum overlap split */ public int get_min_fanout() { return min_fanout; } /** @return the minimum directory capacity */ public int getDirMinimum() { return super.dirMinimum; } /** @return the minimum leaf capacity */ public int getLeafMinimum() { return super.leafMinimum; } /** @return the maximum directory capacity */ public int getDirCapacity() { return super.dirCapacity; } /** @return the maximum leaf capacity */ public int getLeafCapacity() { return super.leafCapacity; } /** @return the tree's objects' dimension */ public int getDimensionality() { return dimensionality; } /** @return the number of elements in this tree */ public long getSize() { return num_elements; } /** * Writes all supernodes to the end of the file. This is only supposed to be * used for a final saving of an XTree. If another page is added to this tree, * the supernodes written to file by this operation are over-written. Note * that this tree will only be completely saved after an additional call of * {@link #close()}. * * @return the number of bytes written to file for this tree's supernodes * @throws IOException if there are any io problems when writing the tree's * supernodes */ public long commit() throws IOException { if(!(super.file instanceof PersistentPageFile)) { throw new IllegalStateException("Trying to commit a non-persistent XTree"); } long npid = super.file.getNextPageID(); XTreeHeader ph = (XTreeHeader) ((PersistentPageFile<N>) super.file).getHeader(); long offset = (ph.getReservedPages() + npid) * ph.getPageSize(); ph.setSupernode_offset(npid * ph.getPageSize()); ph.setNumberOfElements(num_elements); RandomAccessFile ra_file = ((PersistentPageFile<N>) super.file).getFile(); ph.writeHeader(ra_file); ra_file.seek(offset); long nBytes = 0; for(Iterator<N> iterator = supernodes.values().iterator(); iterator.hasNext();) { N supernode = iterator.next(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); supernode.writeSuperNode(oos); oos.close(); baos.close(); byte[] array = baos.toByteArray(); byte[] sn_array = new byte[pageSize * (int) Math.ceil((double) supernode.getCapacity() / dirCapacity)]; if(array.length > sn_array.length) { throw new IllegalStateException("Supernode is too large for fitting in " + ((int) Math.ceil((double) supernode.getCapacity() / dirCapacity)) + " pages of total size " + sn_array.length); } System.arraycopy(array, 0, sn_array, 0, array.length); ((PersistentPageFile<N>) super.file).increaseWriteAccess(); ra_file.write(sn_array); nBytes += sn_array.length; } return nBytes; } @Override protected TreeIndexHeader createHeader() { return new XTreeHeader(pageSize, dirCapacity, leafCapacity, dirMinimum, leafMinimum, min_fanout, num_elements, dimensionality, reinsert_fraction, max_overlap); } /** * Raises the "number of elements" counter. */ @Override protected void preInsert(@SuppressWarnings("unused") E entry) { num_elements++; } public boolean initializeTree(O dataObject) { super.initialize(dataObject); return true; } /** * To be called via the constructor if the tree is to be read from file. */ @Override public void initializeFromFile() { if(getFileName() == null) { throw new IllegalArgumentException("Parameter file name is not specified."); } // init the file (meaning no parameter used in createHeader() survives) XTreeHeader header = (XTreeHeader) createHeader(); // header is read here: super.file = new PersistentPageFile<N>(header, cacheSize, new LRUCache<N>(), getFileName(), getNodeClass()); super.pageSize = header.getPageSize(); super.dirCapacity = header.getDirCapacity(); super.leafCapacity = header.getLeafCapacity(); super.dirMinimum = header.getDirMinimum(); super.leafMinimum = header.getLeafMinimum(); this.min_fanout = header.getMin_fanout(); this.num_elements = header.getNumberOfElements(); this.dimensionality = header.getDimensionality(); this.reinsert_fraction = header.getReinsert_fraction(); this.max_overlap = header.getMaxOverlap(); long superNodeOffset = header.getSupernode_offset(); if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(getClass()); msg.append("\n file = ").append(file.getClass()); logger.debugFine(msg.toString()); } // reset page id maintenance super.file.setNextPageID((int) (superNodeOffset / header.getPageSize())); // read supernodes (if there are any) if(superNodeOffset > 0) { RandomAccessFile ra_file = ((PersistentPageFile<N>) super.file).getFile(); long offset = header.getReservedPages() * pageSize + superNodeOffset; int bs = 0 // omit this: 4 // EMPTY_PAGE or FILLED_PAGE ? + 4 + 1 // isLeaf + 1 // isSupernode + 4 // number of entries + 4; // capacity byte[] buffer = new byte[bs]; try { // go to supernode region ra_file.seek(offset); while(ra_file.getFilePointer() + pageSize <= ra_file.length()) { ((PersistentPageFile<N>) super.file).increaseReadAccess(); ra_file.read(buffer); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer)); int id = ois.readInt(); ois.readBoolean(); // iLeaf boolean supernode = ois.readBoolean(); if(!supernode) { throw new IllegalStateException("Non-supernode at supernode position '" + superNodeOffset + "'"); } int numEntries = ois.readInt(); int capacity = ois.readInt(); ois.close(); N page; try { page = getNodeClass().newInstance(); } catch(IllegalAccessException e) { throw new AbortException("AccessException instantiating a supernode", e); } catch(InstantiationException e) { throw new AbortException("InstantiationException instantiating a supernode", e); } ((PersistentPageFile<N>) super.file).increaseReadAccess(); ra_file.seek(offset); byte[] superbuffer = new byte[pageSize * (int) Math.ceil((double) capacity / dirCapacity)]; // increase offset for the next position seek offset += superbuffer.length; ra_file.read(superbuffer); ois = new ObjectInputStream(new ByteArrayInputStream(buffer)); try { // read from file and add to supernode map page.readSuperNode(ois, this); } catch(ClassNotFoundException e) { throw new AbortException("ClassNotFoundException when loading a supernode", e); } assert numEntries == page.getNumEntries(); assert capacity == page.getCapacity(); assert id == page.getID(); } } catch(IOException e) { throw new RuntimeException("IOException caught when loading tree from file '" + getFileName() + "'" + e); } } super.initialized = true; // compute height super.height = computeHeight(); if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(getClass()); msg.append("\n height = ").append(height); logger.debugFine(msg.toString()); } } @Override protected void initializeCapacities(O object, boolean verbose) { /* Simulate the creation of a leaf page to get the page capacity */ try { int cap = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); SpatialLeafEntry sl = new SpatialLeafEntry(0, new double[object.getDimensionality()]); while(baos.size() <= pageSize) { sl.writeExternal(oos); oos.flush(); cap++; } // the last one caused the page to overflow. leafCapacity = cap - 1; } catch(IOException e) { throw new AbortException("Error determining page sizes.", e); } /* Simulate the creation of a directory page to get the capacity */ try { int cap = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); HyperBoundingBox hb = new HyperBoundingBox(new double[object.getDimensionality()], new double[object.getDimensionality()]); XDirectoryEntry xl = new XDirectoryEntry(0, hb); while(baos.size() <= pageSize) { xl.writeExternal(oos); oos.flush(); cap++; } dirCapacity = cap - 1; } catch(IOException e) { throw new AbortException("Error determining page sizes.", e); } if(dirCapacity <= 1) { throw new IllegalArgumentException("Node size of " + pageSize + " Bytes is chosen too small!"); } if(dirCapacity < 10) { logger.warning("Page size is choosen very small! Maximum number of entries " + "in a directory node = " + (dirCapacity - 1)); } // minimum entries per directory node try { dirMinimum = (int) Math.round((dirCapacity - 1) * MIN_ENTRIES_PARAMETER.getValue()); } catch(UnusedParameterException e) { dirMinimum = (int) Math.round((dirCapacity - 1) * MIN_ENTRIES_PARAMETER.getDefaultValue()); } if(dirMinimum < 2) { dirMinimum = 2; } // minimum entries per directory node try { min_fanout = (int) Math.round((dirCapacity - 1) * MIN_FANOUT_PARAMETER.getValue()); } catch(UnusedParameterException e) { min_fanout = (int) Math.round((dirCapacity - 1) * MIN_FANOUT_PARAMETER.getDefaultValue()); } if(min_fanout < 2) { min_fanout = 2; } if(leafCapacity <= 1) { throw new IllegalArgumentException("Node size of " + pageSize + " Bytes is chosen too small!"); } if(leafCapacity < 10) { logger.warning("Page size is choosen very small! Maximum number of entries " + "in a leaf node = " + (leafCapacity - 1)); } // minimum entries per leaf node try { leafMinimum = (int) Math.round((leafCapacity - 1) * MIN_ENTRIES_PARAMETER.getValue()); } catch(UnusedParameterException e) { leafMinimum = (int) Math.round((leafCapacity - 1) * MIN_ENTRIES_PARAMETER.getDefaultValue()); } if(leafMinimum < 2) { leafMinimum = 2; } dimensionality = object.getDimensionality(); if(verbose) { logger.verbose("Directory Capacity: " + (dirCapacity - 1) + "\nDirectory minimum: " + dirMinimum + "\nLeaf Capacity: " + (leafCapacity - 1) + "\nLeaf Minimum: " + leafMinimum + "\nminimum fanout: " + min_fanout); } } @Override public List<String> setParameters(List<String> args) throws ParameterException { List<String> remainingParameters = super.setParameters(args); remainingParameters = optionHandler.grabOptions(args); try { reinsert_fraction = REINSERT_PARAMETER.getValue().floatValue(); } catch(UnusedParameterException e) {// parameter defaults to .3 reinsert_fraction = REINSERT_PARAMETER.getDefaultValue().floatValue(); } try { max_overlap = MAX_OVERLAP_PARAMETER.getValue().floatValue(); } catch(UnusedParameterException e) {// parameter defaults to .2 max_overlap = MAX_OVERLAP_PARAMETER.getDefaultValue().floatValue(); } String mOType; try { mOType = OVERLAP_TYPE_PARAMETER.getValue(); } catch(UnusedParameterException e) {// defaults to 'volume overlap' mOType = OVERLAP_TYPE_PARAMETER.getDefaultValue(); } if(mOType.equals("DataOverlap")) { overlap_type = DATA_OVERLAP; } else if(mOType.equals("VolumeOverlap")) { overlap_type = VOLUME_OVERLAP; } else { throw new IllegalArgumentException("Wrong input parameter for overlap type '" + mOType + "'"); } return remainingParameters; } /** * Chooses the best path of the specified subtree for insertion of the given * MBR at the specified level. The selection uses the following criteria: * <ol> * <li>Test on containment (<code>mbr</code> <em>is</em> within one of the * children)</li> * <li>If there are multiple containing children, the child with the minimum * volume is chosen.</li> * <li>Else, if the children point to leaf nodes, chooses the child with the * minimum multi-overlap increase.</li> * <li>Else, or the multi-overlap increase leads to ties, the child with the * minimum volume increase is selected.</li> * <li>If there are still ties, the child with the minimum volume is chosen.</li> * </ol> * * @param subtree the subtree to be tested for insertion * @param mbr the MBR to be inserted * @param level the level at which the MBR should be inserted (level 1 * indicates leaf-level) * @return the path of the appropriate subtree to insert the given * <code>mbr</code> */ @Override protected TreeIndexPath<E> choosePath(TreeIndexPath<E> subtree, HyperBoundingBox mbr, int level) { if(logger.isDebuggingFiner()) { logger.debugFiner("node " + subtree + ", level " + level); } N node = getNode(subtree.getLastPathComponent().getEntry()); if(node.isLeaf()) { return subtree; } // first test on containment TreeIndexPathComponent<E> containingEntry = containedTest(node, mbr); if(containingEntry != null) { TreeIndexPath<E> newSubtree = subtree.pathByAddingChild(containingEntry); if(height - subtree.getPathCount() == level) { return newSubtree; } else { return choosePath(newSubtree, mbr, level); } } TreeIndexPathComponent<E> optEntry = null; HyperBoundingBox optTestMBR = null; double optOverlapInc = 0; boolean isLeafContainer = false; // test overlap increase? if((!OMIT_OVERLAP_INCREASE_4_SUPERNODES // also test supernodes || (OMIT_OVERLAP_INCREASE_4_SUPERNODES && !node.isSuperNode())) // don't && getNode(node.getEntry(0)).isLeaf()) { // children are leafs // overlap increase is to be tested optOverlapInc = Double.POSITIVE_INFINITY; isLeafContainer = true; } double optVolume = Double.POSITIVE_INFINITY; double optVolumeInc = Double.POSITIVE_INFINITY; double tempVolume, volume; int index = 0; List<E> entries = node.getChildren(); for(Iterator<E> iterator = entries.iterator(); iterator.hasNext(); index++) { E child = iterator.next(); HyperBoundingBox childMBR = child.getMBR(); HyperBoundingBox testMBR = childMBR.union(mbr); double pairwiseOverlapInc; if(isLeafContainer) { pairwiseOverlapInc = calculateOverlapIncrease(entries, child, testMBR); if(Double.isInfinite(pairwiseOverlapInc) || Double.isNaN(pairwiseOverlapInc)) { throw new IllegalStateException("an entry's MBR is too large to calculate its overlap increase: " + pairwiseOverlapInc + "; \nplease re-scale your data s.t. it can be dealt with"); } } else { // no need to examine overlap increase? pairwiseOverlapInc = 0; } if(pairwiseOverlapInc <= optOverlapInc) { if(pairwiseOverlapInc == optOverlapInc) { // If there are multiple entries with the same overlap increase, // choose the one with the minimum volume increase. // If there are also multiple entries with the same volume increase // choose the one with the minimum volume. volume = childMBR.volume(); if(Double.isInfinite(volume) || Double.isNaN(volume)) { throw new IllegalStateException("an entry's MBR is too large to calculate its volume: " + volume + "; \nplease re-scale your data s.t. it can be dealt with"); } tempVolume = testMBR.volume(); if(Double.isInfinite(tempVolume) || Double.isNaN(tempVolume)) { throw new IllegalStateException("an entry's MBR is too large to calculate its volume: " + tempVolume + "; \nplease re-scale your data s.t. it can be dealt with"); } double volumeInc = tempVolume - volume; if(Double.isNaN(optVolumeInc)) { // has not yet been calculated optVolume = optEntry.getEntry().getMBR().volume(); optVolumeInc = optTestMBR.volume() - optVolume; } if(volumeInc < optVolumeInc) { optVolumeInc = volumeInc; optVolume = volume; optEntry = new TreeIndexPathComponent<E>(child, index); } else if(volumeInc == optVolumeInc && volume < optVolume) { // TODO: decide whether to remove this option System.out.println(" optVolumeInc = volumeInc; optVolume = volume; optEntry = new TreeIndexPathComponent<E>(child, index); } } else { // already better optOverlapInc = pairwiseOverlapInc; optVolume = Double.NaN; optVolumeInc = Double.NaN; optTestMBR = testMBR; // for later calculations optEntry = new TreeIndexPathComponent<E>(child, index); } } } assert optEntry != null; TreeIndexPath<E> newSubtree = subtree.pathByAddingChild(optEntry); if(height - subtree.getPathCount() == level) { return newSubtree; } else { return choosePath(newSubtree, mbr, level); } } /** * Celebrated by the Profiler as a lot faster than the previous variant: that * used to calculate all overlaps of the old MBR and the new MBR with all * other MBRs. Now: The overlaps are only calculated if necessary:<br> * <ul> * <li>the new MBR does not have to be tested on overlaps if the current * dimension has never changed</li> * <li>the old MBR does not have to be tested if the new MBR shows no overlaps * </li> * </ul> * Furthermore tries to avoid rounding errors arising from large value ranges * and / or larger dimensions. <br> * <br> * However: hardly any difference in real runtime! * * @param entries entries to be tested on overlap * @param ei current entry * @param testMBR extended MBR of <code>ei</code> * @return */ private double calculateOverlapIncrease(List<E> entries, E ei, HyperBoundingBox testMBR) { ModifiableHyperBoundingBox eiMBR = new ModifiableHyperBoundingBox(ei.getMBR()); ModifiableHyperBoundingBox testMBRModifiable = new ModifiableHyperBoundingBox(testMBR); double[] lb = eiMBR.getMinRef(); double[] ub = eiMBR.getMaxRef(); double[] lbT = testMBRModifiable.getMinRef(); double[] ubT = testMBRModifiable.getMaxRef(); double[] lbNext = null; // next tested lower bounds double[] ubNext = null; // and upper bounds boolean[] dimensionChanged = new boolean[lb.length]; for(int i = 0; i < dimensionChanged.length; i++) { if(lb[i] > lbT[i] || ub[i] < ubT[i]) { dimensionChanged[i] = true; } } double multiOverlapInc = 0, multiOverlapMult = 1, mOOld = 1, mONew = 1; double ol, olT; // dimensional overlap for(E ej : entries) { if(!ej.getID().equals(ei.getID())) { multiOverlapMult = 1; // is constant for a unchanged dimension mOOld = 1; // overlap for old MBR on changed dimensions mONew = 1; // overlap on new MBR on changed dimension ModifiableHyperBoundingBox ejMBR = new ModifiableHyperBoundingBox(ej.getMBR()); lbNext = ejMBR.getMinRef(); ubNext = ejMBR.getMaxRef(); for(int i = 0; i < dimensionChanged.length; i++) { if(dimensionChanged[i]) { if(lbT[i] > ubNext[i] || ubT[i] < lbNext[i]) { multiOverlapMult = 0; break; // old MBR has no overlap either } olT = (ubT[i] > ubNext[i] ? ubNext[i] : ubT[i]) - (lbT[i] < lbNext[i] ? lbNext[i] : lbT[i]); mONew *= olT; if(mOOld != 0) { // else: no use in calculating overlap ol = (ub[i] > ubNext[i] ? ubNext[i] : ub[i]) - (lb[i] < lbNext[i] ? lbNext[i] : lb[i]); if(ol < 0) { ol = 0; } mOOld *= ol; } } else { if(lb[i] > ubNext[i] || ub[i] < lbNext[i]) { multiOverlapMult = 0; break; } ol = (ub[i] > ubNext[i] ? ubNext[i] : ub[i]) - (lb[i] < lbNext[i] ? lbNext[i] : lb[i]); multiOverlapMult *= ol; } } if(multiOverlapMult != 0) { multiOverlapInc += multiOverlapMult * (mONew - mOOld); } } } return multiOverlapInc; } /** * Splits the specified node and returns the newly created split node. If, due * to an exceeding overlap, no split can be conducted, <code>node</code> is * converted into a supernode and <code>null</code> is returned. * * @param node the node to be split * @param splitAxis field for collecting the split axis used for this split or * <code>-1</code> if the split was not successful * @return Either the newly created split node with its split dimension logged * in <code>splitAxis</code>, or <code>null</code>, if * <code>node</code> has been converted into a supernode. */ private N split(N node, int[] splitAxis) { if(splitAxis.length != 1) { throw new IllegalArgumentException("Expecting integer container for returning the split axis"); } // choose the split dimension and the split point XSplitter splitter = new XSplitter(this, node.getChildren()); XSplitter.SplitSorting split = splitter.topologicalSplit(); double minOv = splitter.getPastOverlap(); if(split == null) { // topological split failed if(node.isLeaf()) { throw new IllegalStateException("The topological split must be successful in leaves."); } split = splitter.minimumOverlapSplit(); if(splitter.getPastOverlap() < minOv) { minOv = splitter.getPastOverlap(); // only used for logging } } if(split != null) {// do the split N newNode; newNode = node.splitEntries(split.getSortedEntries(), split.getSplitPoint()); // write changes to file file.writePage(node); file.writePage(newNode); splitAxis[0] = split.getSplitAxis(); if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append("Split Node ").append(node.getID()).append(" (").append(getClass()).append(")\n"); msg.append(" splitAxis ").append(splitAxis[0]).append("\n"); msg.append(" splitPoint ").append(split.getSplitPoint()).append("\n"); msg.append(" newNode ").append(newNode.getID()).append("\n"); if(logger.isVerbose()) { msg.append(" first: ").append(newNode.getChildren()).append("\n"); msg.append(" second: ").append(node.getChildren()).append("\n"); } logger.debugFine(msg.toString()); } return newNode; } else { // create supernode node.makeSuperNode(); supernodes.put((long) node.getID(), node); file.writePage(node); splitAxis[0] = -1; if(logger.isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append("Created Supernode ").append(node.getID()).append(" (").append(getClass()).append(")\n"); msg.append(" new capacity ").append(node.getCapacity()).append("\n"); msg.append(" minimum overlap: ").append(minOv).append("\n"); logger.debugFine(msg.toString()); } return null; } } /** * Treatment of overflow in the specified node: if the node is not the root * node and this is the first call of overflowTreatment in the given level * during insertion the specified node will be reinserted, otherwise the node * will be split. * * @param node the node where an overflow occurred * @param path the path to the specified node * @param splitAxis field for collecting the split axis used for this split or * <code>-1</code> if the split was not successful * @return In case of a re-insertion: <code>null</code>. In case of a split: * Either the newly created split node with its split dimension logged * in <code>splitAxis</code>, or <code>null</code>, if * <code>node</code> has been converted into a supernode. */ private N overflowTreatment(N node, TreeIndexPath<E> path, int[] splitAxis) { if(node.isSuperNode()) { // only extend supernode; no re-insertions assert node.getCapacity() == node.getNumEntries(); assert node.getCapacity() > dirCapacity; node.growSuperNode(); return null; } int level = height - path.getPathCount() + 1; Boolean reInsert = reinsertions.get(level); // there was still no reinsert operation at this level if(node.getID() != 0 && (reInsert == null || !reInsert) && reinsert_fraction != 0) { reinsertions.put(level, true); if(logger.isDebugging()) { logger.debugFine("REINSERT " + reinsertions); } reInsert(node, level, path); return null; } // there was already a reinsert operation at this level else { return split(node, splitAxis); } } // /** // * Compute the centroid of the MBRs or data objects contained by // * <code>node</code>. Was intended to lead to more central re-insert // * distributions, however, this variant rarely avoids a supernode, and // * definitely costs more time. // * // * @param node // * @return // */ // protected O compute_centroid(N node) { // double[] d = new double[node.getDimensionality()]; // for(int i = 0; i < node.getNumEntries(); i++) { // if(node.isLeaf()) { // double[] values = ((SpatialLeafEntry) node.getEntry(i)).getValues(); // for(int j = 0; j < values.length; j++) { // d[j] += values[j]; // else { // ModifiableHyperBoundingBox mbr = new ModifiableHyperBoundingBox(node.getEntry(i).getMBR()); // double[] min = mbr.getMinRef(); // double[] max = mbr.getMaxRef(); // for(int j = 0; j < min.length; j++) { // d[j] += min[j] + max[j]; // for(int j = 0; j < d.length; j++) { // if(node.isLeaf()) { // d[j] /= node.getNumEntries(); // else { // d[j] /= (node.getNumEntries() * 2); // // FIXME: make generic (or just hope DoubleVector is fine) // return (O) new DoubleVector(d); /** * Reinserts the specified node at the specified level. * * @param node the node to be reinserted * @param level the level of the node * @param path the path to the node */ @Override @SuppressWarnings("unchecked") protected void reInsert(N node, int level, TreeIndexPath<E> path) { HyperBoundingBox mbr = node.mbr(); SquareEuclideanDistanceFunction<O> distFunction = new SquareEuclideanDistanceFunction<O>(); DistanceEntry<DoubleDistance, E>[] reInsertEntries = new DistanceEntry[node.getNumEntries()]; // O centroid = compute_centroid(node); // compute the center distances of entries to the node and sort it // in decreasing order to their distances for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); DoubleDistance dist = distFunction.centerDistance(mbr, entry.getMBR()); // DoubleDistance dist = distFunction.maxDist(entry.getMBR(), centroid); // DoubleDistance dist = distFunction.centerDistance(entry.getMBR(), // centroid); reInsertEntries[i] = new DistanceEntry<DoubleDistance, E>(entry, dist, i); } Arrays.sort(reInsertEntries, Collections.reverseOrder()); // define how many entries will be reinserted int start = (int) (reinsert_fraction * node.getNumEntries()); if(logger.isDebugging()) { logger.debugFine("reinserting " + node.getID() + " ; from 0 to " + (start - 1)); } // initialize the reinsertion operation: move the remaining entries // forward node.initReInsert(start, reInsertEntries); file.writePage(node); // and adapt the mbrs TreeIndexPath<E> childPath = path; N child = node; while(childPath.getParentPath() != null) { N parent = getNode(childPath.getParentPath().getLastPathComponent().getEntry()); int indexOfChild = childPath.getLastPathComponent().getIndex(); child.adjustEntry(parent.getEntry(indexOfChild)); file.writePage(parent); childPath = childPath.getParentPath(); child = parent; } // reinsert the first entries for(int i = 0; i < start; i++) { DistanceEntry<DoubleDistance, E> re = reInsertEntries[i]; if(logger.isDebugging()) { logger.debugFine("reinsert " + re.getEntry() + (node.isLeaf() ? "" : " at " + level)); } insertEntry(re.getEntry(), level); } } /** * Inserts the specified entry at the specified level into this R*-Tree. * * @param entry the entry to be inserted * @param level the level at which the entry is to be inserted; automatically * set to <code>1</code> for leaf entries */ private void insertEntry(E entry, int level) { if(entry.isLeafEntry()) { insertLeafEntry(entry); } else { insertDirectoryEntry(entry, level); } } /** * Inserts the specified leaf entry into this R*-Tree. * * @param entry the leaf entry to be inserted */ @Override protected void insertLeafEntry(E entry) { // choose subtree for insertion HyperBoundingBox mbr = entry.getMBR(); TreeIndexPath<E> subtree = choosePath(getRootPath(), mbr, 1); if(logger.isDebugging()) { logger.debugFine("insertion-subtree " + subtree + "\n"); } N parent = getNode(subtree.getLastPathComponent().getEntry()); parent.addLeafEntry(entry); file.writePage(parent); // since adjustEntry is expensive, try to avoid unnecessary subtree updates if(!hasOverflow(parent) && // no overflow treatment (parent.getID() == getRootEntry().getID() || // is root // below: no changes in the MBR subtree.getLastPathComponent().getEntry().getMBR().contains(((SpatialLeafEntry) entry).getValues()))) { return; // no need to adapt subtree } // adjust the tree from subtree to root adjustTree(subtree); } /** * Inserts the specified directory entry at the specified level into this * R*-Tree. * * @param entry the directory entry to be inserted * @param level the level at which the directory entry is to be inserted */ @Override protected void insertDirectoryEntry(E entry, int level) { // choose node for insertion of o HyperBoundingBox mbr = entry.getMBR(); TreeIndexPath<E> subtree = choosePath(getRootPath(), mbr, level); if(logger.isDebugging()) { logger.debugFine("subtree " + subtree); } N parent = getNode(subtree.getLastPathComponent().getEntry()); parent.addDirectoryEntry(entry); file.writePage(parent); // since adjustEntry is expensive, try to avoid unnecessary subtree updates if(!hasOverflow(parent) && // no overflow treatment (parent.getID() == getRootEntry().getID() || // is root // below: no changes in the MBR subtree.getLastPathComponent().getEntry().getMBR().contains(entry.getMBR()))) { return; // no need to adapt subtree } // adjust the tree from subtree to root adjustTree(subtree); } /** * Adjusts the tree after insertion of some nodes. * * @param subtree the subtree to be adjusted */ @Override protected void adjustTree(TreeIndexPath<E> subtree) { if(logger.isDebugging()) { logger.debugFine("Adjust tree " + subtree); } // get the root of the subtree N node = getNode(subtree.getLastPathComponent().getEntry()); // overflow in node if(hasOverflow(node)) { if(node.isSuperNode()) { int new_capacity = node.growSuperNode(); logger.finest("Extending supernode to new capacity " + new_capacity); if(node.getID() == getRootEntry().getID()) { // is root node.adjustEntry(getRootEntry()); } else { N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); E e = parent.getEntry(subtree.getLastPathComponent().getIndex()); HyperBoundingBox mbr = e.getMBR(); node.adjustEntry(e); if(!mbr.equals(e.getMBR())) { // MBR has changed // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } } else { int[] splitAxis = { -1 }; // treatment of overflow: reinsertion or split N split = overflowTreatment(node, subtree, splitAxis); // node was split if(split != null) { // if the root was split: create a new root containing the two // split nodes if(node.getID() == getRootEntry().getID()) { TreeIndexPath<E> newRootPath = createNewRoot(node, split, splitAxis[0]); height++; adjustTree(newRootPath); } // node is not root else { // get the parent and add the new split node N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); if(logger.isDebugging()) { logger.debugFine("parent " + parent); } E newEntry = createNewDirectoryEntry(split); parent.addDirectoryEntry(newEntry); // The below variant does not work in the persistent version // E oldEntry = subtree.getLastPathComponent().getEntry(); // [reason: if oldEntry is modified, this must be permanent] E oldEntry = parent.getEntry(subtree.getLastPathComponent().getIndex()); // adjust split history SplitHistory sh = ((SplitHistorySpatialEntry) oldEntry).getSplitHistory(); if(sh == null) { // not yet initialized (dimension not known of this tree) sh = new SplitHistory(oldEntry.getDimensionality()); sh.setDim(splitAxis[0]); ((SplitHistorySpatialEntry) oldEntry).setSplitHistory(sh); } else { ((SplitHistorySpatialEntry) oldEntry).addSplitDimension(splitAxis[0]); } try { ((SplitHistorySpatialEntry) newEntry).setSplitHistory((SplitHistory) sh.clone()); } catch(CloneNotSupportedException e) { throw new RuntimeException("Clone of a split history should not throw an Exception", e); } // adjust the entry representing the (old) node, that has // been split node.adjustEntry(oldEntry); // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } } } // no overflow, only adjust parameters of the entry representing the // node else { if(node.getID() != getRootEntry().getID()) { N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); E e = parent.getEntry(subtree.getLastPathComponent().getIndex()); HyperBoundingBox mbr = e.getMBR(); node.adjustEntry(e); if(node.isLeaf() || // we already know that mbr is extended !mbr.equals(e.getMBR())) { // MBR has changed // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } // root level is reached else { node.adjustEntry(getRootEntry()); } } } /** * Creates a new root node that points to the two specified child nodes and * return the path to the new root. * * @param oldRoot the old root of this RTree * @param newNode the new split node * @param splitAxis the split axis used for the split causing this new root * @return the path to the new root node that points to the two specified * child nodes */ protected TreeIndexPath<E> createNewRoot(final N oldRoot, final N newNode, int splitAxis) { N root = createNewDirectoryNode(dirCapacity); file.writePage(root); // get split history SplitHistory sh = null; // TODO: see whether root entry is ALWAYS a directory entry .. it SHOULD! sh = ((XDirectoryEntry) getRootEntry()).getSplitHistory(); if(sh == null) { sh = new SplitHistory(oldRoot.getDimensionality()); } sh.setDim(splitAxis); // switch the ids oldRoot.setID(root.getID()); if(!oldRoot.isLeaf()) { // TODO: test whether this is neccessary for(int i = 0; i < oldRoot.getNumEntries(); i++) { N node = getNode(oldRoot.getEntry(i)); file.writePage(node); } } // adjust supernode id if(oldRoot.isSuperNode()) { supernodes.remove(new Long(getRootEntry().getID())); supernodes.put(new Long(oldRoot.getID()), oldRoot); } root.setID(getRootEntry().getID()); E oldRootEntry = createNewDirectoryEntry(oldRoot); E newNodeEntry = createNewDirectoryEntry(newNode); ((SplitHistorySpatialEntry) oldRootEntry).setSplitHistory(sh); try { ((SplitHistorySpatialEntry) newNodeEntry).setSplitHistory((SplitHistory) sh.clone()); } catch(CloneNotSupportedException e) { throw new RuntimeException("Clone of a split history should not throw an Exception", e); } root.addDirectoryEntry(oldRootEntry); root.addDirectoryEntry(newNodeEntry); file.writePage(root); file.writePage(oldRoot); file.writePage(newNode); if(logger.isDebugging()) { String msg = "Create new Root: ID=" + root.getID(); msg += "\nchild1 " + oldRoot + " " + oldRoot.mbr() + " " + oldRootEntry.getMBR(); msg += "\nchild2 " + newNode + " " + newNode.mbr() + " " + newNodeEntry.getMBR(); msg += "\n"; logger.debugFine(msg); } // the root entry still needs to be set to the new root node's MBR return new TreeIndexPath<E>(new TreeIndexPathComponent<E>(getRootEntry(), null)); } /** * Performs a k-nearest neighbor query for the given NumberVector with the * given parameter k and the according distance function. The query result is * in ascending order to the distance to the query object. * * @param object the query object * @param k the number of nearest neighbors to be returned * @param distanceFunction the distance function that computes the distances * between the objects * @return a List of the query results */ @Override public <D extends Distance<D>> List<DistanceResultPair<D>> kNNQuery(O object, int k, SpatialDistanceFunction<O, D> distanceFunction) { if(k < 1) { throw new IllegalArgumentException("At least one enumeration has to be requested!"); } final KNNList<D> knnList = new MyKNNList<D>(k, distanceFunction.infiniteDistance()); doKNNQuery(object, distanceFunction, knnList); return knnList.toList(); } /** * Performs a k-nearest neighbor query for the given NumberVector with the * given parameter k (in <code>knnList</code>) and the according distance * function. The query result is in ascending order to the distance to the * query object. * * @param object the query object * @param distanceFunction the distance function that computes the distances * between the objects * @param knnList the knn list containing the result */ @SuppressWarnings("unchecked") @Override protected <D extends Distance<D>> void doKNNQuery(Object object, SpatialDistanceFunction<O, D> distanceFunction, KNNList<D> knnList) { // candidate queue PQ<D, DefaultIdentifiable> pq = new PQ<D, DefaultIdentifiable>(PriorityQueue.Ascending, QUEUE_INIT); // push root pq.add(distanceFunction.nullDistance(), new DefaultIdentifiable(getRootEntry().getID())); D maxDist = distanceFunction.infiniteDistance(); // search in tree while(!pq.isEmpty()) { D dist = pq.firstPriority(); Integer firstID = pq.removeFirst().getID(); if(dist.compareTo(maxDist) > 0) { return; } N node = getNode(firstID); // data node if(node.isLeaf()) { for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); D distance = object instanceof Integer ? distanceFunction.minDist(entry.getMBR(), (Integer) object) : distanceFunction.minDist(entry.getMBR(), (O) object); distanceCalcs++; if(distance.compareTo(maxDist) <= 0) { knnList.add(new DistanceResultPair<D>(distance, entry.getID())); maxDist = knnList.getKNNDistance(); } } } // directory node else { for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); D distance = object instanceof Integer ? distanceFunction.minDist(entry.getMBR(), (Integer) object) : distanceFunction.minDist(entry.getMBR(), (O) object); distanceCalcs++; if(distance.compareTo(maxDist) <= 0) { pq.add(distance, new DefaultIdentifiable(entry.getID())); } } } } } /** * Returns a string representation of this XTree. * * @return a string representation of this XTree */ @Override public String toString() { StringBuffer result = new StringBuffer(); long dirNodes = 0; long superNodes = 0; long leafNodes = 0; long objects = 0; long maxSuperCapacity = -1; long minSuperCapacity = Long.MAX_VALUE; BigInteger totalCapacity = BigInteger.ZERO; int levels = 0; if(file != null) { N node = getRoot(); while(!node.isLeaf()) { if(node.getNumEntries() > 0) { E entry = node.getEntry(0); node = getNode(entry); levels++; } } de.lmu.ifi.dbs.elki.index.tree.BreadthFirstEnumeration<O, N, E> enumeration = new de.lmu.ifi.dbs.elki.index.tree.BreadthFirstEnumeration<O, N, E>(this, getRootPath()); while(enumeration.hasMoreElements()) { TreeIndexPath<E> indexPath = enumeration.nextElement(); E entry = indexPath.getLastPathComponent().getEntry(); if(entry.isLeafEntry()) { objects++; } else { node = getNode(entry); if(node.isLeaf()) { leafNodes++; } else { if(node.isSuperNode()) { superNodes++; if(node.getCapacity() > maxSuperCapacity) { maxSuperCapacity = node.getCapacity(); } if(node.getCapacity() < minSuperCapacity) { minSuperCapacity = node.getCapacity(); } } else { dirNodes++; } } totalCapacity = totalCapacity.add(BigInteger.valueOf(node.getCapacity())); } } assert objects == num_elements : "objects=" + objects + ", size=" + num_elements; result.append(getClass().getName()).append(" has ").append((levels + 1)).append(" levels.\n"); result.append(dirNodes).append(" Directory Nodes (max = ").append(dirCapacity - 1).append(", min = ").append(dirMinimum).append(")\n"); result.append(superNodes).append(" Supernodes (max = ").append(maxSuperCapacity - 1).append(", min = ").append(minSuperCapacity - 1).append(")\n"); result.append(leafNodes).append(" Data Nodes (max = ").append(leafCapacity - 1).append(", min = ").append(leafMinimum).append(")\n"); result.append(objects).append(" ").append(dimensionality).append("-dim. points in the tree \n"); result.append("min_fanout = ").append(min_fanout).append(", max_overlap = ").append(max_overlap).append((this.overlap_type == DATA_OVERLAP ? " data overlap" : " volume overlap")).append(", re_inserts = ").append(reinsert_fraction + "\n"); result.append("Read I/O-Access: ").append(file.getPhysicalReadAccess()).append("\n"); result.append("Write I/O-Access: ").append(file.getPhysicalWriteAccess()).append("\n"); result.append("Logical Page-Access: ").append(file.getLogicalPageAccess()).append("\n"); result.append("File ").append(getFileName()).append("\n"); result.append("Storage Quota ").append(BigInteger.valueOf(objects + dirNodes + superNodes + leafNodes).multiply(BigInteger.valueOf(100)).divide(totalCapacity).toString()).append("%\n"); } else { result.append(getClass().getName()).append(" is empty!\n"); } return result.toString(); } }
package php.runtime.launcher; import org.develnext.jphp.core.common.ObjectSizeCalculator; import org.develnext.jphp.core.compiler.jvm.JvmCompiler; import org.develnext.jphp.core.opcode.ModuleOpcodePrinter; import php.runtime.Information; import php.runtime.Memory; import php.runtime.common.Callback; import php.runtime.common.LangMode; import php.runtime.common.StringUtils; import php.runtime.env.*; import php.runtime.exceptions.support.ErrorType; import php.runtime.ext.core.classes.WrapClassLoader; import php.runtime.ext.core.classes.stream.Stream; import php.runtime.ext.support.Extension; import php.runtime.loader.dump.ModuleDumper; import php.runtime.memory.ArrayMemory; import php.runtime.memory.LongMemory; import php.runtime.memory.ReferenceMemory; import php.runtime.memory.StringMemory; import php.runtime.reflection.ClassEntity; import php.runtime.reflection.ModuleEntity; import php.runtime.reflection.support.ReflectionUtils; import java.io.*; import java.net.URL; import java.util.*; public class Launcher { protected final String[] args; protected CompileScope compileScope; protected Environment environment; protected Properties config; protected String pathToConf; protected OutputStream out; protected boolean isDebug; private static Launcher current; private ClassLoader classLoader = Launcher.class.getClassLoader(); private long startTime = System.currentTimeMillis(); public Launcher(String pathToConf, String[] args) { current = this; this.args = args; this.out = System.out != null ? System.out : new ByteArrayOutputStream(); this.compileScope = new CompileScope(); this.pathToConf = pathToConf == null ? "JPHP-INF/launcher.conf" : pathToConf; } public Launcher(String[] args) { this(null, args); } public Launcher(ClassLoader classLoader) { this(); this.classLoader = classLoader; } public Launcher() { this(new String[0]); } public Memory getConfigValue(String key) { return getConfigValue(key, Memory.NULL); } public Memory getConfigValue(String key, Memory def) { String result = config.getProperty(key); if (result == null) return def; return new StringMemory(result); } public Memory getConfigValue(String key, String def) { return getConfigValue(key, new StringMemory(def)); } public Collection<InputStream> getResources(String name) { List<InputStream> result = new ArrayList<InputStream>(); try { Enumeration<URL> urls = classLoader.getResources(name); while (urls.hasMoreElements()) { URL url = urls.nextElement(); result.add(url.openStream()); } return result; } catch (IOException e) { return Collections.emptyList(); } } public InputStream getResource(String name){ InputStream stream = classLoader.getResourceAsStream(name); if (stream == null) { try { return new FileInputStream(name); } catch (FileNotFoundException e) { return null; } } return stream; } protected Context getContext(String file){ InputStream bootstrap = getResource(file); if (bootstrap != null) { return new Context(bootstrap, file, environment.getDefaultCharset()); } else return null; } public void initModule(ModuleEntity moduleEntity){ compileScope.loadModule(moduleEntity); compileScope.addUserModule(moduleEntity); environment.registerModule(moduleEntity); } public ModuleEntity loadFromCompiled(String file) throws IOException { InputStream inputStream = getResource(file); if (inputStream == null) return null; Context context = new Context(inputStream, file, environment.getDefaultCharset()); ModuleDumper moduleDumper = new ModuleDumper(context, environment, true); return moduleDumper.load(inputStream); } public ModuleEntity loadFromFile(String file) throws IOException { InputStream inputStream = getResource(file); if (inputStream == null) return null; Context context = new Context(inputStream, file, environment.getDefaultCharset()); JvmCompiler compiler = new JvmCompiler(environment, context); return compiler.compile(false); } public ModuleEntity loadFrom(String file) throws IOException { if (file.endsWith(".phb")) return loadFromCompiled(file); else return loadFromFile(file); } protected void readConfig(){ this.config = new Properties(); this.compileScope.configuration = new HashMap<>(); String externalConfig = System.getProperty("jphp.config"); if (externalConfig != null) { try { FileInputStream inStream = new FileInputStream(externalConfig); config.load(inStream); inStream.close(); for (String name : config.stringPropertyNames()){ compileScope.configuration.put(name, new StringMemory(config.getProperty(name))); } } catch (IOException e) { throw new LaunchException("Unable to load the config -Djphp.config=" + externalConfig); } } InputStream resource; resource = getResource(pathToConf); if (resource != null) { try { config.load(resource); for (String name : config.stringPropertyNames()){ compileScope.configuration.put(name, new StringMemory(config.getProperty(name))); } isDebug = Boolean.getBoolean("jphp.debug"); compileScope.setDebugMode(isDebug); compileScope.setLangMode( LangMode.valueOf(getConfigValue("env.langMode", LangMode.MODERN.name()).toString().toUpperCase()) ); } catch (IOException e) { throw new LaunchException(e.getMessage()); } } } protected void loadExtensions() { ServiceLoader<Extension> loader = ServiceLoader.load(Extension.class, compileScope.getClassLoader()); for (Extension extension : loader) { compileScope.registerExtension(extension); } } protected void initExtensions() { String tmp = getConfigValue("env.extensions", "spl").toString(); String[] _extensions = StringUtils.split(tmp, ","); Set<String> extensions = new HashSet<String>(); for(String ext : _extensions) { extensions.add(ext.trim()); } loadExtensions(); compileScope.getClassLoader().onAddLibrary(new Callback<Void, URL>() { @Override public Void call(URL param) { loadExtensions(); return null; } }); if (getConfigValue("env.autoregister_extensions", Memory.TRUE).toBoolean()) { for(InputStream list : getResources("JPHP-INF/extensions.list")) { Scanner scanner = new Scanner(list); while (scanner.hasNext()) { String line = scanner.nextLine().trim(); if (!line.isEmpty()) { System.out.println("WARNING!!! Auto-registration via JPHP-INF/extensions.list is deprected, " + line + ", use META-INF/services/php.runtime.ext.support.Extension file"); extensions.add(line); } } } } for(String ext : extensions){ String className = Information.EXTENSIONS.get(ext.trim().toLowerCase()); if (className == null) className = ext.trim(); compileScope.registerExtension(className); } this.environment = getConfigValue("env.concurrent", "1").toBoolean() ? new ConcurrentEnvironment(compileScope, out) : new Environment(compileScope, out); environment.setErrorFlags(ErrorType.E_ALL.value ^ ErrorType.E_NOTICE.value); environment.getDefaultBuffer().setImplicitFlush(true); } public void printTrace(String name) { long t = System.currentTimeMillis() - startTime; System.out.printf("[%s] = " + t + " millis\n", name); startTime = System.currentTimeMillis(); } public void run() throws Throwable { run(true); } public void run(boolean mustBootstrap) throws Throwable { run(mustBootstrap, false); } public void run(boolean mustBootstrap, boolean disableExtensions) throws Throwable { readConfig(); if (!disableExtensions) { initExtensions(); } if (isDebug()){ if (compileScope.getTickHandler() == null) { throw new LaunchException("Cannot find a debugger, please add the jphp-debugger dependency"); } long t = System.currentTimeMillis() - startTime; // System.out.println("Starting delay = " + t + " millis"); } String file = config.getProperty("bootstrap.file", "JPHP-INF/.bootstrap.php"); String classLoader = config.getProperty("env.classLoader", ReflectionUtils.getClassName(WrapClassLoader.WrapLauncherClassLoader.class)); if (classLoader != null && !(classLoader.isEmpty())) { ClassEntity classLoaderEntity = environment.fetchClass(classLoader); if (classLoaderEntity == null) { throw new LaunchException("Class loader class is not found: " + classLoader); } WrapClassLoader loader = classLoaderEntity.newObject(environment, TraceInfo.UNKNOWN, true); environment.invokeMethod(loader, "register", Memory.TRUE); } if (file != null && !file.isEmpty()){ try { ModuleEntity bootstrap = loadFrom(file); if (bootstrap == null) { throw new IOException(); } if (new StringMemory(config.getProperty("bootstrap.showBytecode", "")).toBoolean()) { ModuleOpcodePrinter moduleOpcodePrinter = new ModuleOpcodePrinter(bootstrap); System.out.println(moduleOpcodePrinter.toString()); } initModule(bootstrap); ArrayMemory argv = ArrayMemory.ofStrings(this.args); argv.unshift(Memory.NULL); environment.getGlobals().put("argv", argv); environment.getGlobals().put("argc", LongMemory.valueOf(argv.size())); environment.pushCall(new CallStackItem(new TraceInfo(bootstrap.getName(), -1, -1))); try { bootstrap.includeNoThrow(environment); } finally { environment.popCall(); compileScope.triggerProgramShutdown(environment); if (StringMemory.valueOf(config.getProperty("env.doFinal", "1")).toBoolean()) { environment.doFinal(); } } } catch (IOException e) { throw new LaunchException("Cannot find '" + file + "' resource for `bootstrap.file` option"); } } else if (mustBootstrap) throw new LaunchException("Please set value of the `bootstrap.file` option in the launcher.conf file"); } public boolean isDebug() { return isDebug; } public OutputStream getOut(){ return out; } public CompileScope getCompileScope() { return compileScope; } public Environment getEnvironment() { return environment; } public static Launcher current() { return current; } public static void main(String[] args) throws Throwable { Launcher launcher = new Launcher(args); Launcher.current = launcher; launcher.run(); } }
package explorviz.visualization.timeshift; import java.util.Map; import java.util.Map.Entry; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; public class TimeShiftJS { public static native void init() /*-{ var firstDataDone = false; var dataPointPixelRatio = 17; var panning = false; var dataBegin = 0; var dataEnd = 0; Date.prototype.ddhhmmss = function() { var weekday = new Array(7); weekday[0] = "Su"; weekday[1] = "Mo"; weekday[2] = "Tu"; weekday[3] = "We"; weekday[4] = "Th"; weekday[5] = "Fr"; weekday[6] = "Sa"; var n = weekday[this.getDay()]; var hh = this.getHours().toString(); var mm = this.getMinutes().toString(); var ss = this.getSeconds().toString(); return n + " " + (hh[1] ? hh : "0" + hh[0]) + ":" + (mm[1] ? mm : "0" + mm[0]) + ":" + (ss[1] ? ss : "0" + ss[0]); }; var currentTime = new Date(1463499327511).getTime(); var timeshiftChartDiv = $wnd.jQuery("#timeshiftChartDiv"); //$doc.getElementById('timeshiftChartDiv').style.height = '100px'; //$doc.getElementById('timeshiftChartDiv').style.width = '500px'; var dataSet = [ { data : [], label : "Method Calls", color : '#058DC7' } ]; var options = { series : { lines : { show : true, fill : true, fillColor : "rgba(86, 137, 191, 0.8)" }, points : { show : true, radius : 2 }, downsample : { threshold : 0 // 0 disables downsampling for this series. }, shadowSize : 0, highlightColor: "rgba(255, 0, 0, 0.8)" }, axisLabels : { show : true }, legend : { show : false }, grid : { hoverable : true, clickable : true }, xaxis : { axisLabel: "Time", mode : "time", timezone : "browser" }, yaxis : { position: 'left', axisLabel: 'Method Calls', tickFormatter: function(x) {return x >= 1000 ? (x/1000)+"k": x;}, ticks : 1, tickDecimals : 0, zoomRange : false }, zoom : { interactive : true }, pan : { interactive : true, cursor: "default", frameRate: 60 } }; var plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); function addTooltipDiv() { $wnd.jQuery("<div id='timeshiftTooltip'></div>").css({ position : "absolute", display : "none", border : "1px solid #fdd", padding : "2px", "background-color" : "#fee", opacity : 0.80 }).appendTo("#timeshiftChartDiv"); } addTooltipDiv(); $wnd.jQuery("#timeshiftChartDiv").bind("dblclick", onDblclick); $wnd.jQuery("#timeshiftChartDiv").bind("plotzoom", onZoom); $wnd.jQuery("#timeshiftChartDiv").bind("plothover", onHover); $wnd.jQuery("#timeshiftChartDiv").bind("plotclick", onPointSelection); $wnd.jQuery("#timeshiftChartDiv").bind("plotpan", onPanning); $wnd.jQuery("#timeshiftChartDiv").bind("mouseup", onPanningEnd); function onPanningEnd() { setTimeout(function() { panning = false; } , 100); } function onPanning() { panning = true; } function onPointSelection(event, pos, item) { if (item && !panning) { plot.unhighlight(); plot.highlight(item.series, item.datapoint); @explorviz.visualization.landscapeexchange.LandscapeExchangeManager::stopAutomaticExchange(Ljava/lang/String;)(item.datapoint[0].toString()); @explorviz.visualization.interaction.Usertracking::trackFetchedSpecifcLandscape(Ljava/lang/String;)(item.datapoint[0].toString()); @explorviz.visualization.landscapeexchange.LandscapeExchangeManager::fetchSpecificLandscape(Ljava/lang/String;)(item.datapoint[0].toString()); } } function onDblclick() { options.xaxis.min = dataSet[0].data[0][0]; options.xaxis.max = dataSet[0].data[dataSet[0].data.length - 1][0]; var innerWidth = $wnd.innerWidth; options.series.downsample.threshold = parseInt(innerWidth / dataPointPixelRatio); redraw(); } function onHover(event, pos, item) { if (item) { var x = item.datapoint[0]; var y = item.datapoint[1]; // view-div offset var offset = $wnd.jQuery("#view").offset().top; // timechart-div offset offset += $wnd.jQuery("#timeshiftChartDiv").position().top; showTooltip(item.pageX + 15, (item.pageY - offset), "Method Calls: " + y); } else { $wnd.jQuery("#timeshiftTooltip").hide(); } } function onZoom() { console.log("zooming"); } function showTooltip(x, y, contents) { $wnd.jQuery("#timeshiftTooltip").html(contents).css({ top : y, left : x }).fadeIn(200); } // var cnt = 0; // // function update() { // // var offset = 40; // var dataLength = dataSet[0].data.length; // // if(cnt + offset < dataLength) { // options.xaxis.min = dataSet[0].data[cnt][0]; // options.xaxis.max = dataSet[0].data[cnt + offset][0]; // cnt += offset; // plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); // addTooltipDiv(); // } // setTimeout(update, 500); // } // // update(); function setDatapointsAndOptions(convertedValues, convDataLength) { var innerWidth = $wnd.innerWidth; dataEnd = (innerWidth / dataPointPixelRatio) < convDataLength ? (innerWidth / dataPointPixelRatio) : (convDataLength - 1); dataEnd += dataBegin; dataEnd = parseInt(dataEnd); var newXMin = dataSet[0].data[dataBegin][0]; var newXMax = dataSet[0].data[dataEnd][0]; var oldXMin = firstDataDone ? dataSet[0].data[0][0] : newXMin; var newYMax = Math.max.apply(Math, convertedValues.map(function(o) { return o[1]; })); if (!firstDataDone) firstDataDone = true options.xaxis.min = newXMin; options.xaxis.max = newXMax; var dataSetLength = dataSet[0].data.length; options.xaxis.panRange = [ oldXMin, dataSet[0].data[dataSetLength-1][0] ]; options.yaxis.panRange = [ 0, newYMax ]; options.yaxis.max = newYMax; options.series.downsample.threshold = 0; } function redraw() { if(!panning) { plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); addTooltipDiv(); } } $wnd.jQuery.fn.updateTimeshiftChart = function(data) { var values = data[0].values; var convertedValues = values.map(function(o) { return [ o.x, o.y ]; }); dataSet[0].data = dataSet[0].data.concat(convertedValues); var convDataLength = convertedValues.length; setDatapointsAndOptions(convertedValues, convDataLength); redraw(); dataBegin = dataEnd; } }-*/; public static void updateTimeshiftChart(final Map<Long, Long> data) { final JavaScriptObject jsObj = convertToJSHashMap(data); nativeUpdateTimeshiftChart(jsObj); } private static JavaScriptObject convertToJSHashMap(final Map<Long, Long> data) { final JSONObject obj = new JSONObject(); for (final Entry<Long, Long> entry : data.entrySet()) { obj.put(entry.getKey().toString(), new JSONString(entry.getValue().toString())); } final JavaScriptObject jsObj = obj.getJavaScriptObject(); return jsObj; } public static native void nativeUpdateTimeshiftChart(JavaScriptObject jsObj) /*-{ var keys = Object.keys(jsObj); var series1 = []; keys.forEach(function(entry) { series1.push({ x : Number(entry), y : Number(jsObj[entry]) }); }) // $wnd.jQuery(this).updatettimeline([ { // key : "Timeseries", // values : series1, // color : "#366eff", // area : true // } ]); $wnd.jQuery(this).updateTimeshiftChart([ { key : "Timeseries", values : series1, color : "#366eff", area : true } ]); }-*/; }
package org.voltdb; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltdb.AuthSystem.AuthUser; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Table; import org.voltdb.client.BatchTimeoutOverrideType; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureCallback; import org.voltdb.utils.MiscUtils; /** * This class packs the parameters and dispatches the transactions. * Make sure responses over network thread does not touch this class. */ public class InternalConnectionHandler { final static String DEFAULT_INTERNAL_ADAPTER_NAME = "+!_InternalAdapter_!+"; public final static long SUPPRESS_INTERVAL = 60; private static final VoltLogger m_logger = new VoltLogger("InternalConnectionHandler"); // Atomically allows the catalog reference to change between access private final AtomicLong m_failedCount = new AtomicLong(); private final AtomicLong m_submitSuccessCount = new AtomicLong(); private final AtomicInteger m_backpressureIndication = new AtomicInteger(0); private final InternalClientResponseAdapter m_adapter; private final ClientInterfaceHandleManager m_cihm; public InternalConnectionHandler(InternalClientResponseAdapter adapter, ClientInterfaceHandleManager cihm) { m_adapter = adapter; m_cihm = cihm; } /** * Returns true if a table with the given name exists in the server catalog. */ public boolean hasTable(String name) { Table table = getCatalogContext().tables.get(name); return (table!=null); } public ClientInterfaceHandleManager getClientInterfaceHandleManager() { return m_cihm; } public class NullCallback implements ProcedureCallback { @Override public void clientCallback(ClientResponse response) throws Exception { } } public boolean callProcedure(InternalConnectionContext caller, InternalConnectionStatsCollector statsCollector, String proc, Object... fieldList) { return callProcedure(caller, statsCollector, new NullCallback(), proc, fieldList); } private CatalogContext getCatalogContext() { return VoltDB.instance().getCatalogContext(); } public boolean callProcedure( AuthUser user, boolean isAdmin, int timeout, ProcedureCallback cb, String procName, Object...args) { Procedure catProc = InvocationDispatcher.getProcedureFromName(procName, getCatalogContext()); if (catProc == null) { String fmt = "Cannot invoke procedure %s. Procedure not found."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, null, fmt, procName); m_failedCount.incrementAndGet(); return false; } //Indicate backpressure or not. boolean b = hasBackPressure(); if (b) { applyBackPressure(); } StoredProcedureInvocation task = new StoredProcedureInvocation(); task.setProcName(procName); task.setParams(args); try { task = MiscUtils.roundTripForCL(task); task.setClientHandle(m_adapter.connectionId()); } catch (Exception e) { String fmt = "Cannot invoke procedure %s. failed to create task."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, null, fmt, procName); m_failedCount.incrementAndGet(); return false; } if (timeout != BatchTimeoutOverrideType.NO_TIMEOUT) { task.setBatchTimeout(timeout); } int partition = -1; try { partition = InvocationDispatcher.getPartitionForProcedure(catProc, task); } catch (Exception e) { String fmt = "Can not invoke procedure %s. Partition not found."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, e, fmt, procName); m_failedCount.incrementAndGet(); return false; } InternalAdapterTaskAttributes kattrs = new InternalAdapterTaskAttributes( DEFAULT_INTERNAL_ADAPTER_NAME, isAdmin, m_adapter.connectionId()); if (!m_adapter.createTransaction(kattrs, procName, catProc, cb, null, task, user, partition, System.nanoTime())) { m_failedCount.incrementAndGet(); return false; } m_submitSuccessCount.incrementAndGet(); return true; } // Use backPressureTimeout value <= 0 for no back pressure timeout public boolean callProcedure(InternalConnectionContext caller, InternalConnectionStatsCollector statsCollector, ProcedureCallback procCallback, String proc, Object... fieldList) { Procedure catProc = InvocationDispatcher.getProcedureFromName(proc, getCatalogContext()); if (catProc == null) { String fmt = "Cannot invoke procedure %s from streaming interface %s. Procedure not found."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, null, fmt, proc, caller); m_failedCount.incrementAndGet(); return false; } //Indicate backpressure or not. boolean b = hasBackPressure(); caller.setBackPressure(b); if (b) { applyBackPressure(); } StoredProcedureInvocation task = new StoredProcedureInvocation(); task.setProcName(proc); task.setParams(fieldList); try { task = MiscUtils.roundTripForCL(task); task.setClientHandle(m_adapter.connectionId()); } catch (Exception e) { String fmt = "Cannot invoke procedure %s from streaming interface %s. failed to create task."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, null, fmt, proc, caller); m_failedCount.incrementAndGet(); return false; } int partition = -1; try { partition = InvocationDispatcher.getPartitionForProcedure(catProc, task); } catch (Exception e) { String fmt = "Can not invoke procedure %s from streaming interface %s. Partition not found."; m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, e, fmt, proc, caller); m_failedCount.incrementAndGet(); return false; } InternalAdapterTaskAttributes kattrs = new InternalAdapterTaskAttributes(caller, m_adapter.connectionId()); final AuthUser user = getCatalogContext().authSystem.getImporterUser(); if (!m_adapter.createTransaction(kattrs, proc, catProc, procCallback, statsCollector, task, user, partition, System.nanoTime())) { m_failedCount.incrementAndGet(); return false; } m_submitSuccessCount.incrementAndGet(); return true; } private boolean hasBackPressure() { final boolean b = m_adapter.hasBackPressure(); int prev = m_backpressureIndication.get(); int delta = b ? 1 : -(prev > 1 ? prev >> 1 : 1); int next = prev + delta; while (next >= 0 && next <= 8 && !m_backpressureIndication.compareAndSet(prev, next)) { prev = m_backpressureIndication.get(); delta = b ? 1 : -(prev > 1 ? prev >> 1 : 1); next = prev + delta; } return b; } private void applyBackPressure() { final int count = m_backpressureIndication.get(); if (count > 0) { try { // increase sleep time exponentially to a max of 256ms if (count > 8) { Thread.sleep(256); } else { Thread.sleep(1<<count); } } catch(InterruptedException e) { if (m_logger.isDebugEnabled()) { m_logger.debug("Sleep for back pressure interrupted", e); } } } } }
/** * <p> * Provides a runtime view of the running server, and provides * a registration point to handle internal assets and expose API * pieces. Also provides the attach point for modules, and exposes * runtime information about the modules that are known to the * system. * * <p> * The main goal is to refactor the kernel into a core and a set * of modules that provide higher level functionality. * * @author jason * */ package jj.server;
package org.voltdb.compilereport; import java.io.IOException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.voltdb.VoltDB; import org.voltdb.VoltType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Column; import org.voltdb.catalog.ColumnRef; import org.voltdb.catalog.Connector; import org.voltdb.catalog.ConnectorTableInfo; import org.voltdb.catalog.Constraint; import org.voltdb.catalog.Database; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.Index; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.Feedback; import org.voltdb.dtxn.SiteTracker; import org.voltdb.types.ConstraintType; import org.voltdb.types.IndexType; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.Encoder; import org.voltdb.utils.PlatformProperties; import org.voltdb.utils.SystemStatsCollector; import com.google.common.base.Charsets; import com.google.common.io.Resources; public class ReportMaker { static Date m_timestamp = new Date(); /** * Make an html bootstrap tag with our custom css class. */ static void tag(StringBuilder sb, String color, String text) { sb.append("<span class='label label"); if (color != null) { sb.append("-").append(color); } String classText = text.replace(' ', '_'); sb.append(" l-").append(classText).append("'>").append(text).append("</span>"); } static String genrateIndexRow(Table table, Index index) { StringBuilder sb = new StringBuilder(); sb.append(" <tr class='primaryrow2'>"); // name column String anchor = (table.getTypeName() + "-" + index.getTypeName()).toLowerCase(); sb.append("<td style='white-space: nowrap'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-"); sb.append(anchor).append("' class='togglex'>"); sb.append(index.getTypeName()); sb.append("</a></td>"); // type column sb.append("<td>"); sb.append(IndexType.get(index.getType()).toString()); sb.append("</td>"); // columns column sb.append("<td>"); List<ColumnRef> cols = CatalogUtil.getSortedCatalogItems(index.getColumns(), "index"); List<String> columnNames = new ArrayList<String>(); for (ColumnRef colRef : cols) { columnNames.add(colRef.getColumn().getTypeName()); } sb.append(StringUtils.join(columnNames, ", ")); sb.append("</td>"); // uniqueness column sb.append("<td>"); if (index.getUnique()) { tag(sb, "important", "Unique"); } else { tag(sb, "info", "Multikey"); } sb.append("</td>"); sb.append("</tr>\n"); // BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE sb.append("<tr class='dropdown2'><td colspan='5' id='s-"+ table.getTypeName().toLowerCase() + "-" + index.getTypeName().toLowerCase() + "--dropdown'>\n"); IndexAnnotation annotation = (IndexAnnotation) index.getAnnotation(); if (annotation != null) { if (annotation.proceduresThatUseThis.size() > 0) { sb.append("<p>Used by procedures: "); List<String> procs = new ArrayList<String>(); for (Procedure proc : annotation.proceduresThatUseThis) { procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>"); } sb.append(StringUtils.join(procs, ", ")); sb.append("</p>"); } } sb.append("</td></tr>\n"); return sb.toString(); } static String generateIndexesTable(Table table) { StringBuilder sb = new StringBuilder(); sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" + "<th>Index Name</th>" + "<th>Type</th>" + "<th>Columns</th>" + "<th>Uniqueness</th>" + "</tr></thead>\n <tbody>\n"); for (Index index : table.getIndexes()) { sb.append(genrateIndexRow(table, index)); } sb.append(" </tbody>\n </table>\n"); return sb.toString(); } static String generateSchemaRow(Table table, boolean isExportTable) { StringBuilder sb = new StringBuilder(); sb.append("<tr class='primaryrow'>"); // column 1: table name String anchor = table.getTypeName().toLowerCase(); sb.append("<td style='white-space: nowrap;'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-"); sb.append(anchor).append("' class='togglex'>"); sb.append(table.getTypeName()); sb.append("</a></td>"); // column 2: type sb.append("<td>"); if (table.getMaterializer() != null) { tag(sb, "info", "Materialized View"); } else { if (isExportTable) { tag(sb, "inverse", "Export Table"); } else { tag(sb, null, "Table"); } } sb.append("</td>"); // column 3: partitioning sb.append("<td style='whitespace: nowrap;'>"); if (table.getIsreplicated()) { tag(sb, "warning", "Replicated"); } else { tag(sb, "success", "Partitioned"); Column partitionCol = table.getPartitioncolumn(); if (partitionCol != null) { sb.append("<small> on " + partitionCol.getName() + "</small>"); } else { Table matSrc = table.getMaterializer(); if (matSrc != null) { sb.append("<small> with " + matSrc.getTypeName() + "</small>"); } } } sb.append("</td>"); // column 4: column count sb.append("<td>"); sb.append(table.getColumns().size()); sb.append("</td>"); // column 5: index count sb.append("<td>"); sb.append(table.getIndexes().size()); sb.append("</td>"); // column 6: has pkey sb.append("<td>"); boolean found = false; for (Constraint constraint : table.getConstraints()) { if (ConstraintType.get(constraint.getType()) == ConstraintType.PRIMARY_KEY) { found = true; break; } } if (found) { tag(sb, "info", "Has-PKey"); } else { tag(sb, null, "No-PKey"); } sb.append("</td>"); sb.append("</tr>\n"); // BUILD THE DROPDOWN FOR THE DDL / INDEXES DETAIL sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='s-"+ table.getTypeName().toLowerCase() + "--dropdown'>\n"); TableAnnotation annotation = (TableAnnotation) table.getAnnotation(); if (annotation != null) { // output the DDL if (annotation.ddl == null) { sb.append("<p>MISSING DDL</p>\n"); } else { String ddl = annotation.ddl; sb.append("<p><pre>" + ddl + "</pre></p>\n"); } // make sure procs appear in only one category annotation.proceduresThatReadThis.removeAll(annotation.proceduresThatUpdateThis); if (annotation.proceduresThatReadThis.size() > 0) { sb.append("<p>Read-only by procedures: "); List<String> procs = new ArrayList<String>(); for (Procedure proc : annotation.proceduresThatReadThis) { procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>"); } sb.append(StringUtils.join(procs, ", ")); sb.append("</p>"); } if (annotation.proceduresThatUpdateThis.size() > 0) { sb.append("<p>Read/Write by procedures: "); List<String> procs = new ArrayList<String>(); for (Procedure proc : annotation.proceduresThatUpdateThis) { procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>"); } sb.append(StringUtils.join(procs, ", ")); sb.append("</p>"); } } if (table.getIndexes().size() > 0) { sb.append(generateIndexesTable(table)); } else { sb.append("<p>No indexes defined on table.</p>\n"); } sb.append("</td></tr>\n"); return sb.toString(); } static String generateSchemaTable(CatalogMap<Table> tables, CatalogMap<Connector> connectors) { StringBuilder sb = new StringBuilder(); List<Table> exportTables = getExportTables(connectors); for (Table table : tables) { sb.append(generateSchemaRow(table, exportTables.contains(table) ? true : false)); } return sb.toString(); } static String genrateStatementRow(Procedure procedure, Statement statement) { StringBuilder sb = new StringBuilder(); sb.append(" <tr class='primaryrow2'>"); // name column String anchor = (procedure.getTypeName() + "-" + statement.getTypeName()).toLowerCase(); sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='p-"); sb.append(anchor).append("' class='togglex'>"); sb.append(statement.getTypeName()); sb.append("</a></td>"); // sql column sb.append("<td><tt>"); sb.append(statement.getSqltext()); sb.append("</td></tt>"); // params column sb.append("<td>"); List<StmtParameter> params = CatalogUtil.getSortedCatalogItems(statement.getParameters(), "index"); List<String> paramTypes = new ArrayList<String>(); for (StmtParameter param : params) { paramTypes.add(VoltType.get((byte) param.getJavatype()).name()); } if (paramTypes.size() == 0) { sb.append("<i>None</i>"); } sb.append(StringUtils.join(paramTypes, ", ")); sb.append("</td>"); // r/w column sb.append("<td>"); if (statement.getReadonly()) { tag(sb, "success", "Read"); } else { tag(sb, "warning", "Write"); } sb.append("</td>"); // attributes sb.append("<td>"); if (!statement.getIscontentdeterministic() || !statement.getIsorderdeterministic()) { tag(sb, "inverse", "Determinism"); } if (statement.getSeqscancount() > 0) { tag(sb, "important", "Scans"); } sb.append("</td>"); sb.append("</tr>\n"); // BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE sb.append("<tr class='dropdown2'><td colspan='5' id='p-"+ procedure.getTypeName().toLowerCase() + "-" + statement.getTypeName().toLowerCase() + "--dropdown'>\n"); sb.append("<div class='well well-small'><h4>Explain Plan:</h4>\n"); StatementAnnotation annotation = (StatementAnnotation) statement.getAnnotation(); if (annotation != null) { String plan = annotation.explainPlan; plan = plan.replace("\n", "<br/>"); plan = plan.replace(" ", "&nbsp;"); for (Table t : annotation.tablesRead) { String name = t.getTypeName().toUpperCase(); String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\""; plan = plan.replace("\"" + name + "\"", link); } for (Table t : annotation.tablesUpdated) { String name = t.getTypeName().toUpperCase(); String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\""; plan = plan.replace("\"" + name + "\"", link); } for (Index i : annotation.indexesUsed) { Table t = (Table) i.getParent(); String name = i.getTypeName().toUpperCase(); String link = "\"<a href='#s-" + t.getTypeName() + "-" + i.getTypeName() +"'>" + name + "</a>\""; plan = plan.replace("\"" + name + "\"", link); } sb.append("<tt>").append(plan).append("</tt>"); } else { sb.append("<i>No SQL explain plan found.</i>\n"); } sb.append("</div>\n"); sb.append("</td></tr>\n"); return sb.toString(); } static String generateStatementsTable(Procedure procedure) { StringBuilder sb = new StringBuilder(); sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" + "<th><span style='white-space: nowrap;'>Statement Name</span></th>" + "<th>Statement SQL</th>" + "<th>Params</th>" + "<th>R/W</th>" + "<th>Attributes</th>" + "</tr></thead>\n <tbody>\n"); for (Statement statement : procedure.getStatements()) { sb.append(genrateStatementRow(procedure, statement)); } sb.append(" </tbody>\n </table>\n"); return sb.toString(); } static String generateProcedureRow(Procedure procedure) { StringBuilder sb = new StringBuilder(); sb.append("<tr class='primaryrow'>"); // column 1: procedure name String anchor = procedure.getTypeName().toLowerCase(); sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href=' sb.append(anchor).append("' id='p-").append(anchor).append("' class='togglex'>"); sb.append(procedure.getTypeName()); sb.append("</a></td>"); // column 2: parameter types sb.append("<td>"); List<ProcParameter> params = CatalogUtil.getSortedCatalogItems(procedure.getParameters(), "index"); List<String> paramTypes = new ArrayList<String>(); for (ProcParameter param : params) { String paramType = VoltType.get((byte) param.getType()).name(); if (param.getIsarray()) { paramType += "[]"; } paramTypes.add(paramType); } if (paramTypes.size() == 0) { sb.append("<i>None</i>"); } sb.append(StringUtils.join(paramTypes, ", ")); sb.append("</td>"); // column 3: partitioning sb.append("<td>"); if (procedure.getSinglepartition()) { tag(sb, "success", "Single"); } else { tag(sb, "warning", "Multi"); } sb.append("</td>"); // column 4: read/write sb.append("<td>"); if (procedure.getReadonly()) { tag(sb, "success", "Read"); } else { tag(sb, "warning", "Write"); } sb.append("</td>"); // column 5: access sb.append("<td>"); List<String> groupNames = new ArrayList<String>(); for (GroupRef groupRef : procedure.getAuthgroups()) { groupNames.add(groupRef.getGroup().getTypeName()); } if (groupNames.size() == 0) { sb.append("<i>None</i>"); } sb.append(StringUtils.join(groupNames, ", ")); sb.append("</td>"); // column 6: attributes sb.append("<td>"); if (procedure.getHasjava()) { tag(sb, "info", "Java"); } else { tag(sb, null, "Single-Stmt"); } boolean isND = false; int scanCount = 0; for (Statement stmt : procedure.getStatements()) { scanCount += stmt.getSeqscancount(); if (!stmt.getIscontentdeterministic() || !stmt.getIsorderdeterministic()) { isND = false; } } if (isND) { tag(sb, "inverse", "Determinism"); } if (scanCount > 0) { tag(sb, "important", "Scans"); } sb.append("</td>"); sb.append("</tr>\n"); // BUILD THE DROPDOWN FOR THE STATEMENT/DETAIL TABLE sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='p-"+ procedure.getTypeName().toLowerCase() + "--dropdown'>\n"); // output partitioning parameter info if (procedure.getSinglepartition()) { String pTable = procedure.getPartitioncolumn().getParent().getTypeName(); String pColumn = procedure.getPartitioncolumn().getTypeName(); int pIndex = procedure.getPartitionparameter(); sb.append(String.format("<p>Partitioned on parameter %d which maps to column %s" + " of table <a class='invert' href='#s-%s'>%s</a>.</p>", pIndex, pColumn, pTable, pTable)); } // output what schema this interacts with ProcedureAnnotation annotation = (ProcedureAnnotation) procedure.getAnnotation(); if (annotation != null) { // make sure tables appear in only one category annotation.tablesRead.removeAll(annotation.tablesUpdated); if (annotation.tablesRead.size() > 0) { sb.append("<p>Read-only access to tables: "); List<String> tables = new ArrayList<String>(); for (Table table : annotation.tablesRead) { tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>"); } sb.append(StringUtils.join(tables, ", ")); sb.append("</p>"); } if (annotation.tablesUpdated.size() > 0) { sb.append("<p>Read/Write access to tables: "); List<String> tables = new ArrayList<String>(); for (Table table : annotation.tablesUpdated) { tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>"); } sb.append(StringUtils.join(tables, ", ")); sb.append("</p>"); } if (annotation.indexesUsed.size() > 0) { sb.append("<p>Uses indexes: "); List<String> indexes = new ArrayList<String>(); for (Index index : annotation.indexesUsed) { Table table = (Table) index.getParent(); indexes.add("<a href='#s-" + table.getTypeName() + "-" + index.getTypeName() + "'>" + index.getTypeName() + "</a>"); } sb.append(StringUtils.join(indexes, ", ")); sb.append("</p>"); } } sb.append(generateStatementsTable(procedure)); sb.append("</td></tr>\n"); return sb.toString(); } static String generateProceduresTable(CatalogMap<Procedure> procedures) { StringBuilder sb = new StringBuilder(); for (Procedure procedure : procedures) { if (procedure.getDefaultproc()) { continue; } sb.append(generateProcedureRow(procedure)); } return sb.toString(); } /** * Get some embeddable HTML of some generic catalog/application stats * that is drawn on the first page of the report. */ static String getStatsHTML(Database db, ArrayList<Feedback> warnings) { StringBuilder sb = new StringBuilder(); sb.append("<table class='table table-condensed'>\n"); // count things int indexes = 0, views = 0, statements = 0; int partitionedTables = 0, replicatedTables = 0; int partitionedProcs = 0, replicatedProcs = 0; int readProcs = 0, writeProcs = 0; for (Table t : db.getTables()) { if (t.getMaterializer() != null) { views++; } else { if (t.getIsreplicated()) { replicatedTables++; } else { partitionedTables++; } } indexes += t.getIndexes().size(); } for (Procedure p : db.getProcedures()) { // skip auto-generated crud procs if (p.getDefaultproc()) { continue; } if (p.getSinglepartition()) { partitionedProcs++; } else { replicatedProcs++; } if (p.getReadonly()) { readProcs++; } else { writeProcs++; } statements += p.getStatements().size(); } // version sb.append("<tr><td>Compiled by VoltDB Version</td><td>"); sb.append(VoltDB.instance().getVersionString()).append("</td></tr>\n"); // timestamp sb.append("<tr><td>Compiled on</td><td>"); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); sb.append(sdf.format(m_timestamp)).append("</td></tr>\n"); // tables sb.append("<tr><td>Table Count</td><td>"); sb.append(String.format("%d (%d partitioned / %d replicated)", partitionedTables + replicatedTables, partitionedTables, replicatedTables)); sb.append("</td></tr>\n"); // views sb.append("<tr><td>Materialized View Count</td><td>").append(views).append("</td></tr>\n"); // indexes sb.append("<tr><td>Index Count</td><td>").append(indexes).append("</td></tr>\n"); // procedures sb.append("<tr><td>Procedure Count</td><td>"); sb.append(String.format("%d (%d partitioned / %d replicated) (%d read-only / %d read-write)", partitionedProcs + replicatedProcs, partitionedProcs, replicatedProcs, readProcs, writeProcs)); sb.append("</td></tr>\n"); // statements sb.append("<tr><td>SQL Statement Count</td><td>").append(statements).append("</td></tr>\n"); // warnings if (warnings.size() > 0){ sb.append("<tr><td>Warnings</td><td>").append("<table class='table table-condensed'>\n"); for (Feedback warning : warnings) { String procName = warning.getFileName().replace(".class", ""); String nameLink = ""; // not a warning during compiling procedures, must from the schema if (procName.compareToIgnoreCase("null") == 0) { nameLink += "<a href=' String schemaName = ""; String warningMsg = warning.getMessage().toLowerCase(); if (warningMsg.contains("table ")) { int begin = warningMsg.indexOf("table ") + 6; int end = (warningMsg.substring(begin)).indexOf(" "); schemaName += warningMsg.substring(begin, begin + end); } nameLink += schemaName + "'>" + schemaName.toUpperCase() + "</a>"; } else { nameLink += "<a href='#p-" + procName.toLowerCase() + "'>" + procName + "</a>"; } sb.append("<tr><td>").append(nameLink).append("</td><td>").append(warning.getMessage()).append("</td></tr>\n"); } sb.append("").append("</table>\n").append("</td></tr>\n"); } sb.append("</table>\n"); return sb.toString(); } /** * Generate the HTML catalog report from a newly compiled VoltDB catalog */ public static String report(Catalog catalog, ArrayList<Feedback> warnings) throws IOException { // asynchronously get platform properties new Thread() { @Override public void run() { PlatformProperties.getPlatformProperties(); } }.start(); URL url = Resources.getResource(ReportMaker.class, "template.html"); String contents = Resources.toString(url, Charsets.UTF_8); Cluster cluster = catalog.getClusters().get("cluster"); assert(cluster != null); Database db = cluster.getDatabases().get("database"); assert(db != null); String statsData = getStatsHTML(db, warnings); contents = contents.replace("##STATS##", statsData); String schemaData = generateSchemaTable(db.getTables(), db.getConnectors()); contents = contents.replace("##SCHEMA##", schemaData); String procData = generateProceduresTable(db.getProcedures()); contents = contents.replace("##PROCS##", procData); String platformData = PlatformProperties.getPlatformProperties().toHTML(); contents = contents.replace("##PLATFORM##", platformData); contents = contents.replace("##VERSION##", VoltDB.instance().getVersionString()); DateFormat df = new SimpleDateFormat("d MMM yyyy HH:mm:ss z"); contents = contents.replace("##TIMESTAMP##", df.format(m_timestamp)); String msg = Encoder.hexEncode(VoltDB.instance().getVersionString() + "," + System.currentTimeMillis()); contents = contents.replace("get.py?a=KEY&", String.format("get.py?a=%s&", msg)); return contents; } private static List<Table> getExportTables(CatalogMap<Connector> connectors) { List<Table> retval = new ArrayList<Table>(); for (Connector conn : connectors) { for (ConnectorTableInfo cti : conn.getTableinfo()) { retval.add(cti.getTable()); } } return retval; } public static String getLiveSystemOverview() { // get the start time long t = SystemStatsCollector.getStartTime(); Date date = new Date(t); long duration = System.currentTimeMillis() - t; long minutes = duration / 60000; long hours = minutes / 60; minutes -= hours * 60; long days = hours / 24; hours -= days * 24; String starttime = String.format("%s (%dd %dh %dm)", date.toString(), days, hours, minutes); // handle the basic info page below this SiteTracker st = VoltDB.instance().getSiteTrackerForSnapshot(); // get the cluster info String clusterinfo = st.getAllHosts().size() + " hosts "; clusterinfo += " with " + st.getAllSites().size() + " sites "; clusterinfo += " (" + st.getAllSites().size() / st.getAllHosts().size(); clusterinfo += " per host)"; StringBuilder sb = new StringBuilder(); sb.append("<table class='table table-condensed'>\n"); sb.append("<tr><td>Mode </td><td>" + VoltDB.instance().getMode().toString() + "</td><td>\n"); sb.append("<tr><td>VoltDB Version </td><td>" + VoltDB.instance().getVersionString() + "</td><td>\n"); sb.append("<tr><td>Buildstring </td><td>" + VoltDB.instance().getBuildString() + "</td><td>\n"); sb.append("<tr><td>Cluster Composition </td><td>" + clusterinfo + "</td><td>\n"); sb.append("<tr><td>Running Since </td><td>" + starttime + "</td><td>\n"); sb.append("</table>\n"); return sb.toString(); } /** * Find the pre-compild catalog report in the jarfile, and modify it for use in the * the built-in web portal. */ public static String liveReport() { byte[] reportbytes = VoltDB.instance().getCatalogContext().getFileInJar("catalog-report.html"); String report = new String(reportbytes, Charsets.UTF_8); // remove commented out code report = report.replace("<!--##RESOURCES", ""); report = report.replace("##RESOURCES-->", ""); // inject the cluster overview String clusterStr = "<h4>System Overview</h4>\n<p>" + getLiveSystemOverview() + "</p><br/>\n"; report = report.replace("<!--##CLUSTER##-->", clusterStr); // inject the running system platform properties PlatformProperties pp = PlatformProperties.getPlatformProperties(); String ppStr = "<h4>Cluster Platform</h4>\n<p>" + pp.toHTML() + "</p><br/>\n"; report = report.replace("<!--##PLATFORM2##-->", ppStr); // change the live/static var to live if (VoltDB.instance().getConfig().m_isEnterprise) { report = report.replace("&b=r&", "&b=e&"); } else { report = report.replace("&b=r&", "&b=c&"); } return report; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.cadsr.freestylesearch.util.SearchResults; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModule; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModuleListener; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrPublicApiModule; import gov.nih.nci.ncicb.cadsr.loader.ext.FreestyleModule; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AttributeNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ClassNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; // bad bad import. Fix me! import gov.nih.nci.ncicb.cadsr.dao.EagerConstants; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.HashSet; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import org.apache.log4j.Logger; public class CadsrDialog extends JDialog implements ActionListener, KeyListener, CadsrModuleListener { private CadsrDialog _this = this; private JLabel searchLabel = new JLabel("Search:"); private JTextField searchField = new JTextField(10); private JLabel whereToSearchLabel = new JLabel("Search By"); private JLabel numberOfResultsLabel = new JLabel("Results Per Page"); private JComboBox searchSourceCombo; private JComboBox numberOfResultsCombo; private JButton searchButton = new JButton("Search"); private AbstractTableModel tableModel = null; private JTable resultTable = null; private static final String PUBLIC_ID = "Public ID"; private static final String LONG_NAME = "Long Name"; private JButton previousButton = new JButton("Previous"), nextButton = new JButton("Next"), suggestButton = new JButton("Suggest"), closeButton = new JButton("Close"); private JLabel indexLabel = new JLabel(""); private JLabel searchPrefLabel = new JLabel("Search Preferences"); private CadsrModule cadsrModule; private FreestyleModule freestyleModule; private Collection<Representation> preferredRepTerms; private boolean showRepTermWarning = false; private static String SEARCH = "SEARCH", PREVIOUS = "PREVIOUS", NEXT = "NEXT", SUGGEST = "SUGGEST", CLOSE = "CLOSE"; private java.util.List<SearchResultWrapper> resultSet = new ArrayList<SearchResultWrapper>(); private String[] columnNames = { "LongName", "Workflow Status", "Public Id", "Version", "Preferred Definition", "Context Name", "Registration Status" }; private int colWidth[] = {15, 15, 15, 15, 30, 15, 15}; private UserPreferences prefs = UserPreferences.getInstance(); private int pageSize = prefs.getCadsrResultsPerPage(); private int pageIndex = 0; private AdminComponent choiceAdminComponent = null; public static final int MODE_OC = 1; public static final int MODE_PROP = 2; public static final int MODE_VD = 3; public static final int MODE_DE = 4; public static final int MODE_CD = 5; public static final int MODE_CS = 7; public static final int MODE_REP = 9; private int mode; private static Logger logger = Logger.getLogger(CadsrDialog.class.getName()); private UMLNode node; private InheritedAttributeList inheritedList = InheritedAttributeList.getInstance(); public CadsrDialog(int runMode) { super((JFrame)null, true); this.mode = runMode; switch (mode) { case MODE_OC: this.setTitle("Search for Object Class"); break; case MODE_PROP: this.setTitle("Search for Property"); break; case MODE_CS: this.setTitle("Search for Classification Schemes"); break; case MODE_VD: this.setTitle("Search for Value Domain"); break; case MODE_DE: this.setTitle("Search for Data Element"); break; case MODE_CD: this.setTitle("Search for Conceptual Domain"); break; case MODE_REP: this.setTitle("Search for Rep Term"); break; } this.getContentPane().setLayout(new BorderLayout()); String values[] = {LONG_NAME, PUBLIC_ID}; searchSourceCombo = new JComboBox(values); JPanel searchPanel = new JPanel(new GridBagLayout()); tableModel = new AbstractTableModel() { public String getColumnName(int col) { return columnNames[col].toString(); } public int getRowCount() { return (int)Math.min(resultSet.size(), pageSize); } public int getColumnCount() { return columnNames.length; } public Object getValueAt(int row, int col) { row = row + pageSize * pageIndex; if(row >= resultSet.size()) return ""; SearchResultWrapper res = resultSet.get(row); String s = ""; switch (col) { case 0: s = res.getLongName(); break; case 1: s = res.getWorkflowStatus(); break; case 2: s = res.getPublicId(); break; case 3: s = res.getVersion(); break; case 4: s = res.getPreferredDefinition(); break; case 5: s = res.getContextName(); break; case 6: s = res.getRegistrationStatus(); default: break; } return s; } public boolean isCellEditable(int row, int col) { return false; } }; resultTable = new JTable(tableModel) { public String getToolTipText(java.awt.event.MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); return (String)getModel().getValueAt(rowIndex, colIndex); } }; DefaultTableCellRenderer tcrColumn = new DefaultTableCellRenderer(); tcrColumn.setVerticalAlignment(JTextField.TOP); resultTable.getColumnModel().getColumn(3).setCellRenderer(tcrColumn); resultTable.getColumnModel().getColumn(4).setCellRenderer(tcrColumn); if(mode == MODE_VD) { resultTable.getColumnModel().getColumn(6).setMaxWidth(0); resultTable.getColumnModel().getColumn(6).setResizable(false); } int c = 0; for(int width : colWidth) { TableColumn col = resultTable.getColumnModel().getColumn(c++); col.setPreferredWidth(width); } resultTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if(evt.getClickCount() == 2) { int row = resultTable.getSelectedRow(); if(row > -1) { SearchResultWrapper choiceSearchResultWrapper = (resultSet.get(pageIndex * pageSize + row)); if(mode == MODE_DE) { _this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Map<String, Object> queryFields = new HashMap<String, Object>(); queryFields.put(CadsrModule.PUBLIC_ID, new String(choiceSearchResultWrapper.getPublicId())); queryFields.put(CadsrModule.VERSION, new Float(choiceSearchResultWrapper.getVersion())); try { Collection<DataElement> result = cadsrModule.findDataElement(queryFields); if(result.size() == 0) JOptionPane.showMessageDialog (null, "No Results Found","Empty Result", JOptionPane.ERROR_MESSAGE); DataElement de = result.iterator().next(); choiceAdminComponent = de; //DataElement de = (DataElement)choiceSearchResultWrapper; // is this DE valid? // i.e does it have an Object Class and Property? // if not, throw error message if(de.getDataElementConcept().getObjectClass() == null || de.getDataElementConcept().getProperty() == null) { JOptionPane.showMessageDialog (null, PropertyAccessor.getProperty("de.invalid"), "Invalid Selection", JOptionPane.ERROR_MESSAGE); choiceSearchResultWrapper = null; return; } } catch (Exception e) { logger.error("Error querying Cadsr " + e); } finally { _this.setCursor(Cursor.getDefaultCursor()); } } else { choiceAdminComponent = choiceSearchResultWrapper.getAdminComponent(); } _this.setVisible(false); } } } }); JScrollPane scrollPane = new JScrollPane(resultTable); Integer[] number = {new Integer(5), new Integer(10), new Integer(25), new Integer(50), new Integer(100)}; numberOfResultsCombo = new JComboBox(number); numberOfResultsCombo.setSelectedItem(prefs.getCadsrResultsPerPage()); if(mode == MODE_DE) { searchButton.setText("Freestyle Search"); searchField.setColumns(20); UIUtil.insertInBag(searchPanel, searchLabel, 0, 0); UIUtil.insertInBag(searchPanel, searchField, 1, 0); UIUtil.insertInBag(searchPanel, searchButton, 4, 0); UIUtil.insertInBag(searchPanel, suggestButton, 5, 0); } else { UIUtil.insertInBag(searchPanel, searchLabel, 0, 0); UIUtil.insertInBag(searchPanel, searchField, 1, 0); UIUtil.insertInBag(searchPanel, whereToSearchLabel, 2, 0); UIUtil.insertInBag(searchPanel, searchSourceCombo, 3, 0); UIUtil.insertInBag(searchPanel, searchButton, 4, 0); } searchField.addKeyListener(this); searchButton.addActionListener(this); searchButton.addKeyListener(this); searchButton.setActionCommand(SEARCH); suggestButton.addActionListener(this); suggestButton.setActionCommand(SUGGEST); JPanel browsePanel = new JPanel(); browsePanel.add(previousButton); browsePanel.add(indexLabel); browsePanel.add(nextButton); browsePanel.add(closeButton); browsePanel.add(numberOfResultsLabel); browsePanel.add(numberOfResultsCombo); browsePanel.add(searchPrefLabel); searchPrefLabel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { SearchPreferencesDialog spd = new SearchPreferencesDialog(); spd.setVisible(true); } public void mouseEntered(MouseEvent evt) { searchPrefLabel.setForeground(Color.BLUE); } public void mouseExited(MouseEvent evt) { searchPrefLabel.setForeground(Color.BLACK); } }); numberOfResultsCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JComboBox cb = (JComboBox)event.getSource(); Integer selection = (Integer)cb.getSelectedItem(); pageSize = selection.intValue(); updateTable(); updateIndexLabel(); prefs.setCadsrResultsPerPage(selection.intValue()); } }); previousButton.setActionCommand(PREVIOUS); nextButton.setActionCommand(NEXT); closeButton.setActionCommand(CLOSE); previousButton.setEnabled(false); nextButton.setEnabled(false); previousButton.addActionListener(this); nextButton.addActionListener(this); closeButton.addActionListener(this); this.getContentPane().add(searchPanel, BorderLayout.NORTH); this.getContentPane().add(scrollPane, BorderLayout.CENTER); this.getContentPane().add(browsePanel, BorderLayout.SOUTH); this.setSize(600,525); suggestButton.setVisible(true); } public void startSearch(String searchString) { searchField.setText(searchString); searchButton.doClick(); } public AdminComponent getAdminComponent() { try { return choiceAdminComponent; } finally { choiceAdminComponent = null; } } public void startSearchPreferredRepTerms() { if(preferredRepTerms == null) { try { preferredRepTerms = cadsrModule.findPreferredRepTerms(); } catch (Exception e) { logger.error("Error querying Cadsr " + e); } finally { _this.setCursor(Cursor.getDefaultCursor()); } } if(preferredRepTerms != null) { resultSet = new ArrayList<SearchResultWrapper>(); for(Representation rep : preferredRepTerms) resultSet.add(new SearchResultWrapper(rep)); } } public void startSearchCDEByOCConcept(Concept concept) { resultSet = new ArrayList<SearchResultWrapper>(); for(DataElement de : cadsrModule.findDEByOCConcept(concept)) resultSet.add(new SearchResultWrapper(de)); pageIndex = 0; updateTable(); } public void actionPerformed(ActionEvent event) { JButton button = (JButton)event.getSource(); if(button.getActionCommand().equals(SEARCH)) { if(mode == MODE_REP) { if(!showRepTermWarning) { int result = JOptionPane.showConfirmDialog(_this, PropertyAccessor.getProperty("search.nonPreferred.repTerms"), "Warning", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) return; showRepTermWarning = true; } } String selection = (String) searchSourceCombo.getSelectedItem(); String text = searchField.getText() == null ? "" : searchField.getText().trim(); resultSet = new ArrayList<SearchResultWrapper>(); _this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Map<String, Object> queryFields = new HashMap<String, Object>(); if(selection.equals(LONG_NAME)) { queryFields.put(CadsrModule.LONG_NAME, text); } else if(selection.equals(PUBLIC_ID)) { queryFields.put(CadsrModule.PUBLIC_ID, new Long(text)); } switch (mode) { case MODE_OC: for(ObjectClass oc : cadsrModule.findObjectClass(queryFields)) resultSet.add(new SearchResultWrapper(oc)); break; case MODE_PROP: for(Property p : cadsrModule.findProperty(queryFields)) resultSet.add(new SearchResultWrapper(p)); break; case MODE_DE: UserSelections selections = UserSelections.getInstance(); Boolean er = (Boolean)selections.getProperty("exclude.retired.workflow.status"); boolean excludeRetired = false; if(er != null) excludeRetired = er; DataElement searchDE = (DataElement)node.getUserObject(); Property prop = null; if(inheritedList.isInherited(searchDE)) { DataElement parentDE = inheritedList.getParent(searchDE); prop = parentDE.getDataElementConcept().getProperty(); } for(SearchResults sr : freestyleModule.findSearchResults(text, excludeRetired)) { if(prop != null && prop.getVersion() != null && (!prop.getPublicId().equals(new Integer(sr.getPropertyID()).toString()) || !prop.getVersion().equals(new Float(sr.getPropertyVersion())))) // prop doesn't match, skip this one. continue; ObjectClass searchOC = searchDE.getDataElementConcept().getObjectClass(); if(searchOC.getPublicId() != null && (!searchOC.getPublicId().equals(new Integer(sr.getObjectClassID()).toString()) || !searchOC.getVersion().equals(new Float(sr.getObjectClassVersion())))) continue; Object[] list = (Object[]) selections.getProperty("exclude.registration.statuses"); Set<String> setOfExcluded = new HashSet<String>(); String[] defaultStatuses = PropertyAccessor.getProperty("default.excluded.registration.statuses").split(","); if(list != null) { for(Object s : list) setOfExcluded.add(s.toString()); } else { for(String s : defaultStatuses) setOfExcluded.add(s); } if(sr != null) if(!setOfExcluded.contains(sr.getRegistrationStatus())) resultSet.add(new SearchResultWrapper(sr)); } break; case MODE_CS: List<String> eager = new ArrayList<String>(); eager.add(EagerConstants.CS_CSI); eager.add(EagerConstants.CS_CSI + ".csi"); for(ClassificationScheme cs : cadsrModule.findClassificationScheme(queryFields, eager)) resultSet.add(new SearchResultWrapper(cs)); break; case MODE_CD: for(ConceptualDomain cd : cadsrModule.findConceptualDomain(queryFields)) resultSet.add(new SearchResultWrapper(cd)); break; case MODE_REP: queryFields.put(CadsrModule.WORKFLOW_STATUS, Representation.WF_STATUS_RELEASED); for(Representation rep : cadsrModule.findRepresentation(queryFields)) resultSet.add(new SearchResultWrapper(rep)); break; case MODE_VD: for(ValueDomain vd : cadsrModule.findValueDomain(queryFields)) resultSet.add(new SearchResultWrapper(vd)); } } catch (Exception e){ logger.error("Error querying Cadsr " + e); } // end of try-catch _this.setCursor(Cursor.getDefaultCursor()); // remove excluded contexts { List<String> excludeContext = Arrays.asList(PropertyAccessor.getProperty("vd.exclude.contexts").split(",")); for(ListIterator<SearchResultWrapper> it = resultSet.listIterator(); it.hasNext();) { SearchResultWrapper sr = it.next(); if(excludeContext.contains(sr.getContextName())) { it.remove(); } } } pageIndex = 0; updateTable(); } else if(button.getActionCommand().equals(SUGGEST)) { searchField.setText(""); resultSet = new ArrayList(); AttributeNode attrNode = (AttributeNode)node; DataElement _de = (DataElement)node.getUserObject(); ClassNode classNode = null; if(inheritedList.isInherited(_de)) { classNode = (ClassNode)node.getParent().getParent(); } else { classNode = (ClassNode)node.getParent(); } String className = classNode.getDisplay(); String attrName = attrNode.getDisplay(); _this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { for(DataElement de : cadsrModule.suggestDataElement(className, attrName)) resultSet.add(new SearchResultWrapper(de)); } catch (Exception e) { logger.error("Error querying Cadsr " + e); } _this.setCursor(Cursor.getDefaultCursor()); pageIndex = 0; updateTable(); } else if(button.getActionCommand().equals(PREVIOUS)) { pageIndex updateTable(); } else if(button.getActionCommand().equals(NEXT)) { pageIndex++; updateTable(); } else if(button.getActionCommand().equals(CLOSE)) { this.setVisible(false); } updateIndexLabel(); } private void updateIndexLabel() { if(resultSet.size() == 0) { indexLabel.setText(""); } else { StringBuilder sb = new StringBuilder(); int start = pageSize * pageIndex; int end = (int)Math.min(resultSet.size(), start + pageSize); sb.append(start); sb.append("-"); sb.append(end); sb.append(" of " + resultSet.size()); indexLabel.setText(sb.toString()); } } private void updateTable() { tableModel.fireTableDataChanged(); previousButton.setEnabled(pageIndex > 0); nextButton.setEnabled(resultSet.size() > (pageIndex * pageSize + pageSize)); } public void keyPressed(KeyEvent evt) { if(evt.getKeyCode() == KeyEvent.VK_ENTER) searchButton.doClick(); } public void keyTyped(KeyEvent evt) { if(evt.getKeyCode() == KeyEvent.VK_ENTER) searchButton.doClick(); } public void keyReleased(KeyEvent evt) { } /** * IoC setter */ public void setCadsrModule(CadsrModule module) { this.cadsrModule = module; } public void setFreestyleModule(FreestyleModule freestyleModule) { this.freestyleModule = freestyleModule; } public void init(UMLNode node) { this.node = node; } public static void main(String[] args) { CadsrDialog dialog = new CadsrDialog(CadsrDialog.MODE_REP); dialog.setCadsrModule(new CadsrPublicApiModule()); // Concept con = DomainObjectFactory.newConcept(); // con.setPreferredName("C16612"); // dialog.startSearchCDEByOCConcept(con); dialog.startSearchPreferredRepTerms(); dialog.setVisible(true); } } class SearchResultWrapper { private AdminComponent ac; private SearchResults sr; public SearchResultWrapper(Object o) { if(o instanceof AdminComponent) ac = (AdminComponent)o; else sr = (SearchResults)o; } public AdminComponent getAdminComponent() { return ac; } public SearchResults getSearchResults() { return sr; } public String getLongName() { if(ac != null) return ac.getLongName(); else return sr.getLongName(); } public String getPreferredName() { if(ac != null) return ac.getPreferredName(); else return sr.getPreferredName(); } public String getPublicId() { if(ac != null) return ac.getPublicId(); else return new Integer(sr.getPublicID()).toString(); } public String getVersion() { if (ac != null) return ac.getVersion().toString(); else return new Float(sr.getVersion()).toString(); } public String getPreferredDefinition() { if(ac != null) return ac.getPreferredDefinition(); else return sr.getPreferredDefinition(); } public String getContextName() { if(ac != null) return ac.getContext().getName(); else return sr.getContextName(); } public String getRegistrationStatus() { if(ac != null) return ""; else return sr.getRegistrationStatus(); } public String getWorkflowStatus() { if(ac != null) return ac.getWorkflowStatus(); else return sr.getWorkflowStatus(); } }
package com.malhartech.dag; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public interface Stream extends DAGPart<StreamConfiguration, StreamContext> { public static final StreamContext DISCONNECTED_STREAM_CONTEXT = new StreamContext(null, null) { @Override public void sink(Tuple t) { } }; @Override public void setup(StreamConfiguration config); public void setContext(StreamContext context); public StreamContext getContext(); public void activate(); @Override public void teardown(); }
package etomica.normalmode; import java.awt.Color; import java.util.Arrays; import etomica.action.activity.ActivityIntegrate; import etomica.api.IAtom; import etomica.api.IAtomType; import etomica.api.IBox; import etomica.box.Box; import etomica.data.AccumulatorAverageCovariance; import etomica.data.DataPumpListener; import etomica.data.DataSourceCountSteps; import etomica.data.IData; import etomica.data.meter.MeterPotentialEnergy; import etomica.graphics.ColorScheme; import etomica.graphics.DisplayTextBox; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorMC; import etomica.lattice.crystal.Basis; import etomica.lattice.crystal.BasisCubicFcc; import etomica.lattice.crystal.Primitive; import etomica.lattice.crystal.PrimitiveCubic; import etomica.liquidLJ.DataProcessorReweight; import etomica.liquidLJ.DataProcessorReweightRatio; import etomica.liquidLJ.Potential2SoftSphericalLSMultiLat; import etomica.liquidLJ.ValueCache; import etomica.nbr.list.PotentialMasterList; import etomica.potential.P2LennardJones; import etomica.potential.P2SoftSphere; import etomica.potential.P2SoftSphericalTruncated; import etomica.potential.Potential2SoftSpherical; import etomica.potential.PotentialMasterMonatomic; import etomica.simulation.Simulation; import etomica.space.Boundary; import etomica.space.BoundaryRectangularPeriodic; import etomica.space.Space; import etomica.species.SpeciesSpheresMono; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import etomica.util.RandomMersenneTwister; public class SimLJHTTISuper extends Simulation { public SimLJHTTISuper(Space _space, int numAtoms, double density, double temperature, double rc, boolean ss) { super(_space); potentialMaster = new PotentialMasterList(this, space); species = new SpeciesSpheresMono(this, space); addSpecies(species); // TARGET box = new Box(space); addBox(box); box.setNMolecules(species, numAtoms); integrator = new IntegratorMC(potentialMaster, getRandom(), temperature); MeterPotentialEnergy meterPE = new MeterPotentialEnergy(potentialMaster); meterPE.setBox(box); atomMove = new MCMoveAtomCoupled(potentialMaster, meterPE, getRandom(), space); atomMove.setStepSize(0.1); atomMove.setStepSizeMax(0.5); atomMove.setDoExcludeNonNeighbors(true); integrator.getMoveManager().addMCMove(atomMove); // ((MCMoveStepTracker)atomMove.getTracker()).setNoisyAdjustment(true); double L = Math.pow(4.0/density, 1.0/3.0); double nbrDistance = L / Math.sqrt(2); int n = (int)Math.round(Math.pow(numAtoms/4, 1.0/3.0)); primitive = new PrimitiveCubic(space, n*L); nCells = new int[]{n,n,n}; boundary = new BoundaryRectangularPeriodic(space, n * L); Basis basisFCC = new BasisCubicFcc(); basis = new BasisBigCell(space, basisFCC, nCells); box.setBoundary(boundary); coordinateDefinition = new CoordinateDefinitionLeaf(box, primitive, basis, space); coordinateDefinition.initializeCoordinates(new int[]{1,1,1}); potential = ss ? new P2SoftSphere(space, 1.0, 4.0, 12) : new P2LennardJones(space, 1.0, 1.0); potential = new P2SoftSphericalTruncated(space, potential, rc); atomMove.setPotential(potential); IAtomType sphereType = species.getLeafType(); potentialMaster.addPotential(potential, new IAtomType[] {sphereType, sphereType }); /* * 1-body Potential to Constraint the atom from moving too far * away from its lattice-site * */ P1ConstraintNbr p1Constraint = new P1ConstraintNbr(space, nbrDistance, this); p1Constraint.initBox(box); atomMove.setConstraint(p1Constraint); potentialMaster.lrcMaster().setEnabled(false); integrator.setBox(box); int cellRange = 7; potentialMaster.setRange(rc); potentialMaster.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2 // find neighbors now. Don't hook up NeighborListManager (neighbors won't change) potentialMaster.getNeighborManager(box).reset(); int potentialCells = potentialMaster.getNbrCellManager(box).getLattice().getSize()[0]; if (potentialCells < cellRange*2+1) { throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")"); } activityIntegrate = new ActivityIntegrate(integrator); getController().addAction(activityIntegrate); // extend potential range, so that atoms that move outside the truncation range will still interact // atoms that move in will not interact since they won't be neighbors ((P2SoftSphericalTruncated)potential).setTruncationRadius(0.6*boundary.getBoxSize().getX(0)); } public void initialize(long initSteps) { // equilibrate off the lattice to avoid anomalous contributions activityIntegrate.setMaxSteps(initSteps); getController().actionPerformed(); getController().reset(); integrator.getMoveManager().setEquilibrating(false); } /** * @param args filename containing simulation parameters * @see SimLJHTTI.SimOverlapParam */ public static void main(String[] args) { //set up simulation parameters SimOverlapParam params = new SimOverlapParam(); if (args.length == 0) { params.numAtoms = 500; params.numSteps = 1000000; params.temperature = 1; params.density = 1; params.rcMax1 = 4; params.rcMax0 = 13; params.rc = 3.5; params.rc0 = 3; params.bpharm = new double[]{}; // 864 params.bpharm = new double[]{9.550752087386252e+00,9.554899656911383e+00,9.557975701182272e+00,9.561039289571333e+00,9.561785691168332e+00,9.562084920108349e+00,9.562184015777641e+00,9.562223770855450e+00,9.562237600652669e+00}; //500 params.bpharmLJ = new double[]{1.361085875265710e+00,1.362422294066396e+00,1.363399142959180e+00,1.364383687422787e+00,1.364621191334029e+00,1.364711705394565e+00,1.364747826183867e+00,1.364760708535937e+00,1.364768368160011e+00}; //500 params.ss = false; } else { ParseArgs.doParseArgs(params, args); } boolean ss = params.ss; double density = params.density; long numSteps = params.numSteps; final int numAtoms = params.numAtoms; double temperature = params.temperature; double rc = params.rc; double rc0 = params.rc0; double rcMax0 = params.rcMax0; double rcMax1 = params.rcMax1; if (rcMax1 > rcMax0) rcMax1 = rcMax0; double[] bpharm = params.bpharm; double[] bpharmLJ = params.bpharmLJ; System.out.println("Running "+(ss?"soft-sphere":"Lennard-Jones")+" simulation"); System.out.println(numAtoms+" atoms at density "+density+" and temperature "+temperature); System.out.println(numSteps+" steps"); //instantiate simulation final SimLJHTTISuper sim = new SimLJHTTISuper(Space.getInstance(3), numAtoms, density, temperature, rc*Math.pow(density, -1.0/3.0), ss); int[] seeds = ((RandomMersenneTwister)sim.getRandom()).getSeedArray(); System.out.println("Random seeds: "+Arrays.toString(seeds)); if (false) { SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, sim.space, sim.getController()); simGraphic.setPaintInterval(sim.box, 1000); ColorScheme colorScheme = new ColorScheme() { public Color getAtomColor(IAtom a) { if (allColors==null) { allColors = new Color[768]; for (int i=0; i<256; i++) { allColors[i] = new Color(255-i,i,0); } for (int i=0; i<256; i++) { allColors[i+256] = new Color(0,255-i,i); } for (int i=0; i<256; i++) { allColors[i+512] = new Color(i,0,255-i); } } return allColors[(2*a.getLeafIndex()) % 768]; } protected Color[] allColors; }; simGraphic.getDisplayBox(sim.box).setColorScheme(colorScheme); DisplayTextBox timer = new DisplayTextBox(); DataSourceCountSteps counter = new DataSourceCountSteps(sim.integrator); DataPumpListener counterPump = new DataPumpListener(counter, timer, 100); sim.integrator.getEventManager().addListener(counterPump); simGraphic.getPanel().controlPanel.add(timer.graphic()); simGraphic.makeAndDisplayFrame("SS"); return; } //start simulation double L = Math.pow(numAtoms, 1.0/3.0); if (rcMax1 > 0.494*L) rcMax1 = 0.494*L; double delta = 0.5; int nCutoffs = 1; double c = rc0; for (nCutoffs=1; c<=rcMax1*1.0001; nCutoffs++) { c += delta; if (nCutoffs%2==0) delta += 0.5; } nCutoffs if (nCutoffs > bpharm.length) { throw new RuntimeException("need more beta P harmonic"); } delta = 0.5; double[] cutoffs = new double[nCutoffs]; cutoffs[0] = rc0; for (int i=1; i<nCutoffs; i++) { cutoffs[i] = cutoffs[i-1] + delta; if (i%2==0) delta += 0.5; } for (int i=0; i<nCutoffs; i++) { cutoffs[i] *= Math.pow(density, -1.0/3.0); } PotentialMasterList potentialMasterData; Potential2SoftSpherical potential = ss ? new P2SoftSphere(sim.getSpace(), 1.0, 4.0, 12) : new P2LennardJones(sim.getSpace(), 1.0, 1.0); { // |potential| is our local potential used for data collection. potentialMasterData = new PotentialMasterList(sim, cutoffs[nCutoffs-1], sim.getSpace()); P2SoftSphericalTruncated potentialT = new P2SoftSphericalTruncated(sim.getSpace(), potential, cutoffs[nCutoffs-1]-0.01); IAtomType sphereType = sim.species.getLeafType(); potentialMasterData.addPotential(potentialT, new IAtomType[] {sphereType, sphereType }); potentialMasterData.lrcMaster().setEnabled(false); int cellRange = 7; potentialMasterData.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2 // find neighbors now. Don't hook up NeighborListManager (neighbors won't change) potentialMasterData.getNeighborManager(sim.box).reset(); int potentialCells = potentialMasterData.getNbrCellManager(sim.box).getLattice().getSize()[0]; if (potentialCells < cellRange*2+1) { throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")"); } // extend potential range, so that atoms that move outside the truncation range will still interact // atoms that move in will not interact since they won't be neighbors potentialT.setTruncationRadius(0.6*sim.box.getBoundary().getBoxSize().getX(0)); } PotentialMasterList potentialMasterDataLJ = null; P2LennardJones p2LJ = null; Potential2SoftSpherical potentialLJ = null; if (ss) { // |potential| is our local potential used for data collection. potentialMasterDataLJ = new PotentialMasterList(sim, cutoffs[nCutoffs-1], sim.getSpace()); p2LJ = new P2LennardJones(sim.getSpace()); potentialLJ = new P2SoftSphericalTruncated(sim.getSpace(), p2LJ, cutoffs[nCutoffs-1]-0.01); IAtomType sphereType = sim.species.getLeafType(); potentialMasterDataLJ.addPotential(potentialLJ, new IAtomType[] {sphereType, sphereType }); potentialMasterDataLJ.lrcMaster().setEnabled(false); int cellRange = 7; potentialMasterDataLJ.setCellRange(cellRange); // insanely high, this lets us have neighborRange close to dimensions/2 // find neighbors now. Don't hook up NeighborListManager (neighbors won't change) potentialMasterDataLJ.getNeighborManager(sim.box).reset(); int potentialCells = potentialMasterDataLJ.getNbrCellManager(sim.box).getLattice().getSize()[0]; if (potentialCells < cellRange*2+1) { throw new RuntimeException("oops ("+potentialCells+" < "+(cellRange*2+1)+")"); } // extend potential range, so that atoms that move outside the truncation range will still interact // atoms that move in will not interact since they won't be neighbors ((P2SoftSphericalTruncated)potentialLJ).setTruncationRadius(0.6*sim.box.getBoundary().getBoxSize().getX(0)); } // meter needs lattice energy, so make it now MeterSolidDACut meterSolid = new MeterSolidDACut(sim.getSpace(), potentialMasterData, sim.coordinateDefinition, cutoffs); meterSolid.setTemperature(temperature); meterSolid.setBPRes(bpharm); IData d = meterSolid.getData(); MeterPotentialEnergy meterEnergyShort = new MeterPotentialEnergy(sim.potentialMaster); meterEnergyShort.setBox(sim.box); final double[] uFacCut = new double[cutoffs.length]; double uShort = meterEnergyShort.getDataAsScalar(); for (int i=0; i<uFacCut.length; i++) { uFacCut[i] = d.getValue(5*i)*numAtoms - uShort; } if (ss) { if (bpharmLJ.length != bpharm.length) { throw new RuntimeException("I need LJ harmonic pressures for all cutoffs"); } meterSolid.setPotentialMasterDADv2(potentialMasterDataLJ, bpharmLJ); } double rcMaxLS = 3*0.494*L; if (rcMaxLS>rcMax0) rcMaxLS = rcMax0; if (rcMax1 >= rcMax0) rcMaxLS=0; delta = 0.5; int nCutoffsLS = 1; c = rc0; for (nCutoffsLS=1; c<rcMaxLS*1.0001; nCutoffsLS++) { c += delta; if (nCutoffsLS%2==0) delta += 0.5; } nCutoffsLS if (nCutoffsLS > bpharm.length) { throw new RuntimeException("need more beta P harmonic"); } final double[] cutoffsLS = new double[nCutoffsLS]; PotentialMasterMonatomic potentialMasterLS = new PotentialMasterMonatomic(sim); Potential2SoftSphericalLSMultiLat pLS = null; PotentialMasterMonatomic potentialMasterLJLS = null; Potential2SoftSphericalLSMultiLat pLJLS = null; final double[] uFacCutLS = new double[cutoffsLS.length]; MeterSolidDACut meterSolidLS = null; if (nCutoffsLS>0) { cutoffsLS[0] = rc0; delta = 0.5; for (int i=1; i<cutoffsLS.length; i++) { cutoffsLS[i] = cutoffsLS[i-1] + delta; if (i%2==0) delta += 0.5; } for (int i=0; i<nCutoffsLS; i++) { cutoffsLS[i] *= Math.pow(density, -1.0/3.0); } pLS = new Potential2SoftSphericalLSMultiLat(sim.getSpace(), cutoffsLS, potential, sim.coordinateDefinition); potentialMasterLS.addPotential(pLS, new IAtomType[]{sim.species.getLeafType(),sim.species.getLeafType()}); meterSolidLS = new MeterSolidDACut(sim.getSpace(), potentialMasterLS, sim.coordinateDefinition, cutoffsLS); meterSolidLS.setTemperature(temperature); meterSolidLS.setBPRes(bpharm); d = meterSolidLS.getData(); if (params.ss) { potentialMasterLJLS = new PotentialMasterMonatomic(sim); pLJLS = new Potential2SoftSphericalLSMultiLat(sim.getSpace(), cutoffsLS, p2LJ, sim.coordinateDefinition); potentialMasterLJLS.addPotential(pLJLS, new IAtomType[]{sim.species.getLeafType(),sim.species.getLeafType()}); meterSolidLS.setPotentialMasterDADv2(potentialMasterLJLS, bpharmLJ); } for (int i=0; i<uFacCut.length; i++) { uFacCutLS[i] = uFacCut[i]; } for (int i=uFacCut.length; i<uFacCutLS.length; i++) { uFacCutLS[i] = d.getValue(5*i)*numAtoms - uShort; } } System.out.print("cutoffs: "); if (nCutoffsLS>0) { for (int i=0; i<nCutoffsLS; i++) { System.out.print(" "+cutoffsLS[i]); } } else { for (int i=0; i<nCutoffs; i++) { System.out.print(" "+cutoffs[i]); } } System.out.println(); System.out.print("bPharm "); if (nCutoffsLS>0) { for (int i=0; i<nCutoffsLS; i++) { System.out.print(" "+bpharm[i]); } } else { for (int i=0; i<nCutoffs; i++) { System.out.print(" "+bpharm[i]); } } System.out.println(); if (ss) { System.out.print("bPharmLJ "); if (nCutoffsLS>0) { for (int i=0; i<nCutoffsLS; i++) { System.out.print(" "+bpharmLJ[i]); } } else { for (int i=0; i<nCutoffs; i++) { System.out.print(" "+bpharmLJ[i]); } } System.out.println(); } if (args.length == 0) { // quick initialization sim.initialize(numSteps/10); } else { long nSteps = numSteps/20 + 50*numAtoms + numAtoms*numAtoms*3; if (nSteps > numSteps/2) nSteps = numSteps/2; sim.initialize(nSteps); } int numBlocks = 100; int interval = 2*numAtoms; int intervalLS = 5*interval; long blockSize = numSteps/(numBlocks*interval); if (blockSize == 0) blockSize = 1; long blockSizeLS = numSteps/(numBlocks*intervalLS); if (blockSizeLS == 0) blockSizeLS = 1; int o=2; while (blockSize<numSteps/5 && (numSteps != numBlocks*intervalLS*blockSizeLS || numSteps != numBlocks*interval*blockSize)) { interval = 2*numAtoms+(o%2==0 ? (o/2) : -(o/2)); if (interval < 1 || interval > numSteps/5) { throw new RuntimeException("oops interval "+interval); } // only need to enforce intervalLS if nCutoffsLS>0. whatever. intervalLS = 5*interval; blockSize = numSteps/(numBlocks*interval); if (blockSize == 0) blockSize = 1; blockSizeLS = numSteps/(numBlocks*intervalLS); if (blockSizeLS == 0) blockSizeLS = 1; o++; } if (numSteps != numBlocks*intervalLS*blockSizeLS || numSteps != numBlocks*interval*blockSize) { throw new RuntimeException("unable to find appropriate intervals"); } System.out.println("block size "+blockSize+" interval "+interval); final ValueCache energyFastCache = new ValueCache(meterEnergyShort, sim.integrator); DataProcessorReweight puReweight = new DataProcessorReweight(temperature, energyFastCache, uFacCut, sim.box, cutoffs.length); DataPumpListener pumpPU = new DataPumpListener(meterSolid, puReweight, interval); sim.integrator.getEventManager().addListener(pumpPU); final AccumulatorAverageCovariance avgSolid = new AccumulatorAverageCovariance(blockSize); puReweight.setDataSink(avgSolid); DataProcessorReweightRatio puReweightRatio = new DataProcessorReweightRatio(cutoffs.length); avgSolid.setBlockDataSink(puReweightRatio); AccumulatorAverageCovariance accPUBlocks = new AccumulatorAverageCovariance(1, true); puReweightRatio.setDataSink(accPUBlocks); AccumulatorAverageCovariance accPULSBlocks = null; AccumulatorAverageCovariance accPULS = null; if (nCutoffsLS>0) { DataProcessorReweight puLSReweight = new DataProcessorReweight(temperature, energyFastCache, uFacCutLS, sim.box, nCutoffsLS); DataPumpListener pumpPULS = new DataPumpListener(meterSolidLS, puLSReweight, intervalLS); sim.integrator.getEventManager().addListener(pumpPULS); accPULS = new AccumulatorAverageCovariance(blockSizeLS); puLSReweight.setDataSink(accPULS); DataProcessorReweightRatio puLSReweightRatio = new DataProcessorReweightRatio(nCutoffsLS, nCutoffs-1); accPULS.setBlockDataSink(puLSReweightRatio); accPULSBlocks = new AccumulatorAverageCovariance(1, true); puLSReweightRatio.setDataSink(accPULSBlocks); } final long startTime = System.currentTimeMillis(); sim.activityIntegrate.setMaxSteps(numSteps); sim.getController().actionPerformed(); long endTime = System.currentTimeMillis(); System.out.println(); IData avgRawData = avgSolid.getData(avgSolid.AVERAGE); IData errRawData = avgSolid.getData(avgSolid.ERROR); IData corRawData = avgSolid.getData(avgSolid.BLOCK_CORRELATION); IData covRawData = avgSolid.getData(avgSolid.BLOCK_COVARIANCE); int j = 0; for (int i=0; i<cutoffs.length; i++) { double avgW = avgRawData.getValue(j+5); double errW = errRawData.getValue(j+5); double corW = corRawData.getValue(j+5); System.out.println(String.format("rc: %2d dbA: % 21.15e %10.4e % 5.3f % 6.4f", i, -Math.log(avgW)/numAtoms, errW/avgW/numAtoms, corW, errW/avgW)); j += 6; } System.out.println("\n"); if (nCutoffsLS>0) { avgRawData = accPULS.getData(accPULS.AVERAGE); errRawData = accPULS.getData(accPULS.ERROR); corRawData = accPULS.getData(accPULS.BLOCK_CORRELATION); j = 0; for (int i=0; i<cutoffsLS.length; i++) { double avgW = avgRawData.getValue(j+5); double errW = errRawData.getValue(j+5); double corW = corRawData.getValue(j+5); System.out.println(String.format("rcLS: %2d dbA: % 21.15e %10.4e % 5.3f % 6.4f", i, -Math.log(avgW)/numAtoms, errW/avgW/numAtoms, corW, errW/avgW)); j += 6; } System.out.println("\n"); } IData avgData = accPUBlocks.getData(accPUBlocks.AVERAGE); IData errData = accPUBlocks.getData(accPUBlocks.ERROR); IData corData = accPUBlocks.getData(accPUBlocks.BLOCK_CORRELATION); IData covData = accPUBlocks.getData(accPUBlocks.BLOCK_COVARIANCE); int n = errData.getLength(); avgRawData = avgSolid.getData(avgSolid.AVERAGE); errRawData = avgSolid.getData(avgSolid.ERROR); covRawData = avgSolid.getData(avgSolid.BLOCK_COVARIANCE); int jRaw = 0; j = 0; int nRaw = avgRawData.getLength(); for (int i=0; i<cutoffs.length; i++) { // compute bias based on Taylor series expansion // Xmeasured = Xtrue ( 1 + (ew/w)^2 + (cov_XW)/(X W) ) double avgW = avgRawData.getValue(jRaw+5); double errW = errRawData.getValue(jRaw+5); double errWratio2 = errW*errW/(avgW*avgW); double avgU = avgRawData.getValue(jRaw+0); double errU = errRawData.getValue(jRaw+0); double corUW = covRawData.getValue((jRaw+5)*nRaw+(jRaw+0))/Math.sqrt(covRawData.getValue((jRaw+5)*nRaw+(jRaw+5))*covRawData.getValue((jRaw+0)*nRaw+(jRaw+0))); if (errW < 1e-7) corUW=0; // if this is sampled rc double biasU = errWratio2 - errU*errW/(avgU*avgW)*corUW; errU = Math.abs(avgU/avgW)*Math.sqrt(errU*errU/(avgU*avgU) + errWratio2 - 2*errU*errW/(avgU*avgW)*corUW); avgU /= avgW; avgU /= 1 + biasU; double corU = corData.getValue(j+0); double avgP = avgRawData.getValue(jRaw+1); double errP = errRawData.getValue(jRaw+1); double corPW = covRawData.getValue((jRaw+5)*nRaw+(jRaw+1))/Math.sqrt(covRawData.getValue((jRaw+5)*nRaw+(jRaw+5))*covRawData.getValue((jRaw+1)*nRaw+(jRaw+1))); if (errW < 1e-7) corPW=0; // if this is sampled rc double biasP = errWratio2 - errP*errW/(avgP*avgW)*corPW; errP = Math.abs(avgP/avgW)*Math.sqrt(errP*errP/(avgP*avgP) + errWratio2 - 2*errP*errW/(avgP*avgW)*corPW); avgP /= avgW; avgP /= 1 + biasP; double corP = corData.getValue(j+1); double avgBUc = avgRawData.getValue(jRaw+2); double errBUc = errRawData.getValue(jRaw+2); double corBUcW = covRawData.getValue((jRaw+5)*nRaw+(jRaw+2))/Math.sqrt(covRawData.getValue((jRaw+5)*nRaw+(jRaw+5))*covRawData.getValue((jRaw+2)*nRaw+(jRaw+2))); if (errW < 1e-7) corBUcW=0; // if this is sampled rc double biasBUc = errWratio2 - errBUc*errW/(avgBUc*avgW)*corBUcW; errBUc = Math.abs(avgBUc/avgW)*Math.sqrt(errBUc*errBUc/(avgBUc*avgBUc) + errWratio2 - 2*errBUc*errW/(avgBUc*avgW)*corBUcW); avgBUc /= avgW; avgBUc /= 1 + biasBUc; double corBUc = corData.getValue(j+2); double avgZc = avgRawData.getValue(jRaw+3); double errZc = errRawData.getValue(jRaw+3); double corZcW = covRawData.getValue((jRaw+5)*nRaw+(jRaw+3))/Math.sqrt(covRawData.getValue((jRaw+5)*nRaw+(jRaw+5))*covRawData.getValue((jRaw+3)*nRaw+(jRaw+3))); if (errW < 1e-7) corZcW=0; // if this is sampled rc double biasZc = errWratio2 - errZc*errW/(avgZc*avgW)*corZcW; errZc = Math.abs(avgZc/avgW)*Math.sqrt(errZc*errZc/(avgZc*avgZc) + errWratio2 - 2*errZc*errW/(avgZc*avgW)*corZcW); avgZc /= avgW; avgZc /= 1 + biasZc; double corZc = corData.getValue(j+3); // this is dbAc/dv2 at constant Y (for LJ) double avgDADv2 = avgRawData.getValue(jRaw+4); double errDADv2 = errRawData.getValue(jRaw+4); double corDADv2W = covRawData.getValue((jRaw+5)*nRaw+(jRaw+4))/Math.sqrt(covRawData.getValue((jRaw+5)*nRaw+(jRaw+5))*covRawData.getValue((jRaw+4)*nRaw+(jRaw+4))); if (errW < 1e-7) corDADv2W=0; // if this is sampled rc double biasDADv2 = errWratio2 - errDADv2*errW/(avgDADv2*avgW)*corDADv2W; errDADv2 = Math.abs(avgDADv2/avgW)*Math.sqrt(errDADv2*errDADv2/(avgDADv2*avgDADv2) + errWratio2 - 2*errDADv2*errW/(avgDADv2*avgW)*corDADv2W); avgDADv2 /= avgW; avgDADv2 /= 1 + biasDADv2; double corDADv2 = corData.getValue(j+4); double facDADY = 4*density*density*density*density/temperature; double PUCor = covData.getValue((j+1)*n+(j+0))/Math.sqrt(covData.getValue((j+1)*n+(j+1))*covData.getValue((j+0)*n+(j+0))); double DADACor = covData.getValue((j+2)*n+(j+4))/Math.sqrt(covData.getValue((j+2)*n+(j+2))*covData.getValue((j+4)*n+(j+4))); double ZcUcCor = covData.getValue((j+3)*n+(j+4))/Math.sqrt(covData.getValue((j+3)*n+(j+3))*covData.getValue((j+4)*n+(j+4))); System.out.print(String.format("rc: %2d DADY: % 21.15e %10.4e % 10.4e % 5.3f\n", i, -facDADY*avgBUc, facDADY*errBUc, -facDADY*avgBUc*biasBUc, corBUc)); System.out.print(String.format("rc: %2d DADv2: % 21.15e %10.4e % 10.4e % 5.3f % 8.6f\n", i, avgDADv2, errDADv2, avgDADv2*biasDADv2, corDADv2, DADACor)); System.out.print(String.format("rc: %2d Zc: % 21.15e %10.4e % 10.4e % 5.3f\n", i, avgZc, errZc, avgZc*biasZc, corZc)); System.out.print(String.format("rc: %2d bUc: % 21.15e %10.4e % 10.4e % 5.3f % 8.6f\n", i, avgBUc, errBUc, avgBUc*biasBUc, corBUc, ZcUcCor)); System.out.print(String.format("rc: %2d Uraw: % 21.15e %10.4e % 10.4e % 5.3f\n", i, avgU, errU, avgU*biasU, corU)); System.out.print(String.format("rc: %2d Praw: % 21.15e %10.4e % 10.4e % 5.3f % 8.6f\n", i, avgP, errP, avgP*biasP, corP, PUCor)); System.out.println(); j+=5; jRaw+=6; } if (nCutoffsLS > 0) { avgRawData = accPULS.getData(accPULS.AVERAGE); avgData = accPULSBlocks.getData(accPULSBlocks.AVERAGE); errData = accPULSBlocks.getData(accPULSBlocks.ERROR); covData = accPULSBlocks.getData(accPULSBlocks.BLOCK_COVARIANCE); corData = accPULSBlocks.getData(accPULSBlocks.BLOCK_CORRELATION); n = errData.getLength(); j = 0; jRaw = 0; double avgUref = 0, avgPref = 0, avgZCref = 0, avgBUCref = 0, avgDADv2ref = 0; for (int i=0; i<cutoffsLS.length; i++) { if (i<cutoffs.length-1) { j+=5; jRaw+=6; continue; } // estimate bias based on difference between averages using all data and average of block data // that gives us bias in block data. then divide by number of blocks (bias proportional to variance and covariance) double avgW = avgRawData.getValue(jRaw+5); double avgU = avgRawData.getValue(jRaw+0)/avgW; double avgU1 = avgData.getValue(j+0); double errU = errData.getValue(j+0); double corU = corData.getValue(j+0); double avgP = avgRawData.getValue(jRaw+1)/avgW; double avgP1 = avgData.getValue(j+1); double errP = errData.getValue(j+1); double corP = corData.getValue(j+1); double avgBUc = avgRawData.getValue(jRaw+2)/avgW; double avgBUc1 = avgData.getValue(j+2); double errBUc = errData.getValue(j+2); double corBUc = corData.getValue(j+2); double avgZc = avgRawData.getValue(jRaw+3)/avgW; double avgZc1 = avgData.getValue(j+3); double errZc = errData.getValue(j+3); double corZc = corData.getValue(j+3); // this is dbAc/drho at constant Y (for LJ) double avgDADv2 = avgRawData.getValue(jRaw+4)/avgW; double avgDADv21 = avgData.getValue(j+4); double errDADv2 = errData.getValue(j+4); double corDADv2 = corData.getValue(j+4); double DADACor = covData.getValue(2*n+4)/Math.sqrt(covData.getValue(2*n+2)*covData.getValue(4*n+4)); double ZcUcCor = covData.getValue(3*n+4)/Math.sqrt(covData.getValue(3*n+3)*covData.getValue(4*n+4)); double facDADY = 4*density*density*density*density/temperature; double PUCor = covData.getValue(1*n+0)/Math.sqrt(covData.getValue(1*n+1)*covData.getValue(0*n+0)); if (i==cutoffs.length-1) { avgUref = avgU; avgPref = avgP; avgZCref = avgZc; avgBUCref = avgBUc; avgDADv2ref = avgDADv2; j+=5; jRaw+=6; continue; } avgU -= avgUref; avgP -= avgPref; avgZc -= avgZCref; avgBUc -= avgBUCref; avgDADv2 -= avgDADv2ref; System.out.print(String.format("rcLS: %2d DADY: % 21.15e %10.4e % 11.4e % 5.3f\n", i, -facDADY*avgBUc, facDADY*errBUc, -facDADY*(avgBUc1-avgBUc)/numBlocks, corBUc)); System.out.print(String.format("rcLS: %2d DADv2: % 21.15e %10.4e % 11.4e % 5.3f % 8.6f\n", i, avgDADv2, errDADv2, (avgDADv21-avgDADv2)/numBlocks, corDADv2, DADACor)); System.out.print(String.format("rcLS: %2d Zc: % 21.15e %10.4e % 11.4e % 5.3f\n", i, avgZc, errZc, (avgZc1-avgZc)/numBlocks, corZc)); System.out.print(String.format("rcLS: %2d bUc: % 21.15e %10.4e % 11.4e % 5.3f % 8.6f\n", i, avgBUc, errBUc, (avgBUc1-avgBUc)/numBlocks, corBUc, ZcUcCor)); System.out.print(String.format("rcLS: %2d Uraw: % 21.15e %10.4e % 11.4e % 5.3f\n", i, avgU, errU, (avgU1-avgU)/numBlocks, corU)); System.out.print(String.format("rcLS: %2d Praw: % 21.15e %10.4e % 11.4e % 5.3f % 8.6f\n", i, avgP, errP, (avgP1-avgP)/numBlocks, corP, PUCor)); System.out.println(); j+=5; jRaw+=6; } } System.out.println("time: " + (endTime - startTime)/1000.0); } public IntegratorMC integrator; public ActivityIntegrate activityIntegrate; public IBox box; public Boundary boundary; public int[] nCells; public Basis basis; public Primitive primitive; public MCMoveAtomCoupled atomMove; public PotentialMasterList potentialMaster; public final CoordinateDefinitionLeaf coordinateDefinition; public Potential2SoftSpherical potential; public SpeciesSpheresMono species; /** * Inner class for parameters understood by the HSMD3D constructor */ public static class SimOverlapParam extends ParameterBase { public int numAtoms = 256; public double density = 1.28; public long numSteps = 1000000; public double temperature = 0.1; public double rc = 2.5; public double rc0 = rc; public double rcMax1 = 100; public double rcMax0 = 100; public double[] bpharm = new double[0]; public double[] bpharmLJ = new double[0]; public boolean ss = false; } }
package etomica.potential; import etomica.api.IAtomSet; import etomica.api.IPotential; import etomica.api.IVector; import etomica.atom.AtomLeafAgentManager; import etomica.integrator.IntegratorBox; /** * Sums the force on each iterated atom and adds it to the integrator agent * associated with the atom. */ public class PotentialCalculationForceSum implements PotentialCalculation { private static final long serialVersionUID = 1L; protected AtomLeafAgentManager integratorAgentManager; protected AtomLeafAgentManager.AgentIterator agentIterator; public void setAgentManager(AtomLeafAgentManager agentManager) { integratorAgentManager = agentManager; agentIterator = integratorAgentManager.makeIterator(); } /** * Re-zeros the force vectors. * */ public void reset(){ agentIterator.reset(); while(agentIterator.hasNext()){ Object agent = agentIterator.next(); if (agent instanceof IntegratorBox.Forcible) { ((IntegratorBox.Forcible)agent).force().E(0); } } } /** * Adds forces due to given potential acting on the atoms produced by the iterator. * Implemented for only 1- and 2-body potentials. */ public void doCalculation(IAtomSet atoms, IPotential potential) { PotentialSoft potentialSoft = (PotentialSoft)potential; int nBody = potential.nBody(); IVector[] f = potentialSoft.gradient(atoms); switch(nBody) { case 1: ((IntegratorBox.Forcible)integratorAgentManager.getAgent(atoms.getAtom(0))).force().ME(f[0]); break; case 2: ((IntegratorBox.Forcible)integratorAgentManager.getAgent(atoms.getAtom(0))).force().ME(f[0]); ((IntegratorBox.Forcible)integratorAgentManager.getAgent(atoms.getAtom(1))).force().ME(f[1]); break; default: //XXX atoms.count might not equal f.length. The potential might size its //array of vectors to be large enough for one IAtomSet and then not resize it //back down for another IAtomSet with fewer atoms. for (int i=0; i<atoms.getAtomCount(); i++) { ((IntegratorBox.Forcible)integratorAgentManager.getAgent(atoms.getAtom(i))).force().ME(f[i]); } } } }
package com.helger.jaxb; import java.io.File; import java.io.OutputStream; import java.io.Writer; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.WillClose; import javax.xml.transform.Result; import org.w3c.dom.Document; import com.helger.commons.ValueEnforcer; import com.helger.commons.io.resource.IWritableResource; import com.helger.commons.io.stream.ByteBufferOutputStream; import com.helger.commons.io.stream.NonBlockingStringWriter; import com.helger.commons.io.stream.StreamHelper; import com.helger.commons.state.ESuccess; import com.helger.commons.xml.XMLFactory; import com.helger.commons.xml.transform.TransformResultFactory; /** * Interface for writing JAXB documents to various destinations. * * @author Philip Helger * @param <JAXBTYPE> * The JAXB type to be written */ public interface IJAXBWriter <JAXBTYPE> { /** * Write the passed object to a {@link File}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aResultFile * The result file to be written to. May not be <code>null</code>. * @return {@link ESuccess} */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull final File aResultFile) { return write (aObject, TransformResultFactory.create (aResultFile)); } /** * Write the passed object to an {@link OutputStream}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aOS * The output stream to write to. Will always be closed. May not be * <code>null</code>. * @return {@link ESuccess} */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull @WillClose final OutputStream aOS) { try { return write (aObject, TransformResultFactory.create (aOS)); } finally { // Needs to be manually closed StreamHelper.close (aOS); } } /** * Write the passed object to a {@link Writer}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aWriter * The writer to write to. Will always be closed. May not be * <code>null</code>. * @return {@link ESuccess} */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull @WillClose final Writer aWriter) { try { return write (aObject, TransformResultFactory.create (aWriter)); } finally { // Needs to be manually closed StreamHelper.close (aWriter); } } /** * Write the passed object to a {@link ByteBuffer}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aBuffer * The byte buffer to write to. If the buffer is too small, it is * automatically extended. May not be <code>null</code>. * @return {@link ESuccess} * @throws BufferOverflowException * If the ByteBuffer is too small */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull final ByteBuffer aBuffer) { return write (aObject, new ByteBufferOutputStream (aBuffer, false)); } /** * Write the passed object to an {@link IWritableResource}. * * @param aObject * The object to be written. May not be <code>null</code>. * @param aResource * The result resource to be written to. May not be <code>null</code>. * @return {@link ESuccess} */ @Nonnull default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull final IWritableResource aResource) { return write (aObject, TransformResultFactory.create (aResource)); } /** * Convert the passed object to XML. * * @param aObject * The object to be converted. May not be <code>null</code>. * @param aResult * The result object holder. May not be <code>null</code>. * @return {@link ESuccess} */ @Nonnull ESuccess write (@Nonnull JAXBTYPE aObject, @Nonnull Result aResult); /** * Convert the passed object to a new DOM document. * * @param aObject * The object to be converted. May not be <code>null</code>. * @return <code>null</code> if converting the document failed. */ @Nullable default Document getAsDocument (@Nonnull final JAXBTYPE aObject) { ValueEnforcer.notNull (aObject, "Object"); final Document aDoc = XMLFactory.newDocument (); return write (aObject, TransformResultFactory.create (aDoc)).isSuccess () ? aDoc : null; } /** * Utility method to directly convert the passed domain object to an XML * string. * * @param aObject * The domain object to be converted. May not be <code>null</code>. * @return <code>null</code> if the passed domain object could not be * converted because of validation errors. */ @Nullable default String getAsString (@Nonnull final JAXBTYPE aObject) { final NonBlockingStringWriter aSW = new NonBlockingStringWriter (); return write (aObject, TransformResultFactory.create (aSW)).isSuccess () ? aSW.getAsString () : null; } /** * Write the passed object to a {@link ByteBuffer} and return it. * * @param aObject * The object to be written. May not be <code>null</code>. * @return <code>null</code> if the passed domain object could not be * converted because of validation errors. */ @Nullable default ByteBuffer getAsByteBuffer (@Nonnull final JAXBTYPE aObject) { final ByteBufferOutputStream aBBOS = new ByteBufferOutputStream (); return write (aObject, aBBOS).isFailure () ? null : aBBOS.getBuffer (); } @Nullable default byte [] getAsBytes (@Nonnull final JAXBTYPE aObject) { final ByteBufferOutputStream aBBOS = new ByteBufferOutputStream (); return write (aObject, aBBOS).isFailure () ? null : aBBOS.getAsByteArray (); } }
package pipe.handlers; import pipe.controllers.PetriNetController; import pipe.actions.gui.PipeApplicationModel; import pipe.gui.widgets.EscapableDialog; import pipe.gui.widgets.PlaceEditorPanel; import uk.ac.imperial.pipe.models.petrinet.Place; import javax.swing.*; import java.awt.Container; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; /** * Handles place actions */ public class PlaceHandler extends ConnectableHandler<Place> { /** * Constructor * @param contentpane parent pane of the view * @param place place model * @param controller Petri net controller of the Petri net the place belongs to * @param applicationModel main PIPE application model */ public PlaceHandler(Container contentpane, Place place, PetriNetController controller, PipeApplicationModel applicationModel) { super(contentpane, place, controller, applicationModel); } /** * Creates the pop up meny for a place containing the options * Edit place * * @param e event * @return the pop up menu for the place */ @Override protected JPopupMenu getPopup(MouseEvent e) { int index = 0; JPopupMenu popup = super.getPopup(e); JMenuItem menuItem = new JMenuItem("Edit Place"); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showEditor(); } }; menuItem.addActionListener(actionListener); popup.insert(menuItem, index++); popup.insert(new JPopupMenu.Separator(), index); return popup; } /** * Shows the Place editor dialog where the place components can be edited */ public void showEditor() { // Build interface Window window = SwingUtilities.getWindowAncestor(contentPane); EscapableDialog guiDialog = new EscapableDialog(window, "PIPE5", true); Container contentPane = guiDialog.getContentPane(); // 1 Set layout contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); // 2 Add Place editor contentPane.add( new PlaceEditorPanel(guiDialog.getRootPane(), petriNetController.getPlaceController(component), petriNetController)); guiDialog.setResizable(false); // Make window fit contents' preferred size guiDialog.pack(); // Move window to the middle of the screen guiDialog.setLocationRelativeTo(null); guiDialog.setVisible(true); } }
package nl.mpi.yaas.crawler; import java.net.URI; import java.net.URISyntaxException; import nl.mpi.flap.kinnate.entityindexer.QueryException; import nl.mpi.flap.plugin.PluginException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Main { static public void main(String[] args) { // if (System.getProperty("java.util.logging.config.file") == null) { // try { // LogManager.getLogManager().readConfiguration(Main.class.getResourceAsStream("/logging-initial.properties")); // } catch (IOException exception) { // System.out.println("Could not configure initial logging"); // System.out.println(exception.getMessage()); // System.exit(-1); // } catch (SecurityException exception) { // System.out.println("Could not configure initial logging"); // System.out.println(exception.getMessage()); // System.exit(-1); int defaultNumberToCrawl = 10000; String databaseUrl = "http://192.168.56.101:8080/BaseX76/rest/"; String databaseUser = "admin"; String databasePassword = "admin"; String defaultStartUrl = "http://corpus1.mpi.nl/CGN/COREX6/data/meta/imdi_3.0_eaf/corpora/cgn.imdi"; // create the command line parser CommandLineParser parser = new BasicParser(); //DefaultParser(); // create the Options Options options = new Options(); options.addOption("d", "drop", false, "Drop the existing data and recrawl. This option implies the c option."); options.addOption("c", "crawl", false, "Crawl the provided url or the default url if not otherwise specified."); options.addOption("a", "append", false, "Restart crawling adding missing documents."); options.addOption("n", "number", true, "Number of documents to insert (default is " + defaultNumberToCrawl + ")."); options.addOption("t", "target", true, "Target URL of the start documents to crawl (default is " + defaultStartUrl + "). This option implies the c option."); options.addOption("s", "server", true, "Data base server URL, default is " + databaseUrl); options.addOption("u", "user", true, "Data base user name, default is " + databaseUser); options.addOption("p", "password", true, "Data base password, default is " + databasePassword); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // check for valid actions and show help if none found if (!line.hasOption("d") && !line.hasOption("c") && !line.hasOption("a")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("yaas-crawler", options); System.exit(-1); } String startUrl = defaultStartUrl; int numberToCrawl = defaultNumberToCrawl; boolean crawlOption = line.hasOption("c"); if (line.hasOption("t")) { startUrl = line.getOptionValue("t"); crawlOption = true; } if (line.hasOption("n")) { numberToCrawl = Integer.parseInt(line.getOptionValue("n")); } if (line.hasOption("s")) { databaseUrl = line.getOptionValue("s"); } if (line.hasOption("u")) { databaseUser = line.getOptionValue("u"); } if (line.hasOption("p")) { databasePassword = line.getOptionValue("p"); } try { RemoteArchiveCrawler archiveCrawler = new RemoteArchiveCrawler(RemoteArchiveCrawler.DbType.StandardDB, numberToCrawl, databaseUrl, databaseUser, databasePassword); URI startURI = new URI(startUrl); // URI startURI = new URI("file:///Users/petwit2/.arbil/ArbilWorkingFiles/http/corpus1.mpi.nl/qfs1/media-archive/silang_data/Corpusstructure/1.imdi"); if (line.hasOption("d")) { System.out.println("Dropping and crawing from scratch"); archiveCrawler.dropAllRecords(); crawlOption = true; } if (crawlOption) { System.out.println("Crawling the start URL: " + startURI); archiveCrawler.crawl(startURI); } // if (line.hasOption("a")) { System.out.println("Looking for and appending missing documents"); archiveCrawler.update(); archiveCrawler.clearAndCalculateDbStats(); archiveCrawler.insertKnowIcons(); archiveCrawler.preloadFacets(); System.exit(0); // arbil threads might be requiring this to terminate } catch (URISyntaxException exception) { System.out.println(exception.getMessage()); System.exit(-1); } catch (QueryException exception) { System.out.println(exception.getMessage()); System.exit(-1); } catch (PluginException exception) { System.out.println(exception.getMessage()); System.exit(-1); } } catch (ParseException exp) { System.out.println("Cannot parse the command line input:" + exp.getMessage()); } } }
package claw.tatsu.directive.common; import claw.tatsu.TatsuConstant; import claw.tatsu.common.CompilerDirective; import claw.tatsu.common.Context; import claw.tatsu.common.Message; import claw.tatsu.directive.generator.DirectiveGenerator; import claw.tatsu.primitive.Function; import claw.tatsu.primitive.Pragma; import claw.tatsu.xcodeml.abstraction.FunctionCall; import claw.tatsu.xcodeml.xnode.XnodeUtil; import claw.tatsu.xcodeml.xnode.common.Xattr; import claw.tatsu.xcodeml.xnode.common.Xcode; import claw.tatsu.xcodeml.xnode.common.XcodeProgram; import claw.tatsu.xcodeml.xnode.common.Xnode; import claw.tatsu.xcodeml.xnode.fortran.FfunctionDefinition; import java.util.*; import java.util.stream.Collectors; /** * The class Directive contains only static method to help the * generation of the directive related pragma during code transformations. * * @author clementval */ public final class Directive { public static final int NO_COLLAPSE = 0; private static final String NO_CLAUSES = ""; // Avoid potential instantiation of this class private Directive() { } /** * Generate loop seq directives on the top of loops in the given function * definition. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be * generated. * @param fctDef Function definition in which do statements * will be decorated. * @param noDependencyDirective Directive string used to flag a loop as * no dependency loop. * @return Number of independent flagged loop. */ public static int generateLoopSeq(XcodeProgram xcodeml, FfunctionDefinition fctDef, String noDependencyDirective) { if(Context.get().getCompilerDirective() == CompilerDirective.NONE) { return 0; } int nodepCounter = 0; List<Xnode> doStmts = fctDef.matchAll(Xcode.F_DO_STATEMENT); for(Xnode doStmt : doStmts) { // Check if the nodep directive decorates the loop Xnode noDependency = isDecoratedWith(doStmt, noDependencyDirective); if(noDependency == null) { addPragmasBefore(xcodeml, Context.get().getGenerator(). getStartLoopDirective(NO_COLLAPSE, true, true, ""), doStmt); } else { ++nodepCounter; } XnodeUtil.safeDelete(noDependency); // Debug logging Message.debug(String.format( "%s generated loop %s directive for loop at line: %d", Context.get().getGenerator().getPrefix(), (noDependency == null) ? "seq" : "", doStmt.lineNo())); } return Context.get().getAcceleratorConfig().hasCollapseStrategy() ? nodepCounter : 0; } /** * Generate update directives for device and host data transfer. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param hook Node used as a hook for insertion. Update device are * generated before the hook and update host after the hook. * @param vars List of variables inserted in the directive. * @param direction Direction of the update directive. * @return Last inserted pragma. */ public static Xnode generateUpdate(XcodeProgram xcodeml, Xnode hook, List<String> vars, DataMovement direction) { if(Context.get().getGenerator().getDirectiveLanguage() == CompilerDirective.NONE) { return null; } Xnode p = null; if(direction == DataMovement.HOST_TO_DEVICE || direction == DataMovement.TWO_WAY) { p = addPragmasBefore(xcodeml, Context.get().getGenerator(). getUpdateClause(direction == DataMovement.TWO_WAY ? DataMovement.HOST_TO_DEVICE : direction, vars), hook); } if(direction == DataMovement.DEVICE_TO_HOST || direction == DataMovement.TWO_WAY) { p = addPragmaAfter(xcodeml, Context.get().getGenerator(). getUpdateClause(direction == DataMovement.TWO_WAY ? DataMovement.DEVICE_TO_HOST : direction, vars), hook); } return p; } /** * Check if there is a !$claw nodep directive before the do statement. * * @param doStmt Do statement to be checked. * @return True if the directive is present. False otherwise. */ private static Xnode isDecoratedWith(Xnode doStmt, String directive) { if(!Xnode.isOfCode(doStmt, Xcode.F_DO_STATEMENT)) { return null; } Xnode sibling = doStmt.prevSibling(); while(Xnode.isOfCode(sibling, Xcode.F_PRAGMA_STATEMENT)) { if(sibling.value().toLowerCase().contains(directive.toLowerCase())) { return sibling; } sibling = sibling.prevSibling(); } return null; } /** * Generate corresponding pragmas to surround the code with a parallel * accelerated region. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param startStmt Start statement representing the beginning of the parallel * region. * @param endStmt End statement representing the end of the parallel region. * @return Last stmt inserted or null if nothing is inserted. */ public static Xnode generateParallelRegion(XcodeProgram xcodeml, Xnode startStmt, Xnode endStmt) { return insertPragmas(xcodeml, startStmt, endStmt, Context.get().getGenerator().getStartParallelDirective(NO_CLAUSES), Context.get().getGenerator().getEndParallelDirective()); } /** * Generate directive directive for a parallel loop. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be * generated. * @param privates List of variables to be set privates. * @param startStmt Start statement representing the beginning of the * parallel region. * @param endStmt End statement representing the end of the parallel * region. * @param collapse If value bigger than 0, a corresponding collapse * constructs can be generated. * @param returnEndBlock If true, the end block directive is returned. If * false, start block directive is returned. * @return Start or end block directive. */ public static Xnode generateParallelLoopClause(XcodeProgram xcodeml, List<String> privates, Xnode startStmt, Xnode endStmt, String extraDirective, int collapse, boolean returnEndBlock) { if(Context.get().getGenerator().getDirectiveLanguage() == CompilerDirective.NONE) { return null; } DirectiveGenerator dg = Context.get().getGenerator(); addPragmasBefore(xcodeml, dg.getStartParallelDirective(null), startStmt); Xnode startBlock = addPragmasBefore(xcodeml, dg.getStartLoopDirective(collapse, false, false, format(dg.getPrivateClause(privates), extraDirective)), startStmt); Xnode endBlock = addPragmaAfter(xcodeml, dg.getEndParallelDirective(), endStmt); addPragmaAfter(xcodeml, dg.getEndLoopDirective(), endStmt); return returnEndBlock ? endBlock : startBlock; } /** * Format two string together. * * @param s1 String value or null. * @param s2 String value or null. * @return Formatted trimmed string. */ private static String format(String s1, String s2) { return String.format("%s %s", s1 == null ? "" : s1.trim(), s2 == null ? "" : s2.trim()).trim(); } /** * Generates directive directive for a loop region. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param startStmt Start statement representing the beginning of the loop * region. * @param endStmt End statement representing the end of the loop region. * @param collapse If value bigger than 0, a corresponding collapse * constructs can be generated. */ public static void generateLoopDirectives(XcodeProgram xcodeml, Xnode startStmt, Xnode endStmt, int collapse) { insertPragmas(xcodeml, startStmt, endStmt, Context.get().getGenerator(). getStartLoopDirective(collapse, false, false, ""), Context.get().getGenerator().getEndLoopDirective()); } /** * Generate directive directive for a data region. Some clauses can be ignored * depending on the configuration, if this results to discard all variables * then the directive is not generated. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param presents List of variables to be set as present. * @param creates List of variables to be created. * @param startStmt Start statement representing the beginning of the data * region. * @param endStmt End statement representing the end of the data region. */ public static void generateDataRegionClause(XcodeProgram xcodeml, List<String> presents, List<String> creates, Xnode startStmt, Xnode endStmt) { DirectiveGenerator generator = Context.get().getGenerator(); List<String> clauses = new ArrayList<>(Arrays.asList( generator.getPresentClause(presents), generator.getCreateClause(creates))); clauses.removeAll(Collections.singletonList("")); // No need to create an empty data region if(!clauses.isEmpty()) { insertPragmas(xcodeml, startStmt, endStmt, generator.getStartDataRegion(clauses), generator.getEndDataRegion()); } } /** * Generate corresponding pragmas applied directly after a CLAW pragma. * * @param startStmt Start statement representing the beginning of the parallel * region. * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param accClause Additional clause append at the end of the directive. * @return Last stmt inserted or null if nothing is inserted. */ public static Xnode generateAcceleratorClause( XcodeProgram xcodeml, Xnode startStmt, String accClause) { /* TODO OpenACC and OpenMP loop construct are pretty different ... have to look how to do that properly. See issue #22 */ return addPragmasBefore(xcodeml, Context.get().getGenerator(). getSingleDirective(accClause), startStmt); } /** * Generate all corresponding pragmas to be applied to an accelerated * function/subroutine. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param fctDef Function/subroutine in which directive directives are * generated. */ public static void generateRoutineDirectives(XcodeProgram xcodeml, FfunctionDefinition fctDef) { DirectiveGenerator dirGen = Context.get().getGenerator(); if(dirGen.getDirectiveLanguage() == CompilerDirective.NONE) { return; // Do nothing if "none" is selected for directive } // Find all fct call in the current transformed fct List<FunctionCall> fctCalls = fctDef.matchAll(Xcode.FUNCTION_CALL).stream() .filter(f -> !f.getBooleanAttribute(Xattr.IS_INTRINSIC)) .map(FunctionCall::new) .collect(Collectors.toList()); for(FunctionCall fctCall : fctCalls) { // Do nothing for intrinsic fct or null fctName if(fctCall.getFctName() == null) { continue; } Optional<FfunctionDefinition> calledFctDef = Function.findFunctionDefinitionFromFctCall(xcodeml, fctDef, fctCall); if(calledFctDef.isPresent()) { // TODO - Check that the directive is not present yet. // TODO - Directive.hasDirectives(calledFctDef) addPragmasBefore(xcodeml, dirGen.getRoutineDirective(true), calledFctDef.get().body().child(0)); Message.debug(dirGen.getPrefix() + "generated routine seq directive for " + fctCall.getFctName() + " subroutine/function."); } else { // Could not generate directive for called function. xcodeml.addWarning(fctCall.getFctName() + " has not been found. " + "Automatic routine directive generation could not be done.", fctCall.lineNo()); } } } /** * Generate the correct clauses for private variable on directive. * * @param xcodeml Object representation of the current XcodeML * representation in which the pragmas will be generated. * @param stmt Statement from which we looks for a parallel clause to * append private clauses. * @param var Variable to generate the private clause. */ public static void generatePrivateClause(XcodeProgram xcodeml, Xnode stmt, String var) { if(Context.get().getGenerator().getDirectiveLanguage() == CompilerDirective.NONE) { return; } Xnode hook = Pragma.findPrevious(stmt, Context.get().getGenerator().getParallelKeyword()); // TODO do it with loop as well if hook is null if(hook == null) { xcodeml.addWarning("No parallel construct found to attach private clause", stmt.lineNo()); } else { hook.setValue(hook.value() + " " + Context.get().getGenerator().getPrivateClause(var)); } } /** * Create and insert a pragma statement before the reference node. * * @param xcodeml Current XcodeML program unit. * @param directives Value of the newly created directive. * @param ref Reference node used to insert the newly created pragma. * @return Newly created pragma statement as an Xnode object. */ public static Xnode addPragmasBefore(XcodeProgram xcodeml, String[] directives, Xnode ref) { return insertPragmas(xcodeml, directives, ref, false); } /** * Create and insert a pragma statement after the reference node. * * @param xcodeml Current XcodeML program unit. * @param directives Value of the newly created directive. * @param ref Reference node used to insert the newly created pragma. * @return Newly created pragma statement as an Xnode object. */ private static Xnode addPragmaAfter(XcodeProgram xcodeml, String[] directives, Xnode ref) { return insertPragmas(xcodeml, directives, ref, true); } /** * Create and insert a pragma statement. * * @param xcodeml Current XcodeML program unit. * @param directives Value of the newly created directive. * @param ref Reference node used to insert the newly created pragma. * @param after By default, the pragma is inserted before the reference. * If after is set to true, the pragma is inserted after. * @return Newly created pragma statement as an Xnode object. */ private static Xnode insertPragmas(XcodeProgram xcodeml, String[] directives, Xnode ref, boolean after) { if(directives == null) { return null; } for(String directive : directives) { List<Xnode> pragmas = xcodeml.createPragma(directive, Context.get().getMaxColumns()); for(Xnode pragma : pragmas) { if(after) { ref.insertAfter(pragma); ref = pragma; // Insert pragma sequentially one after another } else { ref.insertBefore(pragma); // Only the first chunk needs to be inserted after = true; ref = pragma; } } } return ref; } /** * Generate corresponding pragmas to surround the code with a parallel * accelerated region. * * @param xcodeml Current XcodeML program unit. * representation in which the pragmas will be * generated. * @param startStmt Start reference statement. * @param endStmt End reference statement. * @param startDirective String value of the start directive. * @param endDirective String value of the end directive. * @return Last stmt inserted or null if nothing is inserted. */ private static Xnode insertPragmas(XcodeProgram xcodeml, Xnode startStmt, Xnode endStmt, String[] startDirective, String[] endDirective) { if(Context.get().getGenerator().getDirectiveLanguage() == CompilerDirective.NONE) { return null; } Xnode begin = addPragmasBefore(xcodeml, startDirective, startStmt); Xnode end = addPragmaAfter(xcodeml, endDirective, endStmt); return end != null ? end : begin; } /** * Skip elements in preamble and find the first element that will be included * in the parallel region. * * @param functionDefinition Function definition in which body checked. * @param from Optional element to start from. If null, starts * from first element in function's body. * @return First element for the parallel region. */ public static Xnode findParallelRegionStart(Xnode functionDefinition, Xnode from) { DirectiveGenerator dg = Context.get().getGenerator(); if(dg.getDirectiveLanguage() == CompilerDirective.NONE || !Xnode.isOfCode(functionDefinition, Xcode.F_FUNCTION_DEFINITION)) { return null; } Xnode first = functionDefinition.body().firstChild(); if(first == null) { return null; } if(from != null) { // Start from given element first = from; } if(dg.getSkippedStatementsInPreamble().isEmpty()) { return first; } else { while(first.nextSibling() != null && ((dg.getSkippedStatementsInPreamble().contains(first.opcode())) || isClawDirective(first))) { if(Xnode.isOfCode(first, Xcode.F_IF_STATEMENT)) { Xnode then = first.matchDescendant(Xcode.THEN); if(then != null && then.hasBody()) { for(Xnode child : then.body().children()) { if(!dg.getSkippedStatementsInPreamble(). contains(child.opcode())) { return first; } } } } else if(first.hasBody()) { for(Xnode child : first.body().children()) { if(!dg.getSkippedStatementsInPreamble(). contains(child.opcode())) { return first; } } } first = first.nextSibling(); } } return first; } /** * Check if the node is a CLAW directive * * @param node Node to check. * @return True if the node is a CLAW directive. False otherwise. */ private static boolean isClawDirective(Xnode node) { return Xnode.isOfCode(node, Xcode.F_PRAGMA_STATEMENT) && node.value().toLowerCase().startsWith(TatsuConstant.DIRECTIVE_CLAW); } /** * Skip elements in epilogue and find the last element that will be included * in the parallel region. * * @param functionDefinition Function definition in which body checked. * @param from Optional element to start from. If null, starts * from last element in function's body. * @return Last element for the parallel region. */ public static Xnode findParallelRegionEnd(Xnode functionDefinition, Xnode from) { DirectiveGenerator dg = Context.get().getGenerator(); if(dg.getDirectiveLanguage() == CompilerDirective.NONE || !Xnode.isOfCode(functionDefinition, Xcode.F_FUNCTION_DEFINITION)) { return null; } Xnode last = functionDefinition.body().lastChild(); if(last == null) { return null; } if(from != null) { // Start from given element last = from; if(last.is(Xcode.F_CONTAINS_STATEMENT)) { last = last.prevSibling(); } } if(dg.getSkippedStatementsInEpilogue().isEmpty() || !last.matchAll(Xcode.F_ASSIGN_STATEMENT).isEmpty()) { return last; } else { while(last.prevSibling() != null && dg.getSkippedStatementsInEpilogue().contains(last.opcode())) { if(last.hasBody() || last.is(Xcode.F_IF_STATEMENT)) { List<Xnode> children = (last.hasBody()) ? last.body().children() : last.matchDirectDescendant(Xcode.THEN).body().children(); for(Xnode child : children) { if(!dg.getSkippedStatementsInEpilogue().contains(child.opcode())) { return last; } } } last = last.prevSibling(); } } return last; } /** * Check if the function definition has directives already. * * @param fctDef Function definition to check * @return True if there is directive of the current chosen directive in the * function definition. False otherwise. */ public static boolean hasDirectives(FfunctionDefinition fctDef) { String prefix = Context.get().getGenerator().getPrefix(); return fctDef.body().matchAll(Xcode.F_PRAGMA_STATEMENT).stream() .map(Xnode::value).map(String::toLowerCase) .anyMatch(p -> p.startsWith(prefix)); } }
package claw.tatsu.xcodeml.xnode.common; import claw.tatsu.xcodeml.xnode.Xname; import claw.tatsu.xcodeml.xnode.fortran.FbasicType; import claw.tatsu.xcodeml.xnode.fortran.FfunctionDefinition; import claw.tatsu.xcodeml.xnode.fortran.FmoduleDefinition; import claw.tatsu.xcodeml.xnode.fortran.FortranType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.List; /** * XcodeML AST node. * * @author clementval */ public class Xnode { public static final int LHS = 0; public static final int RHS = 1; public static final int UNDEF_DEPTH = -1; final Element _baseElement; private boolean _isDeleted = false; /** * Constructs an Xnode object from an element in the AST. * * @param element Base element for the Xnode object. */ public Xnode(Element element) { _baseElement = element; } /** * Delete this nodes with all its next siblings. */ public void deleteWithSiblings() { List<Xnode> toDelete = new ArrayList<>(); toDelete.add(this); Xnode sibling = nextSibling(); while(sibling != null) { toDelete.add(sibling); sibling = sibling.nextSibling(); } for(Xnode n : toDelete) { n.delete(); } } /** * Get the element opcode. * * @return Opcode. */ public Xcode opcode() { if(_baseElement == null) { return Xcode.NONE; } return Xcode.fromString(_baseElement.getTagName().toLowerCase()); } /** * Check whether the element has the corresponding attribute. * * @param attrCode Attribute code. * @return True if the element has the corresponding attribute. */ public boolean hasAttribute(Xattr attrCode) { return hasAttribute(attrCode.toString()); } /** * Check whether the element has the corresponding attribute. * * @param attrCode Attribute code. * @return True if the element has the corresponding attribute. */ private boolean hasAttribute(String attrCode) { return _baseElement != null && _baseElement.hasAttribute(attrCode); } /** * Get the attribute's value. * * @param attrCode Attribute code. * @return Attribute's value. */ public String getAttribute(Xattr attrCode) { return getAttribute(attrCode.toString()); } /** * Get the attribute's value. * * @param attrCode Attribute code. * @return Attribute's value. */ private String getAttribute(String attrCode) { if(_baseElement != null && _baseElement.hasAttribute(attrCode)) { return _baseElement.getAttribute(attrCode); } else { return null; } } /** * Get boolean value of an attribute. * * @param attrCode Attribute code. * @return Attribute's value. False if attribute doesn't exist. */ public boolean getBooleanAttribute(Xattr attrCode) { return getBooleanAttribute(attrCode.toString()); } /** * Get boolean value of an attribute. * * @param attrCode Attribute code. * @return Attribute's value. False if attribute doesn't exist. */ private boolean getBooleanAttribute(String attrCode) { return hasAttribute(attrCode) && _baseElement.getAttribute(attrCode).equals(Xname.TRUE); } /** * Get raw node value. * * @return Raw value. */ public String value() { return _baseElement == null ? "" : _baseElement.getTextContent().trim().toLowerCase(); } /** * Set the element value. * * @param value The element value. */ public void setValue(String value) { if(_baseElement != null) { _baseElement.setTextContent(value); } } /** * Set the value of a boolean attribute. * * @param attrCode Attribute code. * @param value Boolean value to set. */ public void setBooleanAttribute(Xattr attrCode, boolean value) { setBooleanAttribute(attrCode.toString(), value); } /** * Set the value of a boolean attribute. * * @param attrCode Attribute code. * @param value Boolean value to set. */ private void setBooleanAttribute(String attrCode, boolean value) { if(value) { setAttribute(attrCode, Xname.TRUE); } else { setAttribute(attrCode, Xname.FALSE); } } /** * Set attribute value. * * @param attrCode Attribute code. * @param value Value of the attribute. */ public void setAttribute(Xattr attrCode, String value) { setAttribute(attrCode.toString(), value); } /** * Set attribute value. * * @param attrCode Attribute code. * @param value Value of the attribute. */ private void setAttribute(String attrCode, String value) { if(_baseElement != null && value != null) { _baseElement.setAttribute(attrCode, value); } } /** * Remove an attribute from the node. * * @param attrCode Attribute code. */ public void removeAttribute(Xattr attrCode) { if(_baseElement != null && _baseElement.hasAttribute(attrCode.toString())) { _baseElement.removeAttribute(attrCode.toString()); } } /** * Check whether the current element is an element with body element. * * @return True if the element should have a body. False otherwise. */ public boolean hasBody() { return opcode().hasBody(); } /** * Get the inner body element. * * @return The body element if found. Null otherwise. */ public Xnode body() { return matchDirectDescendant(Xcode.BODY); } /** * Get child at position. * * @param pos Position of the child. * @return Child at the corresponding position. */ public Xnode child(int pos) { List<Xnode> children = children(); if(pos < 0 || pos > children.size() - 1) { return null; } return children.get(pos); } /** * Get the list of child elements. * * @return List of children of the current element. */ public List<Xnode> children() { List<Xnode> nodes = new ArrayList<>(); if(_baseElement == null) { return nodes; } NodeList children = _baseElement.getChildNodes(); for(int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); if(child.getNodeType() == Node.ELEMENT_NODE) { nodes.add(new Xnode((Element) child)); } } return nodes; } /** * Get the first child node. * * @return First child or null if no child exists. */ public Xnode firstChild() { List<Xnode> children = this.children(); return children.isEmpty() ? null : children.get(0); } /** * Get the last child node. * * @return Last child or null if no child exists. */ public Xnode lastChild() { List<Xnode> children = this.children(); return children.isEmpty() ? null : children.get(children.size() - 1); } /** * Delete the stored root element and all its children. */ public void delete() { _isDeleted = true; if(_baseElement == null || _baseElement.getParentNode() == null) { return; } _baseElement.getParentNode().removeChild(_baseElement); } /** * Check whether the node has been deleted. * * @return True if the node has been deleted. False otherwise. */ public boolean isDeleted() { return _isDeleted || _baseElement == null; } /** * Get the base element. * * @return Element. */ public Element element() { return _baseElement; } /** * Append an element ot the children of this element. * * @param node The element to append. * @param clone If true, the element is cloned before being appended. If * false, the element is directly appended. */ public void append(Xnode node, boolean clone) { if(node != null && _baseElement != null) { if(clone) { _baseElement.appendChild(node.cloneRawNode()); } else { _baseElement.appendChild(node.element()); } } } /** * Append an element ot the children of this element. Node is not cloned. * * @param node The element to append. */ public void append(Xnode node) { append(node, false); } /** * Insert as first child. * * @param node Node to be inserted. * @param clone Clone or not the element before insertion. */ public void insert(Xnode node, boolean clone) { if(node != null && _baseElement != null) { NodeList children = _baseElement.getChildNodes(); Node toInsert = clone ? node.cloneRawNode() : node.element(); if(children.getLength() == 0) { append(node, clone); } else { _baseElement.insertBefore(toInsert, children.item(0)); } } } /** * Insert as first child. * * @param node Node to be inserted. */ public void insert(Xnode node) { insert(node, false); } /** * Set the lineno attribute in the element. * * @param lineno Line number. */ public void setLine(int lineno) { setAttribute(Xattr.LINENO, String.valueOf(lineno)); } /** * Get the lineno attribute value. This attribute is not defined for every * elements. * * @return Line number. 0 if the attribute is not defined. */ public int lineNo() { return hasAttribute(Xattr.LINENO) ? Integer.parseInt(getAttribute(Xattr.LINENO)) : 0; } /** * Get the file attribute value. This value represents the original filename * from the XcodeML unit. This attribute is not defined for every elements. * * @return File path. Empty string if the file attribute is not defined. */ public String filename() { return hasAttribute(Xattr.FILE) ? getAttribute(Xattr.FILE) : ""; } /** * Set the file attribute of the element. * * @param value File path. */ public void setFilename(String value) { setAttribute(Xattr.FILE, value); } /** * Clone the current element with all its children. * * @return A copy of the current element. */ public Xnode cloneNode() { Node clone = cloneRawNode(); return new Xnode((Element) clone); } /** * Create an identical copy of the element and its children. * * @return A node representing the root element of the clone. */ public Node cloneRawNode() { if(_baseElement == null) { return null; } return _baseElement.cloneNode(true); } /** * Get next sibling node. * * @return Next sibling node. */ public Xnode nextSibling() { if(_baseElement == null) { return null; } Node n = _baseElement.getNextSibling(); while(n != null) { if(n.getNodeType() == Node.ELEMENT_NODE) { return new Xnode((Element) n); } n = n.getNextSibling(); } return null; } /** * Get ancestor node if any. * * @return Ancestor node if any. Null otherwise. */ public Xnode ancestor() { if(_baseElement == null || _baseElement.getParentNode() == null) { return null; } // Reach document root stop here if(_baseElement.getParentNode().getNodeType() == Node.DOCUMENT_NODE) { return null; } return new Xnode((Element) _baseElement.getParentNode()); } /** * Get previous sibling node. * * @return Previous sibling node. */ public Xnode prevSibling() { if(_baseElement == null) { return null; } Node n = _baseElement.getPreviousSibling(); while(n != null) { if(n.getNodeType() == Node.ELEMENT_NODE) { return new Xnode((Element) n); } n = n.getPreviousSibling(); } return null; } /** * Check whether the end node is a direct sibling of this node. If other * nodes are between the two nodes and their opcode is not listed in the * skippedNodes list, the nodes are not direct siblings. * * @param end Node to be check to be a direct sibling. * @param skippedNodes List of opcode that are allowed between the two nodes. * @return True if the nodes are direct siblings. */ public boolean isDirectSibling(Xnode end, List<Xcode> skippedNodes) { if(end == null) { return false; } Xnode nextSibling = nextSibling(); while(nextSibling != null) { if(nextSibling.equals(end)) { return true; } if(skippedNodes.contains(nextSibling.opcode())) { nextSibling = nextSibling.nextSibling(); } else { return false; } } return false; } /** * Find node with the given opcode in the ancestors of the current node. * * @param opcode Opcode of the node to be matched. * @return The matched node. Null if nothing matched. */ public Xnode matchAncestor(Xcode opcode) { return universalMatch(opcode, false); } /** * Find node with the given opcode in the siblings of the given node. * * @param opcode Opcode of the node to be matched. * @return The matched node. Null if no node found. */ public Xnode matchSibling(Xcode opcode) { return universalMatch(opcode, true); } /** * Find nodes with the given opcode in the ancestors of the current node. * * @param opcode Opcode of the node to be matched. * @return List of matched node. Empty list if nothing matched. */ public List<Xnode> matchAllAncestor(Xcode opcode) { return matchAllAncestor(opcode, null); } /** * Find nodes with the given opcode in the ancestors of the current node. * * @param opcode Opcode of the node to be matched. * @param stopCode Stop searching if given opcode is reached. If null, search * until root node. * @return List of matched node. Empty list if nothing matched. */ public List<Xnode> matchAllAncestor(Xcode opcode, Xcode stopCode) { List<Xnode> statements = new ArrayList<>(); Xnode crt = this; while(crt != null && crt.ancestor() != null) { if(crt.ancestor().opcode() == opcode) { statements.add(crt.ancestor()); } // Stop searching when FfunctionDefinition is reached if(stopCode != null && crt.ancestor().opcode() == stopCode) { return statements; } crt = crt.ancestor(); } return statements; } /** * Find node with the given opcode in the descendants of the current node. * * @param opcode Opcode of the node to be matched. * @return The matched node. Null if nothing matched. */ public Xnode matchDescendant(Xcode opcode) { if(_baseElement == null) { return null; } NodeList elements = _baseElement.getElementsByTagName(opcode.code()); if(elements.getLength() == 0) { return null; } return (elements.item(0) == null) ? null : new Xnode((Element) elements.item(0)); } /** * Find node with the given opcode in the direct descendants the current node. * * @param opcode Opcode of the node to be matched. * @return The matched node. Null if nothing matched. */ public Xnode matchDirectDescendant(Xcode opcode) { if(_baseElement == null) { return null; } NodeList nodeList = _baseElement.getChildNodes(); for(int i = 0; i < nodeList.getLength(); i++) { Node nextNode = nodeList.item(i); if(nextNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())) { return new Xnode(element); } } } return null; } /** * Find node with one of the given opcodes in the direct descendants * the current node. * * @param opcodes List of opcodes to be searched. * @return The matched node. Null if no node found. */ public Xnode matchDirectDescendant(List<Xcode> opcodes) { List<Xnode> children = children(); for(Xnode child : children) { if(opcodes.contains(child.opcode())) { return child; } } return null; } /** * Find node with the given path of opcodes from the current node. * * @param opcodes Sequence of opcode to reach the node. * @return The matched node. Null if no node found. */ public Xnode matchSeq(Xcode... opcodes) { Xnode tmp = this; for(Xcode opcode : opcodes) { tmp = tmp.matchDirectDescendant(opcode); if(tmp == null) { return null; } } return tmp; } /** * Match all nodes with the given opcode in the subtree. * * @param opcode Opcode of the nodes to be matched. * @return List of all nodes matched in the subtree. */ public List<Xnode> matchAll(Xcode opcode) { List<Xnode> nodes = new ArrayList<>(); if(_baseElement == null) { return nodes; } NodeList rawNodes = _baseElement.getElementsByTagName(opcode.code()); for(int i = 0; i < rawNodes.getLength(); i++) { Node n = rawNodes.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) { nodes.add(new Xnode((Element) n)); } } return nodes; } /** * Find an element either in the next siblings or in the ancestors. * * @param opcode Opcode of the node to be matched. * @param down If True, search in the siblings. If false, search in the * ancestors. * @return The matched node. Null if no node found. */ private Xnode universalMatch(Xcode opcode, boolean down) { if(_baseElement == null) { return null; } Node nextNode = down ? _baseElement.getNextSibling() : _baseElement.getParentNode(); while(nextNode != null) { if(nextNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())) { return new Xnode(element); } } nextNode = down ? nextNode.getNextSibling() : nextNode.getParentNode(); } return null; } /** * Get the depth of the node in the AST. * * @return A depth value greater or equal to 0. */ public int depth() { if(isDeleted()) { return Xnode.UNDEF_DEPTH; } Node parent = _baseElement.getParentNode(); int depth = 0; while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { ++depth; parent = parent.getParentNode(); } return depth; } /** * Insert a node just after this node. * * @param node The node to be inserted after the current one. */ public void insertAfter(Xnode node) { if(_baseElement != null && node != null) { Node parent = _baseElement.getParentNode(); if(parent != null) { parent.insertBefore(node.element(), _baseElement.getNextSibling()); } } } /** * Compare the inner value of the first child of two nodes. * * @param other Node to compare with * @return True if the value if first childs are identical. False otherwise. */ public boolean compareFirstChildValues(Xnode other) { if(other == null) { return false; } Xnode c1 = child(0); Xnode c2 = other.child(0); return c1 != null && c2 != null && c1.compareValues(c2); } /** * Compare the inner values of two optional nodes. * * @param other Node to compare with * @return True if the values are identical or elements are null. False * otherwise. */ public boolean compareOptionalValues(Xnode other) { return other == null || value().equalsIgnoreCase(other.value()); } /** * Compare the inner values of two nodes. * * @param other Node to compare with * @return True if the values are identical. False otherwise. */ public boolean compareValues(Xnode other) { return other != null && value().equals(other.value()); } /** * Insert a node just before this node. * * @param node The node to be inserted before the current one. */ public void insertBefore(Xnode node) { if(_baseElement != null && node != null) { Node parent = _baseElement.getParentNode(); if(parent != null) { parent.insertBefore(node.element(), _baseElement); } } } /** * Find module definition node in which the current node is nested if any. * * @return A FmoduleDefinition node if found. Null otherwise. */ public FmoduleDefinition findParentModule() { Xnode moduleDef = matchAncestor(Xcode.F_MODULE_DEFINITION); return (moduleDef != null) ? new FmoduleDefinition(moduleDef) : null; } /** * Check whether a node is nested into another one. * * @param ancestor Node in which the current node is supposed to be nested. * @return True if the current node is nested in the ancestor node. False * otherwise. */ public boolean isNestedIn(Xnode ancestor) { if(ancestor == null || element() == null) { return false; } Node possibleAncestor = element().getParentNode(); while(possibleAncestor != null) { if(possibleAncestor == ancestor.element()) { return true; } possibleAncestor = possibleAncestor.getParentNode(); } return false; } /** * Return type hash associated with this node if any. * * @return Type hash. Empty string if there is no type hash associated. */ public String getType() { if(_baseElement == null) { return ""; } switch(opcode()) { case F_ARRAY_REF: String type = getAttribute(Xattr.TYPE); if(FortranType.isBuiltInType(type)) { Xnode child = firstChild(); return (child != null) ? child.getAttribute(Xattr.TYPE) : ""; } return type; case NAMED_VALUE: Xnode child = firstChild(); return (child != null) ? child.getAttribute(Xattr.TYPE) : ""; case F_FUNCTION_DEFINITION: case FUNCTION_CALL: case VAR_DECL: // functionCall has a type attribute but it's the return type Xnode name = matchDirectDescendant(Xcode.NAME); return (name != null) ? name.getAttribute(Xattr.TYPE) : ""; default: return getAttribute(Xattr.TYPE); } } /** * Set type of the node. * * @param type FbasicType to be associated with this node. */ public void setType(FbasicType type) { setAttribute(Xattr.TYPE, type.getType()); } /** * Set the type of the current node. * * @param value Type value. */ public void setType(String value) { setAttribute(Xattr.TYPE, value); } /** * Construct string representation of the node. Only for variable or constant. * * @param withNamedValue If true, keeps the named value, otherwise, just * constructs the argument. * @return String representation. Null if node is null. */ public String constructRepresentation(boolean withNamedValue) { switch(opcode()) { case F_INT_CONSTANT: case F_PRAGMA_STATEMENT: case VAR: return value(); case ARRAY_INDEX: case LOWER_BOUND: case UPPER_BOUND: case VAR_REF: { Xnode n = firstChild(); return (n != null) ? n.constructRepresentation(withNamedValue) : ""; } case INDEX_RANGE: if(getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) { return ":"; } Xnode child0 = child(0); Xnode child1 = child(1); return ((child0 != null) ? child0.constructRepresentation(withNamedValue) : "") + ":" + ((child1 != null) ? child1.constructRepresentation(withNamedValue) : ""); case F_ARRAY_REF: List<Xnode> childs = children(); if(childs.size() == 1) { return childs.get(0).constructRepresentation(withNamedValue); } else { StringBuilder str = new StringBuilder(); str.append(childs.get(0).constructRepresentation(withNamedValue)); str.append("("); for(int i = 1; i < childs.size(); ++i) { str.append(childs.get(i).constructRepresentation(withNamedValue)); if(i != childs.size() - 1) { str.append(","); } } str.append(")"); return str.toString(); } case F_MEMBER_REF: { Xnode n = firstChild(); return ((n != null) ? n.constructRepresentation(withNamedValue) + "%" + getAttribute(Xattr.MEMBER) : ""); } case NAMED_VALUE: { Xnode n = firstChild(); if(withNamedValue) { return ((n != null) ? getAttribute(Xattr.NAME) + "=" + n.constructRepresentation(true) : ""); } return (n != null) ? n.constructRepresentation(false) : ""; } default: return ""; } } /** * Copy the enhanced information from the current node to a target node. * Enhanced information include line number and original file name. * * @param target Target node to copy information to. */ public void copyEnhancedInfo(Xnode target) { target.setLine(lineNo()); target.setFilename(filename()); } /** * Check if the given node is direct children of the same parent node. * * @param n Node to be compared to. * @return True if the given node is direct children of the same parent. False * otherwise. */ public boolean hasSameParentBlock(Xnode n) { return !(n == null || element() == null || n.element() == null) && element().getParentNode() == n.element().getParentNode(); } /** * Find function definition in the ancestor of the current node. * * @return The function definition found. Null if nothing found. */ public FfunctionDefinition findParentFunction() { Xnode fctDef = matchAncestor(Xcode.F_FUNCTION_DEFINITION); if(fctDef == null) { return null; } return new FfunctionDefinition(fctDef); } /** * Copy the attribute from the current node to the given node. * * @param to Xnode to copy to. * @param attr Attribute code to be copied. */ public void copyAttribute(Xnode to, Xattr attr) { if(hasAttribute(attr)) { to.setAttribute(attr, getAttribute(attr)); } } /** * Sync given attribute between two node. Attribute present in this node * is created in "to" if not present yet. Attribute not present in this node * is removed from "to" if present. * * @param to Node to which attribute is synced. * @param attribute Attribute to be synced. */ public void syncBooleanAttribute(Xnode to, Xattr attribute) { if(getBooleanAttribute(attribute) && !to.getBooleanAttribute(attribute)) { to.setBooleanAttribute(attribute, true); } else if(!getBooleanAttribute(attribute) && to.getBooleanAttribute(attribute)) { to.removeAttribute(attribute); } } /** * Return a brief description of the Xnode. * * @return String description of the Xnode as "Opcode (children: n)". */ @Override public String toString() { return String.format("%s (children: %d) - %d", opcode().code(), children().size(), lineNo()); } @Override public int hashCode() { return _baseElement != null ? _baseElement.hashCode() : 0; } @Override public boolean equals(Object o) { return o instanceof Xnode && element() == ((Xnode) o).element(); } /** * Check whether current node is not part of an arrayIndex node. * * @return True if the node is not a direct child of an arrayIndex node. * False otherwise. */ public boolean isNotArrayIndex() { return ancestor() == null || ancestor().opcode() != Xcode.ARRAY_INDEX; } }
package edu.wustl.dao.test; import java.util.List; import org.junit.Test; import edu.wustl.common.dao.queryExecutor.PagenatedResultData; import edu.wustl.common.util.QueryParams; import edu.wustl.common.util.dbmanager.DAOException; import edu.wustl.common.util.global.Constants; import edu.wustl.dao.JDBCDAO; import edu.wustl.dao.QueryWhereClause; import edu.wustl.dao.condition.EqualClause; import edu.wustl.dao.condition.INClause; import edu.wustl.dao.condition.IsNullClause; import edu.wustl.dao.condition.NotNullClause; import edu.wustl.dao.daofactory.IDAOFactory; import edu.wustl.dao.util.DAOConstants; /** * @author kalpana_thakur * */ public class JDBCTestCases extends BaseTestCase *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* *//** *//* {/* * DAO instance. private JDBCDAO jdbcDAO; { setJDBCDAO(); } * This method will be called to set the Default DAO. public void setJDBCDAO() { IDAOFactory daoFactory = daoConfigFactory.getInstance().getDAOFactory("caTissuecore"); try { jdbcDAO = daoFactory.getJDBCDAO(); } catch (DAOException e) { e.printStackTrace(); } } * This test will assert that DAO instance is not null. @Test public void testJDBCDAOInstance() { assertNotNull("DAO Object is null",jdbcDAO); } * This test will assert the execution of query. @Test public void testExecuteUpdateJDBC() { try { jdbcDAO.openSession(null); StringBuffer strbuff = new StringBuffer(); strbuff.append("update xyz_user set EMAIL_ADDRESS ='abc@per.co.in'" + " where FIRST_NAME = 'john'"); jdbcDAO.executeUpdate(strbuff.toString()); jdbcDAO.commit(); jdbcDAO.closeSession(); } catch(Exception exp) { assertFalse("Failed while inserting object :", true); } } * This test will assert that all the objects are retrieved successfully. @Test public void testCaseRetriveAllObjectsJDBC() { try { jdbcDAO.openSession(null); List list = jdbcDAO.retrieve("xyz_user"); jdbcDAO.closeSession(); assertNotNull(list); } catch(Exception exp) { assertFalse("Failed while retrieving object :", true); } } * This test will assert that the object with requested * column will be retrieved successfully. @Test public void testCaseRetriveObjectJDBC() { try { jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve("xyz_user","IDENTIFIER" , Long.valueOf(2)); jdbcDAO.closeSession(); assertNotNull("No objects retrieved",list); assertTrue("No object retrieved ::",!list.isEmpty()); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that requested columns of the objects are * retrieved successfully. @Test public void testCaseRetrieveObjectColumnsJDBC() { try { String[] selectColumnName = {"IDENTIFIER","FIRST_NAME","LAST_NAME","EMAIL_ADDRESS"}; jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve("xyz_user", selectColumnName); jdbcDAO.closeSession(); assertNotNull("No object retrieved ::",list); assertTrue("No object retrieved ::",!list.isEmpty()); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that only distinct rows * retrieved successfully. @Test public void testCaseRetrieveOnlyDistinctRowsJDBC() { try { String[] selectColumnName = {"IDENTIFIER","FIRST_NAME","LAST_NAME","EMAIL_ADDRESS"}; jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve("xyz_user", selectColumnName,true); jdbcDAO.closeSession(); assertNotNull("No object retrieved ::",list); assertTrue("No object retrieved ::",!list.isEmpty()); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that objects retrieved successfully * when where clause holds in condition. @Test public void testRetriveInConditionJDBC() { try { String sourceObjectName = "xyz_user"; Object [] colValues = {Long.valueOf(2),Long.valueOf(4)}; String[] selectColumnName = null; QueryWhereClause queryWhereClause = new QueryWhereClause(); queryWhereClause.addCondition(new INClause("IDENTIFIER",colValues,sourceObjectName)); jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve(sourceObjectName, selectColumnName,queryWhereClause); jdbcDAO.closeSession(); assertNotNull("No value retrieved :",list); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that objects retrieved successfully * when where clause holds not null condition. @Test public void testRetriveIsNotNullConditionJDBC() { try { String sourceObjectName = "xyz_user"; String[] selectColumnName = null; QueryWhereClause queryWhereClause = new QueryWhereClause(); queryWhereClause.addCondition(new NotNullClause("IDENTIFIER",sourceObjectName)); queryWhereClause.operatorOr(); queryWhereClause.addCondition(new NotNullClause("LAST_NAME",sourceObjectName)); jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve(sourceObjectName, selectColumnName,queryWhereClause); jdbcDAO.closeSession(); assertNotNull("No value retrieved :" + list); assertTrue("No object retrieved ::",list.size() > 0); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that objects retrieved successfully * when where clause holds is null condition. @Test public void testRetriveIsNullConditionJDBC() { try { String sourceObjectName = "xyz_user"; String[] selectColumnName = null; QueryWhereClause queryWhereClause = new QueryWhereClause(); queryWhereClause.addCondition(new IsNullClause("LAST_NAME",sourceObjectName)); jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve(sourceObjectName, selectColumnName,queryWhereClause); jdbcDAO.closeSession(); assertNotNull("No object retrieved ::",list); assertTrue("No object retrieved ::",!list.isEmpty()); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that objects retrieved successfully with given column value * Having equal (=)condition. @Test public void testRetriveEqualConditionJDBC() { try { String sourceObjectName = "xyz_user"; String[] selectColumnName = null; QueryWhereClause queryWhereClause = new QueryWhereClause(); queryWhereClause.addCondition(new EqualClause("LAST_NAME","Washu",sourceObjectName)); jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve(sourceObjectName, selectColumnName,queryWhereClause); jdbcDAO.closeSession(); assertNotNull("No object retrieved ::",list); assertTrue("No object retrieved ::",list.size() > 0); } catch(Exception exp) { assertFalse("Failed while retrieving object ::", true); } } * This test will assert that table created successfully. @Test public void testCreateTableJDBC() { try { String tableName = "XYZ_Address"; String[] columnNames = {"City","State"}; jdbcDAO.openSession(null); jdbcDAO.createTable(tableName, columnNames); jdbcDAO.commit(); jdbcDAO.closeSession(); } catch(Exception exp) { assertFalse("Failed while creating table ::", true); } } * This test will assert that table created successfully. @Test public void testCreateTableQueryJDBC() { try { String query = "create table xyz_phoneNumber ( phone_number varchar(20) )"; jdbcDAO.openSession(null); jdbcDAO.createTable(query); jdbcDAO.commit(); jdbcDAO.closeSession(); } catch(Exception exp) { assertFalse("Failed while creating table ::", true); } } * This test will assert that table deleted successfully. @Test public void testDropTableJDBC() { try { jdbcDAO.openSession(null); jdbcDAO.delete("xyz_phoneNumber"); jdbcDAO.delete("XYZ_Address"); jdbcDAO.commit(); jdbcDAO.closeSession(); } catch(Exception exp) { assertFalse("Failed while droping table ::", true); } } * This test will assert that date pattern retrieved successfully. @Test public void testDatePatternJDBC() { String datePattern = jdbcDAO.getDatePattern(); assertNotNull("Problem in geting date pattern.",datePattern); assertTrue("Problem in geting date pattern.",datePattern.contains("%m-%d-%Y")); } * This test will assert that time pattern retrieved successfully. @Test public void testTimePatternJDBC() { String timePattern = jdbcDAO.getTimePattern(); assertNotNull("Problem in geting date pattern.",timePattern); } * This test will assert that date format function retrieved successfully. @Test public void testDateFormatFunctionJDBC() { String dateFormatFunction = jdbcDAO.getDateFormatFunction(); assertNotNull("Problem in geting date pattern.",dateFormatFunction); } * This test will assert that time format function retrieved successfully. @Test public void testTimeFormatFunctionJDBC() { String timeFormatFunction = jdbcDAO.getTimeFormatFunction(); assertNotNull("Problem in geting date pattern.",timeFormatFunction); } * This test will assert that Date to string format function retrieved successfully. @Test public void testDateTostrFunctionJDBC() { String dateTostrFunction = jdbcDAO.getDateTostrFunction(); assertNotNull("Problem in geting date pattern.",dateTostrFunction); } * This test will assert that string to date function retrieved successfully. @Test public void testStrTodateFunctionJDBC() { String strTodateFunction = jdbcDAO.getStrTodateFunction(); assertNotNull("Problem in geting date pattern.",strTodateFunction); } * This test will assert that string to date function retrieved successfully. @Test public void testExecuteQueryJDBC() { try { QueryParams queryParams = new QueryParams(); queryParams.setQuery("select * from xyz_user"); queryParams.setSessionDataBean(null); queryParams.setSecureToExecute(true); queryParams.setHasConditionOnIdentifiedField(false); queryParams.setQueryResultObjectDataMap(null); queryParams.setStartIndex(-1); queryParams.setNoOfRecords(-1); jdbcDAO.openSession(null); PagenatedResultData pagenatedResultData = (PagenatedResultData)jdbcDAO.executeQuery(queryParams); jdbcDAO.closeSession(); assertNotNull("Problem while retrieving data ",pagenatedResultData!=null); } catch(Exception exp) { assertFalse("Problem while retrieving data ", true); } } * This test will create a complex retrieve query having multiple clause(IN,NOT NULL,IS NULL) * It will ensure that objects retrieved successfully. @Test public void testRetriveComplexQueryJDBC() { try { String sourceObjectName = "xyz_user"; Object [] colValues = {Long.valueOf(2),Long.valueOf(4)}; String[] selectColumnName = null; QueryWhereClause queryWhereClause = new QueryWhereClause(); queryWhereClause.addCondition(new INClause("IDENTIFIER",colValues,sourceObjectName)); queryWhereClause.operatorOr(); queryWhereClause.addCondition(new NotNullClause("FIRST_NAME",sourceObjectName)); queryWhereClause.operatorOr(); queryWhereClause.addCondition(new EqualClause("FIRST_NAME","Washu",sourceObjectName)); jdbcDAO.openSession(null); List<Object> list = jdbcDAO.retrieve(sourceObjectName, selectColumnName,queryWhereClause); jdbcDAO.closeSession(); assertNotNull("No data retrieved :",list); assertTrue("No data retrieved :",!list.isEmpty()); } catch(Exception exp) { assertFalse("Problem occurred while retrieving object:", true); } } * This test will assert the audit method implementation. @Test public void testAuditJDBC() { try { jdbcDAO.audit(null, null, null, false); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will delete method implementation. @Test public void testDeleteJDBC() { try { jdbcDAO.delete(new Object()); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will DisableRelatedObjects method implementation. @Test public void testDisableRelatedObjectsJDBC() { try { jdbcDAO.disableRelatedObjects(null, null, null); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will insert method implementation. @Test public void testInsertJDBC() { try { jdbcDAO.insert(null, null, false, false); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will retrieveAttribute() method implementation. @Test public void testRetrieveAttributeJDBC() { try { jdbcDAO.retrieveAttribute(null, null, null, null); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will Update() method implementation. @Test public void testUpdateJDBC() { try { jdbcDAO.update(null); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } * This test will retrieve() method implementation. @Test public void testRetrieveJDBC() { try { jdbcDAO.retrieve(null, Long.valueOf(0)); } catch(Exception exp) { assertEquals(DAOConstants.METHOD_WITHOUT_IMPLEMENTATION,exp.getMessage()); } } */}
package org.jboss.as.version; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Properties; import java.util.jar.Manifest; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; /** * Common location to manage the AS based product name and version. * */ public class ProductConfig implements Serializable { private final String name; private final String version; private final String consoleSlot; public ProductConfig(ModuleLoader loader, String home) { String productName = null; String productVersion = null; String consoleSlot = null; try { FileReader reader = new FileReader(getProductConf(home)); Properties props = new Properties(); props.load(reader); String slot = (String) props.get("slot"); if (slot != null) { Module module = loader.loadModule(ModuleIdentifier.create("org.jboss.as.product", slot)); InputStream stream = module.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF"); Manifest manifest = null; if (stream != null) { manifest = new Manifest(stream); } if (manifest != null) { productName = manifest.getMainAttributes().getValue("JBoss-Product-Release-Name"); productVersion = manifest.getMainAttributes().getValue("JBoss-Product-Release-Version"); consoleSlot = manifest.getMainAttributes().getValue("JBoss-Product-Console-Slot"); } } } catch (Exception e) { // Don't care } name = productName; version = productVersion; this.consoleSlot = consoleSlot; } private static String getProductConf(String home) { final String defaultVal = home + File.separator + "bin" + File.separator + "product.conf"; PrivilegedAction<String> action = new PrivilegedAction<String>() { public String run() { String env = System.getenv("JBOSS_PRODUCT_CONF"); if (env == null) { env = defaultVal; } return env; } }; return System.getSecurityManager() == null ? action.run() : AccessController.doPrivileged(action); } /** Solely for use in unit testing */ public ProductConfig(final String productName, final String productVersion, final String consoleSlot) { this.name = productName; this.version = productVersion; this.consoleSlot = consoleSlot; } public String getProductName() { return name; } public String getProductVersion() { return version; } public String getConsoleSlot() { return consoleSlot; } public String getPrettyVersionString() { if (name != null) return String.format("JBoss %s %s (AS %s)", name, version, Version.AS_VERSION); return String.format("JBoss AS %s \"%s\"", Version.AS_VERSION, Version.AS_RELEASE_CODENAME); } public static String getPrettyVersionString(final String name, String version1, String version2) { if(name != null) { return String.format("JBoss %s %s (AS %s)", name, version1, version2); } return String.format("JBoss AS %s \"%s\"", version1, version2); } }
package info.limpet.rcp.core_view; import info.limpet.IChangeListener; import info.limpet.IStore.IStoreItem; import info.limpet.data.operations.CollectionComplianceTests; import info.limpet.rcp.Activator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; public abstract class CoreAnalysisView extends ViewPart { private Action newView; private Action copyToClipboard; private Action followSelection; private ISelectionListener selListener; protected CollectionComplianceTests aTests; final private List<IStoreItem> curList = new ArrayList<IStoreItem>(); private IChangeListener changeListener; final private String _myId; final private String _myTitle; public CoreAnalysisView(String myId, String myTitle) { super(); _myId = myId; _myTitle = myTitle; aTests = new CollectionComplianceTests(); changeListener = new IChangeListener() { @Override public void dataChanged(IStoreItem subject) { display(curList); } @Override public void collectionDeleted(IStoreItem subject) { // hmm, we should probably stop listening to that collection curList.remove(subject); // and update the UI display(curList); } @Override public void metadataChanged(IStoreItem subject) { display(curList); } }; } /** * external accessor, since we switch off following when a view has been * created specifically to view a particular selection * * @param val */ public void follow(List<IStoreItem> data) { followSelection.setChecked(false); followSelection.setEnabled(false); followSelection .setDescription("Disabled - view focussed on particular dataset"); display(data); // also set the title if (data.size() == 1) { this.setPartName(_myTitle + " - " + data.get(0).getName()); } else { this.setPartName(_myTitle + " - multiple datasets"); } } protected void newSelection(ISelection selection) { List<IStoreItem> res = new ArrayList<IStoreItem>(); if (selection instanceof StructuredSelection) { StructuredSelection str = (StructuredSelection) selection; // check if it/they are suitable Iterator<?> iter = str.iterator(); while (iter.hasNext()) { Object object = (Object) iter.next(); if (object instanceof IAdaptable) { IAdaptable ad = (IAdaptable) object; IStoreItem coll = (IStoreItem) ad.getAdapter(IStoreItem.class); if (coll != null) { res.add(coll); } } } } // ok, stop listening to the old list clearChangeListeners(); // have we found any, and are they suitable for us? if ((res.size()) > 0 && appliesToMe(res, aTests)) { // store the new list curList.addAll(res); // now listen to the new list Iterator<IStoreItem> iter = curList.iterator(); while (iter.hasNext()) { IStoreItem iC = iter.next(); iC.addChangeListener(changeListener); } // ok, display them display(res); } else { // ok, nothing to display - clear the graph display(new ArrayList<IStoreItem>()); } } private void clearChangeListeners() { if (curList.size() > 0) { Iterator<IStoreItem> iter = curList.iterator(); while (iter.hasNext()) { IStoreItem iC = iter.next(); iC.removeChangeListener(changeListener); } // and forget about them all curList.clear(); } } public List<IStoreItem> getData() { return curList; } /** * determine if this set of collections are suitable for displaying * * @param res * @param aTests2 * @return */ abstract protected boolean appliesToMe(List<IStoreItem> res, CollectionComplianceTests aTests2); /** * show this set of collections * * @param res */ abstract public void display(List<IStoreItem> res); protected void fillLocalPullDown(IMenuManager manager) { manager.add(newView); manager.add(copyToClipboard); manager.add(followSelection); manager.add(new Separator()); } protected void fillLocalToolBar(IToolBarManager manager) { manager.add(copyToClipboard); manager.add(followSelection); } protected void copyToClipboard() { Display display = Display.getCurrent(); Clipboard clipboard = new Clipboard(display); String output = getTextForClipboard(); clipboard.setContents(new Object[] { output }, new Transfer[] { TextTransfer.getInstance() }); clipboard.dispose(); } protected void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } protected void setupListener() { // register as selection listener selListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { // are we following the selection? if (followSelection.isChecked()) { newSelection(selection); } } }; getSite().getWorkbenchWindow().getSelectionService() .addSelectionListener(selListener); } public void dispose() { // stop listening for data changes clearChangeListeners(); // and stop listening for selection changes getSite().getWorkbenchWindow().getSelectionService() .removeSelectionListener(selListener); super.dispose(); } abstract protected String getTextForClipboard(); protected void makeActions() { newView = new Action() { public void run() { createNewView(); } }; newView.setText("New instance of " + _myTitle); newView.setToolTipText("Create a fresh instance of this view"); newView.setImageDescriptor(Activator .getImageDescriptor("icons/newView.png")); copyToClipboard = new Action() { public void run() { copyToClipboard(); } }; copyToClipboard.setText("Copy to clipboard"); copyToClipboard.setToolTipText("Copy analysis to clipboard"); copyToClipboard.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); followSelection = new Action("Follow selection", SWT.TOGGLE) { public void run() { // don't worry, we can ignore the events } }; followSelection.setChecked(true); followSelection.setToolTipText("Link with selection"); followSelection.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages().getImageDescriptor(ISharedImages.IMG_ELCL_SYNCED)); } protected void createNewView() { // create a new instance of the specified view IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); try { String millis = "" + System.currentTimeMillis(); page.showView(_myId, millis, IWorkbenchPage.VIEW_ACTIVATE); } catch (PartInitException e) { e.printStackTrace(); } } protected void fillContextMenu(IMenuManager manager) { manager.add(copyToClipboard); // Other plug-ins can contribute there actions here manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } }
// @@@ msg combining AND lrmc at the same time is not supported // @@@ TODO? LRMC echt een ring maken, zodat je weet dat de mcast klaar is -> // handig als een node om updates/object vraagt package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReadMessage; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.WriteMessage; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Communication; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.util.DeepCopy; import ibis.util.Timer; import ibis.util.TypedProperties; import ibis.util.messagecombining.MessageCombiner; import ibis.util.messagecombining.MessageSplitter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import mcast.object.ObjectMulticaster; import mcast.object.SendDoneUpcaller; class OmcInfo implements Config { static final class DataObject { Timer timer; long size; } HashMap<Integer, DataObject> map = new HashMap<Integer, DataObject>(); Timer total = Timer.createTimer(); Satin s; public OmcInfo(Satin s) { this.s = s; } synchronized void registerSend(int id, long size) { DataObject d = new DataObject(); d.timer = Timer.createTimer(); d.size = size; map.put(id, d); d.timer.start(); } public synchronized void sendDone(int id) { DataObject d = map.remove(id); if (d == null) { soBcastLogger.info("SATIN '" + s.ident + "': got upcall for unknow id: " + id); return; } d.timer.stop(); total.add(d.timer); soBcastLogger.info("SATIN '" + s.ident + "': broadcast " + id + " took " + d.timer.totalTime() + " " + ((d.size / d.timer.totalTimeVal()) / 1024 * 1024) + " MB/s"); } void end() { soBcastLogger.info("SATIN '" + s.ident + "': total broadcast time was: " + total.totalTime()); } } final class SOCommunication implements Config, Protocol, SendDoneUpcaller { private static final boolean ASYNC_SO_BCAST = false; private final static int WAIT_FOR_UPDATES_TIME = 60000; public static final boolean DISABLE_SO_BCAST = false; private Satin s; /** the current size of the accumulated so messages */ private long soCurrTotalMessageSize = 0; private long soInvocationsDelayTimer = -1; /** used to broadcast shared object invocations */ private SendPort soSendPort; private PortType soPortType; /** used to do message combining on soSendPort */ private MessageCombiner soMessageCombiner; /** a list of ibis identifiers that we still need to connect to */ private ArrayList<IbisIdentifier> toConnect = new ArrayList<IbisIdentifier>(); private HashMap<IbisIdentifier, ReceivePortIdentifier> ports = new HashMap<IbisIdentifier, ReceivePortIdentifier>(); private ObjectMulticaster omc; private SharedObject sharedObject = null; private boolean receivedNack = false; private OmcInfo omcInfo; protected SOCommunication(Satin s) { this.s = s; } protected void init() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { try { omc = new ObjectMulticaster(s.comm.ibis, true /* efficient multi-cluster */, false, "satinSO", this); omcInfo = new OmcInfo(s); } catch (Exception e) { System.err.println("cannot create OMC: " + e); e.printStackTrace(); System.exit(1); } new SOInvocationReceiver(s, omc).start(); } else { try { soPortType = createSOPortType(); // Create a multicast port to bcast shared object invocations. // Connections are established later. soSendPort = s.comm.ibis.createSendPort(soPortType, "satin so port on " + s.ident); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties props = new TypedProperties(); props.setProperty("ibis.serialization", "ibis"); soMessageCombiner = new MessageCombiner(props, soSendPort); } } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } } private PortType createSOPortType() throws IOException { return new PortType( PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS, PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS, PortType.SERIALIZATION_OBJECT); } /** * Creates SO receive ports for new Satin instances. Do this first, to make * them available as soon as possible. */ protected void handleJoins(IbisIdentifier[] joiners) { if(DISABLE_SO_BCAST) return; // lrmc uses its own ports if (LABEL_ROUTING_MCAST) { for (int i = 0; i < joiners.length; i++) { omc.addIbis(joiners[i]); } // Set the destination for the multicast. // The victimtable does not contain the new joiners yet. IbisIdentifier[] victims; synchronized (s) { victims = s.victims.getIbises(); } HashSet<IbisIdentifier> destinations = new HashSet<IbisIdentifier>(); for (IbisIdentifier id : victims) { destinations.add(id); } for (IbisIdentifier id : joiners) { destinations.add(id); } omc.setDestination(destinations.toArray(new IbisIdentifier[destinations.size()])); return; } for (int i = 0; i < joiners.length; i++) { // create a receive port for this guy try { SOInvocationHandler soInvocationHandler = new SOInvocationHandler(s); ReceivePort rec; rec = s.comm.ibis.createReceivePort(soPortType, "satin so receive port for " + joiners[i], soInvocationHandler, s.ft .getReceivePortConnectHandler(), null); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties s = new TypedProperties(); s.setProperty("ibis.serialization", "ibis"); soInvocationHandler.setMessageSplitter(new MessageSplitter( s, rec)); } rec.enableConnections(); rec.enableMessageUpcalls(); } catch (Exception e) { commLogger.fatal("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } /** Add new connections to the soSendPort */ synchronized (s) { for (int i = 0; i < joiners.length; i++) { toConnect.add(joiners[i]); } } } protected void sendAccumulatedSOInvocations() { if (SO_MAX_INVOCATION_DELAY <= 0) return; long currTime = System.currentTimeMillis(); long elapsed = currTime - soInvocationsDelayTimer; if (soInvocationsDelayTimer > 0 && (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) { try { s.stats.broadcastSOInvocationsTimer.start(); soMessageCombiner.sendAccumulatedMessages(); } catch (IOException e) { System.err.println("SATIN '" + s.ident + "': unable to broadcast shared object invocations " + e); } s.stats.soRealMessageCount++; soCurrTotalMessageSize = 0; soInvocationsDelayTimer = -1; s.stats.broadcastSOInvocationsTimer.stop(); } } protected void broadcastSOInvocation(SOInvocationRecord r) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSOInvocationLRMC(r); } else { if (ASYNC_SO_BCAST) { // We have to make a copy of the object first, the caller might modify it. SOInvocationRecord copy = (SOInvocationRecord) DeepCopy.deepCopy(r); new AsyncBcaster(this, copy).start(); } else { doBroadcastSOInvocation(r); } } } public void sendDone(int id) { if (soLogger.isDebugEnabled()) { soLogger.debug("SATIN '" + s.ident + "': got ACK for send " + id); } omcInfo.sendDone(id); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting so invocation for: " + r.getObjectId()); s.stats.broadcastSOInvocationsTimer.start(); s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); try { int id = omc.send(r); omcInfo.registerSend(id, omc.lastSize()); } catch (Exception e) { soLogger.warn("SOI mcast failed: " + e + " msg: " + e.getMessage()); } s.stats.soInvocations++; s.stats.soRealMessageCount++; s.stats.soInvocationsBytes += omc.lastSize(); s.stats.broadcastSOInvocationsTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; WriteMessage w = null; s.stats.broadcastSOInvocationsTimer.start(); connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); if (soSendPort != null && soSendPort.connectedTo().length > 0) { try { if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining w = soMessageCombiner.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { w = soSendPort.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { if (w != null) { w.finish(e); } System.err .println("SATIN '" + s.ident + "': unable to broadcast a shared object invocation: " + e); } if (SO_MAX_INVOCATION_DELAY > 0) { soCurrTotalMessageSize += byteCount; } else { s.stats.soRealMessageCount++; } } s.stats.soInvocations++; s.stats.soInvocationsBytes += byteCount; s.stats.broadcastSOInvocationsTimer.stop(); // Try to send immediately if needed. // We might not reach a safe point for a considerable time. if (SO_MAX_INVOCATION_DELAY > 0) { sendAccumulatedSOInvocations(); } } /** * This basicaly is optional, if nodes don't have the object, they will * retrieve it. However, one broadcast is more efficient (serialization is * done only once). We MUST use message combining here, we use the same receiveport * as the SO invocation messages. This is only called by exportObject. */ protected void broadcastSharedObject(SharedObject object) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSharedObjectLRMC(object); } else { doBroadcastSharedObject(object); } } protected void doBroadcastSharedObject(SharedObject object) { WriteMessage w = null; long size = 0; s.stats.soBroadcastTransferTimer.start(); connectSendPortToNewReceivers(); if (soSendPort == null) { s.stats.soBroadcastTransferTimer.stop(); return; } IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp); try { if (SO_MAX_INVOCATION_DELAY > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } w.writeByte(SO_TRANSFER); s.stats.soBroadcastSerializationTimer.start(); w.writeObject(object); s.stats.soBroadcastSerializationTimer.stop(); size = w.finish(); w = null; if (SO_MAX_INVOCATION_DELAY > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { if (w != null) { w.finish(e); } System.err.println("SATIN '" + s.ident + "': unable to broadcast a shared object: " + e); } s.stats.soBcasts++; s.stats.soBcastBytes += size; s.stats.soBroadcastTransferTimer.stop(); } /** Broadcast an so invocation */ protected void doBroadcastSharedObjectLRMC(SharedObject object) { IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } soLogger.debug("SATIN '" + s.ident + "': broadcasting object: " + object.getObjectId()); s.stats.soBroadcastTransferTimer.start(); s.so.registerMulticast(object, tmp); try { s.stats.soBroadcastSerializationTimer.start(); int id = omc.send(object); omcInfo.registerSend(id, omc.lastSize()); s.stats.soBroadcastSerializationTimer.stop(); } catch (Exception e) { System.err.println("WARNING, SO mcast failed: " + e + " msg: " + e.getMessage()); e.printStackTrace(); } s.stats.soBcasts++; s.stats.soBcastBytes += omc.lastSize(); s.stats.soBroadcastTransferTimer.stop(); } /** Remove a connection to the soSendPort */ protected void removeSOConnection(IbisIdentifier id) { Satin.assertLocked(s); ReceivePortIdentifier r = ports.remove(id); if (r != null) { Communication.disconnect(soSendPort, r); } } /** Fetch a shared object from another node. * If the Invocation record is null, any version is OK, we just test that we have a * version of the object. If it is not null, we try to satisfy the guard of the * invocation record. It might not be satisfied when this method returns, the * guard might depend on more than one shared object. */ protected void fetchObject(String objectId, IbisIdentifier source, InvocationRecord r) throws SOReferenceSourceCrashedException { if(s.so.waitForObject(objectId, source, r, WAIT_FOR_UPDATES_TIME)) { return; } soLogger.debug("SATIN '" + s.ident + "': did not receive object in time, demanding it now"); // haven't got it, demand it now. sendSORequest(objectId, source, true); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received demanded object"); return; } soLogger .fatal("SATIN '" + s.ident + "': internal error: did not receive shared object after I demanded it. "); } private void sendSORequest(String objectId, IbisIdentifier source, boolean demand) throws SOReferenceSourceCrashedException { // request the shared object from the source WriteMessage w = null; try { s.lb.setCurrentVictim(source); Victim v; synchronized (s) { v = s.victims.getVictim(source); } if (v == null) { // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request"); throw new SOReferenceSourceCrashedException(); } w = v.newMessage(); if (demand) { w.writeByte(SO_DEMAND); } else { w.writeByte(SO_REQUEST); } w.writeString(objectId); v.finish(w); } catch (IOException e) { if (w != null) { w.finish(e); } // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request", e); throw new SOReferenceSourceCrashedException(); } } private boolean waitForSOReply() throws SOReferenceSourceCrashedException { // wait for the reply // there are three possibilities: // 1. we get the object back -> return true // 2. we get a nack back -> return false // 3. the source crashed -> exception while (true) { synchronized (s) { if (sharedObject != null) { s.so.addObject(sharedObject); sharedObject = null; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object"); return true; } if (s.currentVictimCrashed) { s.currentVictimCrashed = false; // the source has crashed, abort the job soLogger.info("SATIN '" + s.ident + "': source crashed while waiting for SO reply"); throw new SOReferenceSourceCrashedException(); } if (receivedNack) { receivedNack = false; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object NACK"); return false; } try { s.wait(); } catch (Exception e) { // ignore } } } } boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) { if (System.currentTimeMillis() - info.lastBroadcastTime > WAIT_FOR_UPDATES_TIME) { return false; } for (int i = 0; i < info.destinations.length; i++) { if (info.destinations[i].equals(dest)) return true; } return false; } protected void handleSORequests() { WriteMessage wm = null; IbisIdentifier origin; String objid; boolean demand; while (true) { Victim v; synchronized (s) { if (s.so.SORequestList.getCount() == 0) { s.so.gotSORequests = false; return; } origin = s.so.SORequestList.getRequester(0); objid = s.so.SORequestList.getobjID(0); demand = s.so.SORequestList.isDemand(0); s.so.SORequestList.removeIndex(0); v = s.victims.getVictim(origin); } if (v == null) { soLogger.debug("SATIN '" + s.ident + "': vicim crached in handleSORequest"); continue; // node might have crashed } SharedObjectInfo info = s.so.getSOInfo(objid); if (ASSERTS && info == null) { soLogger.fatal("SATIN '" + s.ident + "': EEEK, requested shared object: " + objid + " not found! Exiting.."); System.exit(1); // Failed assertion } if (!demand && broadcastInProgress(info, v.getIdent())) { soLogger.debug("SATIN '" + s.ident + "': send NACK back in handleSORequest"); // send NACK back try { wm = v.newMessage(); wm.writeByte(SO_NACK); v.finish(wm); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object NACK", e); } continue; } soLogger.debug("SATIN '" + s.ident + "': send object back in handleSORequest"); sendObjectBack(v, info); } } private void sendObjectBack(Victim v, SharedObjectInfo info) { WriteMessage wm = null; long size; // No need to hold the lock while writing the object. // Updates cannot change the state of the object during the send, // they are delayed until safe a point. s.stats.soTransferTimer.start(); SharedObject so = info.sharedObject; try { wm = v.newMessage(); wm.writeByte(SO_TRANSFER); } catch (IOException e) { s.stats.soTransferTimer.stop(); if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soSerializationTimer.start(); try { wm.writeObject(so); } catch (IOException e) { s.stats.soSerializationTimer.stop(); s.stats.soTransferTimer.stop(); wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soSerializationTimer.stop(); try { size = v.finish(wm); } catch (IOException e) { s.stats.soTransferTimer.stop(); wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soTransfers++; s.stats.soTransfersBytes += size; s.stats.soTransferTimer.stop(); } protected void handleSORequest(ReadMessage m, boolean demand) { String objid = null; IbisIdentifier origin = m.origin().ibisIdentifier(); soLogger.info("SATIN '" + s.ident + "': got so request"); try { objid = m.readString(); // no need to finish the message. We don't do any communication } catch (IOException e) { soLogger.warn("SATIN '" + s.ident + "': got exception while reading" + " shared object request: " + e.getMessage()); } synchronized (s) { s.so.addToSORequestList(origin, objid, demand); } } /** * Receive a shared object from another node (called by the MessageHandler */ protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject) SharedObject obj = null; s.stats.soDeserializationTimer.start(); try { obj = (SharedObject) m.readObject(); } catch (IOException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } catch (ClassNotFoundException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } s.stats.soDeserializationTimer.stop(); // no need to finish the read message here. // We don't block and don't do any communication synchronized (s) { sharedObject = obj; s.notifyAll(); } } protected void handleSONack(ReadMessage m) { synchronized (s) { receivedNack = true; s.notifyAll(); } } private void connectSOSendPort(IbisIdentifier ident) { ReceivePortIdentifier r = Communication.connect(soSendPort, ident, "satin so receiveport for " + s.ident, Satin.CONNECT_TIMEOUT); if (r != null) { synchronized (s) { ports.put(ident, r); } } else { soLogger.warn("SATIN '" + s.ident + "': unable to connect to SO receive port "); // We won't broadcast the object to this receiver. // This is not really a problem, it will get the object if it // needs it. But the node has probably crashed anyway. return; } } private void connectSendPortToNewReceivers() { IbisIdentifier[] tmp; synchronized (s) { tmp = new IbisIdentifier[toConnect.size()]; for (int i = 0; i < toConnect.size(); i++) { tmp[i] = toConnect.get(i); } toConnect.clear(); } // do not keep the lock during connection setup for (int i = 0; i < tmp.length; i++) { connectSOSendPort(tmp[i]); } } public void handleMyOwnJoin() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.addIbis(s.ident); } } public void handleCrash(IbisIdentifier id) { if (LABEL_ROUTING_MCAST) { omc.removeIbis(id); omc.setDestination(s.victims.getIbises()); } } protected void exit() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { omc.done(); omcInfo.end(); } } static class AsyncBcaster extends Thread { private SOCommunication c; private SOInvocationRecord r; AsyncBcaster(SOCommunication c, SOInvocationRecord r) { this.c = c; this.r = r; } public void run() { c.doBroadcastSOInvocation(r); } } }
package io.warp10.hadoop; import io.warp10.continuum.Configuration; import io.warp10.crypto.OrderPreservingBase64; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.util.Progressable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Warp10RecordReader extends RecordReader<Text, BytesWritable> implements Progressable { private BufferedReader br = null; private HttpURLConnection conn = null; private Text key; private BytesWritable value; private long count = 0; private static final Logger LOG = LoggerFactory.getLogger(Warp10RecordReader.class); private Progressable progress = null; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { if (!(split instanceof Warp10InputSplit)) { throw new IOException("Invalid split type."); } this.progress = context; // Retrieve now and timespan parameters long now = Long.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_FETCH_NOW)); long timespan = Long.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_FETCH_TIMESPAN)); int connectTimeout = Integer.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_HTTP_CONNECT_TIMEOUT, Warp10InputFormat.DEFAULT_WARP10_HTTP_CONNECT_TIMEOUT)); int readTimeout = Integer.valueOf(context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_HTTP_READ_TIMEOUT, Warp10InputFormat.DEFAULT_WARP10_HTTP_READ_TIMEOUT)); // Call each provided fetcher until one answers String protocol = context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_FETCHER_PROTOCOL, Warp10InputFormat.DEFAULT_WARP10_FETCHER_PROTOCOL); String port = context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_FETCHER_PORT, Warp10InputFormat.DEFAULT_WARP10_FETCHER_PORT); String path = context.getConfiguration().get(Warp10InputFormat.PROPERTY_WARP10_FETCHER_PATH, Warp10InputFormat.DEFAULT_WARP10_FETCHER_PATH); // FIXME: use Constants instead ?? but warp.timeunits is mandatory and property file must be provided.. String nowHeader = context.getConfiguration().get(Configuration.HTTP_HEADER_NOW_HEADERX, Warp10InputFormat.HTTP_HEADER_NOW_HEADER_DEFAULT); String timespanHeader = context.getConfiguration().get(Configuration.HTTP_HEADER_TIMESPAN_HEADERX, Warp10InputFormat.HTTP_HEADER_TIMESPAN_HEADER_DEFAULT); for (String fetcher: split.getLocations()) { try { String hostUrl = protocol + "://" + fetcher + ":" + port; URL url = new URL(hostUrl + path); LOG.info("Fetcher: " + hostUrl); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); conn.setChunkedStreamingMode(16384); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty(nowHeader, Long.toString(now)); conn.setRequestProperty(timespanHeader, Long.toString(timespan)); conn.setRequestProperty("Content-Type", "application/gzip"); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(((Warp10InputSplit)split).getBytes()); if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { System.err.println(url + " failed - error code: " + conn.getResponseCode()); InputStream is = conn.getErrorStream(); BufferedReader errorReader = new BufferedReader(new InputStreamReader(is)); String line = errorReader.readLine(); while (null != line) { System.err.println(line); line = errorReader.readLine(); } is.close(); continue; } this.br = new BufferedReader(new InputStreamReader(conn.getInputStream())); break; } catch (Exception e) { e.printStackTrace(); LOG.error(e.getMessage(),e); } finally { if (null == this.br && null != conn) { try { conn.disconnect(); } catch (Exception e) {} conn = null; } } } } @Override public boolean nextKeyValue() throws IOException { if (null == br) { return false; } String line = br.readLine(); if (null == line) { return false; } // Format: GTSWrapperId <WSP> HASH <WSP> GTSWrapper String[] tokens = line.split("\\s+"); if (null == key) { key = new Text(); } key.set(tokens[0]); if (null == value) { value = new BytesWritable(); } byte[] wrapper = OrderPreservingBase64.decode(tokens[2].getBytes("US-ASCII")); value.setCapacity(wrapper.length); value.set(wrapper, 0, wrapper.length); count++; return true; } @Override public void close() throws IOException { if (null != this.br) { this.br.close(); } if (null != this.conn) { this.conn.disconnect(); } } @Override public Text getCurrentKey() { return key; } @Override public BytesWritable getCurrentValue() { return value; } @Override public float getProgress() throws IOException { return -1.0F; } @Override public void progress() { if (null != this.progress) { this.progress.progress(); } } }
package org.voovan.tools.json; import org.voovan.tools.FastThreadLocal; import org.voovan.tools.TProperties; import org.voovan.tools.TString; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import java.lang.reflect.Type; import java.text.ParseException; import java.util.function.Supplier; public class JSON { public final static String JSON_CONVERT_ESCAPE_CHAR = TProperties.getString("framework", "JSONConvertEscapeChar", "true"); /** * EscapeChar , true, false */ private static FastThreadLocal<Boolean> convertEscapeChar = FastThreadLocal.withInitial(new Supplier<Boolean>() { @Override public Boolean get() { boolean isEscapeChare = true; if("true".equalsIgnoreCase(JSON_CONVERT_ESCAPE_CHAR.trim())) { isEscapeChare = true; } if("false".equalsIgnoreCase(JSON_CONVERT_ESCAPE_CHAR.trim())) { isEscapeChare = false; } else { isEscapeChare = false; } return isEscapeChare; } }); /** * EscapeChar * @return true: , false: */ public static boolean isConvertEscapeChar() { return convertEscapeChar.get(); } /** * EscapeChar * @param convertEscapeChar true: , false: */ public static void setConvertEscapeChar(boolean convertEscapeChar) { JSON.convertEscapeChar.set(convertEscapeChar); } /** * Java JSON * @param object * @return JSON */ public static String toJSON(Object object){ return toJSON(object, convertEscapeChar.get(), false); } /** * Java JSON * @param object * @param allField * @return JSON */ public static String toJSON(Object object, boolean allField){ return toJSON(object, convertEscapeChar.get(), allField); } /** * Java JSON * @param object * @param convertEscapeChar * @param allField * @return JSON */ public static String toJSON(Object object, boolean convertEscapeChar, boolean allField){ String jsonString = null; try { // convertEscapeChar boolean oldConvertEscapeChar = isConvertEscapeChar(); // convertEscapeChar setConvertEscapeChar(convertEscapeChar); if(allField) { jsonString = JSONEncode.fromObject(TReflect.getMapfromObject(object, allField), allField); } else { jsonString = JSONEncode.fromObject(object, false); } if(jsonString.startsWith("\"") && jsonString.endsWith("\"")){ jsonString = TString.removeSuffix(jsonString); jsonString = TString.removePrefix(jsonString); } // convertEscapeChar setConvertEscapeChar(oldConvertEscapeChar); } catch (ReflectiveOperationException e) { Logger.error("Reflective Operation failed",e); } return jsonString; } /** * JSON Java * @param <T> * @param jsonStr JSON * @param type java * @param ignoreCase * @return Java */ public static <T> T toObject(String jsonStr, Type type, boolean ignoreCase){ T valueObject = null; try { valueObject = JSONDecode.fromJSON(jsonStr, type, ignoreCase); } catch (ReflectiveOperationException | ParseException e) { Logger.error("Reflective Operation failed",e); } return valueObject; } /** * JSON Java , * @param <T> * @param jsonStr JSON * @param type java * @return Java */ public static <T> T toObject(String jsonStr,Type type){ return toObject(jsonStr, type , false); } /** * JSON * {} HashMap,[] ArrayList * @param jsonStr JSON * @return */ public static Object parse(String jsonStr){ Object parseObject = null; parseObject = JSONDecode.parse(jsonStr); return parseObject; } /** * JSON * @param jsonStr JSON * @return JSON */ public static String formatJson(String jsonStr) { if (TString.isNullOrEmpty(jsonStr)){ return ""; } StringBuilder jsongStrBuild = new StringBuilder(); char prevChar = '\0'; char current = '\0'; int indent = 0; boolean inStr = false; for (int i = 0; i < jsonStr.length(); i++) { prevChar = current; current = jsonStr.charAt(i); if(current == '\"' && prevChar!='\\'){ inStr = !inStr; } if(inStr){ jsongStrBuild.append(current); continue; } if(current=='[' || current=='{'){ jsongStrBuild.append(current); jsongStrBuild.append('\n'); indent++; addIndentByNum(jsongStrBuild, indent); continue; } if(current==']' || current=='}'){ jsongStrBuild.append('\n'); indent addIndentByNum(jsongStrBuild, indent); jsongStrBuild.append(current); continue; } if(current==','){ jsongStrBuild.append(current); jsongStrBuild.append('\n'); addIndentByNum(jsongStrBuild, indent); continue; } if(current==':'){ jsongStrBuild.append(current); jsongStrBuild.append(' '); continue; } jsongStrBuild.append(current); } return jsongStrBuild.toString(); } /** * * @param str * @param indent */ private static void addIndentByNum(StringBuilder str, int indent) { for (int i = 0; i < indent; i++) { str.append('\t'); } } /** * jsonnull * @param jsonStr json * @return null */ public static String removeNullNode(String jsonStr){ jsonStr = TString.fastReplaceAll(jsonStr, "\\\"\\w+?\\\":null", ""); jsonStr = TString.fastReplaceAll(jsonStr, "null", ""); return fixJSON(jsonStr); } /** * JSON "," * @param jsonStr json * @return */ protected static String fixJSON(String jsonStr){ while(TString.regexMatch(jsonStr,",[\\s\\r\\n]*,") > 0) { jsonStr = TString.fastReplaceAll(jsonStr, ",[\\s\\r\\n]*,", ","); } jsonStr = TString.fastReplaceAll(jsonStr, "(?:[\\{])[\\s\\r\\n]*,","{"); jsonStr = TString.fastReplaceAll(jsonStr, "(?:[\\[])[\\s\\r\\n]*,","["); jsonStr = TString.fastReplaceAll(jsonStr, ",[\\s\\r\\n]*(?:[\\}])","}"); jsonStr = TString.fastReplaceAll(jsonStr, ",[\\s\\r\\n]*(?:[\\]])","]"); return jsonStr; } /** * JSON map * @param jsonStr * @return true: , false: */ public static boolean isJSONMap(String jsonStr){ return TString.regexMatch(jsonStr, "^\\s*\\{[\\s\\S]*\\}\\s*$") > 0; } /** * JSON list/array * @param jsonStr * @return true: , false: */ public static boolean isJSONList(String jsonStr){ return TString.regexMatch(jsonStr, "^\\s*\\[[\\s\\S]*\\]\\s*$") > 0; } /** * JSON * @param jsonStr * @return true: , false: */ public static boolean isJSON(String jsonStr){ return isJSONMap(jsonStr) || isJSONList(jsonStr); } }
package ibis.smartsockets.virtual; import ibis.smartsockets.direct.IPAddressSet; import java.io.IOException; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.channels.ServerSocketChannel; import java.util.LinkedList; import java.util.ListIterator; import java.util.Map; public class VirtualServerSocket { private final VirtualSocketFactory parent; private int port; private final LinkedList<VirtualSocket> incoming = new LinkedList<VirtualSocket>(); private int backlog; private final int defaultTimeout; private int timeout = 0; private boolean reuseAddress = true; private boolean closed = false; private VirtualSocketAddress localAddress; private Map<String, Object> properties; private boolean bound; private int receiveBufferSize = -1; // Create unbound port protected VirtualServerSocket(VirtualSocketFactory parent, int defaultTimeout, Map<String, Object> p) { this.parent = parent; this.properties = p; this.bound = false; this.defaultTimeout = defaultTimeout; } // Create bound port protected VirtualServerSocket(VirtualSocketFactory parent, VirtualSocketAddress address, int port, int backlog, int defaultTimeout, Map<String, Object> p) { this.parent = parent; this.port = port; this.backlog = backlog; this.localAddress = address; this.properties = p; this.bound = true; this.defaultTimeout = defaultTimeout; } public synchronized int incomingConnection(VirtualSocket s) { if (closed) { return -1; } if (incoming.size() < backlog) { incoming.addLast(s); notifyAll(); return 0; } // Try so remove all closed sockets from the queue ... ListIterator<VirtualSocket> itt = incoming.listIterator(); while (itt.hasNext()) { VirtualSocket v = itt.next(); if (v.isClosed()) { itt.remove(); } } // See if there is room now... if (incoming.size() < backlog) { incoming.addLast(s); notifyAll(); return 0; } // If not, print an error..... if (VirtualSocketFactory.conlogger.isInfoEnabled()) { VirtualSocketFactory.conlogger.info("Incoming connection on port " + port + " refused: QUEUE FULL (" + incoming.size() + ", " + System.currentTimeMillis() + ")"); } return 1; } private synchronized VirtualSocket getConnection() throws SocketTimeoutException { while (incoming.size() == 0 && !closed) { try { wait(timeout); } catch (Exception e) { // ignore } // Check if our wait time has expired. if (timeout > 0 && incoming.size() == 0 && !closed) { throw new SocketTimeoutException("Time out during accept"); } } if (incoming.size() > 0) { return incoming.removeFirst(); } else { return null; } } public VirtualSocket accept() throws IOException { VirtualSocket result = null; while (result == null) { result = getConnection(); if (result == null) { // Can only happen if socket has been closed throw new IOException("Socket closed during accept"); } else if (result.isClosed()) { // Check is the other side is already closed... result = null; } else { // See if the other side is still willing to connect ... try { int t = timeout; if (timeout <= 0) { t = defaultTimeout; } result.connectionAccepted(t); } catch (IOException e) { VirtualSocketFactory.logger.info("VirtualServerPort( " + port + ") got exception during accept!", e); result = null; } } } result.setTcpNoDelay(true); return result; } public synchronized void close() throws IOException { closed = true; notifyAll(); // wakes up any waiting accept while (incoming.size() != 0) { incoming.removeFirst().connectionRejected(1000); } parent.closed(port); } public int getPort() { return port; } public boolean isClosed() { return closed; } public ServerSocketChannel getChannel() { throw new RuntimeException("operation not implemented by " + this); } public IPAddressSet getIbisInetAddress() { throw new RuntimeException("operation not implemented by " + this); } public VirtualSocketAddress getLocalSocketAddress() { return localAddress; } public int getSoTimeout() throws IOException { return timeout; } public void setSoTimeout(int t) throws SocketException { timeout = t; } public boolean getReuseAddress() throws SocketException { return reuseAddress; } public void setReuseAddress(boolean v) throws SocketException { reuseAddress = v; } public String toString() { if (localAddress == null) { return "VirtualServerSocket(UNBOUND)"; } return "VirtualServerSocket(" + localAddress.toString() + ")"; } public Map properties() { return properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } public Object getProperty(String key) { return properties.get(key); } public void setProperty(String key, Object val) { properties.put(key, val); } public boolean isBound() { return bound; } public void setReceiveBufferSize(int size) { // TODO: Find a way to this in the bind operation ? receiveBufferSize = size; } public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { // not implemented } public int getReceiveBufferSize() { return receiveBufferSize; } public int getLocalPort() { return port; } public InetAddress getInetAddress() { // TODO Auto-generated method stub return null; } public void bind(SocketAddress endpoint, int backlog) throws IOException { if (endpoint instanceof VirtualSocketAddress) { int tmp = ((VirtualSocketAddress) endpoint).port(); parent.bindServerSocket(this, tmp); this.port = tmp; this.localAddress = ((VirtualSocketAddress) endpoint); } else { throw new IOException("Unsupported address type"); } } }
package main; import java.io.File; import java.io.PrintWriter; import peer.Peer; /** * Executes all functions at ShutDown */ public class ShutdownHook implements Runnable { private File peerConfig; public void run() { Thread.currentThread().setName("ShutdownHook"); //Save peers.dat try { peerConfig = new File(Utils.defineConfigDir() + "/" + "peers.dat"); if(!peerConfig.exists()) { peerConfig.createNewFile(); } else { PrintWriter writer = new PrintWriter(peerConfig, "UTF-8"); for(Peer peer : Core.peerList) { String peerAddr = peer.ps.getRemoteSocketAddress().toString(); //peerAddr = peerAddr.substring(1, peerAddr.length() - 6); int slashDex = peerAddr.indexOf("/"); peerAddr = peerAddr.substring(0, slashDex); System.out.println("Writing peerAddr: " + peerAddr); writer.println(peerAddr); } writer.close(); } } catch (Exception e) { e.printStackTrace(); } //Save downloadList } }
package jade.core.messaging; //#J2ME_EXCLUDE_FILE import java.io.IOException; import java.util.Date; import jade.core.AID; import jade.core.Profile; import jade.domain.FIPAAgentManagement.InternalError; import jade.util.leap.List; import jade.util.leap.LinkedList; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.Iterator; /** * This class supports the ACL persistent delivery service, managing * actual ACL messages storage, scheduled message delivery and other * utility tasks related to the service. * * @author Giovanni Rimassa - FRAMeTech s.r.l. * @author Nicolas Lhuillier - Motorola * */ class PersistentDeliveryManager { public static synchronized PersistentDeliveryManager instance(Profile p, MessageManager.Channel ch) { if(theInstance == null) { theInstance = new PersistentDeliveryManager(); theInstance.initialize(p, ch); } return theInstance; } // How often to check for expired deliveries private static final long DEFAULT_SENDFAILUREPERIOD = 60*1000; // One minute // Default storage class private static final String DEFAULT_STORAGE = "jade.core.messaging.PersistentDeliveryManager$DummyStorage"; private static class DeliveryItem { public DeliveryItem(GenericMessage msg, AID id, MessageManager.Channel ch, String sid) { toDeliver = msg; receiver = id; channel = ch; storeName = sid; } public GenericMessage getMessage() { return toDeliver; } public AID getReceiver() { return receiver; } public MessageManager.Channel getChannel() { return channel; } public String getStoreName() { return storeName; } private GenericMessage toDeliver; private AID receiver; private MessageManager.Channel channel; private String storeName; } // End of DeliveryItem class private class ExpirationChecker implements Runnable { public ExpirationChecker(long t) { period = t; myThread = new Thread(this, "Persistent Delivery Service -- Expiration Checker Thread"); } public void run() { while(active) { try { Thread.sleep(period); synchronized(pendingMessages) { // Try to send all stored messages... // If the receiver still not exists and the due date has elapsed // the sender will get back a FAILURE Object[] keys = pendingMessages.keySet().toArray(); for(int i = 0; i < keys.length; i++) { flushMessages((AID) keys[i]); } } } catch (InterruptedException ie) { // Just do nothing } } } public void start() { active = true; myThread.start(); } public void stop() { active = false; myThread.interrupt(); } private boolean active = false; private long period; private Thread myThread; } // End of ExpirationChecker class public static class DummyStorage implements MessageStorage { public void init(Profile p) { // Do nothing } public String store(GenericMessage msg, AID receiver) throws IOException { // Do nothing return null; } public void delete(String storeName, AID receiver) throws IOException { // Do nothing } public void loadAll(LoadListener il) throws IOException { // Do nothing } } // End of DummyStorage class public void initialize(Profile p, MessageManager.Channel ch) { users = 0; myMessageManager = MessageManager.instance(p); deliveryChannel = ch; try { // Choose the persistent storage method String storageClass = p.getParameter(Profile.PERSISTENT_DELIVERY_STORAGEMETHOD,DEFAULT_STORAGE); storage = (MessageStorage)Class.forName(storageClass).newInstance(); storage.init(p); // Load all data persisted from previous sessions storage.loadAll(new MessageStorage.LoadListener() { public void loadStarted(String storeName) { System.out.println("--> Load BEGIN <--"); } public void itemLoaded(String storeName, GenericMessage msg, AID receiver) { // Put the item into the pending messages table synchronized(pendingMessages) { List msgs = (List)pendingMessages.get(receiver); if(msgs == null) { msgs = new LinkedList(); pendingMessages.put(receiver, msgs); } DeliveryItem item = new DeliveryItem(msg, receiver, deliveryChannel, storeName); msgs.add(item); } System.out.println("Message for <" + receiver.getLocalName() + ">"); } public void loadEnded(String storeName) { System.out.println("--> Load END <--"); } }); } catch(IOException ioe) { ioe.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } sendFailurePeriod = DEFAULT_SENDFAILUREPERIOD; String s = p.getParameter(Profile.PERSISTENT_DELIVERY_SENDFAILUREPERIOD, null); if(s != null) { try { sendFailurePeriod = Long.parseLong(s); } catch(NumberFormatException nfe) { // Do nothing: the default value will be used... } } } public void storeMessage(String storeName, GenericMessage msg, AID receiver) throws IOException { // Store the ACL message and its receiver for later re-delivery... synchronized(pendingMessages) { List msgs = (List)pendingMessages.get(receiver); if(msgs == null) { msgs = new LinkedList(); pendingMessages.put(receiver, msgs); } String tmpName = storage.store(msg, receiver); msgs.add(new DeliveryItem(msg, receiver, deliveryChannel, tmpName)); } } public int flushMessages(AID receiver) { // Send messages for this agent, if any... int cnt = 0; List l = null; synchronized(pendingMessages) { l = (List)pendingMessages.remove(receiver); } if(l != null) { Iterator it = l.iterator(); while(it.hasNext()) { DeliveryItem item = (DeliveryItem)it.next(); retry(item); cnt++; } } return cnt; } public synchronized void start() { if(users == 0) { failureSender = new ExpirationChecker(sendFailurePeriod); failureSender.start(); } users++; } public synchronized void stop() { users if(users == 0) { failureSender.stop(); } } // A shared instance to have a single thread pool private static PersistentDeliveryManager theInstance; // FIXME: Maybe a table, indexed by a profile subset, would be better? private PersistentDeliveryManager() { } private void retry(DeliveryItem item) { // Remove the message from the storage try { storage.delete(item.getStoreName(), item.getReceiver()); } catch(IOException ioe) { ioe.printStackTrace(); } // Deliver it myMessageManager.deliver(item.getMessage(), item.getReceiver(), item.getChannel()); } // The component managing asynchronous message delivery and retries private MessageManager myMessageManager; // The actual channel over which messages will be sent private MessageManager.Channel deliveryChannel; // How often pending messages due date will be checked (the // message will be sent out if expired) private long sendFailurePeriod; // How many containers are sharing this active component private long users; // The table of undelivered messages to send private Map pendingMessages = new HashMap(); // The active object that periodically checks the due date of ACL // messages and sends them after it expired private ExpirationChecker failureSender; // The component performing the actual storage and retrieval from // a persistent support private MessageStorage storage; }
package org.xins.common.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Stack; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xins.common.Log; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.ProtectedPropertyReader; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.ParseException; import org.xins.common.text.TextUtils; public class ElementParser extends Object { // Class fields /** * Fully-qualified name of this class. This field is not <code>null</code>. */ private static final String CLASSNAME = ElementParser.class.getName(); /** * Fully-qualified name of the inner class <code>Handler</code>. This field * is not <code>null</code>. */ private static final String HANDLER_CLASSNAME = ElementParser.Handler.class.getName(); /** * The key for the <code>ProtectedPropertyReader</code> instances created * by this class. */ private static final Object PROTECTION_KEY = new Object(); /** * Error state for the SAX event handler. */ private static final State ERROR = new State("ERROR"); /** * State for the SAX event handler in the data section (at any depth within * the <code>data</code> element). */ private static final State PARSING = new State("PARSING"); /** * State for the SAX event handler for the final state, when parsing is * finished. */ private static final State FINISHED = new State("FINISHED"); /** * The factory for SAX parsers. This field is never <code>null</code>, it * is initialized by a class initializer. */ private static final SAXParserFactory SAX_PARSER_FACTORY; // Class functions /** * Initializes this class. */ static { SAX_PARSER_FACTORY = SAXParserFactory.newInstance(); SAX_PARSER_FACTORY.setNamespaceAware(true); } // Constructors /** * Constructs a new <code>ElementParser</code>. */ public ElementParser() { // TRACE: Enter constructor Log.log_1000(CLASSNAME, null); // empty // TRACE: Leave constructor Log.log_1002(CLASSNAME, null); } // Fields // Methods public Element parse(byte[] xml) throws IllegalArgumentException, ParseException { final String THIS_METHOD = "parse(byte[])"; // TRACE: Enter method Log.log_1003(CLASSNAME, THIS_METHOD, null); // Check preconditions MandatoryArgumentChecker.check("xml", xml); // Initialize our SAX event handler Handler handler = new Handler(); ByteArrayInputStream bais = null; try { // Construct a SAX parser SAXParser saxParser = SAX_PARSER_FACTORY.newSAXParser(); // Convert the byte array to an input stream bais = new ByteArrayInputStream(xml); // Let SAX parse the XML, using our handler saxParser.parse(bais, handler); } catch (Throwable exception) { // Log: Parsing failed String detail = exception.getMessage(); // XXX: Log.log_2205(exception, detail); // Construct a buffer for the error message FastStringBuffer buffer = new FastStringBuffer(142, "Unable to convert the specified character string to XML"); // Include the exception message in our error message, if any if (detail != null && detail.length() > 0) { buffer.append(": "); buffer.append(detail); } else { buffer.append('.'); } // Throw exception with message, and register cause exception throw new ParseException(buffer.toString(), exception, detail); // Always dispose the ByteArrayInputStream } finally { if (bais != null) { try { bais.close(); } catch (IOException ioException) { Log.log_1051(ioException, CLASSNAME, THIS_METHOD, bais.getClass().getName(), "close()", null); // ignore } } } // TRACE: Leave method Log.log_1005(CLASSNAME, THIS_METHOD, null); return handler.getElement(); } // Inner classes /** * SAX event handler that will parse the result from a call to a XINS * service. * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>) * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.1.0 */ private class Handler extends DefaultHandler { // Constructors /** * Constructs a new <code>Handler</code> instance. */ private Handler() { // TRACE: Enter constructor Log.log_1000(HANDLER_CLASSNAME, null); _state = PARSING; _level = -1; _characters = new FastStringBuffer(45); _dataElementStack = new Stack(); // TRACE: Leave constructor Log.log_1002(HANDLER_CLASSNAME, null); } // Fields /** * The current state. Never <code>null</code>. */ private State _state; /** * The element resulting of the parsing. */ private Element _element; /** * The name of the output parameter that is currently being parsed. */ private String _parameterName; /** * The character content (CDATA or PCDATA) of the element currently * being parsed. */ private final FastStringBuffer _characters; /** * The stack of child elements within the data section. The top element * is always <code>&lt;data/&gt;</code>. */ private Stack _dataElementStack; /** * The level for the element pointer within the XML document. Initially * this field is <code>-1</code>, which indicates the current element * pointer is outside the document. The value <code>0</code> is for the * root element (<code>result</code>), etc. */ private int _level; // Methods public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws IllegalArgumentException, SAXException { final String THIS_METHOD = "startElement(java.lang.String,java.lang.String,java.lang.String,org.xml.sax.Attributes)"; // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; // Make sure namespaceURI is either null or non-empty namespaceURI = "".equals(namespaceURI) ? null : namespaceURI; // Cache quoted version of namespaceURI String quotedNamespaceURI = TextUtils.quote(namespaceURI); // TRACE: Enter method Log.log_1003(HANDLER_CLASSNAME, THIS_METHOD, "_state=" + currentState + "; _level=" + _level + "; namespaceURI=" + quotedNamespaceURI + "; localName=" + TextUtils.quote(localName) + "; qName=" + TextUtils.quote(qName)); // Check preconditions MandatoryArgumentChecker.check("localName", localName, "atts", atts); // Increase the element depth level _level++; if (currentState == ERROR) { String detail = "Unexpected state " + currentState + " (level=" + _level + ')'; throw Utils.logProgrammingError(HANDLER_CLASSNAME, THIS_METHOD, HANDLER_CLASSNAME, THIS_METHOD, detail); } else { // Construct a Element Element element = new Element(namespaceURI, localName); // Add all attributes for (int i = 0; i < atts.getLength(); i++) { String attrNamespaceURI = atts.getURI(i); String attrLocalName = atts.getLocalName(i); String attrValue = atts.getValue(i); element.setAttribute(attrNamespaceURI, attrLocalName, attrValue); } // Push the element on the stack _dataElementStack.push(element); // Reserve buffer for PCDATA _characters.clear(); // Reset the state from ERROR back to PARSING _state = PARSING; } Log.log_1005(HANDLER_CLASSNAME, THIS_METHOD, "_state=" + _state + "; _level=" + _level + "; namespaceURI=" + TextUtils.quote(namespaceURI) + "; localName=" + TextUtils.quote(localName) + "; qName=" + TextUtils.quote(qName)); } public void endElement(String namespaceURI, String localName, String qName) throws IllegalArgumentException { final String THIS_METHOD = "endElement(java.lang.String,java.lang.String,java.lang.String)"; // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; // Make sure namespaceURI is either null or non-empty namespaceURI = "".equals(namespaceURI) ? null : namespaceURI; // Cache quoted version of namespaceURI String quotedNamespaceURI = TextUtils.quote(namespaceURI); // TRACE: Enter method Log.log_1003(HANDLER_CLASSNAME, THIS_METHOD, "_state=" + currentState + "; _level=" + _level + "; namespaceURI=" + TextUtils.quote(namespaceURI) + "; localName=" + TextUtils.quote(localName) + "; qName=" + TextUtils.quote(qName)); // Check preconditions MandatoryArgumentChecker.check("localName", localName); if (currentState == ERROR) { String detail = "Unexpected state " + currentState + " (level=" + _level + ')'; throw Utils.logProgrammingError(HANDLER_CLASSNAME, THIS_METHOD, HANDLER_CLASSNAME, THIS_METHOD, detail); // Within data section } else { // Get the Element for which we process the end tag Element child = (Element) _dataElementStack.pop(); // Set the PCDATA content on the element if (_characters != null && _characters.getLength() > 0) { child.setText(_characters.toString()); } // Add the child to the parent if (_dataElementStack.size() > 0) { Element parent = (Element) _dataElementStack.peek(); parent.addChild(child); // Reset the state back from ERROR to PARSING _state = PARSING; } else { _element = child; _state = FINISHED; } } _level _characters.clear(); // TRACE: Leave method Log.log_1005(HANDLER_CLASSNAME, THIS_METHOD, "_state=" + _state + "; _level=" + _level + "; namespaceURI=" + TextUtils.quote(namespaceURI) + "; localName=" + TextUtils.quote(localName) + "; qName=" + TextUtils.quote(qName)); } /** * Receive notification of character data. * * @param ch * the <code>char</code> array that contains the characters from the * XML document, cannot be <code>null</code>. * * @param start * the start index within <code>ch</code>. * * @param length * the number of characters to take from <code>ch</code>. * * @throws IndexOutOfBoundsException * if characters outside the allowed range are specified. * * @throws SAXException * if the parsing failed. */ public void characters(char[] ch, int start, int length) throws IndexOutOfBoundsException, SAXException { final String THIS_METHOD = "characters(char[],int,int)"; // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; // TRACE: Enter method Log.log_1003(HANDLER_CLASSNAME, THIS_METHOD, null); if (_characters != null) { _characters.append(ch, start, length); } // Reset _state _state = currentState; } /** * Gets the parsed element. * * @return * the element resulting of the parsing of the XML. */ public Element getElement() { final String THIS_METHOD = "getElement()"; // Check state if (_state != FINISHED) { final String DETAIL = "State is " + _state + " instead of " + FINISHED; throw Utils.logProgrammingError(HANDLER_CLASSNAME, THIS_METHOD, HANDLER_CLASSNAME, THIS_METHOD, DETAIL); } return _element; } } /** * State of the event handler. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ private static final class State extends Object { // Constructors private State(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); _name = name; } // Fields /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; // Methods /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ public String getName() { return _name; } /** * Returns a textual representation of this object. * * @return * the name of this state, never <code>null</code>. */ public String toString() { return _name; } } }
package org.renjin.cran.DBI; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.renjin.eval.EvalException; import org.renjin.sexp.DoubleArrayVector; import org.renjin.sexp.IntArrayVector; import org.renjin.sexp.ListVector; import org.renjin.sexp.LogicalArrayVector; import org.renjin.sexp.StringArrayVector; import org.renjin.sexp.StringVector; import org.renjin.sexp.Vector; import org.renjin.sexp.Vector.Builder; public class JDBCUtils { public static boolean hasCompleted(ResultSet rs) { try { return (rs.isClosed() || rs.isAfterLast()); } catch (SQLException e) { return false; } } public static StringVector getTables(Connection con) { try { StringVector.Builder sb = new StringVector.Builder(); DatabaseMetaData dbm = con.getMetaData(); String[] types = { "TABLE" }; ResultSet rsm = dbm.getTables(con.getCatalog(), null, null, types); while (rsm.next()) { sb.add(rsm.getString("TABLE_NAME")); } rsm.close(); return sb.build(); } catch (SQLException e) { throw new EvalException(e); } } public static StringVector getColumns(Connection con, String table) { try { StringVector.Builder sb = new StringVector.Builder(); DatabaseMetaData dbm = con.getMetaData(); ResultSet rsm = dbm.getColumns(con.getCatalog(), null, table, null); while (rsm.next()) { sb.add(rsm.getString("COLUMN_NAME")); } rsm.close(); return sb.build(); } catch (SQLException e) { throw new EvalException(e); } } public static ListVector columnInfo(ResultSet rs) { try { ListVector.Builder tv = new ListVector.Builder(); ResultSetMetaData rsm = rs.getMetaData(); for (int i = 1; i < rsm.getColumnCount() + 1; i++) { ListVector.NamedBuilder cv = new ListVector.NamedBuilder(); cv.add("name", rsm.getColumnName(i)); cv.add("type", rsm.getColumnTypeName(i)); tv.add(cv.build()); } return tv.build(); } catch (SQLException e) { throw new EvalException(e); } } public static enum RTYPE { INTEGER, NUMERIC, CHARACTER, LOGICAL }; public static ListVector fetch(ResultSet rs, long n) { try { if (n < 0) { n = Long.MAX_VALUE; } ListVector ti = columnInfo(rs); /* cache types, we need to look this up for *every* value */ RTYPE[] rtypes = new RTYPE[ti.length()]; /* column builders */ Map<Integer, Builder<Vector>> builders = new HashMap<Integer, Builder<Vector>>(); for (int i = 0; i < ti.length(); i++) { ListVector ci = (ListVector) ti.get(i); String tpe = ci.get("type").asString().toLowerCase(); rtypes[i] = null; if (tpe.endsWith("int") || tpe.equals("wrd") || tpe.startsWith("int")) { // TODO: long values? builders.put(i, new IntArrayVector.Builder()); rtypes[i] = RTYPE.INTEGER; } if (tpe.equals("decimal") || tpe.equals("real") || tpe.startsWith("double") || tpe.startsWith("float")) { builders.put(i, new DoubleArrayVector.Builder()); rtypes[i] = RTYPE.NUMERIC; } if (tpe.equals("boolean")) { builders.put(i, new LogicalArrayVector.Builder()); rtypes[i] = RTYPE.LOGICAL; } if (tpe.equals("clob") || tpe.endsWith("char") || tpe.equals("date") || tpe.equals("time") || tpe.equals("null") || tpe.equals("unknown")) { builders.put(i, new StringArrayVector.Builder()); rtypes[i] = RTYPE.CHARACTER; } if (rtypes[i] == null) { throw new EvalException("Unknown column type " + ci); } } int ival; double nval; boolean lval; String cval; long rows = 0; /* collect values */ while (n > 0 && rs.next()) { rows++; for (int i = 0; i < rtypes.length; i++) { Builder<Vector> bld = builders.get(i); switch (rtypes[i]) { case INTEGER: /* Behold the beauty of JDBC */ ival = rs.getInt(i + 1); if (rs.wasNull()) { bld.addNA(); } else { ((IntArrayVector.Builder) bld).add(ival); } break; case NUMERIC: nval = rs.getDouble(i + 1); if (rs.wasNull()) { bld.addNA(); } else { ((DoubleArrayVector.Builder) bld).add(nval); } break; case LOGICAL: lval = rs.getBoolean(i + 1); if (rs.wasNull()) { bld.addNA(); } else { ((LogicalArrayVector.Builder) bld).add(lval); } break; case CHARACTER: cval = rs.getString(i + 1); if (rs.wasNull()) { bld.addNA(); } else { ((StringArrayVector.Builder) bld).add(cval); } break; } } n } /* call build() on each column and add them as named cols to df */ ListVector.NamedBuilder dfb = new ListVector.NamedBuilder(); for (int i = 0; i < ti.length(); i++) { ListVector ci = (ListVector) ti.get(i); dfb.add(ci.get("name").asString(), builders.get(i).build()); } /* I'm a data.frame object */ IntArrayVector.Builder rnb = new IntArrayVector.Builder(); for (long i = 1; i <= rows; i++) { rnb.add(i); } dfb.setAttribute("row.names", rnb.build()); dfb.setAttribute("class", StringVector.valueOf("data.frame")); ListVector lv = dfb.build(); return lv; } catch (SQLException e) { throw new EvalException(e); } } }
package com.youth.banner; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.ColorInt; import androidx.annotation.ColorRes; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleOwner; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import androidx.viewpager2.widget.CompositePageTransformer; import androidx.viewpager2.widget.MarginPageTransformer; import androidx.viewpager2.widget.ViewPager2; import com.youth.banner.adapter.BannerAdapter; import com.youth.banner.config.BannerConfig; import com.youth.banner.config.IndicatorConfig; import com.youth.banner.indicator.Indicator; import com.youth.banner.listener.OnBannerListener; import com.youth.banner.listener.OnPageChangeListener; import com.youth.banner.transformer.MZScaleInTransformer; import com.youth.banner.transformer.ScaleInTransformer; import com.youth.banner.util.BannerLifecycleObserverAdapter; import com.youth.banner.util.BannerUtils; import com.youth.banner.util.BannerLifecycleObserver; import com.youth.banner.util.LogUtils; import com.youth.banner.util.ScrollSpeedManger; import java.lang.annotation.Retention; import java.lang.ref.WeakReference; import java.util.List; import static java.lang.annotation.RetentionPolicy.SOURCE; public class Banner<T, BA extends BannerAdapter> extends FrameLayout implements BannerLifecycleObserver { public static final int INVALID_VALUE = -1; private ViewPager2 mViewPager2; private AutoLoopTask mLoopTask; private OnPageChangeListener mOnPageChangeListener; private BA mAdapter; private Indicator mIndicator; private CompositePageTransformer mCompositePageTransformer; private BannerOnPageChangeCallback mPageChangeCallback; private boolean mIsInfiniteLoop = BannerConfig.IS_INFINITE_LOOP; private boolean mIsAutoLoop = BannerConfig.IS_AUTO_LOOP; private long mDelayTime = BannerConfig.LOOP_TIME; private int mScrollTime = BannerConfig.SCROLL_TIME; private int mStartPosition = 1; // banner private float mBannerRadius = 0; private int normalWidth = BannerConfig.INDICATOR_NORMAL_WIDTH; private int selectedWidth = BannerConfig.INDICATOR_SELECTED_WIDTH; private int normalColor = BannerConfig.INDICATOR_NORMAL_COLOR; private int selectedColor = BannerConfig.INDICATOR_SELECTED_COLOR; private int indicatorGravity = IndicatorConfig.Direction.CENTER; private int indicatorSpace; private int indicatorMargin; private int indicatorMarginLeft; private int indicatorMarginTop; private int indicatorMarginRight; private int indicatorMarginBottom; private int indicatorHeight = BannerConfig.INDICATOR_HEIGHT; private int indicatorRadius = BannerConfig.INDICATOR_RADIUS; public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; private int mTouchSlop; private float mStartX, mStartY; // viewpager2 private boolean mIsViewPager2Drag; private boolean isIntercept = true; private Paint mRoundPaint; private Paint mImagePaint; @Retention(SOURCE) @IntDef( {HORIZONTAL, VERTICAL}) public @interface Orientation { } public Banner(Context context) { this(context, null); } public Banner(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Banner(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); initTypedArray(context, attrs); } private void init(Context context) { mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop() / 2; mCompositePageTransformer = new CompositePageTransformer(); mPageChangeCallback = new BannerOnPageChangeCallback(); mLoopTask = new AutoLoopTask(this); mViewPager2 = new ViewPager2(context); mViewPager2.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mViewPager2.setOffscreenPageLimit(1); mViewPager2.registerOnPageChangeCallback(mPageChangeCallback); mViewPager2.setPageTransformer(mCompositePageTransformer); ScrollSpeedManger.reflectLayoutManager(this); addView(mViewPager2); mRoundPaint = new Paint(); mRoundPaint.setColor(Color.WHITE); mRoundPaint.setAntiAlias(true); mRoundPaint.setStyle(Paint.Style.FILL); mRoundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); mImagePaint = new Paint(); mImagePaint.setXfermode(null); } private void initTypedArray(Context context, AttributeSet attrs) { if (attrs == null) { return; } TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Banner); mBannerRadius = a.getDimensionPixelSize(R.styleable.Banner_banner_radius, 0); mDelayTime = a.getInt(R.styleable.Banner_delay_time, BannerConfig.LOOP_TIME); mIsAutoLoop = a.getBoolean(R.styleable.Banner_is_auto_loop, BannerConfig.IS_AUTO_LOOP); mIsInfiniteLoop = a.getBoolean(R.styleable.Banner_is_infinite_loop, BannerConfig.IS_INFINITE_LOOP); normalWidth = a.getDimensionPixelSize(R.styleable.Banner_indicator_normal_width, BannerConfig.INDICATOR_NORMAL_WIDTH); selectedWidth = a.getDimensionPixelSize(R.styleable.Banner_indicator_selected_width, BannerConfig.INDICATOR_SELECTED_WIDTH); normalColor = a.getColor(R.styleable.Banner_indicator_normal_color, BannerConfig.INDICATOR_NORMAL_COLOR); selectedColor = a.getColor(R.styleable.Banner_indicator_selected_color, BannerConfig.INDICATOR_SELECTED_COLOR); indicatorGravity = a.getInt(R.styleable.Banner_indicator_gravity, IndicatorConfig.Direction.CENTER); indicatorSpace = a.getDimensionPixelSize(R.styleable.Banner_indicator_space, 0); indicatorMargin = a.getDimensionPixelSize(R.styleable.Banner_indicator_margin, 0); indicatorMarginLeft = a.getDimensionPixelSize(R.styleable.Banner_indicator_marginLeft, 0); indicatorMarginTop = a.getDimensionPixelSize(R.styleable.Banner_indicator_marginTop, 0); indicatorMarginRight = a.getDimensionPixelSize(R.styleable.Banner_indicator_marginRight, 0); indicatorMarginBottom = a.getDimensionPixelSize(R.styleable.Banner_indicator_marginBottom, 0); indicatorHeight = a.getDimensionPixelSize(R.styleable.Banner_indicator_height, BannerConfig.INDICATOR_HEIGHT); indicatorRadius = a.getDimensionPixelSize(R.styleable.Banner_indicator_radius, BannerConfig.INDICATOR_RADIUS); int orientation = a.getInt(R.styleable.Banner_banner_orientation, HORIZONTAL); setOrientation(orientation); setInfiniteLoop(); a.recycle(); } private void initIndicatorAttr() { if (indicatorMargin != 0) { setIndicatorMargins(new IndicatorConfig.Margins(indicatorMargin)); } else if (indicatorMarginLeft != 0 || indicatorMarginTop != 0 || indicatorMarginRight != 0 || indicatorMarginBottom != 0) { setIndicatorMargins(new IndicatorConfig.Margins( indicatorMarginLeft, indicatorMarginTop, indicatorMarginRight, indicatorMarginBottom)); } if (indicatorSpace > 0) { setIndicatorSpace(indicatorSpace); } if (indicatorGravity != IndicatorConfig.Direction.CENTER) { setIndicatorGravity(indicatorGravity); } if (normalWidth > 0) { setIndicatorNormalWidth(normalWidth); } if (selectedWidth > 0) { setIndicatorSelectedWidth(selectedWidth); } if (indicatorHeight > 0) { setIndicatorHeight(indicatorHeight); } if (indicatorRadius > 0) { setIndicatorRadius(indicatorRadius); } setIndicatorNormalColor(normalColor); setIndicatorSelectedColor(selectedColor); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!getViewPager2().isUserInputEnabled()) { return super.dispatchTouchEvent(ev); } int action = ev.getActionMasked(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) { start(); } else if (action == MotionEvent.ACTION_DOWN) { stop(); } return super.dispatchTouchEvent(ev); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (!getViewPager2().isUserInputEnabled() || !isIntercept) { return super.onInterceptTouchEvent(event); } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = event.getX(); mStartY = event.getY(); getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_MOVE: float endX = event.getX(); float endY = event.getY(); float distanceX = Math.abs(endX - mStartX); float distanceY = Math.abs(endY - mStartY); if (getViewPager2().getOrientation() == HORIZONTAL) { mIsViewPager2Drag = distanceX > mTouchSlop && distanceX > distanceY; } else { mIsViewPager2Drag = distanceY > mTouchSlop && distanceY > distanceX; } getParent().requestDisallowInterceptTouchEvent(mIsViewPager2Drag); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: getParent().requestDisallowInterceptTouchEvent(false); break; } return super.onInterceptTouchEvent(event); } // @Override // protected void dispatchDraw(Canvas canvas) { // if (mBannerRadius > 0) { // Path path = new Path(); // path.addRoundRect(new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight()), // mBannerRadius, mBannerRadius, Path.Direction.CW); // canvas.clipPath(path); // super.dispatchDraw(canvas); @Override protected void dispatchDraw(Canvas canvas) { if (mBannerRadius > 0) { canvas.saveLayer(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), mImagePaint, Canvas.ALL_SAVE_FLAG); super.dispatchDraw(canvas); drawTopLeft(canvas); drawTopRight(canvas); drawBottomLeft(canvas); drawBottomRight(canvas); canvas.restore(); } else { super.dispatchDraw(canvas); } } private void drawTopLeft(Canvas canvas) { Path path = new Path(); path.moveTo(0, mBannerRadius); path.lineTo(0, 0); path.lineTo(mBannerRadius, 0); path.arcTo(new RectF(0, 0, mBannerRadius * 2, mBannerRadius * 2), -90, -90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawTopRight(Canvas canvas) { int width = getWidth(); Path path = new Path(); path.moveTo(width - mBannerRadius, 0); path.lineTo(width, 0); path.lineTo(width, mBannerRadius); path.arcTo(new RectF(width - 2 * mBannerRadius, 0, width, mBannerRadius * 2), 0, -90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawBottomLeft(Canvas canvas) { int height = getHeight(); Path path = new Path(); path.moveTo(0, height - mBannerRadius); path.lineTo(0, height); path.lineTo(mBannerRadius, height); path.arcTo(new RectF(0, height - 2 * mBannerRadius, mBannerRadius * 2, height), 90, 90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawBottomRight(Canvas canvas) { int height = getHeight(); int width = getWidth(); Path path = new Path(); path.moveTo(width - mBannerRadius, height); path.lineTo(width, height); path.lineTo(width, height - mBannerRadius); path.arcTo(new RectF(width - 2 * mBannerRadius, height - 2 * mBannerRadius, width, height), 0, 90); path.close(); canvas.drawPath(path, mRoundPaint); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); start(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); stop(); } class BannerOnPageChangeCallback extends ViewPager2.OnPageChangeCallback { private int mTempPosition = INVALID_VALUE; private boolean isScrolled; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), position, getRealCount()); if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } if (mIndicator != null) { mIndicator.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (isScrolled) { mTempPosition = position; int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), position, getRealCount()); if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(realPosition); } if (mIndicator != null) { mIndicator.onPageSelected(realPosition); } } } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager2.SCROLL_STATE_DRAGGING || state == ViewPager2.SCROLL_STATE_SETTLING) { isScrolled = true; } else if (state == ViewPager2.SCROLL_STATE_IDLE) { isScrolled = false; if (mTempPosition != INVALID_VALUE && mIsInfiniteLoop) { if (mTempPosition == 0) { setCurrentItem(getRealCount(), false); } else if (mTempPosition == getItemCount() - 1) { setCurrentItem(1, false); } } } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(state); } if (mIndicator != null) { mIndicator.onPageScrollStateChanged(state); } } } static class AutoLoopTask implements Runnable { private final WeakReference<Banner> reference; AutoLoopTask(Banner banner) { this.reference = new WeakReference<>(banner); } @Override public void run() { Banner banner = reference.get(); if (banner != null && banner.mIsAutoLoop) { int count = banner.getItemCount(); if (count == 0) { return; } int next = (banner.getCurrentItem() + 1) % count; banner.setCurrentItem(next); banner.postDelayed(banner.mLoopTask, banner.mDelayTime); } } } private RecyclerView.AdapterDataObserver mAdapterDataObserver = new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { if (getItemCount() <= 1) { stop(); } else { start(); } setIndicatorPageChange(); } }; private void initIndicator() { if (mIndicator == null || getAdapter() == null) { return; } if (mIndicator.getIndicatorConfig().isAttachToBanner()) { removeIndicator(); addView(mIndicator.getIndicatorView()); } initIndicatorAttr(); setIndicatorPageChange(); } private void setInfiniteLoop() { if (!isInfiniteLoop()) { isAutoLoop(false); } setStartPosition(isInfiniteLoop() ? 1 : 0); } private void setRecyclerViewPadding(int itemPadding) { RecyclerView recyclerView = (RecyclerView) getViewPager2().getChildAt(0); if (getViewPager2().getOrientation() == ViewPager2.ORIENTATION_VERTICAL) { recyclerView.setPadding(0, itemPadding, 0, itemPadding); } else { recyclerView.setPadding(itemPadding, 0, itemPadding, 0); } recyclerView.setClipToPadding(false); } public int getCurrentItem() { return getViewPager2().getCurrentItem(); } public int getItemCount() { if (getAdapter() == null) { return 0; } return getAdapter().getItemCount(); } public int getScrollTime() { return mScrollTime; } public boolean isInfiniteLoop() { return mIsInfiniteLoop; } public BA getAdapter() { if (mAdapter == null) { LogUtils.e(getContext().getString(R.string.banner_adapter_use_error)); } return mAdapter; } public ViewPager2 getViewPager2() { return mViewPager2; } public Indicator getIndicator() { if (mIndicator == null) { LogUtils.e(getContext().getString(R.string.indicator_null_error)); } return mIndicator; } public IndicatorConfig getIndicatorConfig() { if (getIndicator() != null) { return getIndicator().getIndicatorConfig(); } return null; } /** * banner */ public int getRealCount() { return getAdapter().getRealCount(); } /** * * @param intercept * @return */ public Banner setIntercept(boolean intercept) { isIntercept = intercept; return this; } public Banner setCurrentItem(int position) { return setCurrentItem(position, true); } public Banner setCurrentItem(int position, boolean smoothScroll) { getViewPager2().setCurrentItem(position, smoothScroll); return this; } public Banner setIndicatorPageChange() { if (mIndicator != null) { int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), getCurrentItem(), getRealCount()); mIndicator.onPageChanged(getRealCount(), realPosition); } return this; } public Banner removeIndicator() { if (mIndicator != null) { removeView(mIndicator.getIndicatorView()); } return this; } /** * (setAdaptersetDatas) */ public Banner setStartPosition(int mStartPosition) { this.mStartPosition = mStartPosition; return this; } /** * * * @param enabled true false */ public Banner setUserInputEnabled(boolean enabled) { getViewPager2().setUserInputEnabled(enabled); return this; } /** * PageTransformer * {@link ViewPager2.PageTransformer} * implementation "androidx.viewpager2:viewpager2:1.0.0" */ public Banner addPageTransformer(@Nullable ViewPager2.PageTransformer transformer) { mCompositePageTransformer.addTransformer(transformer); return this; } /** * PageTransformeraddPageTransformertransformer */ public Banner setPageTransformer(@Nullable ViewPager2.PageTransformer transformer) { getViewPager2().setPageTransformer(transformer); return this; } public Banner removeTransformer(ViewPager2.PageTransformer transformer) { mCompositePageTransformer.removeTransformer(transformer); return this; } /** * ItemDecoration */ public Banner addItemDecoration(RecyclerView.ItemDecoration decor) { getViewPager2().addItemDecoration(decor); return this; } public Banner addItemDecoration(RecyclerView.ItemDecoration decor, int index) { getViewPager2().addItemDecoration(decor, index); return this; } /** * * * @param isAutoLoop ture false */ public Banner isAutoLoop(boolean isAutoLoop) { this.mIsAutoLoop = isAutoLoop; return this; } /** * * * @param delayTime */ public Banner setDelayTime(long delayTime) { this.mDelayTime = delayTime; return this; } public Banner setScrollTime(int scrollTime) { this.mScrollTime = scrollTime; return this; } public Banner start() { if (mIsAutoLoop) { stop(); postDelayed(mLoopTask, mDelayTime); } return this; } public Banner stop() { if (mIsAutoLoop) { removeCallbacks(mLoopTask); } return this; } public void destroy() { if (getViewPager2() != null && mPageChangeCallback != null) { getViewPager2().unregisterOnPageChangeCallback(mPageChangeCallback); mPageChangeCallback = null; } stop(); } /** * banner */ public Banner setAdapter(BA adapter) { if (adapter == null) { throw new NullPointerException(getContext().getString(R.string.banner_adapter_null_error)); } this.mAdapter = adapter; if (!isInfiniteLoop()) { mAdapter.setIncreaseCount(0); } mAdapter.registerAdapterDataObserver(mAdapterDataObserver); mViewPager2.setAdapter(adapter); setCurrentItem(mStartPosition, false); initIndicator(); return this; } /** * banner * @param adapter * @param isInfiniteLoop * @return */ public Banner setAdapter(BA adapter,boolean isInfiniteLoop) { mIsInfiniteLoop=isInfiniteLoop; setInfiniteLoop(); setAdapter(adapter); return this; } /** * banneradapter, * * @param datas nulldatasbannerUI */ public Banner setDatas(List<T> datas) { if (getAdapter() != null) { getAdapter().setDatas(datas); getAdapter().notifyDataSetChanged(); setCurrentItem(mStartPosition, false); setIndicatorPageChange(); start(); } return this; } /** * banner * * @param orientation {@link Orientation} */ public Banner setOrientation(@Orientation int orientation) { getViewPager2().setOrientation(orientation); return this; } public Banner setTouchSlop(int mTouchSlop) { this.mTouchSlop = mTouchSlop; return this; } public Banner setOnBannerListener(OnBannerListener listener) { if (getAdapter() != null) { getAdapter().setOnBannerListener(listener); } return this; } /** * viewpager * <p> * viewpager2{@link ViewPager2.OnPageChangeCallback} * viewpager{@link ViewPager.OnPageChangeListener} * </p> */ public Banner addOnPageChangeListener(OnPageChangeListener pageListener) { this.mOnPageChangeListener = pageListener; return this; } /** * banner * <p> * 0 * * @param radius */ public Banner setBannerRound(float radius) { mBannerRadius = radius; return this; } /** * banner()5.0 */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public Banner setBannerRound2(float radius) { BannerUtils.setBannerRound(this, radius); return this; } /** * banner * * @param itemWidth item,dp * @param pageMargin ,dp */ public Banner setBannerGalleryEffect(int itemWidth, int pageMargin) { return setBannerGalleryEffect(itemWidth, pageMargin, .85f); } /** * banner * * @param itemWidth item,dp * @param pageMargin ,dp * @param scale [0-1],1 */ public Banner setBannerGalleryEffect(int itemWidth, int pageMargin, float scale) { if (pageMargin > 0) { addPageTransformer(new MarginPageTransformer((int) BannerUtils.dp2px(pageMargin))); } if (scale < 1 && scale > 0) { addPageTransformer(new ScaleInTransformer(scale)); } setRecyclerViewPadding((int) BannerUtils.dp2px(itemWidth + pageMargin)); return this; } /** * banner * * @param itemWidth item,dp */ public Banner setBannerGalleryMZ(int itemWidth) { return setBannerGalleryMZ(itemWidth, .88f); } /** * banner * * @param itemWidth item,dp * @param scale [0-1],1 */ public Banner setBannerGalleryMZ(int itemWidth, float scale) { if (scale < 1 && scale > 0) { addPageTransformer(new MZScaleInTransformer(scale)); } setRecyclerViewPadding((int) BannerUtils.dp2px(itemWidth)); return this; } /** * (banner) */ public Banner setIndicator(Indicator indicator) { return setIndicator(indicator, true); } /** * (attachToBannerfalse) * * @param attachToBanner bannerfalse * false setIndicatorGravity()setIndicatorMargins() * demo */ public Banner setIndicator(Indicator indicator, boolean attachToBanner) { removeIndicator(); indicator.getIndicatorConfig().setAttachToBanner(attachToBanner); this.mIndicator = indicator; initIndicator(); return this; } public Banner setIndicatorSelectedColor(@ColorInt int color) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setSelectedColor(color); } return this; } public Banner setIndicatorSelectedColorRes(@ColorRes int color) { setIndicatorSelectedColor(ContextCompat.getColor(getContext(), color)); return this; } public Banner setIndicatorNormalColor(@ColorInt int color) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setNormalColor(color); } return this; } public Banner setIndicatorNormalColorRes(@ColorRes int color) { setIndicatorNormalColor(ContextCompat.getColor(getContext(), color)); return this; } public Banner setIndicatorGravity(@IndicatorConfig.Direction int gravity) { if (mIndicator != null && mIndicator.getIndicatorConfig().isAttachToBanner()) { mIndicator.getIndicatorConfig().setGravity(gravity); mIndicator.getIndicatorView().postInvalidate(); } return this; } public Banner setIndicatorSpace(int indicatorSpace) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setIndicatorSpace(indicatorSpace); } return this; } public Banner setIndicatorMargins(IndicatorConfig.Margins margins) { if (mIndicator != null && mIndicator.getIndicatorConfig().isAttachToBanner()) { mIndicator.getIndicatorConfig().setMargins(margins); mIndicator.getIndicatorView().requestLayout(); } return this; } public Banner setIndicatorWidth(int normalWidth, int selectedWidth) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setNormalWidth(normalWidth); mIndicator.getIndicatorConfig().setSelectedWidth(selectedWidth); } return this; } public Banner setIndicatorNormalWidth(int normalWidth) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setNormalWidth(normalWidth); } return this; } public Banner setIndicatorSelectedWidth(int selectedWidth) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setSelectedWidth(selectedWidth); } return this; } public Banner<T, BA> setIndicatorRadius(int indicatorRadius) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setRadius(indicatorRadius); } return this; } public Banner<T, BA> setIndicatorHeight(int indicatorHeight) { if (mIndicator != null) { mIndicator.getIndicatorConfig().setHeight(indicatorHeight); } return this; } public Banner addBannerLifecycleObserver(LifecycleOwner owner) { if (owner != null) { owner.getLifecycle().addObserver(new BannerLifecycleObserverAdapter(owner, this)); } return this; } @Override public void onStart(LifecycleOwner owner) { start(); } @Override public void onStop(LifecycleOwner owner) { stop(); } @Override public void onDestroy(LifecycleOwner owner) { destroy(); } }
package org.xins.common.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.text.ParseException; import org.xins.common.text.TextUtils; public class ElementParser { // Class fields /** * Error state for the SAX event handler. */ private static final State ERROR = new State("ERROR"); /** * State for the SAX event handler in the data section (at any depth within * the <code>data</code> element). */ private static final State PARSING = new State("PARSING"); /** * State for the SAX event handler for the final state, when parsing is * finished. */ private static final State FINISHED = new State("FINISHED"); // Constructors /** * Constructs a new <code>ElementParser</code>. */ public ElementParser() { // empty } // Methods public Element parse(String text) throws IllegalArgumentException, ParseException { // Check preconditions MandatoryArgumentChecker.check("text", text); try { return parse(new StringReader(text)); } catch (IOException ioe) { throw Utils.logProgrammingError(ioe); } } public Element parse(InputStream in) throws IllegalArgumentException, IOException, ParseException { // Check preconditions MandatoryArgumentChecker.check("in", in); // Wrap the Reader in a SAX InputSource object InputSource source = new InputSource(in); return parse(source); } public Element parse(Reader in) throws IllegalArgumentException, IOException, ParseException { // Check preconditions MandatoryArgumentChecker.check("in", in); // Wrap the Reader in a SAX InputSource object InputSource source = new InputSource(in); return parse(source); } /** * Parses content of a character stream to create an XML * <code>Element</code> object. * * @param source * the input source that is supposed to contain XML to be parsed, * not <code>null</code>. * * @return * the parsed result, not <code>null</code>. * * @throws IOException * if there is an I/O error. * * @throws ParseException * if the content of the character stream is not considered to be valid * XML. */ private Element parse(InputSource source) throws IOException, ParseException { // TODO: Consider using an XMLReader instead of a SAXParser // Initialize our SAX event handler Handler handler = new Handler(); try { // Let SAX parse the XML, using our handler SAXParserProvider.get().parse(source, handler); } catch (SAXException exception) { // TODO: Log: Parsing failed String exMessage = exception.getMessage(); // Construct complete message String message = "Failed to parse XML"; if (TextUtils.isEmpty(exMessage)) { message += '.'; } else { message += ": " + exMessage; } // Throw exception with message, and register cause exception throw new ParseException(message, exception, exMessage); } Element element = handler.getElement(); return element; } // Inner classes /** * SAX event handler that will parse XML. * * @version $Revision$ $Date$ * @author <a href="mailto:anthony.goubard@orange-ftgroup.com">Anthony Goubard</a> * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> */ private static class Handler extends DefaultHandler { // Constructors /** * Constructs a new <code>Handler</code> instance. */ private Handler() { _state = PARSING; _level = -1; _characters = new StringBuffer(145); _dataElementStack = new Stack(); } // Fields /** * The current state. Never <code>null</code>. */ private State _state; /** * The element resulting of the parsing. */ private Element _element; /** * The character content (CDATA or PCDATA) of the element currently * being parsed. */ private StringBuffer _characters; /** * The stack of child elements within the data section. The top element * is always <code>&lt;data/&gt;</code>. */ private Stack _dataElementStack; /** * The level for the element pointer within the XML document. Initially * this field is <code>-1</code>, which indicates the current element * pointer is outside the document. The value <code>0</code> is for the * root element (<code>result</code>), etc. */ private int _level; // Methods public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws IllegalArgumentException, SAXException { // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; // Make sure namespaceURI is either null or non-empty namespaceURI = "".equals(namespaceURI) ? null : namespaceURI; // Check preconditions MandatoryArgumentChecker.check("localName", localName, "atts", atts); // Increase the element depth level _level++; if (currentState == ERROR) { String detail = "Unexpected state " + currentState + " (level=" + _level + ')'; throw Utils.logProgrammingError(detail); } else { // Construct a Element Element element = new Element(namespaceURI, localName); // Add all attributes for (int i = 0; i < atts.getLength(); i++) { String attrNamespaceURI = atts.getURI(i); String attrLocalName = atts.getLocalName(i); String attrValue = atts.getValue(i); element.setAttribute(attrNamespaceURI, attrLocalName, attrValue); } // Push the element on the stack _dataElementStack.push(element); // Reserve buffer for PCDATA _characters = new StringBuffer(145); // Reset the state from ERROR back to PARSING _state = PARSING; } } public void endElement(String namespaceURI, String localName, String qName) throws IllegalArgumentException { // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; // Check preconditions MandatoryArgumentChecker.check("localName", localName); if (currentState == ERROR) { String detail = "Unexpected state " + currentState + " (level=" + _level + ')'; throw Utils.logProgrammingError(detail); // Within data section } else { // Get the Element for which we process the end tag Element child = (Element) _dataElementStack.pop(); // Set the PCDATA content on the element if (_characters.length() > 0) { child.setText(_characters.toString()); } // Add the child to the parent if (_dataElementStack.size() > 0) { Element parent = (Element) _dataElementStack.peek(); parent.addChild(child); // Reset the state back from ERROR to PARSING _state = PARSING; } else { _element = child; _state = FINISHED; } } _level _characters = new StringBuffer(145); } /** * Receive notification of character data. * * @param ch * the <code>char</code> array that contains the characters from the * XML document, cannot be <code>null</code>. * * @param start * the start index within <code>ch</code>. * * @param length * the number of characters to take from <code>ch</code>. * * @throws IndexOutOfBoundsException * if characters outside the allowed range are specified. * * @throws SAXException * if the parsing failed. */ public void characters(char[] ch, int start, int length) throws IndexOutOfBoundsException, SAXException { // Temporarily enter ERROR state, on success this state is left State currentState = _state; _state = ERROR; _characters.append(ch, start, length); // Reset _state _state = currentState; } /** * Gets the parsed element. * * @return * the element resulting of the parsing of the XML. */ Element getElement() { // Check state if (_state != FINISHED) { String detail = "State is " + _state + " instead of " + FINISHED; throw Utils.logProgrammingError(detail); } return _element; } public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new ByteArrayInputStream(new byte[0])); } } /** * State of the event handler. * * @version $Revision$ $Date$ * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> * * @since XINS 1.0.0 */ private static final class State { // Constructors State(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); _name = name; } // Fields /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; // Methods /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ public String getName() { return _name; } /** * Returns a textual representation of this object. * * @return * the name of this state, never <code>null</code>. */ public String toString() { return _name; } } }
package org.xins.server; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.NullEnumeration; import org.xins.util.MandatoryArgumentChecker; /** * Class that represents the XINS/Java Server Framework library. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.8 */ public final class Library extends Object { // Class fields // Class functions /** * Returns the version of this library. * * @return * the version of this library, for example <code>"%%VERSION%%"</code>, * never <code>null</code>. */ public static final String getVersion() { return "%%VERSION%%"; } // Constructors /** * Constructs a new <code>Library</code> object. */ private Library() { // empty } // Fields // Methods }
package afc.ant.modular; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class SerialDependencyResolver implements DependencyResolver { private ArrayList<Node> shortlist; private Module moduleAcquired; public void init(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException { if (rootModules == null) { throw new NullPointerException("rootModules"); } for (final Module module : rootModules) { if (module == null) { throw new NullPointerException("rootModules contains null element."); } } ensureNoLoops(rootModules); shortlist = buildNodeGraph(rootModules); moduleAcquired = null; } // returns a module that does not have dependencies public Module getFreeModule() { ensureInitialised(); if (moduleAcquired != null) { throw new IllegalStateException("#getFreeModule() is called when there is a module being processed."); } if (shortlist.isEmpty()) { return null; } /* Removing the node from the graph here instead of #moduleProcessed to avoid searching * for this node when #moduleProcessed is invoked. All consistency and input validity * checks are performed so that the caller must follow the correct workflow. */ final Node node = shortlist.remove(shortlist.size()-1); for (int j = 0, n = node.dependencyOf.size(); j < n; ++j) { final Node depOf = node.dependencyOf.get(j); if (--depOf.dependencyCount == 0) { // all modules with no dependencies go to the shortlist shortlist.add(depOf); } } return moduleAcquired = node.module; } public void moduleProcessed(final Module module) { ensureInitialised(); if (module == null) { throw new NullPointerException("module"); } if (moduleAcquired == null) { throw new IllegalStateException("No module is being processed."); } if (moduleAcquired != module) { throw new IllegalArgumentException(MessageFormat.format( "The module ''{0}'' is not being processed.", module.getPath())); } moduleAcquired = null; } private void ensureInitialised() { if (shortlist == null) { throw new IllegalStateException("Resolver is not initialised."); } } private static class Node { private Node(final Module module) { this.module = module; dependencyCount = module.getDependencies().size(); dependencyOf = new ArrayList<Node>(); } private final Module module; /* Knowing just dependency count is enough to detect the moment when this node has no dependencies remaining. */ private int dependencyCount; private final ArrayList<Node> dependencyOf; } /* * Builds a DAG which nodes hold modules and arcs that represent inverted module dependencies. * The list of nodes returned contains the ending vertices of the graph. The modules that * are bound to these vertices do not have dependencies on other modules and are used * as modules to start unwinding dependencies from. */ private static ArrayList<Node> buildNodeGraph(final Collection<Module> rootModules) { /* TODO it is known that there are no loops in the dependency graph. Use it knowledge to eliminate unnecessary checks OR merge buildNodeGraph() with ensureNoLoops() so that loops are checked for while the node graph is being built. */ final IdentityHashMap<Module, Node> registry = new IdentityHashMap<Module, Node>(); // shortlist stores the leaves of the inverted dependency graph. final ArrayList<Node> shortlist = new ArrayList<Node>(); for (final Module module : rootModules) { addNodeDeep(module, shortlist, registry); } return shortlist; } private static Node addNodeDeep(final Module module, final ArrayList<Node> shortlist, final IdentityHashMap<Module, Node> registry) { Node node = registry.get(module); if (node != null) { return node; // the module is already processed } node = new Node(module); registry.put(module, node); final Set<Module> deps = module.getDependencies(); if (deps.isEmpty()) { shortlist.add(node); } else { // inverted dependencies are assigned for (final Module dep : module.getDependencies()) { final Node depNode = addNodeDeep(dep, shortlist, registry); assert depNode != null; depNode.dependencyOf.add(node); } } return node; } private static void ensureNoLoops(final Collection<Module> modules) throws CyclicDependenciesDetectedException { final HashSet<Module> cleanModules = new HashSet<Module>(); final LinkedHashSet<Module> path = new LinkedHashSet<Module>(); for (final Module module : modules) { ensureNoLoops(module, path, cleanModules); } } private static void ensureNoLoops(final Module module, final LinkedHashSet<Module> path, final HashSet<Module> cleanModules) throws CyclicDependenciesDetectedException { if (cleanModules.contains(module)) { return; } if (path.add(module)) { for (final Module dep : module.getDependencies()) { ensureNoLoops(dep, path, cleanModules); } path.remove(module); cleanModules.add(module); return; } /* A loop is detected. It does not necessarily end with the starting node, some leading nodes could be truncated. */ int loopSize = path.size(); final Iterator<Module> it = path.iterator(); while (it.next() != module) { // skipping all leading nodes that are outside the loop --loopSize; } final ArrayList<Module> loop = new ArrayList<Module>(loopSize); loop.add(module); while (it.hasNext()) { loop.add(it.next()); } assert loopSize == loop.size(); throw new CyclicDependenciesDetectedException(loop); } }
package io.compgen.common.io; import java.io.IOException; import java.io.InputStream; /** * This class wraps another inputstream. It will let you peek at [bufferSize] * bytes from the stream without removing them from the stream. This lets one * read from an arbitrary stream (file, stdin, network) and identify a file type * based upon magic bytes. You can then pass this stream to an appropriate * handler, but keep the magic bytes as part of the inputstream. * * @author mbreese */ public class PeekableInputStream extends InputStream { public static final int DEFAULT_BUFFERSIZE = 64*1024; protected final int bufferSize; protected final InputStream parent; private boolean closed = false; private byte[] buffer = null; // position in buffer private int pos = 0; // size of buffer (amount read from parent stream) private int buflen = 0; private int peekpos = 0; public PeekableInputStream(InputStream parent, int bufferSize) throws IOException { this.parent = parent; this.bufferSize = bufferSize; this.buffer = new byte[bufferSize]; } public PeekableInputStream(InputStream parent) throws IOException { this(parent, DEFAULT_BUFFERSIZE); } private void fillBuffer() throws IOException { if (parent == null) { throw new IOException("Parent InputStream is null?"); } buflen = parent.read(buffer, 0, buffer.length); pos = 0; peekpos = 0; } private void resetBuffer() throws IOException { if (pos >= buflen || buflen == 0) { fillBuffer(); } else if (pos > 0) { // copy from pos to new buffer. byte[] tmp = new byte[buffer.length]; for (int i=0; i<buflen - pos; i++) { tmp[i] = buffer[pos + i]; } buflen = buflen - pos; pos = 0; peekpos = 0; } } @Override public int read() throws IOException { if (closed) { throw new IOException("Attempted to read from closed stream!"); } if (pos >= buflen) { fillBuffer(); } if (buflen == -1) { return -1; } return buffer[pos++] & 0xff; } public void close() throws IOException { if (closed) { return; } parent.close(); closed = true; } /** * Preview a few bytes from the stream before actually "reading" them. * * This will let you read a few bytes from a stream (which might be a file, * network, or whatever) without removing the bytes from the stream. This way * you can pre-identify a file with magic bytes without removing the magic bytes. * * @param bytes * @return * @throws IOException */ public byte[] peek(int bytes) throws IOException { if (closed) { throw new IOException("Attempted to read from closed stream!"); } if (pos > 0 || buflen == 0) { // we don't peek into an empty buffer, or one where the current pos is > 0. resetBuffer(); } byte[] out = new byte[bytes]; for (int i=0; i<bytes; i++) { // we will grow the buffer as needed to fulfill the the request... out[i] = peek(); } return out; } public byte peek() throws IOException { if (peekpos >= buflen) { if (buffer.length > (Integer.MAX_VALUE - bufferSize)) { throw new IOException("Attempted to peek beyond buffer!"); } // grow the buffer in bufferSize chunks // System.err.println(" -- growing buffer by " + bufferSize ); byte[] newbuf = new byte[buffer.length + bufferSize]; for (int i=0; i<buflen; i++) { newbuf[i] = buffer[i]; } // fill in the new buffer. int newbuflen = parent.read(newbuf, buflen, bufferSize); if (newbuflen == -1) { throw new IOException("Attempted to peek beyond parent inputstream!"); } buflen += newbuflen; buffer = newbuf; } return buffer[peekpos++]; } public void resetPeek() { peekpos = 0; } }
package net.sf.picard.cmdline; import java.io.File; import java.util.*; import net.sf.picard.metrics.Header; import net.sf.picard.metrics.MetricBase; import net.sf.picard.metrics.MetricsFile; import net.sf.picard.metrics.StringHeader; import net.sf.picard.util.Log; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMFileWriterFactory; import net.sf.samtools.SAMFileWriterImpl; import net.sf.samtools.util.BlockCompressedOutputStream; import net.sf.samtools.util.BlockCompressedStreamConstants; /** * Abstract class to facilitate writing command-line programs. * * To use: * * 1. Extend this class with a concrete class that has data members annotated with @Option, @PositionalArguments * and/or @Usage annotations. * * 2. If there is any custom command-line validation, override customCommandLineValidation(). When this method is * called, the command line has been parsed and set into the data members of the concrete class. * * 3. Implement a method doWork(). This is called after successful comand-line processing. The value it returns is * the exit status of the program. It is assumed that the concrete class emits any appropriate error message before * returning non-zero. doWork() may throw unchecked exceptions, which are caught and reported appropriately. * * 4. Implement the following static method in the concrete class: * * public static void main(String[] argv) { new MyConcreteClass().instanceMainWithExit(argv); } */ public abstract class CommandLineProgram { /** * List of all options in CommandLineProgram, so that these can be skipped when generating * HTML help for a particular program. */ private static final Set<String> STANDARD_OPTIONS = Collections.unmodifiableSet(new HashSet<String>( Arrays.asList("TMP_DIR", "VERBOSITY", "QUIET", "VALIDATION_STRINGENCY", "COMPRESSION_LEVEL", "MAX_RECORDS_IN_RAM", "CREATE_INDEX", "MD5_FILE"))); @Option public File TMP_DIR = (System.getProperty("java.io.tmpdir").endsWith("/" + System.getProperty("user.name"))? new File(System.getProperty("java.io.tmpdir")): new File(System.getProperty("java.io.tmpdir"), System.getProperty("user.name"))); @Option(doc = "Control verbosity of logging.") public Log.LogLevel VERBOSITY = Log.LogLevel.INFO; @Option(doc = "Whether to suppress job-summary info on System.err.") public Boolean QUIET = false; @Option(doc = "Validation stringency for all SAM files read by this program. Setting stringency to SILENT " + "can improve performance when processing a BAM file in which variable-length data (read, qualities, tags) " + "do not otherwise need to be decoded.") public SAMFileReader.ValidationStringency VALIDATION_STRINGENCY = SAMFileReader.ValidationStringency.DEFAULT_STRINGENCY; @Option(doc = "Compression level for all compressed files created (e.g. BAM and GELI).") public int COMPRESSION_LEVEL = BlockCompressedStreamConstants.DEFAULT_COMPRESSION_LEVEL; @Option(doc = "When writing SAM files that need to be sorted, this will specify the number of records stored in RAM before spilling to disk. Increasing this number reduces the number of file handles needed to sort a SAM file, and increases the amount of RAM needed.", optional=true) public Integer MAX_RECORDS_IN_RAM = SAMFileWriterImpl.getDefaultMaxRecordsInRam(); @Option(doc = "Whether to create a BAM index when writing a coordinate-sorted BAM file.") public Boolean CREATE_INDEX = false; @Option(doc="Whether to create an MD5 digest for any BAM files created. ") public boolean CREATE_MD5_FILE = false; private final String standardUsagePreamble = CommandLineParser.getStandardUsagePreamble(getClass()); /** * Initialized in parseArgs. Subclasses may want to access this to do their * own validation, and then print usage using commandLineParser. */ private CommandLineParser commandLineParser; private final List<Header> defaultHeaders = new ArrayList<Header>(); /** * The reconstructed commandline used to run this program. Used for logging * and debugging. */ private String commandLine; /** * Do the work after command line has been parsed. RuntimeException may be * thrown by this method, and are reported appropriately. * @return program exit status. */ protected abstract int doWork(); public void instanceMainWithExit(final String[] argv) { System.exit(instanceMain(argv)); } public int instanceMain(final String[] argv) { if (!parseArgs(argv)) { return 1; } // Build the default headers final Date startDate = new Date(); this.defaultHeaders.add(new StringHeader(commandLine)); this.defaultHeaders.add(new StringHeader("Started on: " + startDate)); Log.setGlobalLogLevel(VERBOSITY); SAMFileReader.setDefaultValidationStringency(VALIDATION_STRINGENCY); BlockCompressedOutputStream.setDefaultCompressionLevel(COMPRESSION_LEVEL); if (MAX_RECORDS_IN_RAM != null) { SAMFileWriterImpl.setDefaultMaxRecordsInRam(MAX_RECORDS_IN_RAM); } if (CREATE_INDEX){ SAMFileWriterFactory.setDefaultCreateIndexWhileWriting(true); } SAMFileWriterFactory.setDefaultCreateMd5File(CREATE_MD5_FILE); if (!TMP_DIR.exists()) { // Intentially not checking the return value, because it may be that the program does not // need a tmp_dir. If this fails, the problem will be discovered downstream. TMP_DIR.mkdir(); } System.setProperty("java.io.tmpdir", TMP_DIR.getAbsolutePath()); if (!QUIET) { System.err.println("[" + new Date() + "] " + commandLine); } final int ret; try { ret = doWork(); } finally { // Emit the time even if program throws if (!QUIET) { System.err.println("[" + new Date() + "] " + getClass().getName() + " done."); System.err.println("Runtime.totalMemory()=" + Runtime.getRuntime().totalMemory()); } } return ret; } /** * Put any custom command-line validation in an override of this method. * clp is initialized at this point and can be used to print usage and access argv. * Any options set by command-line parser can be validated. * @return null if command line is valid. If command line is invalid, returns an array of error message * to be written to the appropriate place. */ protected String[] customCommandLineValidation() { return null; } /** * * @return true if command line is valid */ protected boolean parseArgs(final String[] argv) { commandLineParser = new CommandLineParser(this); final boolean ret = commandLineParser.parseOptions(System.err, argv); commandLine = commandLineParser.getCommandLine(); if (!ret) { return false; } final String[] customErrorMessages = customCommandLineValidation(); if (customErrorMessages != null) { for (final String msg : customErrorMessages) { System.err.println(msg); } commandLineParser.usage(System.err); return false; } return true; } /** Gets a MetricsFile with default headers already written into it. */ protected <A extends MetricBase,B extends Comparable<?>> MetricsFile<A,B> getMetricsFile() { final MetricsFile<A,B> file = new MetricsFile<A,B>(); for (final Header h : this.defaultHeaders) { file.addHeader(h); } return file; } public String getStandardUsagePreamble() { return standardUsagePreamble; } public CommandLineParser getCommandLineParser() { return commandLineParser; } public String getProgramVersion() { return commandLineParser.getProgramVersion(); } public String getCommandLine() { return commandLine; } public static Set<String> getStandardOptions() { return STANDARD_OPTIONS; } }
package nl.b3p.viewer.stripes; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import javax.persistence.NoResultException; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.After; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.StreamingResolution; import net.sourceforge.stripes.action.StrictBinding; import net.sourceforge.stripes.action.UrlBinding; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.Validate; import nl.b3p.viewer.config.app.ApplicationLayer; import nl.b3p.viewer.config.app.ConfiguredAttribute; import nl.b3p.viewer.config.services.AttributeDescriptor; import nl.b3p.viewer.config.services.Layer; import nl.b3p.viewer.config.services.SimpleFeatureType; import nl.b3p.viewer.config.services.WFSFeatureSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.data.store.DataFeatureCollection; import org.geotools.data.wfs.WFSDataStoreFactory; import org.geotools.factory.CommonFactoryFinder; import org.geotools.factory.GeoTools; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.FilterFactory2; import org.opengis.filter.sort.SortBy; import org.opengis.filter.sort.SortOrder; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @UrlBinding("/action/appLayer") @StrictBinding public class AppLayerActionBean implements ActionBean { private static final Log log = LogFactory.getLog(AppLayerActionBean.class); private static final int MAX_FEATURES = 50; private ActionBeanContext context; @Validate private ApplicationLayer appLayer; private Layer layer = null; @Validate private int limit; @Validate private int page; @Validate private int start; @Validate private String dir; @Validate private String sort; @Validate private boolean arrays; @Validate private boolean debug; //<editor-fold defaultstate="collapsed" desc="getters en setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public ApplicationLayer getAppLayer() { return appLayer; } public void setAppLayer(ApplicationLayer appLayer) { this.appLayer = appLayer; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public boolean isArrays() { return arrays; } public void setArrays(boolean arrays) { this.arrays = arrays; } //</editor-fold> @After(stages=LifecycleStage.BindingAndValidation) public void loadLayer() { // TODO check if user has rights to appLayer try { layer = (Layer)Stripersist.getEntityManager().createQuery("from Layer where service = :service and name = :n order by virtual desc") .setParameter("service", appLayer.getService()) .setParameter("n", appLayer.getLayerName()) .setMaxResults(1) .getSingleResult(); } catch(NoResultException nre) { } } public Resolution attributes() throws JSONException { JSONObject json = new JSONObject(); json.put("success", Boolean.FALSE); String error = null; if(appLayer == null) { error = "Invalid parameters"; } else { Map<String,AttributeDescriptor> featureTypeAttributes = new HashMap<String,AttributeDescriptor>(); if(layer != null) { SimpleFeatureType ft = layer.getFeatureType(); if(ft != null) { for(AttributeDescriptor ad: ft.getAttributes()) { featureTypeAttributes.put(ad.getName(), ad); } } } JSONArray attributes = new JSONArray(); for(ConfiguredAttribute ca: appLayer.getAttributes()) { JSONObject j = ca.toJSONObject(); AttributeDescriptor ad = featureTypeAttributes.get(ca.getAttributeName()); if(ad != null) { j.put("alias", ad.getAlias()); j.put("type", ad.getType()); } attributes.put(j); } json.put("attributes", attributes); json.put("success", Boolean.TRUE); } if(error != null) { json.put("error", error); } return new StreamingResolution("application/json", new StringReader(json.toString())); } public Resolution store() throws JSONException, Exception { JSONObject json = new JSONObject(); JSONArray features = new JSONArray(); json.put("features", features); try { int total = 0; if(layer != null && layer.getFeatureType() != null) { FeatureSource fs; if(isDebug() && layer.getFeatureType().getFeatureSource() instanceof WFSFeatureSource) { Map extraDataStoreParams = new HashMap(); extraDataStoreParams.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.FALSE); fs = ((WFSFeatureSource)layer.getFeatureType().getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams); } else { fs = layer.getFeatureType().openGeoToolsFeatureSource(); } boolean startIndexSupported = fs.getQueryCapabilities().isOffsetSupported(); Query q = new Query(fs.getName().toString()); FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); if(sort != null) { String sortAttribute = sort; if(arrays) { int i = Integer.parseInt(sort.substring(1)); int j = 0; for(ConfiguredAttribute ca: appLayer.getAttributes()) { if(ca.isVisible()) { if(j == i) { sortAttribute = ca.getAttributeName(); } j++; } } } q.setSortBy(new SortBy[] { ff2.sort(sortAttribute, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING) }); } total = fs.getCount(q); if(total == -1) { total = MAX_FEATURES; } q.setStartIndex(start); q.setMaxFeatures(Math.min(limit + (startIndexSupported ? 0 : start),MAX_FEATURES)); FeatureCollection fc = fs.getFeatures(q); if(!fc.isEmpty()) { int featureCount; if(fc instanceof DataFeatureCollection) { featureCount = ((DataFeatureCollection)fc).getCount(); } else { featureCount = fc.size(); /* This method swallows exceptions */ } if(featureCount < (startIndexSupported ? limit : start + limit)) { total = start + (startIndexSupported ? featureCount : featureCount - start); } FeatureIterator<SimpleFeature> it = fc.features(); try { while(it.hasNext()) { SimpleFeature f = it.next(); if(!startIndexSupported && start > 0) { start continue; } if(arrays) { JSONObject j = new JSONObject(); int idx = 0; for(ConfiguredAttribute ca: appLayer.getAttributes()) { if(ca.isVisible()) { j.put("c" + idx++, f.getAttribute(ca.getAttributeName())); } } features.put(j); } else { JSONObject j = new JSONObject(); for(ConfiguredAttribute ca: appLayer.getAttributes()) { if(ca.isVisible()) { String name = ca.getAttributeName(); j.put(name, f.getAttribute(name)); } } features.put(j); } } } finally { it.close(); fs.getDataStore().dispose(); } } } json.put("total", total); } catch(Exception e) { log.error("Error loading features", e); json.put("success", false); String message = "Fout bij ophalen features: " + e.toString(); Throwable cause = e.getCause(); while(cause != null) { message += "; " + cause.toString(); cause = cause.getCause(); } json.put("message", message); } return new StreamingResolution("application/json", new StringReader(json.toString())); } }
package org.intermine.pathquery; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import java.util.regex.Pattern; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.util.DynamicUtil; import org.intermine.util.TypeUtil; /** * Class to represent a path-based query. * * @author Matthew Wakeling */ public class PathQuery implements Cloneable { /** A Pattern that finds spaces in a String. */ protected static final Pattern SPACE_SPLITTER = Pattern.compile(" ", Pattern.LITERAL); /** Version number for the userprofile and PathQuery XML format. */ public static final int USERPROFILE_VERSION = 2; /** The lowest code value a constraint may be assigned. **/ public static final char MIN_CODE = 'A'; /** The highest code value a constraint may be assigned. **/ public static final char MAX_CODE = 'Z'; /** The maximum number of coded constraints a PathQuery may hold. **/ public static final int MAX_CONSTRAINTS = MAX_CODE - MIN_CODE; private final Model model; private List<String> view = new ArrayList<String>(); private List<OrderElement> orderBy = new ArrayList<OrderElement>(); private Map<PathConstraint, String> constraints = new LinkedHashMap<PathConstraint, String>(); private LogicExpression logic = null; private Map<String, OuterJoinStatus> outerJoinStatus = new LinkedHashMap<String, OuterJoinStatus>(); private Map<String, String> descriptions = new LinkedHashMap<String, String>(); private String description = null; private String title = null; // Verification variables: private boolean isVerified = false; /** The root path of this query */ private String rootClass = null; /** A Map from path to class name for all PathConstraintSubclass objects in the query. */ private Map<String, String> subclasses = null; /** A Map from path to outer join group for all main paths in the query. */ private Map<String, String> outerJoinGroups = null; /** A Map from outer join group to the set of constraint codes in that group. */ private Map<String, Set<String>> constraintGroups = null; /** A Set of Strings describing all the loop constraints in the query, in order to check for * uniqueness */ private Set<String> existingLoops = null; /** A boolean that determines if the constraints are broken enough to not bother validating the * constraint logic */ private boolean doNotVerifyLogic = false; /** * Constructor. Takes a Model object, to enable verification later. * * @param model a Model object */ public PathQuery(Model model) { this.model = model; } /** * Constructor. Takes an existing PathQuery object, and copies all the data. Similar to the * clone method. * * @param o a PathQuery to copy */ public PathQuery(PathQuery o) { model = o.model; view = new ArrayList<String>(o.view); orderBy = new ArrayList<OrderElement>(o.orderBy); constraints = new LinkedHashMap<PathConstraint, String>(o.constraints); if (o.logic != null) { logic = new LogicExpression(o.logic.toString()); } outerJoinStatus = new LinkedHashMap<String, OuterJoinStatus>(o.outerJoinStatus); descriptions = new LinkedHashMap<String, String>(o.descriptions); description = o.description; } /** * Returns the Model object stored in this object. * * @return a Model */ public Model getModel() { return model; } public synchronized void addView(String viewPath) { deVerify(); checkPathFormat(viewPath); view.add(viewPath); } /** * Removes a single element from the view list. The element should be a normal path expression, * with dots separating the parts. Do not use colons to represent outer joins, and do not use * square brackets to represent subclass constraints. If there are multiple copies of the path * on the view list (which is an invalid query), then this method will remove all of them. * * @param viewPath the path String to remove from the view list * @throws NullPointerException if the viewPath is null * @throws NoSuchElementException if the viewPath is not already on the view list */ public synchronized void removeView(String viewPath) { deVerify(); checkPathFormat(viewPath); if (!view.contains(viewPath)) { throw new NoSuchElementException("Path \"" + viewPath + "\" is not in the view list: \"" + view + "\" - cannot remove it"); } view.removeAll(Collections.singleton(viewPath)); } /** * Clears the entire view list. */ public synchronized void clearView() { deVerify(); view.clear(); } public synchronized void addViews(Collection<String> viewPaths) { deVerify(); try { for (String viewPath : viewPaths) { checkPathFormat(viewPath); } for (String viewPath : viewPaths) { addView(viewPath); } } catch (NullPointerException e) { NullPointerException e2 = new NullPointerException("While adding list to view: " + viewPaths); e2.initCause(e); throw e2; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("While adding list to view: " + viewPaths, e); } } public synchronized void addViews(String ... viewPaths) { deVerify(); try { for (String viewPath : viewPaths) { checkPathFormat(viewPath); } for (String viewPath : viewPaths) { addView(viewPath); } } catch (NullPointerException e) { NullPointerException e2 = new NullPointerException("While adding array to view: " + viewPaths); e2.initCause(e); throw e2; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("While adding array to view: " + viewPaths, e); } } public synchronized void addViewSpaceSeparated(String viewPaths) { deVerify(); try { String[] viewPathArray = SPACE_SPLITTER.split(viewPaths.trim()); for (String viewPath : viewPathArray) { if (!"".equals(viewPath)) { checkPathFormat(viewPath); } } for (String viewPath : viewPathArray) { if (!"".equals(viewPath)) { addView(viewPath); } } } catch (NullPointerException e) { NullPointerException e2 = new NullPointerException("While adding space-separated list " + "to view: \"" + viewPaths + "\""); e2.initCause(e); throw e2; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("While adding space-separated list to view: \"" + viewPaths + "\"", e); } } /** * Returns the current view list. This is an unmodifiable copy of the view list as it is at the * point of execution of this method. Changes in this query are not reflected in the result of * this method. The paths listed are normal path expressions without colons or square brackets. * The paths may not have been verified. * * @return a List of String paths */ public synchronized List<String> getView() { return Collections.unmodifiableList(new ArrayList<String>(view)); } public synchronized void addOrderBy(String orderPath, OrderDirection direction) { deVerify(); addOrderBy(new OrderElement(orderPath, direction)); } /** * Removes an element from the order by list of this query. The element should be a normal path * expression, with dots separating the parts. Do not use colons to represent outer joins, and * do not use square brackets to represent subclass constraints. If there are multiple copies * of the path on the order by list (which is an invalid query), then this method will remove * all of them. * * @param orderPath the path String to remove from the order by list * @throws NullPointerException if the orderPath is null * @throws NoSuchElementException if the orderPath is not already in the order by list */ public synchronized void removeOrderBy(String orderPath) { deVerify(); checkPathFormat(orderPath); boolean found = false; int i = 0; while (i < orderBy.size()) { if (orderPath.equals(orderBy.get(i).getOrderPath())) { orderBy.remove(i); found = true; } else { i++; } } if (!found) { throw new NoSuchElementException("Path \"" + orderPath + "\" is not in the order by " + "list: \"" + orderBy + "\" - cannot remove it"); } } /** * Clears the entire order by list. */ public synchronized void clearOrderBy() { deVerify(); orderBy.clear(); } /** * Adds an element to the order by list of this query. The OrderElement will have already * checked the path for format, and the path will not be verified until the verifyQuery() * method is called. * * @param orderElement an OrderElement to add to the order by list * @throws NullPointerException if orderElement is null */ public synchronized void addOrderBy(OrderElement orderElement) { deVerify(); if (orderElement == null) { throw new NullPointerException("Cannot add a null OrderElement to the order by list"); } orderBy.add(orderElement); } /** * Adds a group of elements to the order by list of this query. The elements will have already * checked the paths for format, but the paths will not be verified until the verifyQuery() * method is called. If there is an error with any of the elements of the collection, then none * of the elements will be added and the query will be unchanged. * * @param orderElements a Collection of OrderElement objects to add to the view list * @throws NullPointerException if orderElements is null or contains a null element */ public synchronized void addOrderBys(Collection<OrderElement> orderElements) { deVerify(); if (orderElements == null) { throw new NullPointerException("Cannot add null collection of OrderElements to order by" + " list"); } for (OrderElement orderElement : orderElements) { if (orderElement == null) { throw new NullPointerException("Cannot add null OrderElement (from collection \"" + orderElements + "\") to the order by list"); } } for (OrderElement orderElement : orderElements) { addOrderBy(orderElement); } } /** * Adds a group of elements to the order by list of this query. The elements will have already * checked the paths for format, but the paths will not be verified until the verifyQuery() * method is called. If there is an error with any of the elements in this array/varargs, then * none of the elements will be added and the query will be unchanged. * * @param orderElements an array/varargs of OrderElement objects to add to the view list * @throws NullPointerException if orderElements is null or contains a null element */ public synchronized void addOrderBys(OrderElement ... orderElements) { deVerify(); if (orderElements == null) { throw new NullPointerException("Cannot add null array of OrderElements to order by " + "list"); } for (OrderElement orderElement : orderElements) { if (orderElement == null) { throw new NullPointerException("Cannot add null OrderElement (from array \"" + orderElements + "\") to the order by list"); } } for (OrderElement orderElement : orderElements) { addOrderBy(orderElement); } } public synchronized void addOrderBySpaceSeparated(String orderString) { deVerify(); try { String[] orderPathArray = SPACE_SPLITTER.split(orderString.trim()); if (orderPathArray.length % 2 != 0) { throw new IllegalArgumentException("Order String must contain alternating paths and" + " directions, so must have an even number of space-separated elements."); } List<OrderElement> toAdd = new ArrayList<OrderElement>(); for (int i = 0; i < orderPathArray.length - 1; i += 2) { if ("asc".equals(orderPathArray[i + 1].toLowerCase())) { toAdd.add(new OrderElement(orderPathArray[i], OrderDirection.ASC)); } else if ("desc".equals(orderPathArray[i + 1].toLowerCase())) { toAdd.add(new OrderElement(orderPathArray[i], OrderDirection.DESC)); } else { throw new IllegalArgumentException("Order direction \"" + orderPathArray[i + 1] + "\" must be either \"asc\" or \"desc\""); } } addOrderBys(toAdd); } catch (NullPointerException e) { NullPointerException e2 = new NullPointerException("While adding space-separated list " + "to order by: \"" + orderString + "\""); e2.initCause(e); throw e2; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("While adding space-separated list to order by: \"" + orderString + "\""); } } /** * Returns the current order by list. This is an unmodifiable copy of the order by list as it is * at the point of execution of this method. Changes in this query are not reflected in the * result of this method. The returned value is a List containing OrderElement objects, which * contain a String path expression without colons or square brackets, and an OrderDirection. * The paths may not have been verified. * * @return a List of OrderElement objects */ public synchronized List<OrderElement> getOrderBy() { return Collections.unmodifiableList(new ArrayList<OrderElement>(orderBy)); } /** * Adds a PathConstraint to this query. The PathConstraint will be attached to the path in the * constraint, which will have already been checked for format (no colons or square brackets), * but will not be verified until the verifyQuery() method is called. This method returns a * String code which is a single character that can be used in the constraint logic to logically * combine constraints. The constraint will be added to the existing constraint logic with the * AND operator - for any other arrangement, set the logic after calling this method. If the * constraint is already present in the query, then this method will do nothing. * * @param constraint the PathConstraint to add to this query * @return a String constraint code for use in the constraint logic * @throws NullPointerException if the constraint is null */ public synchronized String addConstraint(PathConstraint constraint) { deVerify(); if (constraint == null) { throw new NullPointerException("Cannot add a null constraint to this query"); } if (constraints.containsKey(constraint)) { return constraints.get(constraint); } if (constraint instanceof PathConstraintSubclass) { // Subclass constraints don't get a code constraints.put(constraint, null); return null; } Set<String> usedCodes = new HashSet<String>(constraints.values()); char charCode = 'A'; String code = "A"; while (usedCodes.contains(code)) { charCode++; code = "" + charCode; } if (logic == null) { logic = new LogicExpression(code); } else { logic = new LogicExpression("(" + logic.toString() + ") AND " + code); } constraints.put(constraint, code); return code; } public synchronized void addConstraint(PathConstraint constraint, String code) { deVerify(); if (constraint == null) { throw new NullPointerException("Cannot add a null constraint to this query"); } if (constraint instanceof PathConstraintSubclass) { throw new IllegalArgumentException("Cannot associate a code with a subclass constraint." + " Use the addConstraint(PathConstraint) method instead"); } if (code == null) { throw new NullPointerException("Cannot use a null code for a constraint in this query"); } if ((code.length() != 1) || (code.charAt(0) > MAX_CODE) || (code.charAt(0) < MIN_CODE)) { throw new IllegalArgumentException("The constraint code must be a single plain latin " + "uppercase character"); } if (constraints.containsKey(constraint)) { if (code.equals(constraints.get(constraint))) { // Trying to add an identical constraint at the same code. return; } else { throw new IllegalStateException("Given constraint is already associated with code " + constraints.get(constraint) + " - cannot associate with code " + code + "for query " + this.toString()); } } Set<String> usedCodes = new HashSet<String>(constraints.values()); if (usedCodes.contains(code)) { throw new IllegalStateException("Given code " + code + " from constraint " + constraint + " conflicts with an existing constraint for query " + this.toString()); } if (logic == null) { logic = new LogicExpression(code); } else { logic = new LogicExpression("(" + logic.toString() + ") AND " + code); } constraints.put(constraint, code); } /** * Removes a constraint from this query. The PathConstraint should be a constraint that already * exists in this query. The constraint will also be removed from the constraint logic. * * @param constraint the PathConstraint to remove from this query * @throws NullPointerException if the constraint is null * @throws NoSuchElementException if the constraint is not present in the query */ public synchronized void removeConstraint(PathConstraint constraint) { deVerify(); if (constraint == null) { throw new NullPointerException("Cannot remove null constraint from this query"); } if (constraints.containsKey(constraint)) { String code = constraints.remove(constraint); if (code != null) { if (logic.getVariableNames().size() > 1) { logic.removeVariable(code); } else { logic = null; } } } else { throw new NoSuchElementException("Constraint to remove is not present in query"); } } public synchronized void replaceConstraint(PathConstraint old, PathConstraint replacement) { deVerify(); if (old == null) { throw new NullPointerException("Cannot replace a null constraint"); } if (replacement == null) { throw new NullPointerException("Cannot replace a constraint with null"); } if (!constraints.containsKey(old)) { throw new NoSuchElementException("Old constraint is not in the query"); } if (constraints.containsKey(replacement)) { throw new IllegalStateException("Replacement constraint is already in the query"); } String code = constraints.get(old); // Read the next line very carefully! if ((replacement instanceof PathConstraintSubclass) != (code == null)) { throw new IllegalArgumentException("Cannot replace a " + old.getClass().getSimpleName() + " with a " + replacement.getClass().getSimpleName()); } Map<PathConstraint, String> temp = new LinkedHashMap<PathConstraint, String>(constraints); constraints.clear(); for (Map.Entry<PathConstraint, String> entry : temp.entrySet()) { if (old.equals(entry.getKey())) { constraints.put(replacement, code); } else { constraints.put(entry.getKey(), entry.getValue()); } } } /** * Clears the entire set of constraints from this query, and resets the constraint logic. */ public synchronized void clearConstraints() { deVerify(); constraints.clear(); logic = null; } /** * Adds a collection of constraints to this query. The PathConstraints will be attached to the * paths in the constraints, which will have already been checked for format (no colons or * square brackets), but will not be verified until the verifyQuery() method is called. The * constraints will all be given codes, and added to the constraint logic with the default AND * operator. To discover the codes, use the getConstraints() method. If there is an error with * any of the elements in the collection, then none of the elements will be added and the * query will be unchanged. * * @param constraintList the PathConstraint objects to add to this query * @throws NullPointerException if constraints is null, or if it contains a null element */ public synchronized void addConstraints(Collection<PathConstraint> constraintList) { deVerify(); if (constraintList == null) { throw new NullPointerException("Cannot add null collection of PathConstraints to this " + "query"); } for (PathConstraint constraint : constraintList) { if (constraint == null) { throw new NullPointerException("Cannot add null PathConstraint (from collection \"" + constraintList + "\" to this query"); } } for (PathConstraint constraint : constraintList) { addConstraint(constraint); } } /** * Adds a group of constraints to this query. The PathConstraints will be attached to the paths * in the constraints, which will have already been checked for format (no colons or square * brackets), but will not be verified until the verifyQuery() method is called. The constraints * will all be given codes, and added to the constraint logic with the default AND operator. To * discover the codes, use the getConstraints() method. If there is an error with any of the * elements in the array/varargs, then none of the elements will be added and the query will be * unchanged. * * @param constraintList the PathConstraint objects to add to this query * @throws NullPointerException if constraints is null, or if it contains a null element */ public synchronized void addConstraints(PathConstraint ... constraintList) { deVerify(); if (constraintList == null) { throw new NullPointerException("Cannot add null array of PathConstraints to this " + "query"); } for (PathConstraint constraint : constraintList) { if (constraint == null) { throw new NullPointerException("Cannot add null PathConstraint (from array \"" + constraintList + "\" to this query"); } } for (PathConstraint constraint : constraintList) { addConstraint(constraint); } } /** * Returns a Map of all the constraints in this query, from PathConstraint to the constraint * code used in the constraint logic. This returns an unmodifiable copy of the data in the * query at the moment this method is executed, so further changes to the query are not * reflected in the returned value. * * @return a Map from PathConstraint to String constraint code (a single character) */ public synchronized Map<PathConstraint, String> getConstraints() { Map<PathConstraint, String> retval = new LinkedHashMap<PathConstraint, String>(constraints); return retval; } /** * Returns the PathConstraint associated with a given code. * * @param code a single uppercase character * @return a PathConstraint object * @throws NullPointerException if code is null * @throws NoSuchElementException if there is no PathConstraint for that code */ public synchronized PathConstraint getConstraintForCode(String code) { for (Map.Entry<PathConstraint, String> entry : constraints.entrySet()) { if (code.equals(entry.getValue())) { return entry.getKey(); } } throw new NoSuchElementException("No constraint is associated with code " + code + ", valid codes are " + constraints.values()); } /** * Returns a list of PathConstraints applied to a given path or an empty list. * * @param path the path to fetch constraints for * @return a List of PathConstraints or an empty list */ public synchronized List<PathConstraint> getConstraintsForPath(String path) { List<PathConstraint> retval = new ArrayList<PathConstraint>(); for (PathConstraint con : constraints.keySet()) { if (con.getPath().equals(path)) { retval.add(con); } } return Collections.unmodifiableList(retval); } /** * Return the constraint codes used in the query, some constraint types (subclasses) don't * get assigned a code, these are not included. This method returns all of the codes that * should be involved in the logic expression of the query. * @return the constraint codes used in this query */ public synchronized Set<String> getConstraintCodes() { Set<String> codes = new HashSet<String>(); for (String code : constraints.values()) { if (code != null) { codes.add(code); } } return codes; } /** * Returns the current constraint logic. The logic is returned in groups, according to the outer * join layout of the query. Two codes in separate groups can only be combined with an AND * operation, not an OR operation. * * @return the current constraint logic */ public synchronized String getConstraintLogic() { return (logic == null ? "" : logic.toString()); } /** * Sets the current constraint logic. * * @param logic the constraint logic */ public synchronized void setConstraintLogic(String logic) { // TODO method does not work properly allowing (A and B) or C on Outer Joins deVerify(); if (constraints.isEmpty()) { this.logic = null; } else { this.logic = new LogicExpression(logic); for (String code : constraints.values()) { if (!this.logic.getVariableNames().contains(code)) { this.logic = new LogicExpression("(" + this.logic.toString() + ") and " + code); } } this.logic.removeAllVariablesExcept(constraints.values()); } } public synchronized OuterJoinStatus getOuterJoinStatus(String path) { checkPathFormat(path); return outerJoinStatus.get(path); } public synchronized void setOuterJoinStatus(String path, OuterJoinStatus status) { deVerify(); checkPathFormat(path); if (status == null) { outerJoinStatus.remove(path); } else { outerJoinStatus.put(path, status); } } /** * Returns an unmodifiable Map which is a copy of the current outer join status of this query at * the time of execution of this method. Further changes to this object will not be reflected in * the object that was returned from this method. * * @return a Map from String path to OuterJoinStatus */ public synchronized Map<String, OuterJoinStatus> getOuterJoinStatus() { return Collections.unmodifiableMap( new LinkedHashMap<String, OuterJoinStatus>(outerJoinStatus)); } /** * Clears all outer join status data from this query. */ public synchronized void clearOuterJoinStatus() { deVerify(); outerJoinStatus.clear(); } /** * Returns a Map from path to TRUE for all paths that are outer joined. That is, if the path is * an outer join (not referring to its parents - use isCompletelyInner() for that), then it is * present in this map mapped onto the value TRUE. * * @return a Map from String to Boolean TRUE */ public synchronized Map<String, Boolean> getOuterMap() { Map<String, Boolean> retval = new HashMap<String, Boolean>(); for (Map.Entry<String, OuterJoinStatus> stat : outerJoinStatus.entrySet()) { if (OuterJoinStatus.OUTER.equals(stat.getValue())) { retval.put(stat.getKey(), Boolean.TRUE); } } return retval; } public synchronized String getDescription(String path) { checkPathFormat(path); return descriptions.get(path); } public synchronized void setDescription(String path, String description) { deVerify(); checkPathFormat(path); if (description == null) { descriptions.remove(path); } else { descriptions.put(path, description); } } /** * Returns an unmodifiable Map which is a copy of the current set of path descriptions of this * query at the time of execution of this method. Further changes to this object will not * be reflected in the object that was returned from this method. * * @return a Map from String path to description */ public synchronized Map<String, String> getDescriptions() { return Collections.unmodifiableMap(new LinkedHashMap<String, String>(descriptions)); } /** * Removes all path descriptions from this query. */ public synchronized void clearDescriptions() { deVerify(); descriptions.clear(); } public synchronized String getGeneratedPathDescription(String path) { checkPathFormat(path); String retval = descriptions.get(path); if (retval == null) { int lastDot = path.lastIndexOf('.'); if (lastDot == -1) { return path; } else { return getGeneratedPathDescription(path.substring(0, lastDot)) + " > " + path.substring(lastDot + 1); } } else { return retval; } } /** * Returns the paths descriptions for the view. * @param pq * @return A list of column names */ public List<String> getColumnHeaders() { List<String> columnNames = new ArrayList<String>(); for (String viewString : getView()) { columnNames.add(getGeneratedPathDescription(viewString)); } return columnNames; } // The two attributes description and title are used for display // in various queries contexts. /** * Sets the description for this PathQuery. * * @param description the new description, or null for none */ public synchronized void setDescription(String description) { deVerify(); this.description = description; } /** * Gets the description for this PathQuery. * * @return description */ public synchronized String getDescription() { return description; } /** * Gets the title for this query. * @return The title of the query */ public String getTitle() { return title; } /** * Sets the name of the query. * @param title the new title, or null for none. */ public void setTitle(String title) { deVerify(); this.title = title; } public synchronized void removeAllUnder(String path) { checkPathFormat(path); deVerify(); for (String v : getView()) { if (isPathUnder(path, v)) { removeView(v); } } for (OrderElement order : getOrderBy()) { if (isPathUnder(path, order.getOrderPath())) { removeOrderBy(order.getOrderPath()); } } for (PathConstraint con : getConstraints().keySet()) { if (isPathUnder(path, con.getPath())) { removeConstraint(con); } } for (String join : getOuterJoinStatus().keySet()) { if (isPathUnder(path, join)) { setOuterJoinStatus(join, null); } } for (String desc : getDescriptions().keySet()) { if (isPathUnder(desc, path) && !isAnyViewWithPathUnder(desc)) { setDescription(desc, null); } } } private static boolean isPathUnder(String parent, String child) { if (parent.equals(child)) { return true; } return child.startsWith(parent + "."); } private boolean isAnyViewWithPathUnder(String parent) { for (String v : getView()) { if (parent.equals(v) || v.startsWith(parent + ".")) { return true; } } return false; } /** * Removes everything from this query that is irrelevant, and therefore making the query * invalid. If the query is invalid for other reasons, then this method will either throw an * exception or ignore that part of the query, depending on the error, however the query is * unlikely to be made valid. * * @throws PathException if the query is invalid for a reason other than irrelevance */ public synchronized void removeAllIrrelevant() throws PathException { deVerify(); List<String> problems = new ArrayList<String>(); // Validate subclass constraints and build subclass constraint map buildSubclassMap(problems); rootClass = null; Set<String> validMainPaths = new LinkedHashSet<String>(); // Validate view paths validateView(problems, validMainPaths); // Validate constraints validateConstraints(problems, validMainPaths); // Now the validMainPaths set contains all the main (ie class) paths that are permitted in // this query. if (!problems.isEmpty()) { throw new PathException(problems.toString(), null); } for (OrderElement order : getOrderBy()) { Path path = new Path(model, order.getOrderPath(), subclasses); if (path.endIsAttribute()) { path = path.getPrefix(); } if (!validMainPaths.contains(path.getNoConstraintsString())) { removeOrderBy(order.getOrderPath()); } } for (String join : getOuterJoinStatus().keySet()) { Path path = new Path(model, join, subclasses); if (path.endIsAttribute()) { path = path.getPrefix(); } if (!validMainPaths.contains(path.getNoConstraintsString())) { setOuterJoinStatus(join, null); } } for (String desc : getDescriptions().keySet()) { Path path = new Path(model, desc, subclasses); if (path.endIsAttribute()) { path = path.getPrefix(); } if (!validMainPaths.contains(path.getNoConstraintsString())) { setDescription(desc, null); } } } /** * Fixes up the order by list and the constraint logic, given the arrangement of outer joins in * the query. * * @return a List of messages about the changes that this method has made to the query * @throws PathException if the query is invalid in any way other than that which this method * will fix. */ public synchronized List<String> fixUpForJoinStyle() throws PathException { deVerify(); List<String> problems = new ArrayList<String>(); // Validate subclass constraints and build subclass constraint map buildSubclassMap(problems); rootClass = null; Set<String> validMainPaths = new LinkedHashSet<String>(); // Validate view paths validateView(problems, validMainPaths); // Validate constraints validateConstraints(problems, validMainPaths); // Now the validMainPaths set contains all the main (ie class) paths that are permitted in // this query. validateOuterJoins(problems, validMainPaths); calculateConstraintGroups(problems); if (!problems.isEmpty()) { throw new PathException(problems.toString(), null); } List<String> messages = new ArrayList<String>(); for (OrderElement order : getOrderBy()) { // We cannot rely on the query being valid, as we are trying to make it valid! String orderString = order.getOrderPath(); boolean outer = false; while (orderString.contains(".")) { if (OuterJoinStatus.OUTER.equals(outerJoinStatus.get(orderString))) { outer = true; break; } orderString = orderString.substring(0, orderString.lastIndexOf('.')); } if (outer) { removeOrderBy(order.getOrderPath()); messages.add("Removed path " + order.getOrderPath() + " from ORDER BY because of " + "outer joins"); } } if (logic != null) { List<Set<String>> groups = new ArrayList<Set<String>>(constraintGroups.values()); try { logic.split(groups); } catch (IllegalArgumentException e) { // The logic is invalid - we need to straighten it up. String oldLogic = logic.toString(); logic = logic.validateForGroups(groups); messages.add("Changed constraint logic from " + oldLogic + " to " + logic.toString() + " because of outer joins"); } } return messages; } public synchronized List<String> removeSubclassAndFixUp(String path) throws PathException { checkPathFormat(path); List<String> problems = verifyQuery(); if (!problems.isEmpty()) { throw new PathException("Query does not verify: " + problems, null); } deVerify(); List<String> messages = new ArrayList<String>(); PathConstraint toRemove = null; for (PathConstraint con : getConstraints().keySet()) { if (con instanceof PathConstraintSubclass) { if (con.getPath().equals(path)) { toRemove = con; break; } } } if (toRemove == null) { return messages; } removeConstraint(toRemove); buildSubclassMap(problems); // Remove things from view for (String viewPath : getView()) { try { @SuppressWarnings("unused") Path viewPathObj = new Path(model, viewPath, subclasses); } catch (PathException e) { // This one is now invalid. Remove removeView(viewPath); messages.add("Removed path " + viewPath + " from view, because you removed the " + "subclass constraint that it depended on."); } } for (PathConstraint con : getConstraints().keySet()) { try { @SuppressWarnings("unused") Path constraintPath = new Path(model, con.getPath(), subclasses); if (con instanceof PathConstraintLoop) { try { @SuppressWarnings("unused") Path loopPath = new Path(model, ((PathConstraintLoop) con).getLoopPath(), subclasses); } catch (PathException e) { removeConstraint(con); messages.add("Removed constraint " + con + " because you removed the " + "subclass constraint it depended on."); } } } catch (PathException e) { removeConstraint(con); messages.add("Removed constraint " + con + " because you removed the " + "subclass constraint it depended on."); } } for (OrderElement order : getOrderBy()) { try { @SuppressWarnings("unused") Path orderPath = new Path(model, order.getOrderPath(), subclasses); } catch (PathException e) { removeOrderBy(order.getOrderPath()); messages.add("Removed path " + order.getOrderPath() + " from ORDER BY, because you " + "removed the subclass constraint it depended on."); } } for (String join : getOuterJoinStatus().keySet()) { try { @SuppressWarnings("unused") Path joinPath = new Path(model, join, subclasses); } catch (PathException e) { setOuterJoinStatus(join, null); } } for (String desc : getDescriptions().keySet()) { try { @SuppressWarnings("unused") Path descPath = new Path(model, desc, subclasses); } catch (PathException e) { setDescription(desc, null); messages.add("Removed description on path " + desc + ", because you removed the " + "subclass constraint it depended on."); } } removeAllIrrelevant(); return messages; } /** * Returns a deep copy of this object. The resulting object may be modified without impacting * this object. * * @return a PathQuery */ @Override public PathQuery clone() { try { PathQuery retval = (PathQuery) super.clone(); retval.view = new ArrayList<String>(retval.view); retval.orderBy = new ArrayList<OrderElement>(retval.orderBy); retval.constraints = new LinkedHashMap<PathConstraint, String>(retval.constraints); if (retval.logic != null) { retval.logic = new LogicExpression(retval.logic.toString()); } retval.outerJoinStatus = new LinkedHashMap<String, OuterJoinStatus>(retval .outerJoinStatus); retval.descriptions = new LinkedHashMap<String, String>(retval.descriptions); return retval; } catch (CloneNotSupportedException e) { throw new Error("Should never happen", e); } } /** * Produces a Path object from the given path String, using subclass information from the query. * Note that this method does not verify the query, but merely attempts to extract as much sane * subclass information as possible to construct the Path. * * @param path the String path * @return a Path object * @throws PathException if something goes wrong, or if the path is in an invalid format */ public synchronized Path makePath(String path) throws PathException { Map<String, String> lSubclasses = new HashMap<String, String>(); for (PathConstraint subclass : constraints.keySet()) { if (subclass instanceof PathConstraintSubclass) { lSubclasses.put(subclass.getPath(), ((PathConstraintSubclass) subclass).getType()); } } return new Path(model, path, lSubclasses); } private synchronized void deVerify() { isVerified = false; } /** * Returns true if the query verifies correctly. * * @return a boolean */ public boolean isValid() { return verifyQuery().isEmpty(); } /** * Verifies the contents of this query against the model, and for internal integrity. Returns * a list of String problems that would need to be rectified for this query to pass validation * and be executed. If the return value is an empty List, then the query is valid. * <BR> * This method validates a few important characteristics about the query: * <UL><LI>All subclass constraints must be subclasses of the class they would otherwise be</LI> * <LI>All paths must validate against the model</LI> * <LI>All paths need to extend from the same root class</LI> * <LI>Paths in the order by list, the outer join status, and the descriptions, must all be * attached to classes already defined by the view list and the constraints. Otherwise, it would * be possible to change the number of rows by changing the order</LI> * <LI>All elements of the view list and the order by list must be attributes, and all * paths for outer join status and subclass constraints must not be attributes</LI> * <LI>Subclass constraints cannot be on the root class of the query</LI> * <LI>Loop constraints cannot cross an outer join</LI> * <LI>Check constraint values against their types in the model and specific * characteristics</LI> * <LI>Check constraint logic for sanity and that it can be split into separate ANDed outer * join sections</LI> * </UL> * * @return a List of problems */ public synchronized List<String> verifyQuery() { List<String> problems = new ArrayList<String>(); if (isVerified) { // Query is already verified correctly. Return no problems return problems; } // Validate subclass constraints and build subclass constraint map buildSubclassMap(problems); rootClass = null; Set<String> validMainPaths = new LinkedHashSet<String>(); // Validate view paths validateView(problems, validMainPaths); // Validate constraints validateConstraints(problems, validMainPaths); // Now the validMainPaths set contains all the main (ie class) paths that are permitted in // this query. // Validate subclass constraints against validMainPaths for (PathConstraint constraint : constraints.keySet()) { if (constraint instanceof PathConstraintSubclass) { try { Path path = new Path(model, constraint.getPath(), subclasses); if (path.endIsAttribute()) { // Should have already caught this problem above. Ignore and suppress continue; } } catch (PathException e) { // Should have already been caught above. Ignore, and suppress further checking continue; } if (!validMainPaths.contains(constraint.getPath())) { problems.add("Subclass constraint on path " + constraint.getPath() + " is not relevant to the query"); } } } // Validate outer join paths validateOuterJoins(problems, validMainPaths); // Validate description paths for (String descPath : descriptions.keySet()) { try { Path path = new Path(model, descPath, subclasses); if (path.endIsAttribute()) { path = path.getPrefix(); } if (!validMainPaths.contains(path.getNoConstraintsString())) { problems.add("Description on path " + descPath + " is not relevant to the query"); continue; } } catch (PathException e) { problems.add("Path " + descPath + " for description is not in the model"); continue; } } // Validate order by paths for (OrderElement orderPath : orderBy) { try { Path path = new Path(model, orderPath.getOrderPath(), subclasses); if (!path.endIsAttribute()) { problems.add("Path " + orderPath.getOrderPath() + " in order by list must be " + "an attribute"); continue; } if (!validMainPaths.contains(path.getPrefix().toStringNoConstraints())) { problems.add("Order by element for path " + orderPath.getOrderPath() + " is not relevant to the query"); continue; } if (!rootClass.equals(outerJoinGroups.get(path.getPrefix() .getNoConstraintsString()))) { problems.add("Order by element " + orderPath + " is not in the root outer join group"); } } catch (PathException e) { problems.add("Path " + orderPath.getOrderPath() + " in order by list is not in the model"); continue; } } calculateConstraintGroups(problems); if (logic != null) { if (!doNotVerifyLogic) { try { logic.split(new ArrayList<Set<String>>(constraintGroups.values())); } catch (IllegalArgumentException e) { problems.add("Logic expression is not compatible with outer join status: " + e.getMessage()); } } } if (problems.isEmpty()) { isVerified = true; } return problems; } private void calculateConstraintGroups(List<String> problems) { doNotVerifyLogic = false; // Put all constraints into groups constraintGroups = new LinkedHashMap<String, Set<String>>(); for (Map.Entry<PathConstraint, String> constraintEntry : constraints.entrySet()) { if (constraintEntry.getValue() != null) { try { Path path = new Path(model, constraintEntry.getKey().getPath(), subclasses); if (path.getStartClassDescriptor().getUnqualifiedName().equals(rootClass)) { if (path.endIsAttribute()) { path = path.getPrefix(); } String groupPath = outerJoinGroups.get(path.getNoConstraintsString()); if (groupPath != null) { Set<String> group = constraintGroups.get(groupPath); if (group == null) { group = new HashSet<String>(); constraintGroups.put(groupPath, group); } group.add(constraintEntry.getValue()); } } else { doNotVerifyLogic = true; } } catch (PathException e) { // If this happens, then we have already noted the problem. Ignore. doNotVerifyLogic = true; } } if (constraintEntry.getKey() instanceof PathConstraintLoop) { PathConstraintLoop loop = (PathConstraintLoop) constraintEntry.getKey(); String aGroup = outerJoinGroups.get(loop.getPath()); String bGroup = outerJoinGroups.get(loop.getLoopPath()); // If one of these is null, then we must have recorded a problem above. Ignore. if ((aGroup != null) && (bGroup != null)) { if (!aGroup.equals(bGroup)) { problems.add("Loop constraint " + loop + " crosses an outer join"); continue; } } } } for (String group : new HashSet<String>(outerJoinGroups.values())) { if (!constraintGroups.containsKey(group)) { constraintGroups.put(group, new HashSet<String>()); } } } private void validateOuterJoins(List<String> problems, Set<String> validMainPaths) { for (String joinPath : outerJoinStatus.keySet()) { try { Path path = new Path(model, joinPath, subclasses); if (path.endIsAttribute()) { problems.add("Outer join status on path " + joinPath + " must not be on an attribute"); continue; } if (path.isRootPath()) { problems.add("Outer join status cannot be set on root path " + joinPath); continue; } } catch (PathException e) { problems.add("Path " + joinPath + " for outer join status is not in the model"); continue; } if (!validMainPaths.contains(joinPath)) { problems.add("Outer join status path " + joinPath + " is not relevant to the " + "query"); } } // Calculate outer join groups from the validMainPaths list of paths outerJoinGroups = new LinkedHashMap<String, String>(); for (String validPath : validMainPaths) { try { Path path = new Path(model, validPath, subclasses); while (isInner(path)) { path = path.getPrefix(); } outerJoinGroups.put(validPath, path.getNoConstraintsString()); } catch (PathException e) { // Should never happen, as we have already checked in validateOuterJoins throw new Error(e); } } } private void validateConstraints(List<String> problems, Set<String> validMainPaths) { existingLoops = new HashSet<String>(); // Validate constraint paths for (PathConstraint constraint : constraints.keySet()) { try { Path path = new Path(model, constraint.getPath(), subclasses); if (rootClass == null) { rootClass = path.getStartClassDescriptor().getUnqualifiedName(); } else { String newRootClass = path.getStartClassDescriptor().getUnqualifiedName(); if (!rootClass.equals(newRootClass)) { problems.add("Multiple root classes in query: " + rootClass + " and " + newRootClass); continue; } } if (path.endIsAttribute()) { addValidPaths(validMainPaths, path.getPrefix()); } else { addValidPaths(validMainPaths, path); } if (constraint instanceof PathConstraintAttribute) { if (!path.endIsAttribute()) { problems.add("Constraint " + constraint + " must be on an attribute"); continue; } Class<?> valueType = path.getEndType(); try { TypeUtil.stringToObject(valueType, ((PathConstraintAttribute) constraint).getValue()); } catch (Exception e) { problems.add("Value in constraint " + constraint + " is not in correct " + "format for type of " + DynamicUtil.getFriendlyName(valueType)); continue; } } else if (constraint instanceof PathConstraintNull) { if (path.isRootPath()) { problems.add("Constraint " + constraint + " cannot be applied to the root path"); continue; } if (constraint.getOp().equals(ConstraintOp.IS_NULL)) { if (!path.endIsAttribute()) { problems.add("Constraint " + constraint + " is invalid - can only set IS NULL on an attribute"); continue; } } } else if (constraint instanceof PathConstraintBag) { // We do not check that the bag exists here. Call getBagNames() and check // elsewhere. if (path.endIsAttribute()) { problems.add("Constraint " + constraint + " must not be on an attribute"); continue; } } else if (constraint instanceof PathConstraintIds) { if (path.endIsAttribute()) { problems.add("Constraint " + constraint + " must not be on an attribute"); continue; } } else if (constraint instanceof PathConstraintMultiValue) { if (!path.endIsAttribute()) { problems.add("Constraint " + constraint + " must be on an attribute"); continue; } Class<?> valueType = path.getEndType(); for (String value : ((PathConstraintMultiValue) constraint).getValues()) { try { TypeUtil.stringToObject(valueType, value); } catch (Exception e) { problems.add("Value (" + value + ") in list in constraint " + constraint + " is not in correct format for type of " + DynamicUtil.getFriendlyName(valueType)); continue; } } } else if (constraint instanceof PathConstraintLoop) { if (path.endIsAttribute()) { problems.add("Constraint " + constraint + " must not be on an attribute"); continue; } String loopPathString = ((PathConstraintLoop) constraint).getLoopPath(); try { Path loopPath = new Path(model, loopPathString, subclasses); if (loopPath.endIsAttribute()) { problems.add("Loop path in constraint " + constraint + " must not be an attribute"); continue; } String newRootClass = loopPath.getStartClassDescriptor() .getUnqualifiedName(); if (!rootClass.equals(newRootClass)) { problems.add("Multiple root classes in query: " + rootClass + " and " + newRootClass); continue; } addValidPaths(validMainPaths, loopPath); if (constraint.getPath().equals(loopPathString)) { problems.add("Path " + constraint.getPath() + " may not be looped back on itself"); continue; } if (model.isGeneratedClassesAvailable()) { Class<?> aClass = path.getEndType(); Class<?> bClass = loopPath.getEndType(); if (!(aClass.isAssignableFrom(bClass) || bClass.isAssignableFrom(aClass))) { problems.add("Loop constraint " + constraint + " must loop between similar types"); continue; } } String loop = ((PathConstraintLoop) constraint).getDescriptiveString(); if (existingLoops.contains(loop)) { problems.add("Cannot have two loop constraints between paths " + constraint.getPath() + " and " + loopPathString); continue; } existingLoops.add(loop); } catch (PathException e) { problems.add("Path " + loopPathString + " in loop constraint from " + constraint.getPath() + " is not in the model"); continue; } } else if (constraint instanceof PathConstraintLookup) { if (path.endIsAttribute()) { problems.add("Constraint " + constraint + " must not be on an attribute"); } } else if (constraint instanceof PathConstraintSubclass) { // Do nothing } else { problems.add("Unrecognised constraint type " + constraint.getClass().getName()); continue; } } catch (PathException e) { if (!(constraint instanceof PathConstraintSubclass)) { problems.add("Path " + constraint.getPath() + " in constraint is not in the model"); } } } } private Set<String> validateView(List<String> problems, Set<String> validMainPaths) { for (String viewPath : view) { try { Path path = new Path(model, viewPath, subclasses); if (!path.endIsAttribute()) { problems.add("Path " + viewPath + " in view list must be an attribute"); continue; } if (rootClass == null) { rootClass = path.getStartClassDescriptor().getUnqualifiedName(); } else { String newRootClass = path.getStartClassDescriptor().getUnqualifiedName(); if (!rootClass.equals(newRootClass)) { problems.add("Multiple root classes in query: " + rootClass + " and " + newRootClass); continue; } } addValidPaths(validMainPaths, path.getPrefix()); } catch (PathException e) { problems.add("Path " + viewPath + " in view list is not in the model"); } } return validMainPaths; } private void buildSubclassMap(List<String> problems) { List<PathConstraintSubclass> subclassConstraints = new ArrayList<PathConstraintSubclass>(); for (PathConstraint constraint : constraints.keySet()) { if (constraint instanceof PathConstraintSubclass) { subclassConstraints.add((PathConstraintSubclass) constraint); } } PathConstraintSubclass[] subclassConstraintArray = subclassConstraints.toArray(new PathConstraintSubclass[0]); Arrays.sort(subclassConstraintArray, new Comparator<PathConstraintSubclass>() { @Override public int compare(PathConstraintSubclass o1, PathConstraintSubclass o2) { return o1.getPath().length() - o2.getPath().length(); } }); // subclassConstraintArray should now be in order of increasing length of path string, so it // should be fine to just build the subclass constraints map subclasses = new LinkedHashMap<String, String>(); for (PathConstraintSubclass subclass : subclassConstraintArray) { if (subclasses.containsKey(subclass.getPath())) { problems.add("Cannot have multiple subclass constraints on path " + subclass.getPath()); continue; } Path subclassPath = null; try { subclassPath = new Path(model, subclass.getPath(), subclasses); } catch (PathException e) { problems.add("Path " + subclass.getPath() + " (from subclass constraint) is not in" + " the model"); continue; } if (subclassPath.isRootPath()) { problems.add("Root node " + subclass.getPath() + " may not have a subclass constraint"); continue; } if (subclassPath.endIsAttribute()) { problems.add("Path " + subclass.getPath() + " (from subclass constraint) must not " + "be an attribute"); continue; } ClassDescriptor subclassDesc = model.getClassDescriptorByName(subclass.getType()); if (model.isGeneratedClassesAvailable()) { Class<?> parentClassType = subclassPath.getEndClassDescriptor().getType(); Class<?> subclassType = (subclassDesc == null ? null : subclassDesc.getType()); if (subclassType == null) { problems.add("Subclass " + subclass.getType() + " (for path " + subclass.getPath() + ") is not in the model"); continue; } if (!parentClassType.isAssignableFrom(subclassType)) { problems.add("Subclass constraint on path " + subclass.getPath() + " (type " + DynamicUtil.getFriendlyName(parentClassType) + ") restricting to type " + DynamicUtil.getFriendlyName(subclassType) + " is not possible, as it is " + "not a subclass"); continue; } } subclasses.put(subclass.getPath(), subclass.getType()); } } /** * Returns the root path for this query, if the query verifies correctly. * * @return a String path which is the root class * @throws PathException if the query does not verify */ public synchronized String getRootClass() throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { return rootClass; } throw new PathException("Query does not verify: " + problems, null); } /** * Returns the subclass Map for this query, if the query verifies correctly. * * @return a Map from path String to subclass name, for all PathConstraintSubclass objects * @throws PathException if the query does not verify */ public synchronized Map<String, String> getSubclasses() throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { return Collections.unmodifiableMap(new LinkedHashMap<String, String>(subclasses)); } throw new PathException("Query does not verify: " + problems, null); } /** * Returns all bag names used in constraints on this query. * * @return the bag names used in this query or an empty set */ public synchronized Set<String> getBagNames() { Set<String> bagNames = new HashSet<String>(); for (PathConstraint constraint : constraints.keySet()) { if (constraint instanceof PathConstraintBag) { bagNames.add(((PathConstraintBag) constraint).getBag()); } } return bagNames; } /** * Returns the outer join groups map for this query, if the query verifies correctly. This is a * Map from all the class paths in the query to the outer join group, represented by the path of * the root of the group. * * @return a Map from path String to the outer join group it is in * @throws PathException if the query does not verify */ public synchronized Map<String, String> getOuterJoinGroups() throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { return Collections.unmodifiableMap(new LinkedHashMap<String, String>(outerJoinGroups)); } throw new PathException("Query does not verify: " + problems, null); } /** * Returns the set of loop constraint descriptive strings, for the purpose of checking for * uniqueness. * * @return a Set of Strings * @throws PathException if the query does not verify */ public synchronized Set<String> getExistingLoops() throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { return Collections.unmodifiableSet(new HashSet<String>(existingLoops)); } throw new PathException("Query does not verify: " + problems, null); } /** * Returns the outer join group that the given path is in. * * @param stringPath a pathString * @return a String representing the outer join group that the path is in * @throws NullPointerException if pathString is null * @throws PathException if the query is invalid or the path is invalid * @throws NoSuchElementException is the path is not in the query */ public String getOuterJoinGroup(String stringPath) throws PathException { if (stringPath == null) { throw new NullPointerException("stringPath is null"); } Map<String, String> groups = getOuterJoinGroups(); Path path = makePath(stringPath); if (path.endIsAttribute()) { path = path.getPrefix(); } if (!groups.containsKey(path.getNoConstraintsString())) { throw new NoSuchElementException("Path " + stringPath + " is not in the query"); } return groups.get(path.getNoConstraintsString()); } /** * Returns true if a path string is in the root outer join group of this query. * * @param stringPath a path String * @return true if the given path is in the root outer join group, false if it contains outer * joins * @throws NullPointerException if pathString is null * @throws PathException if the query is invalid or the path is invalid * @throws NoSuchElementException if the path is not in the query */ public boolean isPathCompletelyInner(String stringPath) throws PathException { String root = getRootClass(); return root.equals(getOuterJoinGroup(stringPath)); } public synchronized Set<String> getCandidateLoops(String stringPath) throws PathException { if (stringPath == null) { throw new NullPointerException("stringPath is null"); } Path path = makePath(stringPath); if (path.endIsAttribute()) { throw new IllegalArgumentException("stringPath \"" + stringPath + "\" is an attribute, not a class"); } String lRootClass = getRootClass(); String rootOfStringPath = path.getStartClassDescriptor().getUnqualifiedName(); if ((lRootClass != null) && (!lRootClass.equals(rootOfStringPath))) { throw new NoSuchElementException("Path " + stringPath + " is not in the query"); } if (lRootClass == null) { outerJoinGroups.put(rootOfStringPath, rootOfStringPath); } Map<String, String> groups = new HashMap<String, String>(getOuterJoinGroups()); Path groupPath = path; Set<String> toAdd = new HashSet<String>(); while (!(groups.containsKey(groupPath.getNoConstraintsString()))) { toAdd.add(groupPath.toStringNoConstraints()); groupPath = groupPath.getPrefix(); } String group = groups.get(groupPath.getNoConstraintsString()); for (String toAddElement : toAdd) { groups.put(toAddElement, group); } Class<?> type = path.getEndType(); Set<String> lExistingLoops = getExistingLoops(); Set<String> retval = new HashSet<String>(); for (Map.Entry<String, String> entry : groups.entrySet()) { if (!entry.getKey().equals(stringPath)) { Path entryPath = makePath(entry.getKey()); if (type.isAssignableFrom(entryPath.getEndType()) || entryPath.getEndType().isAssignableFrom(type)) { if (group.equals(entry.getValue())) { String desc = stringPath.compareTo(entry.getKey()) > 0 ? entry.getKey() + " -- " + stringPath : stringPath + " -- " + entry.getKey(); if (!lExistingLoops.contains(desc)) { retval.add(entry.getKey()); } } } } } return retval; } /** * Returns the outer join constraint codes groups map for this query, if the query verifies * correctly. * * @return a Map from outer join group to the Set of constraint codes in the group * @throws PathException if the query does not verify */ public synchronized Map<String, Set<String>> getConstraintGroups() throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { return Collections.unmodifiableMap(new LinkedHashMap<String, Set<String>>( constraintGroups)); } throw new PathException("Query does not verify: " + problems, null); } /** * Returns a List of logic Strings according to the different outer join sections of the query. * * @return a List of String * @throws PathException if the query does not verify */ public synchronized List<String> getGroupedConstraintLogic() throws PathException { if (logic == null) { return Collections.emptyList(); } Map<String, Set<String>> groups = getConstraintGroups(); List<LogicExpression> grouped = logic.split(new ArrayList<Set<String>>(groups.values())); List<String> retval = new ArrayList<String>(); for (LogicExpression group : grouped) { if (group != null) { retval.add(group.toString()); } } return retval; } public synchronized LogicExpression getConstraintLogicForGroup(String group) throws PathException { List<String> problems = verifyQuery(); if (problems.isEmpty()) { if (logic == null) { return null; } else { Set<String> codes = constraintGroups.get(group); if (codes == null) { throw new IllegalArgumentException("Outer join group " + group + " does not seem to be in this query. Valid inputs are " + constraintGroups.keySet()); } if (codes.isEmpty()) { return null; } else { return logic.getSection(codes); } } } throw new PathException("Query does not verify: " + problems, null); } /** * Adds all the parts of a Path to a Set. Call this with only a non-attribute Path. * * @param validMainPaths a Set of Strings to add to * @param path a Path object */ private static void addValidPaths(Set<String> validMainPaths, Path path) { Path pathToAdd = path; while (!pathToAdd.isRootPath()) { validMainPaths.add(pathToAdd.toStringNoConstraints()); pathToAdd = pathToAdd.getPrefix(); } validMainPaths.add(pathToAdd.toStringNoConstraints()); } private boolean isInner(Path path) { if (path.isRootPath()) { return false; } if (path.endIsAttribute()) { throw new IllegalArgumentException("Cannot call isInner() with a path that is an " + "attribute"); } OuterJoinStatus status = getOuterJoinStatus(path.getNoConstraintsString()); if (OuterJoinStatus.INNER.equals(status)) { return true; } else if (OuterJoinStatus.OUTER.equals(status)) { return false; } // Fall back on defaults return true; } private static final Pattern PATH_MATCHER = Pattern.compile("([a-zA-Z0-9]+\\.)*[a-zA-Z0-9]+"); public static void checkPathFormat(String path) { if (path == null) { throw new NullPointerException("Path must not be null"); } if (!PATH_MATCHER.matcher(path).matches()) { throw new IllegalArgumentException("Path \"" + path + "\" does not match regular " + "expression \"([a-zA-Z0-9]+\\.)*[a-zA-Z0-9]+\""); } } /** * Get the PathQuery that should be executed. This should be called by code creating an * ObjectStore query from a PathQuery. For PathQuery the method returns this, subclasses can * override. TemplateQuery removes optional constraints that have been switched off in the * returned query. * @return a version of the query to execute */ public PathQuery getQueryToExecute() { return this; } /** * A method to sort constraints by a given lists, provided to allow TemplateQuery to set a * specific sort order that will be preserved in a round-trip to XML. A list of constraints * is provided, the constraints map is updated to reflect that order. The list does not need * to contain all constraints in the query - TemplateQuery only needs to order the editable * constraints. * @param listToSortBy a list to define the new constraint order */ protected synchronized void sortConstraints(List<PathConstraint> listToSortBy) { ConstraintComparator comparator = new ConstraintComparator(listToSortBy); TreeMap<PathConstraint, String> orderedConstraints = new TreeMap<PathConstraint, String>(comparator); orderedConstraints.putAll(constraints); constraints = new LinkedHashMap<PathConstraint, String>(orderedConstraints); } private class ConstraintComparator implements Comparator<PathConstraint> { private final List<PathConstraint> listToSortBy; public ConstraintComparator (List<PathConstraint> listToSortBy) { this.listToSortBy = listToSortBy; } @Override public int compare(PathConstraint c1, PathConstraint c2) { // if neither in list we don't care how they compare, but want a consistent order if (!listToSortBy.contains(c1) && !listToSortBy.contains(c2)) { return -1; } // otherwise put lowest index first, if not in list indexOf() will return -1 so // constraints not in list will move to start return (listToSortBy.indexOf(c1) < listToSortBy.indexOf(c2)) ? -1 : 1; } } /** * Converts this object into a rudimentary String format, containing all the data. * * {@inheritDoc} */ @Override public synchronized String toString() { return "PathQuery( view: " + view + ", orderBy: " + orderBy + ", constraints: " + constraints + ", logic: " + logic + ", outerJoinStatus: " + outerJoinStatus + ", descriptions: " + descriptions + ", description: " + description + ")"; } /** * Convert a PathQuery to XML, using the default value of PathQuery.USERPROFILE_VERSION * @return This query as xml */ public synchronized String toXml() { return this.toXml(PathQuery.USERPROFILE_VERSION); } /** * Convert a PathQuery to XML. * * @param version the version number of the XML format * @return this template query as XML. */ public synchronized String toXml(int version) { StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(sw); PathQueryBinding.marshal(this, "query", model.getName(), writer, version); } catch (XMLStreamException e) { throw new RuntimeException(e); } return sw.toString(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof PathQuery) { return ((PathQuery) other).toXml().equals(this.toXml()); } return false; } @Override public int hashCode() { return toXml().hashCode(); } }
package org.deuce.transform.asm; import java.util.LinkedList; import org.deuce.objectweb.asm.AnnotationVisitor; import org.deuce.objectweb.asm.FieldVisitor; import org.deuce.objectweb.asm.MethodVisitor; import org.deuce.objectweb.asm.Opcodes; import org.deuce.objectweb.asm.Type; import org.deuce.objectweb.asm.commons.Method; import org.deuce.transaction.Context; import org.deuce.transform.Exclude; import org.deuce.transform.util.Util; @Exclude public class ClassTransformer extends ByteCodeVisitor{ private boolean exclude = false; private boolean visitclinit = false; final private LinkedList<Field> fields = new LinkedList<Field>(); private Field staticField = null; public ClassTransformer( String className){ super( className); } /** * Checks if the class is marked as {@link Exclude @Exclude} */ @Override public AnnotationVisitor visitAnnotation( String desc, boolean visible) { exclude = exclude ? exclude : Type.getDescriptor(Exclude.class).equals(desc); return super.visitAnnotation(desc, visible); } /** * Creates a new static filed for each existing field. * The field will be statically initialized to hold the field address. */ @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { FieldVisitor fieldVisitor = super.visitField(access, name, desc, signature, value); if( exclude) return fieldVisitor; String addressFieldName = Util.getAddressField( name); int fieldAccess = Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; Field field = new Field(name, addressFieldName); fields.add( field); if( staticField == null && (access & Opcodes.ACC_STATIC) != 0) staticField = field; super.visitField( fieldAccess, addressFieldName, Type.LONG_TYPE.getDescriptor(), null, null); return fieldVisitor; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor originalMethod = super.visitMethod(access, name, desc, signature, exceptions); if( exclude) return originalMethod; if( name.equals("<clinit>")) { visitclinit = true; int fieldAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC; super.visitField( fieldAccess, StaticMethodTransformer.CLASS_BASE, Type.getDescriptor(Object.class), null, null); return new StaticMethodTransformer( originalMethod, fields, className, staticField); } else { Method newMethod = createNewMethod(name, desc); MethodVisitor copyMethod = super.visitMethod(access, name, newMethod.getDescriptor(), signature, exceptions); return new MethodTransformer( originalMethod, copyMethod, className, access, name, desc, newMethod); } } @Override public void visitEnd() { if( !exclude & !visitclinit) { visitclinit = true; MethodVisitor method = visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); method.visitCode(); method.visitInsn(Opcodes.RETURN); method.visitMaxs(100, 100); // TODO set the right value method.visitEnd(); } super.visitEnd(); } public static Method createNewMethod(String name, String desc) { Method method = new Method( name, desc); Type[] arguments = method.getArgumentTypes(); Type[] newArguments = new Type[ arguments.length + 1]; System.arraycopy( arguments, 0, newArguments, 0, arguments.length); newArguments[newArguments.length - 1] = Context.CONTEXT_TYPE; // add as a constant Method newMethod = new Method( name, method.getReturnType(), newArguments); return newMethod; } }
package org.jdesktop.swingx.painter; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import javax.swing.JComponent; /** * <p>A Painter implementation that simulates a gloss effect. The gloss can * be positionned at the top or bottom of the drawing area. To fill the gloss, * this painter uses a Paint instance which can be used to fill with a color * (opaque or translucent), a texture, a gradient...</p> * <p>The following example creates a white gloss at the top of the drawing * area:</p> * <pre> * GlossPainter p = new GlossPainter(); * p.setPaint(new Color(1.0f, 1.0f, 1.0f, 0.2f); * p.setPosition(GlossPainter.GlossPosition.TOP); * panel.setBackgroundPainter(p); * </pre> * <p>The values shown in this examples are the values used by default if * they are not specified.</p> * * @author Romain Guy <romain.guy@mac.com> */ public class GlossPainter extends AbstractPainter { /** * <p>Used to define the position of the gloss on the painted area.</p> */ public enum GlossPosition { TOP, BOTTOM } private Paint paint; private GlossPosition position; /** * <p>Creates a new gloss painter positionned at the top of the painted * area with a 20% translucent white color.</p> */ public GlossPainter() { this(new Color(1.0f, 1.0f, 1.0f, 0.2f), GlossPosition.TOP); } /** * <p>Creates a new gloss painter positionned at the top of the painted * area with the specified paint.</p> * * @param paint The paint to be used when filling the gloss */ public GlossPainter(Paint paint) { this(paint, GlossPosition.TOP); } /** * <p>Creates a new gloss painter positionned at the specified position * and using a white, 20% translucent paint.</p> * * @param position The position of the gloss on the painted area */ public GlossPainter(GlossPosition position) { this(new Color(1.0f, 1.0f, 1.0f, 0.2f), position); } /** * <p>Creates a new gloss painter positionned at the specified position * and painted with the specified paint.</p> * * @param paint The paint to be used when filling the gloss * @param position The position of the gloss on the painted area */ public GlossPainter(Paint paint, GlossPosition position) { this.setPaint(paint); this.setPosition(position); setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } /** * {@inheritDoc} */ protected void paintBackground(Graphics2D g, JComponent component) { if (getPaint() != null) { Ellipse2D ellipse = new Ellipse2D.Double(-component.getWidth() / 2.0, component.getHeight() / 2.7, component.getWidth() * 2.0, component.getHeight() * 2.0); Area gloss = new Area(ellipse); if (getPosition() == GlossPosition.TOP) { Area area = new Area(new Rectangle(0, 0, component.getWidth(), component.getHeight())); area.subtract(new Area(ellipse)); gloss = area; } if(getClip() != null) { gloss.intersect(new Area(getClip())); } g.setPaint(getPaint()); g.fill(gloss); } } /** * <p>Returns the paint currently used by the painter to fill the gloss.</p> * * @return the current Paint instance used by the painter */ public Paint getPaint() { return paint; } /** * <p>Changes the paint to be used to fill the gloss. When the specified * paint is null, nothing is painted. A paint can be an instance of * Color.</p> * * @param paint The Paint instance to be used to fill the gloss */ public void setPaint(Paint paint) { Paint old = this.paint; this.paint = paint; firePropertyChange("paint", old, getPaint()); } /** * <p>Returns the position at which the gloss is painted.</p> * * @return the position of the gloss in the painted area */ public GlossPosition getPosition() { return position; } /** * <p>Changes the position of the gloss in the painted area. Only the * values defined in the GlossPosition enum are valid.</p> * * @param position The position at which the gloss is painted */ public void setPosition(GlossPosition position) { GlossPosition old = this.position; this.position = position; firePropertyChange("position", old, getPosition()); } }
package org.jivesoftware.spark.util; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Label; import java.awt.MediaTracker; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPopupMenu; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.spark.util.log.Log; /** * <code>GraphicsUtils</code> class defines common user-interface related utility * functions. */ public final class GraphicUtils { private static final Insets HIGHLIGHT_INSETS = new Insets(1, 1, 1, 1); public static final Color SELECTION_COLOR = new java.awt.Color(166, 202, 240); public static final Color TOOLTIP_COLOR = new java.awt.Color(166, 202, 240); protected final static Component component = new Component() { private static final long serialVersionUID = -7556405112141454291L; }; protected final static MediaTracker tracker = new MediaTracker(component); private static Map<String,Image> imageCache = new HashMap<String,Image>(); /** * The default Hand cursor. */ public static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR); /** * The default Text Cursor. */ public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); private GraphicUtils() { } /** * Sets the location of the specified window so that it is centered on screen. * * @param window The window to be centered. */ public static void centerWindowOnScreen(Window window) { final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); final Dimension size = window.getSize(); if (size.height > screenSize.height) { size.height = screenSize.height; } if (size.width > screenSize.width) { size.width = screenSize.width; } window.setLocation((screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2); } /** * Draws a single-line highlight border rectangle. * * @param g The graphics context to use for drawing. * @param x The left edge of the border. * @param y The top edge of the border. * @param width The width of the border. * @param height The height of the border. * @param raised <code>true</code> if the border is to be drawn raised, * <code>false</code> if lowered. * @param shadow The shadow color for the border. * @param highlight The highlight color for the border. * @see javax.swing.border.EtchedBorder */ public static void drawHighlightBorder(Graphics g, int x, int y, int width, int height, boolean raised, Color shadow, Color highlight) { final Color oldColor = g.getColor(); g.translate(x, y); g.setColor(raised ? highlight : shadow); g.drawLine(0, 0, width - 2, 0); g.drawLine(0, 1, 0, height - 2); g.setColor(raised ? shadow : highlight); g.drawLine(width - 1, 0, width - 1, height - 1); g.drawLine(0, height - 1, width - 2, height - 1); g.translate(-x, -y); g.setColor(oldColor); } /** * Return the amount of space taken up by a highlight border drawn by * <code>drawHighlightBorder()</code>. * * @return The <code>Insets</code> needed for the highlight border. * @see #drawHighlightBorder */ public static Insets getHighlightBorderInsets() { return HIGHLIGHT_INSETS; } public static ImageIcon createImageIcon(Image image) { if (image == null) { return null; } synchronized (tracker) { tracker.addImage(image, 0); try { tracker.waitForID(0, 0); } catch (InterruptedException e) { System.out.println("INTERRUPTED while loading Image"); } tracker.removeImage(image, 0); } return new ImageIcon(image); } /** * Returns a point where the given popup menu should be shown. The * point is calculated by adjusting the X and Y coordinates from the * given mouse event so that the popup menu will not be clipped by * the screen boundaries. * * @param popup the popup menu * @param event the mouse event * @return the point where the popup menu should be shown */ public static Point getPopupMenuShowPoint(JPopupMenu popup, MouseEvent event) { Component source = (Component)event.getSource(); Point topLeftSource = source.getLocationOnScreen(); Point ptRet = getPopupMenuShowPoint(popup, topLeftSource.x + event.getX(), topLeftSource.y + event.getY()); ptRet.translate(-topLeftSource.x, -topLeftSource.y); return ptRet; } /** * Returns a point where the given popup menu should be shown. The * point is calculated by adjusting the X and Y coordinates so that * the popup menu will not be clipped by the screen boundaries. * * @param popup the popup menu * @param x the x position in screen coordinate * @param y the y position in screen coordinates * @return the point where the popup menu should be shown in screen * coordinates */ public static Point getPopupMenuShowPoint(JPopupMenu popup, int x, int y) { Dimension sizeMenu = popup.getPreferredSize(); Point bottomRightMenu = new Point(x + sizeMenu.width, y + sizeMenu.height); Rectangle[] screensBounds = getScreenBounds(); int n = screensBounds.length; for (int i = 0; i < n; i++) { Rectangle screenBounds = screensBounds[i]; if (screenBounds.x <= x && x <= (screenBounds.x + screenBounds.width)) { Dimension sizeScreen = screenBounds.getSize(); sizeScreen.height -= 32; // Hack to help prevent menu being clipped by Windows/Linux/Solaris Taskbar. int xOffset = 0; if (bottomRightMenu.x > (screenBounds.x + sizeScreen.width)) xOffset = -sizeMenu.width; int yOffset = 0; if (bottomRightMenu.y > (screenBounds.y + sizeScreen.height)) yOffset = sizeScreen.height - bottomRightMenu.y; return new Point(x + xOffset, y + yOffset); } } return new Point(x, y); // ? that would mean that the top left point was not on any screen. } /** * Centers the window over a component (usually another window). * The window must already have been sized. * @param window Window to center. * @param over Component to center over. */ public static void centerWindowOnComponent(Window window, Component over) { if ((over == null) || !over.isShowing()) { centerWindowOnScreen(window); return; } Point parentLocation = over.getLocationOnScreen(); Dimension parentSize = over.getSize(); Dimension size = window.getSize(); // Center it. int x = parentLocation.x + (parentSize.width - size.width) / 2; int y = parentLocation.y + (parentSize.height - size.height) / 2; // Now, make sure it's onscreen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // This doesn't actually work on the Mac, where the screen // doesn't necessarily start at 0,0 if (x + size.width > screenSize.width) x = screenSize.width - size.width; if (x < 0) x = 0; if (y + size.height > screenSize.height) y = screenSize.height - size.height; if (y < 0) y = 0; window.setLocation(x, y); } /** * @param c Component to check on. * @return returns true if the component of one of its child has the focus */ public static boolean isAncestorOfFocusedComponent(Component c) { if (c.hasFocus()) { return true; } else { if (c instanceof Container) { Container cont = (Container)c; int n = cont.getComponentCount(); for (int i = 0; i < n; i++) { Component child = cont.getComponent(i); if (isAncestorOfFocusedComponent(child)) return true; } } } return false; } /** * Returns the first component in the tree of <code>c</code> that can accept * the focus. * * @param c the root of the component hierarchy to search * @see #focusComponentOrChild * @deprecated replaced by {@link #getFocusableComponentOrChild(Component,boolean)} * @return Component that was focused on. */ public static Component getFocusableComponentOrChild(Component c) { return getFocusableComponentOrChild(c, false); } /** * Returns the first component in the tree of <code>c</code> that can accept * the focus. * * @param c the root of the component hierarchy to search * @param deepest if <code>deepest</code> is true the method will return the first and deepest component that can accept the * focus. For example, if both a child and its parent are focusable and <code>deepest</code> is true, the child is * returned. * @see #focusComponentOrChild * @return Component that was focused on. */ public static Component getFocusableComponentOrChild(Component c, boolean deepest) { if (c != null && c.isEnabled() && c.isVisible()) { if (c instanceof Container) { Container cont = (Container)c; if (!deepest) { // first one is a good one if (c instanceof JComponent) { JComponent jc = (JComponent)c; if (jc.isRequestFocusEnabled()) { return jc; } } } int n = cont.getComponentCount(); for (int i = 0; i < n; i++) { Component child = cont.getComponent(i); Component focused = getFocusableComponentOrChild(child, deepest); if (focused != null) { return focused; } } if (c instanceof JComponent) { if (deepest) { JComponent jc = (JComponent)c; if (jc.isRequestFocusEnabled()) { return jc; } } } else { return c; } } } return null; } /** * Puts the focus on the first component in the tree of <code>c</code> that * can accept the focus. * * @see #getFocusableComponentOrChild * @param c Component to focus on. * @return Component that was focused on. */ public static Component focusComponentOrChild(Component c) { return focusComponentOrChild(c, false); } /** * Puts the focus on the first component in the tree of <code>c</code> that * can accept the focus. * * @param c the root of the component hierarchy to search * @param deepest if <code>deepest</code> is true the method will focus the first and deepest component that can * accept the focus. * For example, if both a child and its parent are focusable and <code>deepest</code> is true, the child is focused. * @see #getFocusableComponentOrChild * @return Component that was focused on. */ public static Component focusComponentOrChild(Component c, boolean deepest) { final Component focusable = getFocusableComponentOrChild(c, deepest); if (focusable != null) { focusable.requestFocus(); } return focusable; } /** * Loads an {@link Image} named <code>imageName</code> as a resource * relative to the Class <code>cls</code>. If the <code>Image</code> can * not be loaded, then <code>null</code> is returned. Images loaded here * will be added to an internal cache based upon the full {@link URL} to * their location. * <p/> * <em>This method replaces legacy code from JDeveloper 3.x and earlier.</em> * * @see Class#getResource(String) * @see Toolkit#createImage(URL) * @param imageName Name of the resource to load. * @param cls Class to pull resource from. * @return Image loaded from resource. */ public static Image loadFromResource(String imageName, Class cls) { try { final URL url = cls.getResource(imageName); if (url == null) { return null; } Image image = imageCache.get(url.toString()); if (image == null) { image = Toolkit.getDefaultToolkit().createImage(url); imageCache.put(url.toString(), image); } return image; } catch (Exception e) { Log.error(e); } return null; } public static Rectangle[] getScreenBounds() { GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice[] screenDevices = graphicsEnvironment.getScreenDevices(); Rectangle[] screenBounds = new Rectangle[screenDevices.length]; for (int i = 0; i < screenDevices.length; i++) { GraphicsDevice screenDevice = screenDevices[i]; final GraphicsConfiguration defaultConfiguration = screenDevice.getDefaultConfiguration(); screenBounds[i] = defaultConfiguration.getBounds(); } return screenBounds; } public static void makeSameSize(JComponent... comps) { if (comps.length == 0) { return; } int max = 0; for (JComponent comp1 : comps) { int w = comp1.getPreferredSize().width; max = w > max ? w : max; } Dimension dim = new Dimension(max, comps[0].getPreferredSize().height); for (JComponent comp : comps) { comp.setPreferredSize(dim); } } /** * Return the hexidecimal color from a java.awt.Color * * @param c Color to convert. * @return hexadecimal string */ public static String toHTMLColor(Color c) { int color = c.getRGB(); color |= 0xff000000; String s = Integer.toHexString(color); return s.substring(2); } public static String createToolTip(String text, int width) { final String htmlColor = toHTMLColor(TOOLTIP_COLOR); return "<html><table width=" + width + " bgColor=" + htmlColor + "><tr><td>" + text + "</td></tr></table></table>"; } public static String createToolTip(String text) { final String htmlColor = toHTMLColor(TOOLTIP_COLOR); return "<html><table bgColor=" + htmlColor + "><tr><td>" + text + "</td></tr></table></table>"; } public static String getHighlightedWords(String text, String query) { final StringTokenizer tkn = new StringTokenizer(query, " "); int tokenCount = tkn.countTokens(); String[] words = new String[tokenCount]; for (int j = 0; j < tokenCount; j++) { String queryWord = tkn.nextToken(); words[j] = queryWord; } String highlightedWords; try { highlightedWords = StringUtils.highlightWords(text, words, "<font style=background-color:yellow;font-weight:bold;>", "</font>"); } catch (Exception e) { highlightedWords = text; } return highlightedWords; } public static ImageIcon createShadowPicture(Image buf) { buf = removeTransparency(buf); BufferedImage splash; JLabel label = new JLabel(); int width = buf.getWidth(null); int height = buf.getHeight(null); int extra = 4; splash = new BufferedImage(width + extra, height + extra, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D)splash.getGraphics(); BufferedImage shadow = new BufferedImage(width + extra, height + extra, BufferedImage.TYPE_INT_ARGB); Graphics g = shadow.getGraphics(); g.setColor(new Color(0.0f, 0.0f, 0.0f, 0.3f)); g.fillRoundRect(0, 0, width, height, 12, 12); g2.drawImage(shadow, getBlurOp(7), 0, 0); g2.drawImage(buf, 0, 0, label); return new ImageIcon(splash); } public static BufferedImage removeTransparency(Image image) { int w = image.getWidth(null); int h = image.getHeight(null); BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi2.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.drawImage(image, 0, 0, null); g.dispose(); return bi2; } public static Image toImage(BufferedImage bufferedImage) { return Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource()); } private static ConvolveOp getBlurOp(int size) { float[] data = new float[size * size]; float value = 1 / (float)(size * size); for (int i = 0; i < data.length; i++) { data[i] = value; } return new ConvolveOp(new Kernel(size, size, data)); } public static BufferedImage convert(Image im) throws InterruptedException, IOException { load(im); BufferedImage bi = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics bg = bi.getGraphics(); bg.drawImage(im, 0, 0, null); bg.dispose(); return bi; } public static void load(Image image) throws InterruptedException, IOException { MediaTracker tracker = new MediaTracker(new Label()); //any component will do tracker.addImage(image, 0); tracker.waitForID(0); if (tracker.isErrorID(0)) throw new IOException("error loading image"); } public static byte[] getBytesFromImage(Image image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(convert(image), "PNG", baos); } catch (IOException e) { Log.error(e); } catch (InterruptedException e) { Log.error(e); } return baos.toByteArray(); } /** * Returns a scaled down image if the height or width is smaller than * the image size. * * @param icon the image icon. * @param newHeight the preferred height. * @param newWidth the preferred width. * @return the icon. */ public static ImageIcon scaleImageIcon(ImageIcon icon, int newHeight, int newWidth) { Image img = icon.getImage(); int height = icon.getIconHeight(); int width = icon.getIconWidth(); if (height > newHeight) { height = newHeight; } if (width > newWidth) { width = newWidth; } img = img.getScaledInstance(width, height, Image.SCALE_SMOOTH); return new ImageIcon(img); } /** * Returns a scaled down image if the height or width is smaller than * the image size. * * @param icon the image icon. * @param newHeight the preferred height. * @param newWidth the preferred width. * @return the icon. */ public static ImageIcon scale(ImageIcon icon, int newHeight, int newWidth) { Image img = icon.getImage(); img = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); return new ImageIcon(img); } /** * Returns the native icon, if one exists for the filetype, otherwise * returns a default document icon. * * @param file the file to check icon type. * @return the native icon, otherwise default document icon. */ public static Icon getIcon(File file) { try { sun.awt.shell.ShellFolder sf = sun.awt.shell.ShellFolder.getShellFolder(file); // Get large icon return new ImageIcon(sf.getIcon(true), sf.getFolderType()); } catch (Exception e) { try { return new JFileChooser().getIcon(file); } catch (Exception e1) { // Do nothing. } } return SparkRes.getImageIcon(SparkRes.DOCUMENT_INFO_32x32); } public static BufferedImage getBufferedImage(File file) { // Why wasn't this using it's code that pulled from the file? Hrm. Icon icon = SparkRes.getImageIcon(SparkRes.DOCUMENT_INFO_32x32); BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.OPAQUE); Graphics bg = bi.getGraphics(); ImageIcon i = (ImageIcon)icon; bg.drawImage(i.getImage(), 0, 0, null); bg.dispose(); return bi; } }
package org.neo4j.impl.core; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.neo4j.api.core.NotFoundException; import org.neo4j.api.core.NotInTransactionException; import org.neo4j.impl.persistence.IdGenerator; import org.neo4j.impl.persistence.PersistenceManager; import org.neo4j.impl.util.ArrayMap; public class PropertyIndexManager { private ArrayMap<String,List<PropertyIndex>> indexMap = new ArrayMap<String,List<PropertyIndex>>( 5, true, false ); private ArrayMap<Integer,PropertyIndex> idToIndexMap = new ArrayMap<Integer,PropertyIndex>( 9, true, false ); private ArrayMap<Transaction,TxCommitHook> txCommitHooks = new ArrayMap<Transaction,TxCommitHook>( 5, true, false ); private final TransactionManager transactionManager; private final PersistenceManager persistenceManager; private final IdGenerator idGenerator; private boolean hasAll = false; PropertyIndexManager( TransactionManager transactionManager, PersistenceManager persistenceManager, IdGenerator idGenerator ) { this.transactionManager = transactionManager; this.persistenceManager = persistenceManager; this.idGenerator = idGenerator; } void clear() { indexMap = new ArrayMap<String,List<PropertyIndex>>( 5, true, false ); idToIndexMap = new ArrayMap<Integer,PropertyIndex>( 9, true, false ); txCommitHooks.clear(); } public Iterable<PropertyIndex> index( String key ) { List<PropertyIndex> list = indexMap.get( key ); TxCommitHook hook = txCommitHooks.get( getTransaction() ); if ( hook != null ) { PropertyIndex index = hook.getIndex( key ); if ( index != null ) { List<PropertyIndex> added = new ArrayList<PropertyIndex>(); if ( list != null ) { added.addAll( list ); } added.add( index ); return added; } } if ( list == null ) { list = Collections.emptyList(); } return list; } void setHasAll( boolean status ) { hasAll = status; } boolean hasAll() { return hasAll; } public boolean hasIndexFor( int keyId ) { return idToIndexMap.get( keyId ) != null; } void addPropertyIndexes( RawPropertyIndex[] indexes ) { for ( RawPropertyIndex rawIndex : indexes ) { addPropertyIndex( new PropertyIndex( rawIndex.getValue(), rawIndex.getKeyId() ) ); } } public PropertyIndex getIndexFor( int keyId ) { PropertyIndex index = idToIndexMap.get( keyId ); if ( index == null ) { TxCommitHook commitHook = txCommitHooks.get( getTransaction() ); if ( commitHook != null ) { index = commitHook.getIndex( keyId ); if ( index != null ) { return index; } } String indexString; indexString = persistenceManager.loadIndex( keyId ); if ( indexString == null ) { throw new NotFoundException( "Index not found [" + keyId + "]" ); } index = new PropertyIndex( indexString, keyId ); addPropertyIndex( index ); } return index; } // need synch here so we don't create multiple lists private synchronized void addPropertyIndex( PropertyIndex index ) { List<PropertyIndex> list = indexMap.get( index.getKey() ); if ( list == null ) { list = new CopyOnWriteArrayList<PropertyIndex>(); indexMap.put( index.getKey(), list ); } list.add( index ); idToIndexMap.put( index.getKeyId(), index ); } private Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch ( javax.transaction.SystemException e ) { throw new NotInTransactionException( e ); } catch ( Exception e ) { throw new NotInTransactionException( e ); } } // concurent transactions may create duplicate keys, oh well PropertyIndex createPropertyIndex( String key ) { Transaction tx = getTransaction(); TxCommitHook hook = txCommitHooks.get( tx ); if ( hook == null ) { hook = new TxCommitHook( tx ); txCommitHooks.put( tx, hook ); try { if ( tx == null ) { throw new NotInTransactionException( "Unable to create property index for " + key ); } tx.registerSynchronization( hook ); } catch ( javax.transaction.SystemException e ) { throw new NotInTransactionException( e ); } catch ( Exception e ) { throw new NotInTransactionException( e ); } } PropertyIndex index = hook.getIndex( key ); if ( index != null ) { return index; } int id = idGenerator.nextId( PropertyIndex.class ); index = new PropertyIndex( key, id ); hook.addIndex( index ); persistenceManager.createPropertyIndex( key, id ); return index; } void setRollbackOnly() { try { transactionManager.setRollbackOnly(); } catch ( javax.transaction.SystemException se ) { se.printStackTrace(); } } private class TxCommitHook implements Synchronization { private Map<String,PropertyIndex> createdIndexes = new HashMap<String,PropertyIndex>(); private Map<Integer,PropertyIndex> idToIndex = new HashMap<Integer,PropertyIndex>(); private final Transaction tx; TxCommitHook( Transaction tx ) { this.tx = tx; } void addIndex( PropertyIndex index ) { assert !createdIndexes.containsKey( index.getKey() ); createdIndexes.put( index.getKey(), index ); idToIndex.put( index.getKeyId(), index ); } PropertyIndex getIndex( String key ) { return createdIndexes.get( key ); } PropertyIndex getIndex( int keyId ) { return idToIndex.get( keyId ); } public void afterCompletion( int status ) { try { if ( status == Status.STATUS_COMMITTED ) { for ( PropertyIndex index : createdIndexes.values() ) { addPropertyIndex( index ); } } txCommitHooks.remove( tx ); } catch ( Throwable t ) { t.printStackTrace(); } } public void beforeCompletion() { } } }
package com.ibm.streamsx.topology.builder; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ibm.json.java.JSONArray; import com.ibm.json.java.JSONObject; import com.ibm.json.java.OrderedJSONObject; import com.ibm.streams.flow.declare.InputPortDeclaration; import com.ibm.streams.flow.declare.OperatorInvocation; import com.ibm.streams.flow.declare.OutputPortDeclaration; import com.ibm.streams.operator.Attribute; import com.ibm.streams.operator.Operator; import com.ibm.streams.operator.StreamSchema; import com.ibm.streams.operator.model.Namespace; import com.ibm.streams.operator.model.PrimitiveOperator; // Union(A,B) // OpC(A,B) // Union(A,B) --> // Parallel /** * JSON representation. * * Operator: * * params: Object of Parameters, keyed by parameter name. outputs: Array of * output ports (see BStream) inputs: Array in input ports type: connections: * array of connection names as strings * * Parameter value: Value of parameter. */ public class BOperatorInvocation extends BOperator { private final OperatorInvocation<? extends Operator> op; protected List<BInputPort> inputs; protected List<BOutputPort> outputs; private final JSONObject jparams = new OrderedJSONObject(); public BOperatorInvocation(GraphBuilder bt, Class<? extends Operator> opClass, Map<String, ? extends Object> params) { super(bt); op = bt.graph().addOperator(opClass); json().put("name", op.getName()); json().put("parameters", jparams); if (!Operator.class.equals(opClass)) { json().put("runtime", "spl.java"); json().put("kind", getKind(opClass)); json().put("kind.javaclass", opClass.getCanonicalName()); } if (params != null) { for (String paramName : params.keySet()) { setParameter(paramName, params.get(paramName)); } } } public BOperatorInvocation(GraphBuilder bt, String name, Class<? extends Operator> opClass, Map<String, ? extends Object> params) { super(bt); op = bt.graph().addOperator(name, opClass); json().put("name", op.getName()); json().put("parameters", jparams); if (!Operator.class.equals(opClass)) { json().put("runtime", "spl.java"); json().put("kind", getKind(opClass)); json().put("kind.javaclass", opClass.getCanonicalName()); } if (params != null) { for (String paramName : params.keySet()) { setParameter(paramName, params.get(paramName)); } } } public BOperatorInvocation(GraphBuilder bt, Map<String, ? extends Object> params) { this(bt, Operator.class, params); } public BOperatorInvocation(GraphBuilder bt, String name, Map<String, ? extends Object> params) { this(bt, name, Operator.class, params); } /* public BOperatorInvocation(GraphBuilder bt, String kind, Map<String, ? extends Object> params) { this(bt, Operator.class, params); json().put("kind", kind); } */ public void setParameter(String name, Object value) { Object jsonValue = value; String jsonType = null; // Set the value in the OperatorInvocation. if (value instanceof String) { op.setStringParameter(name, (String) value); } else if (value instanceof Byte) { op.setByteParameter(name, (Byte) value); } else if (value instanceof Short) { op.setShortParameter(name, (Short) value); } else if (value instanceof Integer) { op.setIntParameter(name, (Integer) value); } else if (value instanceof Long) { op.setLongParameter(name, (Long) value); } else if (value instanceof Float) { op.setFloatParameter(name, (Float) value); } else if (value instanceof Double) { op.setDoubleParameter(name, (Double) value); } else if (value instanceof Boolean) { op.setBooleanParameter(name, (Boolean) value); } else if (value instanceof BigDecimal) { op.setBigDecimalParameter(name, (BigDecimal) value); jsonValue = value.toString(); // Need to maintain exact value } else if (value instanceof Enum) { op.setCustomLiteralParameter(name, (Enum<?>) value); jsonValue = ((Enum<?>) value).name(); jsonType = "enum"; } else if (value instanceof StreamSchema) { jsonValue = ((StreamSchema) value).getLanguageType(); jsonType = "spltype"; } else if (value instanceof String[]) { String[] sa = (String[]) value; JSONArray a = new JSONArray(sa.length); for (String vs : sa) a.add(vs); jsonValue = a; op.setStringParameter(name, sa); } else if (value instanceof Attribute) { Attribute attr = (Attribute) value; jsonValue = attr.getName(); jsonType = "attribute"; op.setAttributeParameter(name, attr.getName()); } else { throw new IllegalArgumentException("Type for parameter " + name + " is not supported:" + value.getClass()); } // Set the value as JSON JSONObject param = new JSONObject(); param.put("value", jsonValue); if (jsonType != null) param.put("type", jsonType); jparams.put(name, param); } public BOutputPort addOutput(StreamSchema schema) { if (outputs == null) outputs = new ArrayList<>(); final OutputPortDeclaration port = op.addOutput(schema); final BOutputPort stream = new BOutputPort(this, port); outputs.add(stream); return stream; } public BInputPort inputFrom(BOutput output, BInputPort input) { if (input != null) { assert input.operator() == this.op; assert inputs != null; output.connectTo(input); return input; } if (inputs == null) { inputs = new ArrayList<>(); } InputPortDeclaration inputPort = op.addInput(this.op.getName() + "_IN" + inputs.size(), output.schema()); input = new BInputPort(this, inputPort); inputs.add(input); output.connectTo(input); return input; } @Override public JSONObject complete() { final JSONObject json = super.complete(); if (outputs != null) { JSONArray oa = new JSONArray(outputs.size()); for (BOutputPort output : outputs) { oa.add(output.complete()); } json.put("outputs", oa); } if (inputs != null) { JSONArray ia = new JSONArray(inputs.size()); for (BInputPort input : inputs) { ia.add(input.complete()); } json.put("inputs", ia); } return json; } // Needed by the DependencyResolver to determine whether the operator // has a 'jar' parameter by calling // op instance of FunctionFunctor public OperatorInvocation<? extends Operator> op() { return op; } private static String getKind(Class<?> opClass) { PrimitiveOperator primitive = opClass.getAnnotation(PrimitiveOperator.class); final String kindName = primitive.name().length() == 0 ? opClass.getSimpleName() : primitive.name(); String namespace; if (primitive.namespace().length() != 0) namespace = primitive.namespace(); else { Package pkg = opClass.getPackage(); if (pkg != null) { Namespace ns = pkg.getAnnotation(Namespace.class); if (ns == null) namespace = pkg.getName(); else namespace = ns.value(); } else { namespace = ""; } } return namespace + "::" + kindName; } }
package com.semmle.ts.extractor; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.semmle.util.trap.TrapWriter; import com.semmle.util.trap.TrapWriter.Label; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Extracts type and symbol information into TRAP files. * * <p>This is closely coupled with the <tt>type_table.ts</tt> file in the parser-wrapper. Type * strings and symbol strings generated in that file are parsed here. See that file for reference * and documentation. */ public class TypeExtractor { private final TrapWriter trapWriter; private final TypeTable table; private static final Map<String, Integer> tagToKind = new LinkedHashMap<String, Integer>(); private static final int referenceKind = 6; private static final int objectKind = 7; private static final int typevarKind = 8; private static final int typeofKind = 9; private static final int uniqueSymbolKind = 15; private static final int tupleKind = 18; private static final int lexicalTypevarKind = 19; private static final int thisKind = 20; private static final int numberLiteralTypeKind = 21; private static final int stringLiteralTypeKind = 22; private static final int bigintLiteralTypeKind = 25; static { tagToKind.put("any", 0); tagToKind.put("string", 1); tagToKind.put("number", 2); tagToKind.put("union", 3); tagToKind.put("true", 4); tagToKind.put("false", 5); tagToKind.put("reference", referenceKind); tagToKind.put("object", objectKind); tagToKind.put("typevar", typevarKind); tagToKind.put("typeof", typeofKind); tagToKind.put("void", 10); tagToKind.put("undefined", 11); tagToKind.put("null", 12); tagToKind.put("never", 13); tagToKind.put("plainsymbol", 14); tagToKind.put("uniquesymbol", uniqueSymbolKind); tagToKind.put("objectkeyword", 16); tagToKind.put("intersection", 17); tagToKind.put("tuple", tupleKind); tagToKind.put("lextypevar", lexicalTypevarKind); tagToKind.put("this", thisKind); tagToKind.put("numlit", numberLiteralTypeKind); tagToKind.put("strlit", stringLiteralTypeKind); tagToKind.put("unknown", 23); tagToKind.put("bigint", 24); tagToKind.put("bigintlit", bigintLiteralTypeKind); } private static final Map<String, Integer> symbolKind = new LinkedHashMap<String, Integer>(); static { symbolKind.put("root", 0); symbolKind.put("member", 1); symbolKind.put("other", 2); } public TypeExtractor(TrapWriter trapWriter, TypeTable table) { this.trapWriter = trapWriter; this.table = table; } public void extract() { for (int i = 0; i < table.getNumberOfTypes(); ++i) { extractType(i); } extractPropertyLookups(table.getPropertyLookups()); for (int i = 0; i < table.getNumberOfSymbols(); ++i) { extractSymbol(i); } extractSymbolNameMapping("symbol_module", table.getModuleMappings()); extractSymbolNameMapping("symbol_global", table.getGlobalMappings()); extractSignatureMappings(table.getSignatureMappings()); for (int i = 0; i < table.getNumberOfSignatures(); ++i) { extractSignature(i); } extractIndexTypeTable(table.getNumberIndexTypes(), "number_index_type"); extractIndexTypeTable(table.getStringIndexTypes(), "string_index_type"); extractBaseTypes(table.getBaseTypes()); extractSelfTypes(table.getSelfTypes()); } private void extractType(int id) { Label lbl = trapWriter.globalID("type;" + id); String contents = table.getTypeString(id); String[] parts = split(contents); int kind = tagToKind.get(parts[0]); trapWriter.addTuple("types", lbl, kind, table.getTypeToStringValue(id)); int firstChild = 1; switch (kind) { case referenceKind: case typevarKind: case typeofKind: case uniqueSymbolKind: { // The first part of a reference is the symbol for name binding. Label symbol = trapWriter.globalID("symbol;" + parts[1]); trapWriter.addTuple("type_symbol", lbl, symbol); ++firstChild; break; } case tupleKind: { // The first two parts denote minimum length and presence of rest element. trapWriter.addTuple("tuple_type_min_length", lbl, Integer.parseInt(parts[1])); if (parts[2].equals("t")) { trapWriter.addTuple("tuple_type_rest", lbl); } firstChild += 2; break; } case objectKind: case lexicalTypevarKind: firstChild = parts.length; // No children. break; case numberLiteralTypeKind: case stringLiteralTypeKind: case bigintLiteralTypeKind: firstChild = parts.length; // No children. // The string value may contain `;` so don't use the split(). String value = contents.substring(parts[0].length() + 1); trapWriter.addTuple("type_literal_value", lbl, value); break; } for (int i = firstChild; i < parts.length; ++i) { Label childLabel = trapWriter.globalID("type;" + parts[i]); trapWriter.addTuple("type_child", childLabel, lbl, i - firstChild); } } private void extractPropertyLookups(JsonObject lookups) { JsonArray baseTypes = lookups.get("baseTypes").getAsJsonArray(); JsonArray names = lookups.get("names").getAsJsonArray(); JsonArray propertyTypes = lookups.get("propertyTypes").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); String name = names.get(i).getAsString(); int propertyType = propertyTypes.get(i).getAsInt(); trapWriter.addTuple( "type_property", trapWriter.globalID("type;" + baseType), name, trapWriter.globalID("type;" + propertyType)); } } private void extractSymbol(int index) { // Format is: kind;decl;parent;name String[] parts = split(table.getSymbolString(index), 4); int kind = symbolKind.get(parts[0]); String name = parts[3]; Label label = trapWriter.globalID("symbol;" + index); trapWriter.addTuple("symbols", label, kind, name); String parentStr = parts[2]; if (parentStr.length() > 0) { Label parentLabel = trapWriter.globalID("symbol;" + parentStr); trapWriter.addTuple("symbol_parent", label, parentLabel); } } private void extractSymbolNameMapping(String relationName, JsonObject mappings) { JsonArray symbols = mappings.get("symbols").getAsJsonArray(); JsonArray names = mappings.get("names").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { Label symbol = trapWriter.globalID("symbol;" + symbols.get(i).getAsInt()); String moduleName = names.get(i).getAsString(); trapWriter.addTuple(relationName, symbol, moduleName); } } private void extractSignature(int index) { // Format is: // kind;numTypeParams;requiredParams;returnType(;paramName;paramType)* String[] parts = split(table.getSignatureString(index)); Label label = trapWriter.globalID("signature;" + index); int kind = Integer.parseInt(parts[0]); int numberOfTypeParameters = Integer.parseInt(parts[1]); int requiredParameters = Integer.parseInt(parts[2]); Label returnType = trapWriter.globalID("type;" + parts[3]); trapWriter.addTuple( "signature_types", label, kind, table.getSignatureToStringValue(index), numberOfTypeParameters, requiredParameters); trapWriter.addTuple("signature_contains_type", returnType, label, -1); int numberOfParameters = (parts.length - 4) / 2; // includes type parameters for (int i = 0; i < numberOfParameters; ++i) { int partIndex = 4 + (2 * i); String paramName = parts[partIndex]; String paramTypeId = parts[partIndex + 1]; if (paramTypeId.length() > 0) { // Unconstrained type parameters have an empty type ID. Label paramType = trapWriter.globalID("type;" + parts[partIndex + 1]); trapWriter.addTuple("signature_contains_type", paramType, label, i); } trapWriter.addTuple("signature_parameter_name", label, i, paramName); } } private void extractSignatureMappings(JsonObject mappings) { JsonArray baseTypes = mappings.get("baseTypes").getAsJsonArray(); JsonArray kinds = mappings.get("kinds").getAsJsonArray(); JsonArray indices = mappings.get("indices").getAsJsonArray(); JsonArray signatures = mappings.get("signatures").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); int kind = kinds.get(i).getAsInt(); int index = indices.get(i).getAsInt(); int signatureId = signatures.get(i).getAsInt(); trapWriter.addTuple( "type_contains_signature", trapWriter.globalID("type;" + baseType), kind, index, trapWriter.globalID("signature;" + signatureId)); } } private void extractIndexTypeTable(JsonObject table, String relationName) { JsonArray baseTypes = table.get("baseTypes").getAsJsonArray(); JsonArray propertyTypes = table.get("propertyTypes").getAsJsonArray(); for (int i = 0; i < baseTypes.size(); ++i) { int baseType = baseTypes.get(i).getAsInt(); int propertyType = propertyTypes.get(i).getAsInt(); trapWriter.addTuple( relationName, trapWriter.globalID("type;" + baseType), trapWriter.globalID("type;" + propertyType)); } } private void extractBaseTypes(JsonObject table) { JsonArray symbols = table.get("symbols").getAsJsonArray(); JsonArray baseTypeSymbols = table.get("baseTypeSymbols").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { int symbolId = symbols.get(i).getAsInt(); int baseTypeSymbolId = baseTypeSymbols.get(i).getAsInt(); trapWriter.addTuple( "base_type_names", trapWriter.globalID("symbol;" + symbolId), trapWriter.globalID("symbol;" + baseTypeSymbolId)); } } private void extractSelfTypes(JsonObject table) { JsonArray symbols = table.get("symbols").getAsJsonArray(); JsonArray selfTypes = table.get("selfTypes").getAsJsonArray(); for (int i = 0; i < symbols.size(); ++i) { int symbolId = symbols.get(i).getAsInt(); int typeId = selfTypes.get(i).getAsInt(); trapWriter.addTuple( "self_types", trapWriter.globalID("symbol;" + symbolId), trapWriter.globalID("type;" + typeId)); } } /** Like {@link #split(String)} without a limit. */ private static String[] split(String input) { return split(input, -1); } /** * Splits the input around the semicolon (<code>;</code>) character, preserving all empty * substrings. * * <p>At most <code>limit</code> substrings will be extracted. If the limit is reached, the last * substring will extend to the end of the string, possibly itself containing semicolons. * * <p>Note that the {@link String#split(String)} method does not preserve empty substrings at the * end of the string in case the string ends with a semicolon. */ private static String[] split(String input, int limit) { List<String> result = new ArrayList<String>(); int lastPos = 0; for (int i = 0; i < input.length(); ++i) { if (input.charAt(i) == ';') { result.add(input.substring(lastPos, i)); lastPos = i + 1; if (result.size() == limit - 1) break; } } result.add(input.substring(lastPos)); return result.toArray(EMPTY_STRING_ARRAY); } private static final String[] EMPTY_STRING_ARRAY = new String[0]; }
package org.jlib.container; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jlib.container.sequence.Sequence; import org.jlib.container.sequence.index.ReplaceIndexSequence; import org.jlib.core.array.ArrayUtility; import org.jlib.core.traverser.Traverser; /** * Empty {@link Sequence}. * * @param <Item> * type of the items * * @author Igor Akkerman */ public class EmptyContainer<Item> implements Container<Item> { /** sole instance of this class */ private static final EmptyContainer<?> INSTANCE = new EmptyContainer<>(); /** * Returns the sole instance of this class. * * @param <Item> * type of potential items potentially held in this * {@link EmptyContainer} * * @return sole {@link ReplaceIndexSequence} */ @SuppressWarnings("unchecked") public static <Item> EmptyContainer<Item> getInstance() { return (EmptyContainer<Item>) INSTANCE; } /** * Creates a new {@link EmptyContainer}. */ protected EmptyContainer() { super(); } @Override public final Traverser<Item> createTraverser() { return EmptyContainerTraverser.getInstance(); } @Override public final int getItemsCount() { return 0; } @Override public final boolean isEmpty() { return true; } @Override public final boolean contains(final Item item) { return false; } @Override public final boolean contains(final Container<? extends Item> items) { return false; } @Override public final boolean contains(final Collection<? extends Item> items) { return false; } @Override @SafeVarargs public final boolean contains(final Item... items) { return false; } @Override public final List<Item> toList() { return Collections.emptyList(); } @Override public final List<Item> toSequentialList() { return Collections.emptyList(); } @Override public final Item[] toArray() { return ArrayUtility.getEmptyArray(); } @Override public final Iterator<Item> iterator() { return Collections.emptyIterator(); } // equals/hashCode don't need to be extended as Object.equals already checks for identity @Override public boolean containsEqualItems(final Container<Item> otherContainer) { return otherContainer.isEmpty(); } }
package edu.umd.cs.findbugs; import java.io.*; import java.util.*; import java.util.zip.*; import edu.umd.cs.pugh.io.IO; import edu.umd.cs.pugh.visitclass.Constants2; import org.apache.bcel.classfile.*; import org.apache.bcel.Repository; import org.apache.bcel.util.ClassPath; import org.apache.bcel.util.SyntheticRepository; /** * An instance of this class is used to apply the selected set of * analyses on some collection of Java classes. It also implements the * comand line interface. * * @author Bill Pugh * @author David Hovemeyer */ public class FindBugs implements Constants2, ExitCodes { /** * Interface for an object representing a source of class files to analyze. */ private interface ClassProducer { /** * Get the next class to analyze. * @return the class, or null of there are no more classes for this ClassProducer * @throws IOException if an IOException occurs * @throws InterruptedException if the thread is interrupted */ public JavaClass getNextClass() throws IOException, InterruptedException; } /** * ClassProducer for single class files. */ private static class SingleClassProducer implements ClassProducer { private String fileName; /** * Constructor. * @param fileName the single class file to be analyzed */ public SingleClassProducer(String fileName) { this.fileName = fileName; } public JavaClass getNextClass() throws IOException, InterruptedException { if (fileName == null) return null; if (Thread.interrupted()) throw new InterruptedException(); String fileNameToParse = fileName; fileName = null; // don't return it next time try { return new ClassParser(fileNameToParse).parse(); } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileNameToParse + ": " + e.getMessage()); } } } /** * ClassProducer for .zip and .jar files. * Nested jar and zip files are also scanned for classes; * this is needed for .ear and .war files associated with EJBs. */ private static class ZipClassProducer implements ClassProducer { private String fileName; private String nestedFileName; private ZipFile zipFile; private Enumeration entries; private ZipInputStream zipStream; // a DataInputStream wrapper that cannot be closed private static class DupDataStream extends DataInputStream { public DupDataStream( InputStream in ) { super( in ); } public void close() { }; } /** * Constructor. * @param fileName the name of the zip or jar file */ public ZipClassProducer(String fileName) throws IOException { this.fileName = fileName; this.zipFile = new ZipFile(fileName); this.entries = zipFile.entries(); this.zipStream = null; this.nestedFileName = null; } private void setZipStream( ZipInputStream in, String fileName ) { zipStream = in; nestedFileName = fileName; } private void closeZipStream() throws IOException { zipStream.close(); zipStream = null; nestedFileName = null; } private JavaClass getNextNestedClass() throws IOException, InterruptedException { JavaClass parsedClass = null; if ( zipStream != null ) { ZipEntry entry = zipStream.getNextEntry(); while ( entry != null ) { if (Thread.interrupted()) throw new InterruptedException(); if ( entry.getName().endsWith( ".class" ) ) { try { parsedClass = new ClassParser( new DupDataStream(zipStream), entry.getName()).parse(); break; } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ":" + nestedFileName + ":" + entry.getName() + ": " + e.getMessage()); } } entry = zipStream.getNextEntry(); } if ( parsedClass == null ) { closeZipStream(); } } return parsedClass; } public JavaClass getNextClass() throws IOException, InterruptedException { JavaClass parsedClass = getNextNestedClass(); if ( parsedClass == null ) { while (entries.hasMoreElements()) { if (Thread.interrupted()) throw new InterruptedException(); ZipEntry entry = (ZipEntry) entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { try { parsedClass = new ClassParser(zipFile.getInputStream(entry), name).parse(); break; } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ":" + name + ": " + e.getMessage()); } } else if ( name.endsWith(".jar") || name.endsWith( ".zip" ) ) { setZipStream(new ZipInputStream(zipFile.getInputStream(entry)), name ); parsedClass = getNextNestedClass(); if ( parsedClass != null ) { break; } } } } return parsedClass; } } /** * ClassProducer for directories. * The directory is scanned recursively for class files. */ private static class DirectoryClassProducer implements ClassProducer { private Iterator<String> rfsIter; public DirectoryClassProducer(String dirName) throws InterruptedException { FileFilter filter = new FileFilter() { public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".class"); } }; // This will throw InterruptedException if the thread is // interrupted. RecursiveFileSearch rfs = new RecursiveFileSearch(dirName, filter).search(); this.rfsIter = rfs.fileNameIterator(); } public JavaClass getNextClass() throws IOException, InterruptedException { if (!rfsIter.hasNext()) return null; String fileName = rfsIter.next(); try { return new ClassParser(fileName).parse(); } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ": " + e.getMessage()); } } } /** * A delegating bug reporter which counts reported bug instances, * missing classes, and serious analysis errors. */ private static class ErrorCountingBugReporter extends DelegatingBugReporter { private int bugCount; private int missingClassCount; private int errorCount; public ErrorCountingBugReporter(BugReporter realBugReporter) { super(realBugReporter); this.bugCount = 0; this.missingClassCount = 0; this.errorCount = 0; // Add an observer to record when bugs make it through // all priority and filter criteria, so our bug count is // accurate. realBugReporter.addObserver(new BugReporterObserver() { public void reportBug(BugInstance bugInstance) { ++bugCount; } }); } public int getBugCount() { return bugCount; } public int getMissingClassCount() { return missingClassCount; } public int getErrorCount() { return errorCount; } public void logError(String message) { ++errorCount; super.logError(message); } public void reportMissingClass(ClassNotFoundException ex) { ++missingClassCount; super.reportMissingClass(ex); } } private static final boolean DEBUG = Boolean.getBoolean("findbugs.debug"); /** FindBugs home directory. */ private static String home; private ErrorCountingBugReporter bugReporter; private Project project; private Detector detectors []; private FindBugsProgress progressCallback; /** * Constructor. * @param bugReporter the BugReporter object that will be used to report * BugInstance objects, analysis errors, class to source mapping, etc. * @param project the Project indicating which files to analyze and * the auxiliary classpath to use */ public FindBugs(BugReporter bugReporter, Project project) { if (bugReporter == null) throw new IllegalArgumentException("null bugReporter"); if (project == null) throw new IllegalArgumentException("null project"); this.bugReporter = new ErrorCountingBugReporter(bugReporter); this.project = project; // Create a no-op progress callback. this.progressCallback = new FindBugsProgress() { public void reportNumberOfArchives(int numArchives) { } public void finishArchive() { } public void startAnalysis(int numClasses) { } public void finishClass() { } public void finishPerClassAnalysis() { } }; } /** * Set the progress callback that will be used to keep track * of the progress of the analysis. * @param progressCallback the progress callback */ public void setProgressCallback(FindBugsProgress progressCallback) { this.progressCallback = progressCallback; } /** * Set filter of bug instances to include or exclude. * @param filterFileName the name of the filter file * @param include true if the filter specifies bug instances to include, * false if it specifies bug instances to exclude */ public void setFilter(String filterFileName, boolean include) throws IOException, FilterException { Filter filter = new Filter(filterFileName); BugReporter origBugReporter = bugReporter.getRealBugReporter(); BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include); bugReporter.setRealBugReporter(filterBugReporter); } /** * Execute FindBugs on the Project. * All bugs found are reported to the BugReporter object which was set * when this object was constructed. * @throws java.io.IOException if an I/O exception occurs analyzing one of the files * @throws InterruptedException if the thread is interrupted while conducting the analysis */ public void execute() throws java.io.IOException, InterruptedException { if (detectors == null) createDetectors(); clearRepository(); String[] argv = project.getJarFileArray(); progressCallback.reportNumberOfArchives(argv.length); List<String> repositoryClassList = new LinkedList<String>(); for (int i = 0; i < argv.length; i++) { addFileToRepository(argv[i], repositoryClassList); } progressCallback.startAnalysis(repositoryClassList.size()); for (Iterator<String> i = repositoryClassList.iterator(); i.hasNext(); ) { String className = i.next(); examineClass(className); } progressCallback.finishPerClassAnalysis(); this.reportFinal(); // Flush any queued bug reports bugReporter.finish(); // Flush any queued error reports bugReporter.reportQueuedErrors(); } /** * Get the number of bug instances that were reported during analysis. */ public int getBugCount() { return bugReporter.getBugCount(); } /** * Get the number of errors that occurred during analysis. */ public int getErrorCount() { return bugReporter.getErrorCount(); } /** * Get the number of time missing classes were reported during analysis. */ public int getMissingClassCount() { return bugReporter.getMissingClassCount(); } /** * Set the FindBugs home directory. */ public static void setHome(String home) { FindBugs.home = home; } /** * Get the FindBugs home directory. */ public static String getHome() { if (home == null) { home = System.getProperty("findbugs.home"); if (home == null) { System.err.println("Error: The findbugs.home property is not set!"); System.exit(1); } } return home; } /** * Create Detectors for each DetectorFactory which is enabled. * This will populate the detectors array. */ private void createDetectors() { ArrayList<Detector> result = new ArrayList<Detector>(); Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); int count = 0; while (i.hasNext()) { DetectorFactory factory = i.next(); if (factory.isEnabled()) result.add(factory.create(bugReporter)); } detectors = result.toArray(new Detector[0]); } /** * Clear the Repository and update it to reflect the classpath * specified by the current project. */ private void clearRepository() { // Purge repository of previous contents Repository.clearCache(); // Create a SyntheticRepository based on the current project, // and make it current. // Add aux class path entries specified in project StringBuffer buf = new StringBuffer(); List auxClasspathEntryList = project.getAuxClasspathEntryList(); Iterator i = auxClasspathEntryList.iterator(); while (i.hasNext()) { String entry = (String) i.next(); buf.append(entry); buf.append(File.pathSeparatorChar); } // Add the system classpath entries buf.append(ClassPath.getClassPath()); // Set up the Repository to use the combined classpath ClassPath classPath = new ClassPath(buf.toString()); SyntheticRepository repository = SyntheticRepository.getInstance(classPath); Repository.setRepository(repository); } /** * Add all classes contained in given file to the BCEL Repository. * @param fileName the file, which may be a jar/zip archive, a single class file, * or a directory to be recursively searched for class files */ private void addFileToRepository(String fileName, List<String> repositoryClassList) throws IOException, InterruptedException { try { ClassProducer classProducer; // Create the ClassProducer if (fileName.endsWith(".jar") || fileName.endsWith(".zip") || fileName.endsWith(".war") || fileName.endsWith(".ear")) classProducer = new ZipClassProducer(fileName); else if (fileName.endsWith(".class")) classProducer = new SingleClassProducer(fileName); else { File dir = new File(fileName); if (!dir.isDirectory()) throw new IOException("Path " + fileName + " is not an archive, class file, or directory"); classProducer = new DirectoryClassProducer(fileName); } // Load all referenced classes into the Repository for (;;) { if (Thread.interrupted()) throw new InterruptedException(); try { JavaClass jclass = classProducer.getNextClass(); if (jclass == null) break; Repository.addClass(jclass); repositoryClassList.add(jclass.getClassName()); } catch (ClassFormatException e) { e.printStackTrace(); bugReporter.logError(e.getMessage()); } } progressCallback.finishArchive(); } catch (IOException e) { // You'd think that the message for a FileNotFoundException would include // the filename, but you'd be wrong. So, we'll add it explicitly. throw new IOException("Could not analyze " + fileName + ": " + e.getMessage()); } } /** * Examine a single class by invoking all of the Detectors on it. * @param className the fully qualified name of the class to examine */ private void examineClass(String className) throws InterruptedException { if (DEBUG) System.out.println("Examining class " + className); JavaClass javaClass; try { javaClass = Repository.lookupClass(className); ClassContext classContext = new ClassContext(javaClass); for (int i = 0; i < detectors.length; ++i) { if (Thread.interrupted()) throw new InterruptedException(); try { Detector detector = detectors[i]; if (DEBUG) System.out.println(" running " + detector.getClass().getName()); detector.visitClassContext(classContext); } catch (AnalysisException e) { bugReporter.logError("Analysis exception: " + e.toString()); } } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); bugReporter.logError("Could not find class " + className + " in Repository: " + e.getMessage()); } progressCallback.finishClass(); } /** * Call report() on all detectors, to give them a chance to * report any accumulated bug reports. */ private void reportFinal() throws InterruptedException { for (int i = 0; i < detectors.length; ++i) { if (Thread.interrupted()) throw new InterruptedException(); detectors[i].report(); } } private static final int PRINTING_REPORTER = 0; private static final int SORTING_REPORTER = 1; private static final int XML_REPORTER = 2; public static void main(String argv[]) throws Exception { int bugReporterType = PRINTING_REPORTER; Project project = new Project(); boolean quiet = false; String filterFile = null; boolean include = false; boolean setExitCode = false; int priorityThreshold = Detector.NORMAL_PRIORITY; // Process command line options int argCount = 0; while (argCount < argv.length) { String option = argv[argCount]; if (!option.startsWith("-")) break; if (option.equals("-home")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String homeDir = argv[argCount]; FindBugs.setHome(homeDir); } else if (option.equals("-low")) priorityThreshold = Detector.LOW_PRIORITY; else if (option.equals("-medium")) priorityThreshold = Detector.NORMAL_PRIORITY; else if (option.equals("-high")) priorityThreshold = Detector.HIGH_PRIORITY; else if (option.equals("-sortByClass")) bugReporterType = SORTING_REPORTER; else if (option.equals("-xml")) bugReporterType = XML_REPORTER; else if (option.equals("-visitors") || option.equals("-omitVisitors")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); boolean omit = option.equals("-omitVisitors"); if (!omit) { // Selecting detectors explicitly, so start out by // disabling all of them. The selected ones will // be re-enabled. Iterator<DetectorFactory> factoryIter = DetectorFactoryCollection.instance().factoryIterator(); while (factoryIter.hasNext()) { DetectorFactory factory = factoryIter.next(); factory.setEnabled(false); } } // Explicitly enable or disable the selector detectors. StringTokenizer tok = new StringTokenizer(argv[argCount], ","); while (tok.hasMoreTokens()) { String visitorName = tok.nextToken(); DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName); if (factory == null) throw new IllegalArgumentException("Unknown detector: " + visitorName); factory.setEnabled(!omit); } } else if (option.equals("-exclude") || option.equals("-include")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); filterFile = argv[argCount]; include = option.equals("-include"); } else if (option.equals("-quiet")) { quiet = true; } else if (option.equals("-auxclasspath")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String auxClassPath = argv[argCount]; StringTokenizer tok = new StringTokenizer(auxClassPath, File.pathSeparator); while (tok.hasMoreTokens()) project.addAuxClasspathEntry(tok.nextToken()); } else if (option.equals("-project")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String projectFile = argv[argCount]; // Convert project file to be an absolute path projectFile = new File(projectFile).getAbsolutePath(); project = new Project(projectFile); project.read(new BufferedInputStream(new FileInputStream(projectFile))); } else if (option.equals("-exitcode")) { setExitCode = true; } else throw new IllegalArgumentException("Unknown option: [" + option + "]"); ++argCount; } if (argCount == argv.length && project.getNumJarFiles() == 0) { InputStream in = FindBugs.class.getClassLoader().getResourceAsStream("USAGE"); if (in == null) { System.out.println("FindBugs tool, version " + Version.RELEASE); System.out.println("usage: java -jar findbugs.jar [options] <classfiles, zip/jar files, or directories>"); System.out.println("Example: java -jar findbugs.jar rt.jar"); System.out.println("Options:"); System.out.println(" -home <home directory> specify FindBugs home directory"); System.out.println(" -quiet suppress error messages"); System.out.println(" -low report all bugs"); System.out.println(" -medium report medium and high priority bugs [default]"); System.out.println(" -high report high priority bugs only"); System.out.println(" -sortByClass sort bug reports by class"); System.out.println(" -xml XML output"); System.out.println(" -visitors <v1>,<v2>,... run only named visitors"); System.out.println(" -omitVisitors <v1>,<v2>,... omit named visitors"); System.out.println(" -exclude <filter file> exclude bugs matching given filter"); System.out.println(" -include <filter file> include only bugs matching given filter"); System.out.println(" -auxclasspath <classpath> set aux classpath for analysis"); System.out.println(" -project <project> analyze given project"); System.out.println(" -exitcode set exit code of process"); } else IO.copy(in,System.out); return; } BugReporter bugReporter = null; switch (bugReporterType) { case PRINTING_REPORTER: bugReporter = new PrintingBugReporter(); break; case SORTING_REPORTER: bugReporter = new SortingBugReporter(); break; case XML_REPORTER: bugReporter = new XMLBugReporter(project); break; default: throw new IllegalStateException(); } if (quiet) bugReporter.setErrorVerbosity(BugReporter.SILENT); bugReporter.setPriorityThreshold(priorityThreshold); for (int i = argCount; i < argv.length; ++i) project.addJar(argv[i]); FindBugs findBugs = new FindBugs(bugReporter, project); if (filterFile != null) findBugs.setFilter(filterFile, include); findBugs.execute(); int bugCount = findBugs.getBugCount(); int missingClassCount = findBugs.getMissingClassCount(); int errorCount = findBugs.getErrorCount(); if (!quiet || setExitCode) { if (bugCount > 0) System.err.println("Bugs found: " + bugCount); if (missingClassCount > 0) System.err.println("Missing classes: " + missingClassCount); if (errorCount > 0) System.err.println("Analysis errors: " + errorCount); } if (setExitCode) { int exitCode = 0; if (errorCount > 0) exitCode |= ERROR_FLAG; if (missingClassCount > 0) exitCode |= MISSING_CLASS_FLAG; if (bugCount > 0) exitCode |= BUGS_FOUND_FLAG; System.exit(exitCode); } } }
package org.jlib.core.observer; import org.jlib.core.IllegalJlibArgumentException; import org.jlib.core.IllegalJlibStateException; /** * * * @author Igor Akkerman */ public final class ObserverUtility { /** no visible constructor */ private ObserverUtility() {} @SafeVarargs public static <Item> void replace(final Replaceable<Item> replaceable, final Item newItem, final ItemObserver<Item>... observers) { try { for (final ItemObserver<Item> observer : observers) observer.handleBefore(newItem, replaceable); replaceable.replace(newItem); for (final ItemObserver<Item> observer : observers) observer.handleAfterSuccess(newItem, replaceable); } catch (IllegalJlibArgumentException | IllegalJlibStateException exception) { for (final ItemObserver<Item> observer : observers) observer.handleAfterFailure(newItem, replaceable); } } }
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.executor; import jp.oist.flint.phsp.PhspException; import jp.oist.flint.sedml.SedmlException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.SwingWorker; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import jp.oist.flint.dao.SimulationDao; import jp.oist.flint.filesystem.Workspace; import jp.oist.flint.phsp.IPhspConfiguration; import jp.oist.flint.phsp.PhspWriter; import jp.oist.flint.phsp.entity.Model; import jp.oist.flint.sedml.ISimulationConfigurationList; import jp.oist.flint.sedml.SedmlWriter; public class PhspSimulator extends SwingWorker <Boolean, Integer> { private final SimulatorService mService; private final File mWorkingDir; private final SimulationDao mSimulationDao; private final ISimulationConfigurationList mSedmlConfig; private final IPhspConfiguration mPhspConfig; private final File mSedmlFile; private final File mPhspFile; private final File mLogFile; public PhspSimulator (SimulatorService service, ISimulationConfigurationList sedml, IPhspConfiguration phsp) throws IOException, ParserConfigurationException, PhspException, SedmlException, TransformerException { mService = service; mSedmlConfig = sedml; mPhspConfig = phsp; Model[] models = phsp.getModels(); for (Model model : models) model.validate(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss-"); String prefix = sdf.format(new Date()); mWorkingDir = Workspace.createTempDirectory(prefix); mPhspFile = new File(mWorkingDir, "input.phsp"); mPhspFile.deleteOnExit(); mSedmlFile = new File(mWorkingDir, "input.xml"); mSedmlFile.deleteOnExit(); try (FileOutputStream phspStream = new FileOutputStream(mPhspFile)) { PhspWriter phspWriter = new PhspWriter(); phspWriter.write(mPhspConfig, phspStream, true); } try (FileOutputStream sedmlStream = new FileOutputStream(mSedmlFile)) { SedmlWriter sedmlWriter = new SedmlWriter(true); sedmlWriter.writeSimulationConfiguration(mSedmlConfig, sedmlStream); } mSimulationDao = new SimulationDao(mWorkingDir); mLogFile = new File(mWorkingDir, "flint.log"); mLogFile.deleteOnExit(); } public File getSedmlFile () { return mSedmlFile; } public File getPhspFile () { return mPhspFile; } public File getLogFile () { return mLogFile; } public ISimulationConfigurationList getSimulationConfigurationList () { return mSedmlConfig; } public IPhspConfiguration getPhspConfiguration () { return mPhspConfig; } public File getWorkingDirectory () { return mWorkingDir; } public SimulationDao getSimulationDao () { return mSimulationDao; } public boolean isStarted () { return StateValue.STARTED.equals(getState()); } @Override protected Boolean doInBackground() throws Exception { FlintExecJob job = new FlintExecJob(mSedmlFile, mPhspFile, mWorkingDir); return mService.call(job, mLogFile); } }
package us.dot.its.jpo.ode.dds; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Hex; import org.apache.tomcat.util.buf.HexUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.oss.asn1.AbstractData; import com.oss.asn1.Coder; import us.dot.its.jpo.ode.OdeProperties; import us.dot.its.jpo.ode.asn1.j2735.J2735Util; import us.dot.its.jpo.ode.j2735.J2735; import us.dot.its.jpo.ode.j2735.dsrc.DDateTime; import us.dot.its.jpo.ode.j2735.dsrc.DDay; import us.dot.its.jpo.ode.j2735.dsrc.DHour; import us.dot.its.jpo.ode.j2735.dsrc.DMinute; import us.dot.its.jpo.ode.j2735.dsrc.DMonth; import us.dot.its.jpo.ode.j2735.dsrc.DOffset; import us.dot.its.jpo.ode.j2735.dsrc.DSecond; import us.dot.its.jpo.ode.j2735.dsrc.DYear; import us.dot.its.jpo.ode.j2735.dsrc.TemporaryID; import us.dot.its.jpo.ode.j2735.semi.ConnectionPoint; import us.dot.its.jpo.ode.j2735.semi.GroupID; import us.dot.its.jpo.ode.j2735.semi.IPv4Address; import us.dot.its.jpo.ode.j2735.semi.IPv6Address; import us.dot.its.jpo.ode.j2735.semi.IpAddress; import us.dot.its.jpo.ode.j2735.semi.PortNumber; import us.dot.its.jpo.ode.j2735.semi.SemiDialogID; import us.dot.its.jpo.ode.j2735.semi.SemiSequenceID; import us.dot.its.jpo.ode.j2735.semi.ServiceRequest; import us.dot.its.jpo.ode.j2735.semi.ServiceResponse; import us.dot.its.jpo.ode.j2735.semi.Sha256Hash; /* * This class receives service request from the OBU and forwards it to the SDC. * It also receives service response from SDC and forwards it back to the OBU. */ public class TrustManager implements Callable<ServiceResponse> { public class TrustManagerException extends Exception { private static final long serialVersionUID = 1L; public TrustManagerException(String string) { super(string); } public TrustManagerException(String string, Exception e) { super(string, e); } } private OdeProperties odeProperties; private static Coder coder = J2735.getPERUnalignedCoder(); private Logger logger = LoggerFactory.getLogger(this.getClass()); private DatagramSocket socket = null; private ExecutorService execService; private boolean trustEstablished = false; private boolean establishingTrust = false; public TrustManager(OdeProperties odeProps, DatagramSocket socket) { this.odeProperties = odeProps; this.socket = socket; execService = Executors.newCachedThreadPool(Executors.defaultThreadFactory()); } public ServiceRequest createServiceRequest(TemporaryID requestID, SemiDialogID dialogID, GroupID groupID) throws TrustManagerException { //GroupID groupID = new GroupID(OdeProperties.JPO_ODE_GROUP_ID); //Random randgen = new Random(); //TemporaryID requestID = new TemporaryID(ByteBuffer.allocate(4).putInt(randgen.nextInt(256)).array()); // TODO use groupID = 0 ServiceRequest request = new ServiceRequest( dialogID, SemiSequenceID.svcReq, groupID, requestID); IpAddress ipAddr = new IpAddress(); if (!StringUtils.isEmpty(odeProperties.getExternalIpv4())) { ipAddr.setIpv4Address( new IPv4Address(J2735Util.ipToBytes(odeProperties.getExternalIpv4()))); logger.debug("Return IPv4: {}", odeProperties.getExternalIpv4()); } else if (!StringUtils.isEmpty(odeProperties.getExternalIpv6())) { ipAddr.setIpv6Address( new IPv6Address(J2735Util.ipToBytes(odeProperties.getExternalIpv6()))); logger.debug("Return IPv6: {}", odeProperties.getExternalIpv6()); } else { throw new TrustManagerException( "Invalid ode.externalIpv4 [" + odeProperties.getExternalIpv4() + "] and ode.externalIpv6 [" + odeProperties.getExternalIpv6() + "] properties"); } ConnectionPoint returnAddr = new ConnectionPoint( ipAddr, new PortNumber(socket.getLocalPort())); //request.setDestination(returnAddr); logger.debug("Response Destination {}:{}", returnAddr.getAddress().toString(), returnAddr.getPort().intValue()); return request; } public ServiceResponse receiveServiceResponse() throws TrustManagerException { ServiceResponse servResponse = null; try { byte[] buffer = new byte[odeProperties.getServiceResponseBufferSize()]; logger.debug("Waiting for ServiceResponse from SDC..."); DatagramPacket responeDp = new DatagramPacket(buffer, buffer.length); socket.receive(responeDp); if (buffer.length <= 0) throw new TrustManagerException("Received empty service response from SDC"); AbstractData response = J2735Util.decode(coder, buffer); if (response instanceof ServiceResponse) { logger.debug("Received ServiceResponse from SDC {}", response.toString()); servResponse = (ServiceResponse) response; if (J2735Util.isExpired(servResponse.getExpiration())) { throw new TrustManagerException("ServiceResponse Expired"); } byte[] actualPacket = Arrays.copyOf(responeDp.getData(), responeDp.getLength()); logger.debug("\nServiceResponse in hex: \n{}\n", Hex.encodeHexString(actualPacket)); } } catch (Exception e) { throw new TrustManagerException("Error Receiving Service Response", e); } return servResponse; } public ServiceResponse createServiceResponse(ServiceRequest request) { ServiceResponse response = new ServiceResponse(); response.setDialogID(request.getDialogID()); ZonedDateTime expiresAt = ZonedDateTime.now().plusSeconds(odeProperties.getServiceRespExpirationSeconds()); response.setExpiration(new DDateTime( new DYear(expiresAt.getYear()), new DMonth(expiresAt.getMonthValue()), new DDay(expiresAt.getDayOfMonth()), new DHour(expiresAt.getHour()), new DMinute(expiresAt.getMinute()), new DSecond(expiresAt.getSecond()), new DOffset(0))); response.setGroupID(request.getGroupID()); response.setRequestID(request.getRequestID()); response.setSeqID(SemiSequenceID.svcResp); response.setHash(new Sha256Hash(ByteBuffer.allocate(32).putInt(1).array())); return response; } public void sendServiceResponse(ServiceResponse response, String ip, int port) { try { logger.debug("Sending ServiceResponse {} to {}:{}", response.toString(), ip, port); byte[] responseBytes = J2735Util.encode(coder, response); socket.send(new DatagramPacket(responseBytes, responseBytes.length, new InetSocketAddress(ip, port))); } catch (IOException e) { logger.error("Error Sending ServiceResponse", e); } } public void sendServiceRequest(ServiceRequest request, String ip, int port) { try { trustEstablished = false; logger.debug("Sending ServiceRequest {} to {}:{}", request.toString(), ip, port); byte[] requestBytes = J2735Util.encode(coder, request); socket.send(new DatagramPacket(requestBytes,requestBytes.length, new InetSocketAddress(ip, port))); } catch (IOException e) { logger.error("Error ServiceRequest", e); } } public boolean establishTrust(int srcPort, String destIp, int destPort, TemporaryID requestId, SemiDialogID dialogId, GroupID groupId) throws SocketException, TrustManagerException { logger.info("Establishing trust..."); // if (this.socket != null && !trustEstablished) { // logger.debug("Closing outbound socket srcPort={}, destPort={}", srcPort, destPort); // socket.close(); // socket = null; if (this.socket == null) { socket = new DatagramSocket(srcPort); logger.debug("Creating outbound socket srcPort={}, destPort={}", srcPort, destPort); } // Launch a trust manager thread to listen for the service response Future<ServiceResponse> f = execService.submit(this); ServiceRequest request = createServiceRequest(requestId, dialogId, groupId); // send the service request this.sendServiceRequest(request, destIp, destPort); // Wait for service response try { ServiceResponse response = f.get( odeProperties.getServiceRespExpirationSeconds(), TimeUnit.SECONDS); logger.info("Received ServiceResponse from SDC {}", response.toString()); if (response.getRequestID().equals(request.getRequestID())) { trustEstablished = true; logger.info("Trust established, session request ID: {}", HexUtils.toHexString(request.getRequestID().byteArrayValue())); } else { logger.error("Received ServiceResponse from SDC but the requestID does not match! {} != {}", response.getRequestID(), request.getRequestID()); trustEstablished = false; } } catch (Exception e) { trustEstablished = false; // throw new TrustManagerException("Did not receive Service Response within alotted " + // + odeProperties.getServiceRespExpirationSeconds() + // " seconds", e); logger.error("Did not receive Service Response within alotted " + + odeProperties.getServiceRespExpirationSeconds() + " seconds", e); } return trustEstablished; } @Override public ServiceResponse call() throws Exception { return receiveServiceResponse(); } public boolean isTrustEstablished() { return trustEstablished; } public void setTrustEstablished(boolean trustEstablished) { this.trustEstablished = trustEstablished; } public boolean isEstablishingTrust() { return establishingTrust; } public void setEstablishingTrust(boolean establishingTrust) { this.establishingTrust = establishingTrust; } }
package org.jpos.transaction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.io.NotActiveException; import java.io.SerializablePermission; import java.io.UnsupportedEncodingException; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import org.jdom2.Comment; import org.jdom2.Element; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.core.SimpleConfiguration; import org.jpos.core.SubConfiguration; import org.jpos.transaction.participant.BSHTransactionParticipant; import org.jpos.transaction.participant.CheckPoint; import org.jpos.transaction.participant.Debug; import org.jpos.transaction.participant.Forward; import org.jpos.transaction.participant.HasEntry; import org.jpos.transaction.participant.Join; import org.jpos.transaction.participant.Trace; import org.jpos.util.LogEvent; import org.junit.Before; import org.junit.Test; @SuppressWarnings("unchecked") public class TransactionManagerTest { private TransactionManager transactionManager; private List members; @Before public void onSetup() { transactionManager = new TransactionManager(); members = new ArrayList(); } @Test public void testAbort2() throws Throwable { members.add(new Join()); transactionManager.abort(1, 100L, "", members, false, null, null); assertEquals("(ArrayList) members.size()", 1, members.size()); } @Test public void testAbort3() throws Throwable { LogEvent evt = new LogEvent("testTransactionManagerTag", Integer.valueOf(2)); transactionManager.abort(1, 100L, Boolean.TRUE, members, members.add(new Forward()), evt, null); assertEquals("evt.payLoad.size()", 2, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(1)", " abort: org.jpos.transaction.participant.Forward", evt.getPayLoad().get(1)); } @Test public void testAbort4() throws Throwable { members.add(new Debug()); LogEvent evt = new LogEvent("testTransactionManagerTag"); transactionManager.abort(1, 100L, "", members, false, evt, null); assertEquals("evt.payLoad.size()", 1, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(0)", " abort: org.jpos.transaction.participant.Debug", evt.getPayLoad().get(0)); } @Test public void testAbort5() throws Throwable { transactionManager.abort(1, 100L, Long.valueOf(-64L), members, members.add(new Join()), null, null); assertEquals("(ArrayList) members.size()", 1, members.size()); } @Test public void testAbort6() throws Throwable { LogEvent evt = new LogEvent(); transactionManager.abort(1, 100L, new NotActiveException(), members, true, evt, null); assertEquals("(ArrayList) members.size()", 0, members.size()); } @Test public void testAbortThrowsNullPointerException() throws Throwable { LogEvent evt = new LogEvent("testTransactionManagerTag"); try { transactionManager.abort(1, 100L, new NotActiveException("testTransactionManagerParam1"), members, members.add(null), evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertEquals("(ArrayList) members.size()", 1, members.size()); } } @Test public void testAbortThrowsNullPointerException2() throws Throwable { LogEvent evt = new LogEvent("testTransactionManagerTag", ""); try { transactionManager.abort(1, 100L, new File("testTransactionManagerParam1"), null, true, evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); } } @Test public void testCheckRetryTask() throws Throwable { transactionManager.checkRetryTask(); transactionManager.checkRetryTask(); assertNotNull("transactionManager.retryTask", transactionManager.retryTask); } @Test public void testCheckRetryTask1() throws Throwable { transactionManager.checkRetryTask(); assertNotNull("transactionManager.retryTask", transactionManager.retryTask); } @Test public void testCheckTailThrowsNullPointerException() throws Throwable { try { transactionManager.checkTail(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.sp", transactionManager.sp); assertEquals("transactionManager.tail", 0L, transactionManager.tail); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testCommit1() throws Throwable { transactionManager.commit(1, 100L, "", members, members.add(new HasEntry()), null, null); assertEquals("(ArrayList) members.size()", 1, members.size()); } @Test public void testCommit2() throws Throwable { members.add(new CheckPoint()); transactionManager.commit(1, 100L, new IOException(), members, false, null, null); assertEquals("(ArrayList) members.size()", 1, members.size()); } @Test public void testCommit3() throws Throwable { members.add(new Debug()); LogEvent evt = new LogEvent(); transactionManager.commit(1, 100L, Boolean.FALSE, members, false, evt, null); assertEquals("evt.payLoad.size()", 1, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(0)", " commit: org.jpos.transaction.participant.Debug", evt.getPayLoad().get(0)); } @Test public void testCommit4() throws Throwable { LogEvent evt = new LogEvent("testTransactionManagerTag"); transactionManager.commit(1, 100L, new NotActiveException("testTransactionManagerParam1"), members, true, evt, null); assertEquals("(ArrayList) members.size()", 0, members.size()); } @Test public void testCommit5() throws Throwable { TransactionParticipant p = new Trace(); transactionManager.commit(p, 100L, Boolean.FALSE); assertTrue("Test completed without Exception", true); } @Test public void testCommit6() throws Throwable { TransactionParticipant p = new CheckPoint(); transactionManager.commit(p, 100L, ""); assertTrue("Test completed without Exception", true); } @Test public void testCommitThrowsNullPointerException() throws Throwable { LogEvent evt = new LogEvent(); try { transactionManager.commit(1, 100L, "testString", members, members.add(null), evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertEquals("(ArrayList) members.size()", 1, members.size()); } } @Test public void testCommitThrowsNullPointerException2() throws Throwable { LogEvent evt = new LogEvent(); try { transactionManager.commit(1, 100L, new SerializablePermission("testTransactionManagerParam1"), null, true, evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); } } @Test public void testConstructor() throws Throwable { assertNull("transactionManager.retryTask", transactionManager.retryTask); assertEquals("transactionManager.getLog().getRealm()", "org.jpos.transaction.TransactionManager", transactionManager .getLog().getRealm()); assertEquals("transactionManager.getState()", -1, transactionManager.getState()); assertTrue("transactionManager.isModified()", transactionManager.isModified()); assertEquals("transactionManager.pauseTimeout", 0L, transactionManager.pauseTimeout); assertEquals("transactionManager.retryInterval", 5000L, transactionManager.retryInterval); } @Test public void testGetHead() throws Throwable { long result = new TransactionManager().getHead(); assertEquals("result", 0L, result); } @Test public void testGetKeyThrowsNullPointerException() throws Throwable { try { transactionManager.getKey(null, 100L); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); } } @Test public void testGetOutstandingTransactions() throws Throwable { int result = new TransactionManager().getOutstandingTransactions(); assertEquals("result", -1, result); } @Test public void testGetParticipantsThrowsNullPointerException() throws Throwable { try { transactionManager.getParticipants("testTransactionManagerGroupName"); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.groups", transactionManager.groups); } } @Test public void testGetTail() throws Throwable { long result = new TransactionManager().getTail(); assertEquals("result", 0L, result); } @Test public void testInitCounterThrowsNullPointerException() throws Throwable { try { transactionManager.initCounter("testTransactionManagerName", 100L); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testInitParticipantsThrowsNullPointerException() throws Throwable { Element config = new Element("testTransactionManagerName"); try { transactionManager.initParticipants(config); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.groups", transactionManager.groups); assertEquals("config.getName()", "testTransactionManagerName", config.getName()); } } @Test public void testInitServiceThrowsConfigurationException() throws Throwable { Configuration cfg = new SimpleConfiguration(); transactionManager.setConfiguration(cfg); try { transactionManager.initService(); fail("Expected ConfigurationException to be thrown"); } catch (ConfigurationException ex) { assertEquals("ex.getMessage()", "queue property not specified", ex.getMessage()); assertNull("ex.getNested()", ex.getNested()); assertNull("transactionManager.queue", transactionManager.queue); assertSame("transactionManager.getConfiguration()", cfg, transactionManager.getConfiguration()); assertEquals("transactionManager.tail", 0L, transactionManager.tail); assertTrue("transactionManager.isModified()", transactionManager.isModified()); assertNull("transactionManager.sp", transactionManager.sp); assertNull("transactionManager.psp", transactionManager.psp); assertEquals("transactionManager.head", 0L, transactionManager.head); assertNull("transactionManager.groups", transactionManager.groups); assertNull("transactionManager.tailLock", transactionManager.tailLock); } } @Test public void testInitServiceThrowsNullPointerException() throws Throwable { try { transactionManager.initService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.queue", transactionManager.queue); assertNull("transactionManager.getConfiguration()", transactionManager.getConfiguration()); assertEquals("transactionManager.tail", 0L, transactionManager.tail); assertTrue("transactionManager.isModified()", transactionManager.isModified()); assertNull("transactionManager.sp", transactionManager.sp); assertNull("transactionManager.psp", transactionManager.psp); assertEquals("transactionManager.head", 0L, transactionManager.head); assertNull("transactionManager.groups", transactionManager.groups); assertNull("transactionManager.tailLock", transactionManager.tailLock); } } @Test public void testInitTailLockThrowsNullPointerException() throws Throwable { try { transactionManager.initTailLock(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.sp", transactionManager.sp); } } @Test public void testNextIdThrowsNullPointerException() throws Throwable { try { transactionManager.nextId(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertEquals("transactionManager.head", 0L, transactionManager.head); } } @Test public void testPrepare10() throws Throwable { HasEntry hasEntry = new HasEntry(); AbstractList<TransactionParticipant> arrayList = new ArrayList(); arrayList.add(new Debug()); int result = transactionManager.prepare(1, 100L, new NotActiveException("testTransactionManagerParam1"), members, arrayList.iterator(), members.add(hasEntry), null, null); assertEquals("(ArrayList) members.size()", 2, members.size()); assertSame("(ArrayList) members.get(0)", hasEntry, members.get(0)); assertEquals("result", 0, result); } @Test public void testPrepare2() throws Throwable { int result = transactionManager.prepare(new CheckPoint(), 100L, Boolean.FALSE); assertEquals("result", 193, result); } @Test public void testPrepare5() throws Throwable { int result = transactionManager.prepare(1, 100L, new File("testTransactionManagerParam1"), new ArrayList(), new ArrayList( 1000).iterator(), true, new LogEvent("testTransactionManagerTag"), null); assertEquals("result", 64, result); } @Test public void testPrepare7() throws Throwable { transactionManager = new TransactionManager(); List<TransactionParticipant> members = new ArrayList(); List<TransactionParticipant> arrayList = new ArrayList(); BSHTransactionParticipant bSHTransactionParticipant = new BSHTransactionParticipant(); boolean abort = arrayList.add(bSHTransactionParticipant); LogEvent evt = new LogEvent(); int result = transactionManager.prepare(1, 100L, Boolean.FALSE, members, arrayList.iterator(), abort, evt, null); assertEquals("(ArrayList) members.size()", 1, members.size()); assertSame("(ArrayList) members.get(0)", bSHTransactionParticipant, members.get(0)); assertEquals("evt.payLoad.size()", 1, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(0)", "prepareForAbort: org.jpos.transaction.participant.BSHTransactionParticipant", evt .getPayLoad().get(0)); assertEquals("result", 0, result); } @Test public void testPrepare8() throws Throwable { AbstractList<TransactionParticipant> arrayList = new ArrayList(1000); arrayList.add(new HasEntry()); LogEvent evt = new LogEvent(); int result = transactionManager.prepare(1, 100L, Boolean.TRUE, new ArrayList(), arrayList.iterator(), false, evt, null); assertEquals("evt.payLoad.size()", 3, evt.getPayLoad().size()); assertEquals("result", 64, result); } @Test public void testPrepareForAbort1() throws Throwable { int result = transactionManager.prepareForAbort(new Trace(), 100L, new File("testTransactionManagerParam1")); assertEquals("result", 64, result); } @Test public void testPrepareForAbort2() throws Throwable { int result = transactionManager.prepareForAbort(new Debug(), 100L, Boolean.FALSE); assertEquals("result", 129, result); } @Test public void testPrepareThrowsNullPointerException3() throws Throwable { List<TransactionParticipant> members = new ArrayList(); List<TransactionParticipant> arrayList = new ArrayList(); arrayList.add(new Forward()); LogEvent evt = new LogEvent(); try { transactionManager.prepare(1, 100L, Boolean.FALSE, members, arrayList.iterator(), false, evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertEquals("evt.payLoad.size()", 1, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(0)", " prepare: org.jpos.transaction.participant.Forward ABORTED", evt.getPayLoad() .get(0)); assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertNull("transactionManager.groups", transactionManager.groups); assertEquals("(ArrayList) members.size()", 0, members.size()); } } @Test public void testPrepareThrowsNullPointerException5() throws Throwable { LogEvent evt = new LogEvent("testTransactionManagerTag"); List<TransactionParticipant> members = new ArrayList(); List<TransactionParticipant> arrayList = new ArrayList(); boolean abort = arrayList.add(new Trace()); try { transactionManager.prepare(1, 100L, new NotActiveException(), members, arrayList.iterator(), abort, evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertEquals("evt.payLoad.size()", 1, evt.getPayLoad().size()); assertEquals("evt.payLoad.get(0)", "prepareForAbort: org.jpos.transaction.participant.Trace", evt.getPayLoad().get(0)); assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertNull("transactionManager.groups", transactionManager.groups); assertEquals("(ArrayList) members.size()", 0, members.size()); } } @Test public void testPrepareThrowsNullPointerException9() throws Throwable { LogEvent evt = new LogEvent(); try { transactionManager.prepare(1, 100L, new UnsupportedEncodingException(), members, null, true, evt, null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertNull("transactionManager.groups", transactionManager.groups); assertEquals("(ArrayList) members.size()", 0, members.size()); } } @Test public void testPurgeThrowsNullPointerException() throws Throwable { try { transactionManager.purge(100L, true); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testRecoverThrowsNullPointerException() throws Throwable { try { transactionManager.recover(1, 100L); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertNull("transactionManager.groups", transactionManager.groups); } } @Test public void testRecoverThrowsNullPointerException1() throws Throwable { try { transactionManager.recover(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertEquals("transactionManager.tail", 0L, transactionManager.tail); assertNull("transactionManager.groups", transactionManager.groups); } } @Test public void testRetryTaskRun() throws Throwable { new TransactionManager().new RetryTask().run(); assertTrue("Test completed without Exception", true); } @Test public void testSetConfiguration() throws Throwable { Configuration cfg = new SimpleConfiguration(); transactionManager.setConfiguration(cfg); assertTrue("transactionManager.debug", transactionManager.debug); assertSame("transactionManager.getConfiguration()", cfg, transactionManager.getConfiguration()); assertEquals("transactionManager.pauseTimeout", 0L, transactionManager.pauseTimeout); assertEquals("transactionManager.retryInterval", 5000L, transactionManager.retryInterval); } @Test public void testSetConfigurationThrowsNullPointerException() throws Throwable { Configuration cfg = new SubConfiguration(); try { transactionManager.setConfiguration(cfg); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertFalse("transactionManager.debug", transactionManager.debug); assertSame("transactionManager.getConfiguration()", cfg, transactionManager.getConfiguration()); assertEquals("transactionManager.pauseTimeout", 0L, transactionManager.pauseTimeout); assertEquals("transactionManager.retryInterval", 5000L, transactionManager.retryInterval); } } @Test public void testSetStateThrowsNullPointerException() throws Throwable { try { transactionManager.setState(100L, Integer.valueOf(-1)); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testSnapshotThrowsNullPointerException() throws Throwable { try { transactionManager.snapshot(100L, "testString", Integer.valueOf(-100)); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testSnapshotThrowsNullPointerException1() throws Throwable { try { transactionManager.snapshot(100L, new Comment("testTransactionManagerText")); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } @Test public void testStartServiceThrowsNullPointerException1() throws Throwable { transactionManager.setName("testTransactionManagerName"); try { transactionManager.startService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); assertNull("transactionManager.threads", transactionManager.threads); assertNull("transactionManager.getConfiguration()", transactionManager.getConfiguration()); assertEquals("transactionManager.tail", 0L, transactionManager.tail); assertNull("transactionManager.groups", transactionManager.groups); } } @Test public void testTailDoneThrowsNullPointerException() throws Throwable { try { transactionManager.tailDone(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertNull("transactionManager.psp", transactionManager.psp); } } }
package jsprit.core.algorithm.box; import jsprit.core.algorithm.SearchStrategy; import jsprit.core.algorithm.VehicleRoutingAlgorithm; import jsprit.core.algorithm.listener.StrategySelectedListener; import jsprit.core.algorithm.recreate.InsertionData; import jsprit.core.algorithm.recreate.listener.BeforeJobInsertionListener; import jsprit.core.algorithm.recreate.listener.JobInsertedListener; import jsprit.core.algorithm.ruin.listener.RuinListener; import jsprit.core.algorithm.termination.VariationCoefficientTermination; import jsprit.core.problem.Location; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.io.VrpXMLReader; import jsprit.core.problem.job.Job; import jsprit.core.problem.job.Service; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.vehicle.VehicleImpl; import jsprit.core.util.RandomNumberGeneration; import jsprit.core.util.Solutions; import junit.framework.Assert; import org.junit.Test; import java.util.*; public class JspritTest { @Test public void whenRunningJspritWithSingleCustomer_itShouldWork(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(10000); final Map<String,Integer> counts = new HashMap<String,Integer>(); vra.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { count(discoveredSolution.getStrategyId()); } private void count(String strategyId) { if(!counts.containsKey(strategyId)) counts.put(strategyId,1); counts.put(strategyId,counts.get(strategyId)+1); } }); try { vra.searchSolutions(); Assert.assertTrue(true); } catch (Exception e){ Assert.assertTrue(false); } } // @Test // public void defaultStrategyProbabilitiesShouldWork_(){ // Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); // Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); // VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); // VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(s2).addJob(s).build(); // VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); // vra.setMaxIterations(5000); // final Map<String,Integer> counts = new HashMap<String,Integer>(); // vra.addListener(new StrategySelectedListener() { // @Override // public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { // count(discoveredSolution.getStrategyId()); // private void count(String strategyId) { // if(!counts.containsKey(strategyId)) counts.put(strategyId,1); // Integer integer = counts.get(strategyId); // counts.put(strategyId, integer +1); // vra.searchSolutions(); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.RADIAL_BEST.toString())); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.WORST_BEST.toString())); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.CLUSTER_BEST.toString())); // Integer randomBestCounts = counts.get(Jsprit.Strategy.RANDOM_BEST.toString()); // Assert.assertEquals(5000.*0.5/3.5,(double) randomBestCounts,100); // Assert.assertEquals(5000.*0.5/3.5,(double) counts.get(Jsprit.Strategy.RANDOM_REGRET.toString()),100); // Assert.assertEquals(5000.*0.5/3.5,(double) counts.get(Jsprit.Strategy.RADIAL_REGRET.toString()),100); // Assert.assertEquals(5000.*1./3.5,(double) counts.get(Jsprit.Strategy.WORST_REGRET.toString()),100); // Assert.assertEquals(5000.*1./3.5,(double) counts.get(Jsprit.Strategy.CLUSTER_REGRET.toString()),100); // @Test // public void whenChangingStratProb_itShouldBeReflected(){ // Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); // Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); // VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); // VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(s2).addJob(s).build(); // VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp) // .setProperty(Jsprit.Strategy.RANDOM_BEST,"100.").buildAlgorithm(); // vra.setMaxIterations(5000); // final Map<String,Integer> counts = new HashMap<String,Integer>(); // vra.addListener(new StrategySelectedListener() { // @Override // public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { // count(discoveredSolution.getStrategyId()); // private void count(String strategyId) { // if(!counts.containsKey(strategyId)) counts.put(strategyId,1); // Integer integer = counts.get(strategyId); // counts.put(strategyId, integer +1); // vra.searchSolutions(); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.RADIAL_BEST.toString())); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.WORST_BEST.toString())); // Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.CLUSTER_BEST.toString())); // Integer randomBestCounts = counts.get(Jsprit.Strategy.RANDOM_BEST.toString()); // Assert.assertEquals(5000.*100./103.,(double) randomBestCounts,100); // Assert.assertEquals(5000.*0.5/103.,(double) counts.get(Jsprit.Strategy.RANDOM_REGRET.toString()),100); // Assert.assertEquals(5000.*0.5/103.,(double) counts.get(Jsprit.Strategy.RADIAL_REGRET.toString()),100); // Assert.assertEquals(5000.*1./103.,(double) counts.get(Jsprit.Strategy.WORST_REGRET.toString()),100); // Assert.assertEquals(5000.*1./103.,(double) counts.get(Jsprit.Strategy.CLUSTER_REGRET.toString()),100); @Test public void whenActivatingStrat_itShouldBeReflected(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.Builder.newInstance(vrp) .setProperty(Jsprit.Strategy.RADIAL_BEST,"100.").buildAlgorithm(); vra.setMaxIterations(5000); final Map<String,Integer> counts = new HashMap<String,Integer>(); vra.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { count(discoveredSolution.getStrategyId()); } private void count(String strategyId) { if(!counts.containsKey(strategyId)) counts.put(strategyId,1); Integer integer = counts.get(strategyId); counts.put(strategyId, integer +1); } }); vra.searchSolutions(); Assert.assertTrue(counts.containsKey(Jsprit.Strategy.RADIAL_BEST.toString())); } @Test public void test_v3(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(5000); final Map<String,Integer> counts = new HashMap<String,Integer>(); vra.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { count(discoveredSolution.getStrategyId()); } private void count(String strategyId) { if(!counts.containsKey(strategyId)) counts.put(strategyId,1); counts.put(strategyId,counts.get(strategyId)+1); } }); vra.searchSolutions(); Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.RADIAL_BEST)); } @Test public void test_v4(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(1,2)).build(); Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(5000); final Map<String,Integer> counts = new HashMap<String,Integer>(); vra.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { count(discoveredSolution.getStrategyId()); } private void count(String strategyId) { if(!counts.containsKey(strategyId)) counts.put(strategyId,1); counts.put(strategyId,counts.get(strategyId)+1); } }); vra.searchSolutions(); Assert.assertTrue(!counts.containsKey(Jsprit.Strategy.RADIAL_BEST)); } @Test public void strategyDrawShouldBeReproducible(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(1,2)).build(); Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(1000); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { firstRecord.add(discoveredSolution.getStrategyId()); } }); vra.searchSolutions(); RandomNumberGeneration.reset(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(1000); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new StrategySelectedListener() { @Override public void informSelectedStrategy(SearchStrategy.DiscoveredSolution discoveredSolution, VehicleRoutingProblem vehicleRoutingProblem, Collection<VehicleRoutingProblemSolution> vehicleRoutingProblemSolutions) { secondRecord.add(discoveredSolution.getStrategyId()); } }); second.searchSolutions(); for(int i=0;i<1000;i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ org.junit.Assert.assertFalse(true); } } org.junit.Assert.assertTrue(true); } @Test public void ruinedJobsShouldBeReproducible(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(1,2)).build(); Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(1000); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { firstRecord.add(job.getId()); } }); vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(1000); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { secondRecord.add(job.getId()); } }); second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); } @Test public void whenBiggerProblem_ruinedJobsShouldBeReproducible(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(1000); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { firstRecord.add(job.getId()); } }); vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(1000); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { secondRecord.add(job.getId()); } }); second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); } @Test public void insertionShouldBeReproducible(){ Service s = Service.Builder.newInstance("s1").setLocation(Location.newInstance(1,1)).build(); Service s2 = Service.Builder.newInstance("s2").setLocation(Location.newInstance(1,2)).build(); Service s3 = Service.Builder.newInstance("s3").setLocation(Location.newInstance(1,2)).build(); Service s4 = Service.Builder.newInstance("s4").setLocation(Location.newInstance(1,2)).build(); VehicleImpl v = VehicleImpl.Builder.newInstance("v").setStartLocation(Location.newInstance(0,0)).build(); VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addJob(s4).addJob(s3).addVehicle(v).addJob(s2).addJob(s).build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(1000); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { firstRecord.add(job2insert.getId()); } }); vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(1000); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { secondRecord.add(job2insert.getId()); } }); second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); } @Test public void whenBiggerProblem_insertionShouldBeReproducible(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(200); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { firstRecord.add(job2insert.getId()); } }); vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(200); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { secondRecord.add(job2insert.getId()); } }); second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); } @Test public void whenBiggerProblem_insertionPositionsShouldBeReproducible(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(200); final List<Integer> firstRecord = new ArrayList<Integer>(); vra.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { firstRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> firstSolutions = vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(200); final List<Integer> secondRecord = new ArrayList<Integer>(); second.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { secondRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> secondSolutions = second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); Assert.assertEquals(Solutions.bestOf(firstSolutions).getCost(),Solutions.bestOf(secondSolutions).getCost()); } @Test public void whenTerminatingWithVariationCoefficient_terminationShouldBeReproducible(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(1000); VariationCoefficientTermination termination = new VariationCoefficientTermination(50, 0.005); vra.setPrematureAlgorithmTermination(termination); vra.addListener(termination); final List<Integer> firstRecord = new ArrayList<Integer>(); vra.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { firstRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> firstSolutions = vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); VariationCoefficientTermination secondTermination = new VariationCoefficientTermination(50, 0.005); second.setPrematureAlgorithmTermination(secondTermination); second.addListener(secondTermination); second.setMaxIterations(1000); final List<Integer> secondRecord = new ArrayList<Integer>(); second.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { secondRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> secondSolutions = second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); Assert.assertEquals(Solutions.bestOf(firstSolutions).getCost(), Solutions.bestOf(secondSolutions).getCost()); } @Test public void whenBiggerProblem_insertioPositionsShouldBeReproducibleWithoutResetingRNGExplicitly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(200); final List<Integer> firstRecord = new ArrayList<Integer>(); vra.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { firstRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> firstSolutions = vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(200); final List<Integer> secondRecord = new ArrayList<Integer>(); second.addListener(new BeforeJobInsertionListener() { @Override public void informBeforeJobInsertion(Job job, InsertionData data, VehicleRoute route) { secondRecord.add(data.getDeliveryInsertionIndex()); } }); Collection<VehicleRoutingProblemSolution> secondSolutions = second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); Assert.assertEquals(Solutions.bestOf(firstSolutions).getCost(),Solutions.bestOf(secondSolutions).getCost()); } @Test public void whenBiggerProblem_ruinedJobsShouldBeReproducibleWithoutResetingRNGExplicitly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/vrpnc1-jsprit-with-deliveries.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); vra.setMaxIterations(200); final List<String> firstRecord = new ArrayList<String>(); vra.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { firstRecord.add(job.getId()); } }); vra.searchSolutions(); VehicleRoutingAlgorithm second = Jsprit.createAlgorithm(vrp); second.setMaxIterations(200); final List<String> secondRecord = new ArrayList<String>(); second.addListener(new RuinListener() { @Override public void ruinStarts(Collection<VehicleRoute> routes) { } @Override public void ruinEnds(Collection<VehicleRoute> routes, Collection<Job> unassignedJobs) { } @Override public void removed(Job job, VehicleRoute fromRoute) { secondRecord.add(job.getId()); } }); second.searchSolutions(); Assert.assertEquals(secondRecord.size(),firstRecord.size()); for(int i=0;i<firstRecord.size();i++){ if(!firstRecord.get(i).equals(secondRecord.get(i))){ Assert.assertFalse(true); } } Assert.assertTrue(true); } }
package org.junit.gen5.launcher; import static java.util.Arrays.asList; import java.util.List; import org.junit.gen5.engine.FilterResult; import org.junit.gen5.engine.TestTag; /** * Factory methods for creating {@link PostDiscoveryFilter PostDiscoveryFilters} * based on <em>include</em> and <em>exclude</em> tags. * * @since 5.0 */ public final class TagFilter { private TagFilter() { /* no-op */ } /** * Create an <em>include</em> filter based on the supplied {@code tags}. * * <p>Containers and tests will only be executed if they are tagged with * at least one of the supplied <em>include</em> tags. */ public static PostDiscoveryFilter includeTags(String... tags) { return includeTags(asList(tags)); } /** * Create an <em>include</em> filter based on the supplied {@code tags}. * * <p>Containers and tests will only be executed if they are tagged with * at least one of the supplied <em>include</em> tags. */ public static PostDiscoveryFilter includeTags(List<String> tags) { // @formatter:off return descriptor -> FilterResult.includedIf( descriptor.getTags().stream() .map(TestTag::getName) .map(String::trim) .anyMatch(tags::contains)); // @formatter:on } /** * Create an <em>exclude</em> filter based on the supplied {@code tags}. * * <p>Containers and tests will only be executed if they are <em>not</em> * tagged with any of the supplied <em>exclude</em> tags. */ public static PostDiscoveryFilter excludeTags(String... tags) { return excludeTags(asList(tags)); } /** * Create an <em>exclude</em> filter based on the supplied {@code tags}. * * <p>Containers and tests will only be executed if they are <em>not</em> * tagged with any of the supplied <em>exclude</em> tags. */ public static PostDiscoveryFilter excludeTags(List<String> tags) { // @formatter:off return descriptor -> FilterResult.includedIf( descriptor.getTags().stream() .map(TestTag::getName) .map(String::trim) .noneMatch(tags::contains)); // @formatter:on } }
package test; import java.io.*; import java.util.concurrent.*; import junit.framework.*; import aQute.bnd.build.*; import aQute.lib.io.*; public class LauncherTest extends TestCase { /** * Tests if the properties are cleaned up. This requires some knowledge of * the launcher unfortunately. It is also not sure if the file is not just * deleted by the onExit ... * * @throws Exception */ public static void testCleanup() throws Exception { Project project = getProject(); File target = project.getTarget(); IO.deleteWithException(target); project.clear(); assertNoProperties(target); final ProjectLauncher l = project.getProjectLauncher(); l.setTrace(true); Thread t = new Thread() { @Override public void run() { try { Thread.sleep(1000); l.cancel(); } catch (Exception e) { // Ignore } } }; t.start(); l.getRunProperties().put("test.cmd", "timeout"); l.launch(); assertNoProperties(target); } /** * The properties file is an implementation detail ... so this is white box * testing. * * @param project * @throws Exception */ private static void assertNoProperties(File target) throws Exception { if (!target.exists()) return; for (File file : target.listFiles()) { if (file.getAbsolutePath().startsWith("launch")) { fail("There is a launch file in the target directory: " + file); } } } public static void testSimple() throws Exception { Project project = getProject(); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTrace(true); l.getRunProperties().put("test.cmd", "exit"); assertEquals(42, l.launch()); } // public static void testWorkspaceWithSpace() throws Exception { // Project project = getProjectFromWorkspaceWithSpace(); // project.clear(); // project.clean(); // // reuse built .class files from the demo project. // String base = new File("").getAbsoluteFile().getParentFile().getAbsolutePath(); // new File(base + "/biz.aQute.bndlib.tests/test/a space/test/bin/test/").mkdirs(); // IO.copy(new File(base + "/demo/bin/test/TestActivator$1.class"), // new File(base + "/biz.aQute.bndlib.tests/test/a space/test/bin/test/TestActivator$1.class")); // IO.copy(new File(base + "/demo/bin/test/TestActivator.class"), // new File(base + "/biz.aQute.bndlib.tests/test/a space/test/bin/test/TestActivator.class")); // project.clear(); // project.build(); // ProjectLauncher l = project.getProjectLauncher(); // l.setTrace(true); // l.getRunProperties().put("test.cmd", "exit"); // assertEquals(42, l.launch()); /** * @return * @throws Exception */ static Project getProject() throws Exception { Workspace workspace = Workspace.getWorkspace(new File("").getAbsoluteFile().getParentFile()); Project project = workspace.getProject("demo"); return project; } static Project getProjectFromWorkspaceWithSpace() throws Exception { Workspace workspace = Workspace.getWorkspace(new File("test/a space")); Project project = workspace.getProject("test"); return project; } public static void testTester() throws Exception { Project project = getProject(); project.clear(); project.build(); ProjectTester pt = project.getProjectTester(); pt.addTest("test.TestCase1"); assertEquals(2, pt.test()); } public static void testTimeoutActivator() throws Exception { Project project = getProject(); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(100, TimeUnit.MILLISECONDS); l.setTrace(false); assertEquals(ProjectLauncher.TIMEDOUT, l.launch()); } public static void testTimeout() throws Exception { Project project = getProject(); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(100, TimeUnit.MILLISECONDS); l.setTrace(false); l.getRunProperties().put("test.cmd", "timeout"); assertEquals(ProjectLauncher.TIMEDOUT, l.launch()); } public static void testMainThread() throws Exception { Project project = getProject(); project.clear(); ProjectLauncher l = project.getProjectLauncher(); l.setTimeout(10000, TimeUnit.MILLISECONDS); l.setTrace(false); l.getRunProperties().put("test.cmd", "main.thread"); assertEquals(ProjectLauncher.OK, l.launch()); } }
package aQute.bnd.build; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import java.util.regex.Pattern; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.service.repository.ContentNamespace; import org.osgi.service.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.build.Container.TYPE; import aQute.bnd.exporter.executable.ExecutableJarExporter; import aQute.bnd.exporter.runbundles.RunbundlesExporter; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.help.Syntax; import aQute.bnd.http.HttpClient; import aQute.bnd.maven.support.Pom; import aQute.bnd.maven.support.ProjectPom; import aQute.bnd.osgi.About; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Builder; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Instruction; import aQute.bnd.osgi.Instructions; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.JarResource; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Packages; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Resource; import aQute.bnd.osgi.Verifier; import aQute.bnd.osgi.eclipse.EclipseClasspath; import aQute.bnd.osgi.resource.CapReqBuilder; import aQute.bnd.osgi.resource.ResourceUtils; import aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability; import aQute.bnd.service.CommandPlugin; import aQute.bnd.service.DependencyContributor; import aQute.bnd.service.Deploy; import aQute.bnd.service.RepositoryPlugin; import aQute.bnd.service.RepositoryPlugin.PutOptions; import aQute.bnd.service.RepositoryPlugin.PutResult; import aQute.bnd.service.Scripter; import aQute.bnd.service.Strategy; import aQute.bnd.service.action.Action; import aQute.bnd.service.action.NamedAction; import aQute.bnd.service.export.Exporter; import aQute.bnd.service.release.ReleaseBracketingPlugin; import aQute.bnd.version.Version; import aQute.bnd.version.VersionRange; import aQute.lib.collections.ExtList; import aQute.lib.collections.Iterables; import aQute.lib.converter.Converter; import aQute.lib.exceptions.Exceptions; import aQute.lib.io.IO; import aQute.lib.strings.Strings; import aQute.lib.utf8properties.UTF8Properties; import aQute.libg.command.Command; import aQute.libg.generics.Create; import aQute.libg.glob.Glob; import aQute.libg.qtokens.QuotedTokenizer; import aQute.libg.reporter.ReporterMessages; import aQute.libg.sed.Replacer; import aQute.libg.sed.Sed; import aQute.libg.tuple.Pair; /** * This class is NOT threadsafe */ public class Project extends Processor { private final static Logger logger = LoggerFactory.getLogger(Project.class); static class RefreshData { Parameters installRepositories; } final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy"; public final static String BNDFILE = "bnd.bnd"; final static Path BNDPATH = Paths.get(BNDFILE); public final static String BNDCNF = "cnf"; public final static String SHA_256 = "SHA-256"; final Workspace workspace; private final AtomicBoolean preparedPaths = new AtomicBoolean(); private final Set<Project> dependenciesFull = new LinkedHashSet<>(); private final Set<Project> dependenciesBuild = new LinkedHashSet<>(); private final Set<Project> dependenciesTest = new LinkedHashSet<>(); private final Set<Project> dependents = new LinkedHashSet<>(); final Collection<Container> classpath = new LinkedHashSet<>(); final Collection<Container> buildpath = new LinkedHashSet<>(); final Collection<Container> testpath = new LinkedHashSet<>(); final Collection<Container> runpath = new LinkedHashSet<>(); final Collection<Container> runbundles = new LinkedHashSet<>(); final Collection<Container> runfw = new LinkedHashSet<>(); File runstorage; final Map<File, Attrs> sourcepath = new LinkedHashMap<>(); final Collection<File> allsourcepath = new LinkedHashSet<>(); final Collection<Container> bootclasspath = new LinkedHashSet<>(); final Map<String, Version> versionMap = new LinkedHashMap<>(); File output; File target; private final AtomicInteger revision = new AtomicInteger(); private File files[]; boolean delayRunDependencies = true; final ProjectMessages msgs = ReporterMessages.base(this, ProjectMessages.class); private Properties ide; final Packages exportedPackages = new Packages(); final Packages importedPackages = new Packages(); final Packages containedPackages = new Packages(); final PackageInfo packageInfo = new PackageInfo(this); private Makefile makefile; private volatile RefreshData data = new RefreshData(); public Map<String, Container> unreferencedClasspathEntries = new HashMap<>(); public Project(Workspace workspace, File unused, File buildFile) { super(workspace); this.workspace = workspace; setFileMustExist(false); if (buildFile != null) setProperties(buildFile); // For backward compatibility reasons, we also read readBuildProperties(); } public Project(Workspace workspace, File buildDir) { this(workspace, buildDir, new File(buildDir, BNDFILE)); } private void readBuildProperties() { try { File f = getFile("build.properties"); if (f.isFile()) { Properties p = loadProperties(f); for (String key : Iterables.iterable(p.propertyNames(), String.class::cast)) { String newkey = key; if (key.indexOf('$') >= 0) { newkey = getReplacer().process(key); } setProperty(newkey, p.getProperty(key)); } } } catch (Exception e) { e.printStackTrace(); } } public static Project getUnparented(File propertiesFile) throws Exception { propertiesFile = propertiesFile.getAbsoluteFile(); Workspace workspace = new Workspace(propertiesFile.getParentFile()); Project project = new Project(workspace, propertiesFile.getParentFile()); project.setProperties(propertiesFile); project.setFileMustExist(true); return project; } public boolean isValid() { if (getBase() == null || !getBase().isDirectory()) return false; return getPropertiesFile() == null || getPropertiesFile().isFile(); } /** * Return a new builder that is nicely setup for this project. Please close * this builder after use. * * @param parent The project builder to use as parent, use this project if * null * @throws Exception */ public ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception { ProjectBuilder builder; if (parent == null) builder = new ProjectBuilder(this); else builder = new ProjectBuilder(parent); builder.setBase(getBase()); builder.use(this); return builder; } public int getChanged() { return revision.get(); } /* * Indicate a change in the external world that affects our build. This will * clear any cached results. */ public void setChanged() { // if (refresh()) { preparedPaths.set(false); files = null; revision.getAndIncrement(); } public Workspace getWorkspace() { return workspace; } @Override public String toString() { return getName(); } /** * Set up all the paths */ public void prepare() throws Exception { if (!isValid()) { warning("Invalid project attempts to prepare: %s", this); return; } synchronized (preparedPaths) { if (preparedPaths.get()) { // ensure output folders exist getSrcOutput0(); getTarget0(); return; } if (!workspace.trail.add(this)) { throw new CircularDependencyException(workspace.trail.toString() + "," + this); } try { String basePath = IO.absolutePath(getBase()); dependenciesFull.clear(); dependenciesBuild.clear(); dependenciesTest.clear(); dependents.clear(); buildpath.clear(); testpath.clear(); sourcepath.clear(); allsourcepath.clear(); bootclasspath.clear(); // JIT runpath.clear(); runbundles.clear(); runfw.clear(); // We use a builder to construct all the properties for // use. setProperty("basedir", basePath); // If a bnd.bnd file exists, we read it. // Otherwise, we just do the build properties. if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) { // Get our Eclipse info, we might depend on other // projects // though ideally this should become empty and void doEclipseClasspath(); } // Calculate our source directories Parameters srces = new Parameters(mergeProperties(Constants.DEFAULT_PROP_SRC_DIR), this); if (srces.isEmpty()) srces.add(Constants.DEFAULT_PROP_SRC_DIR, new Attrs()); for (Entry<String, Attrs> e : srces.entrySet()) { File dir = getFile(removeDuplicateMarker(e.getKey())); if (!IO.absolutePath(dir) .startsWith(basePath)) { error("The source directory lies outside the project %s directory: %s", this, dir) .header(Constants.DEFAULT_PROP_SRC_DIR) .context(e.getKey()); continue; } if (!dir.exists()) { try { IO.mkdirs(dir); } catch (Exception ex) { exception(ex, "could not create src directory (in src property) %s", dir) .header(Constants.DEFAULT_PROP_SRC_DIR) .context(e.getKey()); continue; } if (!dir.exists()) { error("could not create src directory (in src property) %s", dir) .header(Constants.DEFAULT_PROP_SRC_DIR) .context(e.getKey()); continue; } } if (dir.isDirectory()) { sourcepath.put(dir, new Attrs(e.getValue())); allsourcepath.add(dir); } else error("the src path (src property) contains an entry that is not a directory %s", dir) .header(Constants.DEFAULT_PROP_SRC_DIR) .context(e.getKey()); } // Set default bin directory output = getSrcOutput0(); if (!output.isDirectory()) { msgs.NoOutputDirectory_(output); } // Where we store all our generated stuff. target = getTarget0(); // Where the launched OSGi framework stores stuff String runStorageStr = getProperty(Constants.RUNSTORAGE); runstorage = runStorageStr != null ? getFile(runStorageStr) : null; // We might have some other projects we want build // before we do anything, but these projects are not in // our path. The -dependson allows you to build them before. // The values are possibly negated globbing patterns. Set<String> requiredProjectNames = new LinkedHashSet<>( getMergedParameters(Constants.DEPENDSON).keySet()); // Allow DependencyConstributors to modify requiredProjectNames List<DependencyContributor> dcs = getPlugins(DependencyContributor.class); for (DependencyContributor dc : dcs) dc.addDependencies(this, requiredProjectNames); Instructions is = new Instructions(requiredProjectNames); Collection<Project> projects = getWorkspace().getAllProjects(); projects.remove(this); // since -dependson could use a wildcard Set<Instruction> unused = new HashSet<>(); Set<Project> buildDeps = new LinkedHashSet<>(is.select(projects, unused, false)); for (Instruction u : unused) msgs.MissingDependson_(u.getInput()); // We have two paths that consists of repo files, projects, // or some other stuff. The doPath routine adds them to the // path and extracts the projects so we can build them // before. doPath(buildpath, buildDeps, parseBuildpath(), bootclasspath, false, BUILDPATH); Set<Project> testDeps = new LinkedHashSet<>(buildDeps); doPath(testpath, testDeps, parseTestpath(), bootclasspath, false, TESTPATH); if (!delayRunDependencies) { doPath(runfw, testDeps, parseRunFw(), null, false, RUNFW); doPath(runpath, testDeps, parseRunpath(), null, false, RUNPATH); doPath(runbundles, testDeps, parseRunbundles(), null, true, RUNBUNDLES); } // We now know all dependent projects. But we also depend // on whatever those projects depend on. This creates an // ordered list without any duplicates. This of course assumes // that there is no circularity. However, this is checked // by the inPrepare flag, will throw an exception if we // are circular. Set<Project> visited = new HashSet<>(); visited.add(this); for (Project project : testDeps) { project.traverse(dependenciesFull, this, visited); } dependenciesBuild.addAll(dependenciesFull); dependenciesBuild.retainAll(buildDeps); dependenciesTest.addAll(dependenciesFull); dependenciesTest.retainAll(testDeps); for (Project project : dependenciesFull) { allsourcepath.addAll(project.getSourcePath()); } preparedPaths.set(true); } finally { workspace.trail.remove(this); } } } private File getSrcOutput0() throws IOException { File output = getSrcOutput().getAbsoluteFile(); if (!output.exists()) { IO.mkdirs(output); getWorkspace().changedFile(output); } return output; } private File getTarget0() throws IOException { File target = getTargetDir(); if (!target.exists()) { IO.mkdirs(target); getWorkspace().changedFile(target); } return target; } /** * This method is deprecated because this can handle only one source dir. * Use getSourcePath. For backward compatibility we will return the first * entry on the source path. * * @return first entry on the {@link #getSourcePath()} */ @Deprecated public File getSrc() throws Exception { prepare(); if (sourcepath.isEmpty()) return getFile("src"); return sourcepath.keySet() .iterator() .next(); } public File getSrcOutput() { return getFile(getProperty(Constants.DEFAULT_PROP_BIN_DIR)); } public File getTestSrc() { return getFile(getProperty(Constants.DEFAULT_PROP_TESTSRC_DIR)); } public File getTestOutput() { return getFile(getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR)); } public File getTargetDir() { return getFile(getProperty(Constants.DEFAULT_PROP_TARGET_DIR)); } private void traverse(Set<Project> dependencies, Project dependent, Set<Project> visited) throws Exception { if (visited.add(this)) { for (Project project : getTestDependencies()) { project.traverse(dependencies, this, visited); } dependencies.add(this); } dependents.add(dependent); } /** * Iterate over the entries and place the projects on the projects list and * all the files of the entries on the resultpath. * * @param resultpath The list that gets all the files * @param projects The list that gets any projects that are entries * @param entries The input list of classpath entries */ private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries, Collection<Container> bootclasspath, boolean noproject, String name) { for (Container cpe : entries) { if (cpe.getError() != null) error("%s", cpe.getError()).header(name) .context(cpe.getBundleSymbolicName()); else { if (cpe.getType() == Container.TYPE.PROJECT) { projects.add(cpe.getProject()); if (noproject && since(About._2_3) && VERSION_ATTR_PROJECT.equals(cpe.getAttributes() .get(VERSION_ATTRIBUTE))) { // we're trying to put a project's output directory on // -runbundles list error( "%s is specified with version=project on %s. This version uses the project's output directory, which is not allowed since it must be an actual JAR file for this list.", cpe.getBundleSymbolicName(), name).header(name) .context(cpe.getBundleSymbolicName()); } } if (bootclasspath != null && (cpe.getBundleSymbolicName() .startsWith("ee.") || cpe.getAttributes() .containsKey("boot"))) bootclasspath.add(cpe); else resultpath.add(cpe); } } } /** * Parse the list of bundles that are a prerequisite to this project. * Bundles are listed in repo specific names. So we just let our repo * plugins iterate over the list of bundles and we get the highest version * from them. */ private List<Container> parseBuildpath() throws Exception { List<Container> bundles = getBundles(Strategy.LOWEST, mergeProperties(Constants.BUILDPATH), Constants.BUILDPATH); return bundles; } private List<Container> parseRunpath() throws Exception { return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNPATH), Constants.RUNPATH); } private List<Container> parseRunbundles() throws Exception { return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNBUNDLES), Constants.RUNBUNDLES); } private List<Container> parseRunFw() throws Exception { return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNFW), Constants.RUNFW); } private List<Container> parseTestpath() throws Exception { return getBundles(Strategy.HIGHEST, mergeProperties(Constants.TESTPATH), Constants.TESTPATH); } /** * Analyze the header and return a list of files that should be on the * build, test or some other path. The list is assumed to be a list of bsns * with a version specification. The special case of version=project * indicates there is a project in the same workspace. The path to the * output directory is calculated. The default directory ${bin} can be * overridden with the output attribute. * * @param strategyx STRATEGY_LOWEST or STRATEGY_HIGHEST * @param spec The header */ public List<Container> getBundles(Strategy strategyx, String spec, String source) throws Exception { List<Container> result = new ArrayList<>(); Parameters bundles = new Parameters(spec, this); try { for (Iterator<Entry<String, Attrs>> i = bundles.entrySet() .iterator(); i.hasNext();) { Entry<String, Attrs> entry = i.next(); String bsn = removeDuplicateMarker(entry.getKey()); Map<String, String> attrs = entry.getValue(); Container found = null; String versionRange = attrs.get("version"); boolean triedGetBundle = false; if (bsn.indexOf('*') >= 0) { return getBundlesWildcard(bsn, versionRange, strategyx, attrs); } if (versionRange != null) { if (versionRange.equals(VERSION_ATTR_LATEST) || versionRange.equals(VERSION_ATTR_SNAPSHOT)) { found = getBundle(bsn, versionRange, strategyx, attrs); triedGetBundle = true; } } if (found == null) { // TODO This looks like a duplicate // of what is done in getBundle?? if (versionRange != null && (versionRange.equals(VERSION_ATTR_PROJECT) || versionRange.equals(VERSION_ATTR_LATEST))) { // Use the bin directory ... Project project = getWorkspace().getProject(bsn); if (project != null && project.exists()) { File f = project.getOutput(); found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs, null); } else { msgs.NoSuchProject(bsn, spec) .context(bsn) .header(source); continue; } } else if (versionRange != null && versionRange.equals("file")) { File f = getFile(bsn); String error = null; if (!f.exists()) error = "File does not exist: " + IO.absolutePath(f); if (f.getName() .endsWith(".lib")) { found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs, null); } else { found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs, null); } } else if (!triedGetBundle) { found = getBundle(bsn, versionRange, strategyx, attrs); } } if (found != null) { List<Container> libs = found.getMembers(); for (Container cc : libs) { if (result.contains(cc)) { if (isPedantic()) warning("Multiple bundles with the same final URL: %s, dropped duplicate", cc); } else { if (cc.getError() != null) { error("Cannot find %s", cc).context(bsn) .header(source); } result.add(cc); } } } else { // Oops, not a bundle in sight :-( Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null, bsn + ";version=" + versionRange + " not found", attrs, null); result.add(x); error("Can not find URL for bsn %s", bsn).context(bsn) .header(source); } } } catch (CircularDependencyException e) { String message = e.getMessage(); if (source != null) message = String.format("%s (from property: %s)", message, source); msgs.CircularDependencyContext_Message_(getName(), message); } catch (IOException e) { exception(e, "Unexpected exception in get bundles", spec); } return result; } /** * Just calls a new method with a default parm. * * @throws Exception */ Collection<Container> getBundles(Strategy strategy, String spec) throws Exception { return getBundles(strategy, spec, null); } /** * Get all bundles matching a wildcard expression. * * @param bsnPattern A bsn wildcard, e.g. "osgi*" or just "*". * @param range A range to narrow the versions of bundles found, or null to * return any version. * @param strategyx The version selection strategy, which may be 'HIGHEST' * or 'LOWEST' only -- 'EXACT' is not permitted. * @param attrs Additional search attributes. * @throws Exception */ public List<Container> getBundlesWildcard(String bsnPattern, String range, Strategy strategyx, Map<String, String> attrs) throws Exception { if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range)) return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null, "Cannot use snapshot or project version with wildcard matches", null, null)); if (strategyx == Strategy.EXACT) return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null, "Cannot use exact version strategy with wildcard matches", null, null)); VersionRange versionRange; if (range == null || VERSION_ATTR_LATEST.equals(range)) versionRange = new VersionRange("0"); else versionRange = new VersionRange(range); RepoFilter repoFilter = parseRepoFilter(attrs); if (bsnPattern != null) { bsnPattern = bsnPattern.trim(); if (bsnPattern.length() == 0 || bsnPattern.equals("*")) bsnPattern = null; } SortedMap<String, Pair<Version, RepositoryPlugin>> providerMap = new TreeMap<>(); List<RepositoryPlugin> plugins = workspace.getRepositories(); for (RepositoryPlugin plugin : plugins) { if (repoFilter != null && !repoFilter.match(plugin)) continue; List<String> bsns = plugin.list(bsnPattern); if (bsns != null) for (String bsn : bsns) { SortedSet<Version> versions = plugin.versions(bsn); if (versions != null && !versions.isEmpty()) { Pair<Version, RepositoryPlugin> currentProvider = providerMap.get(bsn); Version candidate; switch (strategyx) { case HIGHEST : candidate = versions.last(); if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) > 0) { providerMap.put(bsn, new Pair<>(candidate, plugin)); } break; case LOWEST : candidate = versions.first(); if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) < 0) { providerMap.put(bsn, new Pair<>(candidate, plugin)); } break; default : // we shouldn't have reached this point! throw new IllegalStateException( "Cannot use exact version strategy with wildcard matches"); } } } } List<Container> containers = new ArrayList<>(providerMap.size()); for (Entry<String, Pair<Version, RepositoryPlugin>> entry : providerMap.entrySet()) { String bsn = entry.getKey(); Version version = entry.getValue() .getFirst(); RepositoryPlugin repo = entry.getValue() .getSecond(); DownloadBlocker downloadBlocker = new DownloadBlocker(this); File bundle = repo.get(bsn, version, attrs, downloadBlocker); if (bundle != null && !bundle.getName() .endsWith(".lib")) { containers .add(new Container(this, bsn, range, Container.TYPE.REPO, bundle, null, attrs, downloadBlocker)); } } return containers; } static void mergeNames(String names, Set<String> set) { StringTokenizer tokenizer = new StringTokenizer(names, ","); while (tokenizer.hasMoreTokens()) set.add(tokenizer.nextToken() .trim()); } static String flatten(Set<String> names) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String name : names) { if (!first) builder.append(','); builder.append(name); first = false; } return builder.toString(); } static void addToPackageList(Container container, String newPackageNames) { Set<String> merged = new HashSet<>(); String packageListStr = container.getAttributes() .get("packages"); if (packageListStr != null) mergeNames(packageListStr, merged); if (newPackageNames != null) mergeNames(newPackageNames, merged); container.putAttribute("packages", flatten(merged)); } /** * The user selected pom in a path. This will place the pom as well as its * dependencies on the list * * @param strategyx the strategy to use. * @param result The list of result containers * @throws Exception anything goes wrong */ public void doMavenPom(Strategy strategyx, List<Container> result, String action) throws Exception { File pomFile = getFile("pom.xml"); if (!pomFile.isFile()) msgs.MissingPom(); else { ProjectPom pom = getWorkspace().getMaven() .createProjectModel(pomFile); if (action == null) action = "compile"; Pom.Scope act = Pom.Scope.valueOf(action); Set<Pom> dependencies = pom.getDependencies(act); for (Pom sub : dependencies) { File artifact = sub.getArtifact(); Container container = new Container(artifact, null); result.add(container); } } } /** * Return the full transitive dependencies of this project. * * @return A set of the full transitive dependencies of this project. * @throws Exception */ public Collection<Project> getDependson() throws Exception { prepare(); return dependenciesFull; } /** * Return the direct build dependencies of this project. * * @return A set of the direct build dependencies of this project. * @throws Exception */ public Set<Project> getBuildDependencies() throws Exception { prepare(); return dependenciesBuild; } /** * Return the direct test dependencies of this project. * <p> * The result includes the direct build dependencies of this project as * well, so the result is a super set of {@link #getBuildDependencies()}. * * @return A set of the test build dependencies of this project. * @throws Exception */ public Set<Project> getTestDependencies() throws Exception { prepare(); return dependenciesTest; } /** * Return the full transitive dependents of this project. * <p> * The result includes projects which have build and test dependencies on * this project. * <p> * Since the full transitive dependents of this project is updated during * the computation of other project dependencies, until all projects are * prepared, the dependents result may be partial. * * @return A set of the transitive set of projects which depend on this * project. * @throws Exception */ public Set<Project> getDependents() throws Exception { prepare(); return dependents; } public Collection<Container> getBuildpath() throws Exception { prepare(); return buildpath; } public Collection<Container> getTestpath() throws Exception { prepare(); return testpath; } /** * Handle dependencies for paths that are calculated on demand. * * @param testpath2 * @param parseTestpath */ private void justInTime(Collection<Container> path, List<Container> entries, boolean noproject, String name) { if (delayRunDependencies && path.isEmpty()) doPath(path, dependenciesFull, entries, null, noproject, name); } public Collection<Container> getRunpath() throws Exception { prepare(); justInTime(runpath, parseRunpath(), false, RUNPATH); return runpath; } public Collection<Container> getRunbundles() throws Exception { prepare(); justInTime(runbundles, parseRunbundles(), true, RUNBUNDLES); return runbundles; } /** * Return the run framework * * @throws Exception */ public Collection<Container> getRunFw() throws Exception { prepare(); justInTime(runfw, parseRunFw(), false, RUNFW); return runfw; } public File getRunStorage() throws Exception { prepare(); return runstorage; } public boolean getRunBuilds() { boolean result; String runBuildsStr = getProperty(Constants.RUNBUILDS); if (runBuildsStr == null) result = !getPropertiesFile().getName() .toLowerCase() .endsWith(Constants.DEFAULT_BNDRUN_EXTENSION); else result = Boolean.parseBoolean(runBuildsStr); return result; } public Collection<File> getSourcePath() throws Exception { prepare(); return sourcepath.keySet(); } public Collection<File> getAllsourcepath() throws Exception { prepare(); return allsourcepath; } public Collection<Container> getBootclasspath() throws Exception { prepare(); return bootclasspath; } public File getOutput() throws Exception { prepare(); return output; } private void doEclipseClasspath() throws Exception { EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase()); eclipse.setRecurse(false); // We get the file directories but in this case we need // to tell ant that the project names for (File dependent : eclipse.getDependents()) { Project required = workspace.getProject(dependent.getName()); dependenciesFull.add(required); } for (File f : eclipse.getClasspath()) { buildpath.add(new Container(f, null)); } for (File f : eclipse.getBootclasspath()) { bootclasspath.add(new Container(f, null)); } for (File f : eclipse.getSourcepath()) { sourcepath.put(f, new Attrs()); } allsourcepath.addAll(eclipse.getAllSources()); output = eclipse.getOutput(); } public String _p_dependson(String args[]) throws Exception { return list(args, toFiles(getDependson())); } private Collection<?> toFiles(Collection<Project> projects) { List<File> files = new ArrayList<>(); for (Project p : projects) { files.add(p.getBase()); } return files; } public String _p_buildpath(String args[]) throws Exception { return list(args, getBuildpath()); } public String _p_testpath(String args[]) throws Exception { return list(args, getRunpath()); } public String _p_sourcepath(String args[]) throws Exception { return list(args, getSourcePath()); } public String _p_allsourcepath(String args[]) throws Exception { return list(args, getAllsourcepath()); } public String _p_bootclasspath(String args[]) throws Exception { return list(args, getBootclasspath()); } public String _p_output(String args[]) throws Exception { if (args.length != 1) throw new IllegalArgumentException("${output} should not have arguments"); return IO.absolutePath(getOutput()); } private String list(String[] args, Collection<?> list) { if (args.length > 3) throw new IllegalArgumentException( "${" + args[0] + "[;<separator>]} can only take a separator as argument, has " + Arrays.toString(args)); String separator = ","; if (args.length == 2) { separator = args[1]; } return join(list, separator); } @Override protected Object[] getMacroDomains() { return new Object[] { workspace }; } public File release(String jarName, InputStream jarStream) throws Exception { return release(null, jarName, jarStream); } public URI releaseURI(String jarName, InputStream jarStream) throws Exception { return releaseURI(null, jarName, jarStream); } /** * Release * * @param name The repository name * @param jarName * @param jarStream * @throws Exception */ public File release(String name, String jarName, InputStream jarStream) throws Exception { URI uri = releaseURI(name, jarName, jarStream); if (uri != null && uri.getScheme() .equals("file")) { return new File(uri); } return null; } public URI releaseURI(String name, String jarName, InputStream jarStream) throws Exception { List<RepositoryPlugin> releaseRepos = getReleaseRepos(name); if (releaseRepos.isEmpty()) { return null; } RepositoryPlugin releaseRepo = releaseRepos.get(0); // use only first // release repo return releaseRepo(releaseRepo, jarName, jarStream); } private URI releaseRepo(RepositoryPlugin releaseRepo, String jarName, InputStream jarStream) throws Exception { logger.debug("release to {}", releaseRepo.getName()); try { PutOptions putOptions = new RepositoryPlugin.PutOptions(); // TODO find sub bnd that is associated with this thing putOptions.context = this; PutResult r = releaseRepo.put(jarStream, putOptions); logger.debug("Released {} to {} in repository {}", jarName, r.artifact, releaseRepo); return r.artifact; } catch (Exception e) { msgs.Release_Into_Exception_(jarName, releaseRepo, e); return null; } } private List<RepositoryPlugin> getReleaseRepos(String names) { Parameters repoNames = parseReleaseRepos(names); List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class); List<RepositoryPlugin> result = new ArrayList<>(); if (repoNames == null) { // -releaserepo unspecified for (RepositoryPlugin plugin : plugins) { if (plugin.canWrite()) { result.add(plugin); break; } } if (result.isEmpty()) { msgs.NoNameForReleaseRepository(); } return result; } repoNames: for (String repoName : repoNames.keySet()) { for (RepositoryPlugin plugin : plugins) { if (plugin.canWrite() && repoName.equals(plugin.getName())) { result.add(plugin); continue repoNames; } } msgs.ReleaseRepository_NotFoundIn_(repoName, plugins); } return result; } private Parameters parseReleaseRepos(String names) { if (names == null) { names = mergeProperties(RELEASEREPO); if (names == null) { return null; // -releaserepo unspecified } } return new Parameters(names, this); } public void release(boolean test) throws Exception { release(null, test); } /** * Release * * @param name The respository name * @param test Run testcases * @throws Exception */ public void release(String name, boolean test) throws Exception { List<RepositoryPlugin> releaseRepos = getReleaseRepos(name); if (releaseRepos.isEmpty()) { return; } logger.debug("release"); File[] jars = getBuildFiles(false); if (jars == null) { jars = build(test); // If build fails jars will be null if (jars == null) { logger.debug("no jars built"); return; } } logger.debug("releasing {} - {}", jars, releaseRepos); for (RepositoryPlugin releaseRepo : releaseRepos) { for (File jar : jars) { releaseRepo(releaseRepo, jar.getName(), new BufferedInputStream(IO.stream(jar))); } } } /** * Get a bundle from one of the plugin repositories. If an exact version is * required we just return the first repository found (in declaration order * in the build.bnd file). * * @param bsn The bundle symbolic name * @param range The version range * @param strategy set to LOWEST or HIGHEST * @return the file object that points to the bundle or null if not found * @throws Exception when something goes wrong */ public Container getBundle(String bsn, String range, Strategy strategy, Map<String, String> attrs) throws Exception { if (range == null) range = "0"; if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range)) { return getBundleFromProject(bsn, attrs); } else if (VERSION_ATTR_HASH.equals(range)) { return getBundleByHash(bsn, attrs); } Strategy useStrategy = strategy; if (VERSION_ATTR_LATEST.equals(range)) { Container c = getBundleFromProject(bsn, attrs); if (c != null) return c; useStrategy = Strategy.HIGHEST; } useStrategy = overrideStrategy(attrs, useStrategy); RepoFilter repoFilter = parseRepoFilter(attrs); List<RepositoryPlugin> plugins = workspace.getRepositories(); if (useStrategy == Strategy.EXACT) { if (!Verifier.isVersion(range)) return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range + " Invalid version", null, null); // For an exact range we just iterate over the repos // and return the first we find. Version version = new Version(range); for (RepositoryPlugin plugin : plugins) { DownloadBlocker blocker = new DownloadBlocker(this); File result = plugin.get(bsn, version, attrs, blocker); if (result != null) return toContainer(bsn, range, attrs, result, blocker); } } else { VersionRange versionRange = VERSION_ATTR_LATEST.equals(range) ? new VersionRange("0") : new VersionRange(range); // We have a range search. Gather all the versions in all the repos // and make a decision on that choice. If the same version is found // multiple repos we take the first SortedMap<Version, RepositoryPlugin> versions = new TreeMap<>(); for (RepositoryPlugin plugin : plugins) { if (repoFilter != null && !repoFilter.match(plugin)) continue; try { SortedSet<Version> vs = plugin.versions(bsn); if (vs != null) { for (Version v : vs) { if (!versions.containsKey(v) && versionRange.includes(v)) versions.put(v, plugin); } } } catch (UnsupportedOperationException ose) { // We have a plugin that cannot list versions, try // if it has this specific version // The main reaosn for this code was the Maven Remote // Repository // To query, we must have a real version if (!versions.isEmpty() && Verifier.isVersion(range)) { Version version = new Version(range); DownloadBlocker blocker = new DownloadBlocker(this); File file = plugin.get(bsn, version, attrs, blocker); // and the entry must exist // if it does, return this as a result if (file != null) return toContainer(bsn, range, attrs, file, blocker); } } } // We have to augment the list of returned versions // with info from the workspace. We use null as a marker // to indicate that it is a workspace project SortedSet<Version> localVersions = getWorkspace().getWorkspaceRepository() .versions(bsn); for (Version v : localVersions) { if (!versions.containsKey(v) && versionRange.includes(v)) versions.put(v, null); } // Verify if we found any, if so, we use the strategy to pick // the first or last if (!versions.isEmpty()) { Version provider = null; switch (useStrategy) { case HIGHEST : provider = versions.lastKey(); break; case LOWEST : provider = versions.firstKey(); break; case EXACT : // TODO need to handle exact better break; } if (provider != null) { RepositoryPlugin repo = versions.get(provider); if (repo == null) { // A null provider indicates that we have a local // project return getBundleFromProject(bsn, attrs); } String version = provider.toString(); DownloadBlocker blocker = new DownloadBlocker(this); File result = repo.get(bsn, provider, attrs, blocker); if (result != null) return toContainer(bsn, version, attrs, result, blocker); } else { msgs.FoundVersions_ForStrategy_ButNoProvider(versions, useStrategy); } } } // If we get this far we ran into an error somewhere return new Container(this, bsn, range, Container.TYPE.ERROR, null, bsn + ";version=" + range + " Not found in " + plugins, null, null); } /** * @param attrs * @param useStrategy */ protected Strategy overrideStrategy(Map<String, String> attrs, Strategy useStrategy) { if (attrs != null) { String overrideStrategy = attrs.get("strategy"); if (overrideStrategy != null) { if ("highest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.HIGHEST; else if ("lowest".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.LOWEST; else if ("exact".equalsIgnoreCase(overrideStrategy)) useStrategy = Strategy.EXACT; } } return useStrategy; } private static class RepoFilter { private Pattern[] patterns; RepoFilter(Pattern[] patterns) { this.patterns = patterns; } boolean match(RepositoryPlugin repo) { if (patterns == null) return true; for (Pattern pattern : patterns) { if (pattern.matcher(repo.getName()) .matches()) return true; } return false; } } protected RepoFilter parseRepoFilter(Map<String, String> attrs) { if (attrs == null) return null; String patternStr = attrs.get("repo"); if (patternStr == null) return null; List<Pattern> patterns = new LinkedList<>(); QuotedTokenizer tokenize = new QuotedTokenizer(patternStr, ","); String token = tokenize.nextToken(); while (token != null) { patterns.add(Glob.toPattern(token)); token = tokenize.nextToken(); } return new RepoFilter(patterns.toArray(new Pattern[0])); } /** * @param bsn * @param range * @param attrs * @param result */ protected Container toContainer(String bsn, String range, Map<String, String> attrs, File result, DownloadBlocker db) { File f = result; if (f == null) { msgs.ConfusedNoContainerFile(); f = new File("was null"); } Container container; if (f.getName() .endsWith("lib")) container = new Container(this, bsn, range, Container.TYPE.LIBRARY, f, null, attrs, db); else container = new Container(this, bsn, range, Container.TYPE.REPO, f, null, attrs, db); return container; } /** * Look for the bundle in the workspace. The premise is that the bsn must * start with the project name. * * @param bsn The bsn * @param attrs Any attributes * @throws Exception */ private Container getBundleFromProject(String bsn, Map<String, String> attrs) throws Exception { String pname = bsn; while (true) { Project p = getWorkspace().getProject(pname); if (p != null && p.isValid()) { Container c = p.getDeliverable(bsn, attrs); return c; } int n = pname.lastIndexOf('.'); if (n <= 0) return null; pname = pname.substring(0, n); } } private Container getBundleByHash(String bsn, Map<String, String> attrs) throws Exception { String hashStr = attrs.get("hash"); String algo = SHA_256; String hash = hashStr; int colonIndex = hashStr.indexOf(':'); if (colonIndex > -1) { algo = hashStr.substring(0, colonIndex); int afterColon = colonIndex + 1; hash = (colonIndex < hashStr.length()) ? hashStr.substring(afterColon) : ""; } for (RepositoryPlugin plugin : workspace.getRepositories()) { // The plugin *may* understand version=hash directly DownloadBlocker blocker = new DownloadBlocker(this); File result = plugin.get(bsn, Version.LOWEST, Collections.unmodifiableMap(attrs), blocker); // If not, and if the repository implements the OSGi Repository // Service, use a capability search on the osgi.content namespace. if (result == null && plugin instanceof Repository) { Repository repo = (Repository) plugin; if (!SHA_256.equals(algo)) // R5 repos only support SHA-256 continue; Requirement contentReq = new CapReqBuilder(ContentNamespace.CONTENT_NAMESPACE) .filter(String.format("(%s=%s)", ContentNamespace.CONTENT_NAMESPACE, hash)) .buildSyntheticRequirement(); Set<Requirement> reqs = Collections.singleton(contentReq); Map<Requirement, Collection<Capability>> providers = repo.findProviders(reqs); Collection<Capability> caps = providers != null ? providers.get(contentReq) : null; if (caps != null && !caps.isEmpty()) { Capability cap = caps.iterator() .next(); IdentityCapability idCap = ResourceUtils.getIdentityCapability(cap.getResource()); Map<String, Object> idAttrs = idCap.getAttributes(); String id = (String) idAttrs.get(IdentityNamespace.IDENTITY_NAMESPACE); Object version = idAttrs.get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE); Version bndVersion = version != null ? Version.parseVersion(version.toString()) : Version.LOWEST; if (!bsn.equals(id)) { String error = String.format("Resource with requested hash does not match ID '%s' [hash: %s]", bsn, hashStr); return new Container(this, bsn, "hash", Container.TYPE.ERROR, null, error, null, null); } result = plugin.get(id, bndVersion, null, blocker); } } if (result != null) return toContainer(bsn, "hash", attrs, result, blocker); } // If we reach this far, none of the repos found the resource. return new Container(this, bsn, "hash", Container.TYPE.ERROR, null, "Could not find resource by content hash " + hashStr, null, null); } /** * Deploy the file (which must be a bundle) into the repository. * * @param name The repository name * @param file bundle */ public void deploy(String name, File file) throws Exception { List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class); RepositoryPlugin rp = null; for (RepositoryPlugin plugin : plugins) { if (!plugin.canWrite()) { continue; } if (name == null) { rp = plugin; break; } else if (name.equals(plugin.getName())) { rp = plugin; break; } } if (rp != null) { try { rp.put(new BufferedInputStream(IO.stream(file)), new RepositoryPlugin.PutOptions()); return; } catch (Exception e) { msgs.DeployingFile_On_Exception_(file, rp.getName(), e); } return; } logger.debug("No repo found {}", file); throw new IllegalArgumentException("No repository found for " + file); } /** * Deploy the file (which must be a bundle) into the repository. * * @param file bundle */ public void deploy(File file) throws Exception { String name = getProperty(Constants.DEPLOYREPO); deploy(name, file); } /** * Deploy the current project to a repository * * @throws Exception */ public void deploy() throws Exception { Parameters deploy = new Parameters(getProperty(DEPLOY), this); if (deploy.isEmpty()) { warning("Deploying but %s is not set to any repo", DEPLOY); return; } File[] outputs = getBuildFiles(); for (File output : outputs) { for (Deploy d : getPlugins(Deploy.class)) { logger.debug("Deploying {} to: {}", output.getName(), d); try { if (d.deploy(this, output.getName(), new BufferedInputStream(IO.stream(output)))) logger.debug("deployed {} successfully to {}", output, d); } catch (Exception e) { msgs.Deploying(e); } } } } /** * Macro access to the repository ${repo;<bsn>[;<version>[;<low|high>]]} */ static String _repoHelp = "${repo ';'<bsn> [ ; <version> [; ('HIGHEST'|'LOWEST')]}"; public String _repo(String args[]) throws Exception { if (args.length < 2) { msgs.RepoTooFewArguments(_repoHelp, args); return null; } String bsns = args[1]; String version = null; Strategy strategy = Strategy.HIGHEST; if (args.length > 2) { version = args[2]; if (args.length == 4) { if (args[3].equalsIgnoreCase("HIGHEST")) strategy = Strategy.HIGHEST; else if (args[3].equalsIgnoreCase("LOWEST")) strategy = Strategy.LOWEST; else if (args[3].equalsIgnoreCase("EXACT")) strategy = Strategy.EXACT; else msgs.InvalidStrategy(_repoHelp, args); } } Collection<String> parts = split(bsns); List<String> paths = new ArrayList<>(); for (String bsn : parts) { Container container = getBundle(bsn, version, strategy, null); if (container.getError() != null) { error("${repo} macro refers to an artifact %s-%s (%s) that has an error: %s", bsn, version, strategy, container.getError()); } else add(paths, container); } return join(paths); } private void add(List<String> paths, Container container) throws Exception { if (container.getType() == Container.TYPE.LIBRARY) { List<Container> members = container.getMembers(); for (Container sub : members) { add(paths, sub); } } else { if (container.getError() == null) paths.add(IO.absolutePath(container.getFile())); else { paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : " + container.getError() + ">>"); if (isPedantic()) { warning("Could not expand repo path request: %s ", container); } } } } public File getTarget() throws Exception { prepare(); return target; } /** * This is the external method that will pre-build any dependencies if it is * out of date. * * @param underTest * @throws Exception */ public File[] build(boolean underTest) throws Exception { if (isNoBundles()) return null; if (getProperty("-nope") != null) { warning("Please replace -nope with %s", NOBUNDLES); return null; } logger.debug("building {}", this); File[] files = buildLocal(underTest); install(files); return files; } private void install(File[] files) throws Exception { if (files == null) return; Parameters p = getInstallRepositories(); for (Map.Entry<String, Attrs> e : p.entrySet()) { RepositoryPlugin rp = getWorkspace().getRepository(e.getKey()); if (rp != null) { for (File f : files) { install(f, rp, e.getValue()); } } else warning("No such repository to install into: %s", e.getKey()); } } public Parameters getInstallRepositories() { if (data.installRepositories == null) { data.installRepositories = new Parameters(mergeProperties(BUILDREPO), this); } return data.installRepositories; } private void install(File f, RepositoryPlugin repo, Attrs value) throws Exception { try (Processor p = new Processor()) { p.getProperties() .putAll(value); PutOptions options = new PutOptions(); options.context = p; try (InputStream in = IO.stream(f)) { repo.put(in, options); } catch (Exception e) { exception(e, "Cannot install %s into %s because %s", f, repo.getName(), e); } } } /** * Return the files */ public File[] getFiles() { return files; } /** * Check if this project needs building. This is defined as: */ public boolean isStale() throws Exception { Set<Project> visited = new HashSet<>(); return isStale(visited); } boolean isStale(Set<Project> visited) throws Exception { // When we do not generate anything ... if (isNoBundles()) return false; if (!visited.add(this)) { return false; } long buildTime = 0; File[] files = getBuildFiles(false); if (files == null) return true; for (File f : files) { if (f.lastModified() < lastModified()) return true; if (buildTime < f.lastModified()) buildTime = f.lastModified(); } for (Project dependency : getDependson()) { if (dependency == this) continue; if (dependency.isNoBundles()) { continue; } if (dependency.isStale(visited)) { return true; } File[] deps = dependency.getBuildFiles(false); if (deps == null) { return true; } for (File f : deps) { if (buildTime < f.lastModified()) { return true; } } } return false; } /** * This method must only be called when it is sure that the project has been * build before in the same session. It is a bit yucky, but ant creates * different class spaces which makes it hard to detect we already build it. * This method remembers the files in the appropriate instance vars. */ public File[] getBuildFiles() throws Exception { return getBuildFiles(true); } public File[] getBuildFiles(boolean buildIfAbsent) throws Exception { File[] current = files; if (current != null) { return current; } File bfs = new File(getTarget(), BUILDFILES); if (bfs.isFile()) { try (BufferedReader rdr = IO.reader(bfs)) { List<File> list = newList(); for (String s = rdr.readLine(); s != null; s = rdr.readLine()) { s = s.trim(); File ff = new File(s); if (!ff.isFile()) { // Originally we warned the user // but lets just rebuild. That way // the error is not noticed but // it seems better to correct, // See #154 rdr.close(); IO.delete(bfs); return files = buildIfAbsent ? buildLocal(false) : null; } list.add(ff); } return files = list.toArray(new File[0]); } } return files = buildIfAbsent ? buildLocal(false) : null; } /** * Build without doing any dependency checking. Make sure any dependent * projects are built first. * * @param underTest * @throws Exception */ public File[] buildLocal(boolean underTest) throws Exception { if (isNoBundles()) { return files = null; } versionMap.clear(); getMakefile().make(); File[] buildfiles = getBuildFiles(false); File bfs = new File(getTarget(), BUILDFILES); files = null; // #761 tstamp can vary between invocations in one build // Macro can handle a @tstamp time so we freeze the time at // the start of the build. We do this carefully so someone higher // up the chain can actually freeze the time longer boolean tstamp = false; if (getProperty(TSTAMP) == null) { setProperty(TSTAMP, Long.toString(System.currentTimeMillis())); tstamp = true; } try (ProjectBuilder builder = getBuilder(null)) { if (underTest) builder.setProperty(Constants.UNDERTEST, "true"); Jar jars[] = builder.builds(); getInfo(builder); if (isPedantic() && !unreferencedClasspathEntries.isEmpty()) { warning("Unreferenced class path entries %s", unreferencedClasspathEntries.keySet()); } if (!isOk()) { return null; } Set<File> builtFiles = Create.set(); long lastModified = 0L; for (Jar jar : jars) { File file = saveBuild(jar); if (file == null) { getInfo(builder); error("Could not save %s", jar.getName()); return null; } builtFiles.add(file); if (lastModified < file.lastModified()) { lastModified = file.lastModified(); } } boolean bfsWrite = !bfs.exists() || (lastModified > bfs.lastModified()); if (buildfiles != null) { Set<File> removed = Create.set(buildfiles); if (!removed.equals(builtFiles)) { bfsWrite = true; removed.removeAll(builtFiles); for (File remove : removed) { IO.delete(remove); getWorkspace().changedFile(remove); } } } // Write out the filenames in the buildfiles file // so we can get them later even in another process if (bfsWrite) { try (PrintWriter fw = IO.writer(bfs)) { for (File f : builtFiles) { fw.write(IO.absolutePath(f)); fw.write('\n'); } } getWorkspace().changedFile(bfs); } bfs = null; // avoid delete in finally block return files = builtFiles.toArray(new File[0]); } finally { if (tstamp) unsetProperty(TSTAMP); if (bfs != null) { IO.delete(bfs); // something went wrong, so delete getWorkspace().changedFile(bfs); } } } /** * Answer if this project does not have any output */ public boolean isNoBundles() { return isTrue(getProperty(NOBUNDLES)); } public File saveBuild(Jar jar) throws Exception { try { File outputFile = getOutputFile(jar.getName(), jar.getVersion()); File logicalFile = outputFile; String msg = ""; if (!outputFile.exists() || outputFile.lastModified() < jar.lastModified()) { reportNewer(outputFile.lastModified(), jar); File fp = outputFile.getParentFile(); if (!fp.isDirectory()) { IO.mkdirs(fp); } // On windows we sometimes cannot delete a file because // someone holds a lock in our or another process. So if // we set the -overwritestrategy flag we use an avoiding // strategy. // We will always write to a temp file name. Basically the // calculated name + a variable suffix. We then create // a link with the constant name to this variable name. // This allows us to pick a different suffix when we cannot // delete the file. Yuck, but better than the alternative. String overwritestrategy = getProperty("-x-overwritestrategy", "classic"); swtch: switch (overwritestrategy) { case "delay" : for (int i = 0; i < 10; i++) { try { IO.deleteWithException(outputFile); jar.write(outputFile); break swtch; } catch (Exception e) { Thread.sleep(500); } } // Execute normal case to get classic behavior // FALL THROUGH case "classic" : IO.deleteWithException(outputFile); jar.write(outputFile); break swtch; case "gc" : try { IO.deleteWithException(outputFile); } catch (Exception e) { System.gc(); System.runFinalization(); IO.deleteWithException(outputFile); } jar.write(outputFile); break swtch; case "windows-only-disposable-names" : boolean isWindows = File.separatorChar == '\\'; if (!isWindows) { IO.deleteWithException(outputFile); jar.write(outputFile); break; } // Fall through case "disposable-names" : int suffix = 0; while (true) { outputFile = new File(outputFile.getParentFile(), outputFile.getName() + "-" + suffix); IO.delete(outputFile); if (!outputFile.isFile()) { // Succeeded to delete the file jar.write(outputFile); Files.createSymbolicLink(logicalFile.toPath(), outputFile.toPath()); break; } else { warning("Could not delete build file {} ", overwritestrategy); logger.warn("Cannot delete file {} but that should be ok", outputFile); } suffix++; } break swtch; default : error( "Invalid value for -x-overwritestrategy: %s, expected classic, delay, gc, windows-only-disposable-names, disposable-names", overwritestrategy); IO.deleteWithException(outputFile); jar.write(outputFile); break swtch; } // For maven we've got the shitty situation that the // files in the generated directories have an ever changing // version number so it is hard to refer to them in test cases // and from for example bndtools if you want to refer to the // latest so the following code attempts to create a link to the // output file if this is using some other naming scheme, // creating a constant name. Would probably be more logical to // always output in the canonical name and then create a link to // the desired name but not sure how much that would break BJ's // maven handling that caused these versioned JARs File canonical = new File(getTarget(), jar.getName() + ".jar"); if (!canonical.equals(logicalFile)) { IO.delete(canonical); if (!IO.createSymbolicLink(canonical, outputFile)) { // As alternative, we copy the file IO.copy(outputFile, canonical); } getWorkspace().changedFile(canonical); } getWorkspace().changedFile(outputFile); if (!outputFile.equals(logicalFile)) getWorkspace().changedFile(logicalFile); } else { msg = "(not modified since " + new Date(outputFile.lastModified()) + ")"; } logger.debug("{} ({}) {} {}", jar.getName(), outputFile.getName(), jar.getResources() .size(), msg); return logicalFile; } finally { jar.close(); } } /** * Calculate the file for a JAR. The default name is bsn.jar, but this can * be overridden with an * * @throws Exception */ public File getOutputFile(String bsn, String version) throws Exception { if (version == null) version = "0"; try (Processor scoped = new Processor(this)) { scoped.setProperty("@bsn", bsn); scoped.setProperty("@version", version); String path = scoped.getProperty(OUTPUTMASK, bsn + ".jar"); return IO.getFile(getTarget(), path); } } public File getOutputFile(String bsn) throws Exception { return getOutputFile(bsn, "0.0.0"); } private void reportNewer(long lastModified, Jar jar) { if (isTrue(getProperty(Constants.REPORTNEWER))) { StringBuilder sb = new StringBuilder(); String del = "Newer than " + new Date(lastModified); for (Map.Entry<String, Resource> entry : jar.getResources() .entrySet()) { if (entry.getValue() .lastModified() > lastModified) { sb.append(del); del = ", \n "; sb.append(entry.getKey()); } } if (sb.length() > 0) warning("%s", sb.toString()); } } /** * Refresh if we are based on stale data. This also implies our workspace. */ @Override public boolean refresh() { versionMap.clear(); data = new RefreshData(); boolean changed = false; if (isCnf()) { changed = workspace.refresh(); } return super.refresh() || changed; } public boolean isCnf() { try { return getBase().getCanonicalPath() .equals(getWorkspace().getBuildDir() .getCanonicalPath()); } catch (IOException e) { return false; } } @Override public void propertiesChanged() { super.propertiesChanged(); preparedPaths.set(false); files = null; makefile = null; versionMap.clear(); data = new RefreshData(); } public String getName() { return getBase().getName(); } public Map<String, Action> getActions() { Map<String, Action> all = newMap(); Map<String, Action> actions = newMap(); fillActions(all); getWorkspace().fillActions(all); for (Map.Entry<String, Action> action : all.entrySet()) { String key = getReplacer().process(action.getKey()); if (key != null && key.trim() .length() != 0) actions.put(key, action.getValue()); } return actions; } public void fillActions(Map<String, Action> all) { List<NamedAction> plugins = getPlugins(NamedAction.class); for (NamedAction a : plugins) all.put(a.getName(), a); Parameters actions = new Parameters(getProperty("-actions", DEFAULT_ACTIONS), this); for (Entry<String, Attrs> entry : actions.entrySet()) { String key = Processor.removeDuplicateMarker(entry.getKey()); Action action; if (entry.getValue() .get("script") != null) { // TODO check for the type action = new ScriptAction(entry.getValue() .get("type"), entry.getValue() .get("script")); } else { action = new ReflectAction(key); } String label = entry.getValue() .get("label"); all.put(label.toLowerCase(), action); } } public void release() throws Exception { release(false); } public Map.Entry<String, Resource> export(String type, Map<String, String> options) throws Exception { Exporter exporter = getExporter(type); if (exporter == null) { error("No exporter for %s", type); return null; } if (options == null) { options = Collections.emptyMap(); } Parameters exportTypes = parseHeader(getProperty(Constants.EXPORTTYPE)); Map<String, String> attrs = exportTypes.get(type); if (attrs != null) { attrs.putAll(options); options = attrs; } return exporter.export(type, this, options); } private Exporter getExporter(String type) { List<Exporter> exporters = getPlugins(Exporter.class); for (Exporter e : exporters) { for (String exporterType : e.getTypes()) { if (type.equals(exporterType)) { return e; } } } return null; } public void export(String runFilePath, boolean keep, File output) throws Exception { Map<String, String> options = Collections.singletonMap("keep", Boolean.toString(keep)); Entry<String, Resource> export; if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) { clear(); export = export(ExecutableJarExporter.EXECUTABLE_JAR, options); } else { File runFile = IO.getFile(getBase(), runFilePath); if (!runFile.isFile()) throw new IOException( String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile))); try (Run run = new Run(getWorkspace(), getBase(), runFile)) { export = run.export(ExecutableJarExporter.EXECUTABLE_JAR, options); getInfo(run); } } if (export != null) { try (JarResource r = (JarResource) export.getValue()) { r.getJar() .write(output); } } } /** * @since 2.4 */ public void exportRunbundles(String runFilePath, File outputDir) throws Exception { Map<String, String> options = Collections.emptyMap(); Entry<String, Resource> export; if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) { clear(); export = export(RunbundlesExporter.RUNBUNDLES, options); } else { File runFile = IO.getFile(getBase(), runFilePath); if (!runFile.isFile()) throw new IOException( String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile))); try (Run run = new Run(getWorkspace(), getBase(), runFile)) { export = run.export(RunbundlesExporter.RUNBUNDLES, options); getInfo(run); } } if (export != null) { try (JarResource r = (JarResource) export.getValue()) { r.getJar() .writeFolder(outputDir); } } } /** * Release. * * @param name The repository name * @throws Exception */ public void release(String name) throws Exception { release(name, false); } public void clean() throws Exception { clean(getTargetDir(), "target"); clean(getSrcOutput(), "source output"); clean(getTestOutput(), "test output"); } void clean(File dir, String type) throws IOException { if (!dir.exists()) return; String basePath = getBase().getCanonicalPath(); String dirPath = dir.getCanonicalPath(); if (!dirPath.startsWith(basePath)) { logger.debug("path outside the project dir {}", type); return; } if (dirPath.length() == basePath.length()) { error("Trying to delete the project directory for %s", type); return; } IO.delete(dir); if (dir.exists()) { error("Trying to delete %s (%s), but failed", dir, type); return; } IO.mkdirs(dir); } public File[] build() throws Exception { return build(false); } private Makefile getMakefile() { if (makefile == null) { makefile = new Makefile(this); } return makefile; } public void run() throws Exception { try (ProjectLauncher pl = getProjectLauncher()) { pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE))); pl.launch(); } } public void runLocal() throws Exception { try (ProjectLauncher pl = getProjectLauncher()) { pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE))); pl.start(null); } } public void test() throws Exception { test(null); } public void test(List<String> tests) throws Exception { String testcases = getProperties().getProperty(Constants.TESTCASES); if (testcases == null) { warning("No %s set", Constants.TESTCASES); return; } clear(); test(null, tests); } public void test(File reportDir, List<String> tests) throws Exception { ProjectTester tester = getProjectTester(); if (reportDir != null) { logger.debug("Setting reportDir {}", reportDir); IO.delete(reportDir); tester.setReportDir(reportDir); } if (tests != null) { logger.debug("Adding tests {}", tests); for (String test : tests) { tester.addTest(test); } } tester.prepare(); if (!isOk()) { logger.error("Tests not run because project has errors"); return; } int errors = tester.test(); if (errors == 0) { logger.info("No Errors"); } else { if (errors > 0) { logger.info("{} Error(s)", errors); } else { logger.info("Error {}", errors); } } } /** * Run JUnit * * @throws Exception */ public void junit() throws Exception { @SuppressWarnings("resource") JUnitLauncher launcher = new JUnitLauncher(this); launcher.launch(); } /** * This methods attempts to turn any jar into a valid jar. If this is a * bundle with manifest, a manifest is added based on defaults. If it is a * bundle, but not r4, we try to add the r4 headers. * * @throws Exception */ public Jar getValidJar(File f) throws Exception { Jar jar = new Jar(f); return getValidJar(jar, IO.absolutePath(f)); } public Jar getValidJar(URL url) throws Exception { try (Resource resource = Resource.fromURL(url, getPlugin(HttpClient.class))) { Jar jar = Jar.fromResource(url.getFile() .replace('/', '.'), resource); return getValidJar(jar, url.toString()); } } public Jar getValidJar(Jar jar, String id) throws Exception { Manifest manifest = jar.getManifest(); if (manifest == null) { logger.debug("Wrapping with all defaults"); Builder b = new Builder(this); this.addClose(b); b.addClasspath(jar); b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest"); b.setProperty(Constants.EXPORT_PACKAGE, "*"); b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional"); jar = b.build(); } else if (manifest.getMainAttributes() .getValue(Constants.BUNDLE_MANIFESTVERSION) == null) { logger.debug("Not a release 4 bundle, wrapping with manifest as source"); Builder b = new Builder(this); this.addClose(b); b.addClasspath(jar); b.setProperty(Constants.PRIVATE_PACKAGE, "*"); b.mergeManifest(manifest); String imprts = manifest.getMainAttributes() .getValue(Constants.IMPORT_PACKAGE); if (imprts == null) imprts = ""; else imprts += ","; imprts += "*;resolution=optional"; b.setProperty(Constants.IMPORT_PACKAGE, imprts); b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest"); jar = b.build(); } return jar; } public String _project(@SuppressWarnings("unused") String args[]) { return IO.absolutePath(getBase()); } /** * Bump the version of this project. First check the main bnd file. If this * does not contain a version, check the include files. If they still do not * contain a version, then check ALL the sub builders. If not, add a version * to the main bnd file. * * @param mask the mask for bumping, see {@link Macro#_version(String[])} * @throws Exception */ public void bump(String mask) throws Exception { String pattern = "(" + Constants.BUNDLE_VERSION + "\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))"; String replace = "$1${version;" + mask + ";$3}"; try { // First try our main bnd file if (replace(getPropertiesFile(), pattern, replace)) return; logger.debug("no version in bnd.bnd"); // Try the included filed in reverse order (last has highest // priority) for (Iterator<File> iter = new ArrayDeque<>(getIncluded()).descendingIterator(); iter.hasNext();) { File file = iter.next(); if (replace(file, pattern, replace)) { logger.debug("replaced version in file {}", file); return; } } logger.debug("no version in included files"); boolean found = false; // Replace in all sub builders. try (ProjectBuilder b = getBuilder(null)) { for (Builder sub : b.getSubBuilders()) { found |= replace(sub.getPropertiesFile(), pattern, replace); } } if (!found) { logger.debug("no version in sub builders, add it to bnd.bnd"); String bndfile = IO.collect(getPropertiesFile()); bndfile += "\n# Added by by bump\n" + Constants.BUNDLE_VERSION + ": 0.0.0\n"; IO.store(bndfile, getPropertiesFile()); } } finally { forceRefresh(); } } boolean replace(File f, String pattern, String replacement) throws IOException { final Macro macro = getReplacer(); Sed sed = new Sed(new Replacer() { @Override public String process(String line) { return macro.process(line); } }, f); sed.replace(pattern, replacement); return sed.doIt() > 0; } public void bump() throws Exception { bump(getProperty(BUMPPOLICY, "=+0")); } public void action(String command) throws Exception { action(command, new Object[0]); } public void action(String command, Object... args) throws Exception { Map<String, Action> actions = getActions(); Action a = actions.get(command); if (a == null) a = new ReflectAction(command); before(this, command); try { if (args.length == 0) a.execute(this, command); else a.execute(this, args); } catch (Exception t) { after(this, command, t); throw t; } } /** * Run all before command plugins */ void before(@SuppressWarnings("unused") Project p, String a) { List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class); for (CommandPlugin testPlugin : testPlugins) { testPlugin.before(this, a); } } /** * Run all after command plugins */ void after(@SuppressWarnings("unused") Project p, String a, Throwable t) { List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class); for (int i = testPlugins.size() - 1; i >= 0; i testPlugins.get(i) .after(this, a, t); } } public void refreshAll() { workspace.refresh(); refresh(); } @SuppressWarnings("unchecked") public void script(@SuppressWarnings("unused") String type, String script) throws Exception { script(type, script, new Object[0]); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void script(String type, String script, Object... args) throws Exception { // TODO check tyiping List<Scripter> scripters = getPlugins(Scripter.class); if (scripters.isEmpty()) { msgs.NoScripters_(script); return; } Properties p = new UTF8Properties(getProperties()); for (int i = 0; i < args.length; i++) p.setProperty("" + i, Converter.cnv(String.class, args[i])); scripters.get(0) .eval((Map) p, new StringReader(script)); } public String _repos(@SuppressWarnings("unused") String args[]) throws Exception { List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class); List<String> names = new ArrayList<>(); for (RepositoryPlugin rp : repos) names.add(rp.getName()); return join(names, ", "); } public String _help(String args[]) throws Exception { if (args.length == 1) return "Specify the option or header you want information for"; Syntax syntax = Syntax.HELP.get(args[1]); if (syntax == null) return "No help for " + args[1]; String what = null; if (args.length > 2) what = args[2]; if (what == null || what.equals("lead")) return syntax.getLead(); if (what.equals("example")) return syntax.getExample(); if (what.equals("pattern")) return syntax.getPattern(); if (what.equals("values")) return syntax.getValues(); return "Invalid type specified for help: lead, example, pattern, values"; } /** * Returns containers for the deliverables of this project. The deliverables * is the project builder for this project if no -sub is specified. * Otherwise it contains all the sub bnd files. * * @return A collection of containers * @throws Exception */ public Collection<Container> getDeliverables() throws Exception { List<Container> result = new ArrayList<>(); try (ProjectBuilder pb = getBuilder(null)) { for (Builder builder : pb.getSubBuilders()) { Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT, getOutputFile(builder.getBsn(), builder.getVersion()), null, null, null); result.add(c); } return result; } } /** * Return a builder associated with the give bnd file or null. The bnd.bnd * file can contain -sub option. This option allows specifying files in the * same directory that should drive the generation of multiple deliverables. * This method figures out if the bndFile is actually one of the bnd files * of a deliverable. * * @param bndFile A file pointing to a bnd file. * @return null or a builder for a sub file, the caller must close this * builder * @throws Exception */ public Builder getSubBuilder(File bndFile) throws Exception { bndFile = bndFile.getAbsoluteFile(); // Verify that we are inside the project. if (!bndFile.toPath() .startsWith(getBase().toPath())) return null; ProjectBuilder pb = getBuilder(null); boolean close = true; try { for (Builder b : pb.getSubBuilders()) { File propertiesFile = b.getPropertiesFile(); if (propertiesFile != null) { if (propertiesFile.equals(bndFile)) { // Found it! // disconnect from its parent life cycle if (b == pb) { close = false; } else { pb.removeClose(b); } return b; } } } return null; } finally { if (close) { pb.close(); } } } /** * Return a build that maps to the sub file. * * @param string * @throws Exception */ public ProjectBuilder getSubBuilder(String string) throws Exception { ProjectBuilder pb = getBuilder(null); boolean close = true; try { for (Builder b : pb.getSubBuilders()) { if (b.getBsn() .equals(string) || b.getBsn() .endsWith("." + string)) { // disconnect from its parent life cycle if (b == pb) { close = false; } else { pb.removeClose(b); } return (ProjectBuilder) b; } } return null; } finally { if (close) { pb.close(); } } } /** * Answer the container associated with a given bsn. * * @throws Exception */ public Container getDeliverable(String bsn, Map<String, String> attrs) throws Exception { try (ProjectBuilder pb = getBuilder(null)) { for (Builder b : pb.getSubBuilders()) { if (b.getBsn() .equals(bsn)) return new Container(this, getOutputFile(bsn, b.getVersion()), attrs); } } return null; } /** * Get a list of the sub builders. A bnd.bnd file can contain the -sub * option. This will generate multiple deliverables. This method returns the * builders for each sub file. If no -sub option is present, the list will * contain a builder for the bnd.bnd file. * * @return A list of builders. * @throws Exception * @deprecated As of 3.4. Replace with * * <pre> * try (ProjectBuilder pb = getBuilder(null)) { * for (Builder b : pb.getSubBuilders()) { * ... * } * } * </pre> */ @Deprecated public Collection<? extends Builder> getSubBuilders() throws Exception { ProjectBuilder pb = getBuilder(null); boolean close = true; try { List<Builder> builders = pb.getSubBuilders(); for (Builder b : builders) { if (b == pb) { close = false; } else { pb.removeClose(b); } } return builders; } finally { if (close) { pb.close(); } } } /** * Calculate the classpath. We include our own runtime.jar which includes * the test framework and we include the first of the test frameworks * specified. * * @throws Exception */ Collection<File> toFile(Collection<Container> containers) throws Exception { ArrayList<File> files = new ArrayList<>(); for (Container container : containers) { container.contributeFiles(files, this); } return files; } public Collection<String> getRunVM() { Parameters hdr = getMergedParameters(RUNVM); return hdr.keyList(); } public Collection<String> getRunProgramArgs() { Parameters hdr = getMergedParameters(RUNPROGRAMARGS); return hdr.keyList(); } public Map<String, String> getRunProperties() { return OSGiHeader.parseProperties(mergeProperties(RUNPROPERTIES)); } /** * Get a launcher. * * @throws Exception */ public ProjectLauncher getProjectLauncher() throws Exception { return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher"); } public ProjectTester getProjectTester() throws Exception { String defaultDefault = since(About._3_0) ? "biz.aQute.tester" : "biz.aQute.junit"; return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN, getProperty(Constants.TESTER, defaultDefault)); } private <T> T getHandler(Class<T> target, Collection<Container> containers, String header, String defaultHandler) throws Exception { Class<? extends T> handlerClass = target; // Make sure we find at least one handler, but hope to find an earlier // one List<Container> withDefault = Create.list(); withDefault.addAll(containers); withDefault.addAll(getBundles(Strategy.HIGHEST, defaultHandler, null)); logger.debug("candidates for handler {}: {}", target, withDefault); for (Container c : withDefault) { Manifest manifest = c.getManifest(); if (manifest != null) { String launcher = manifest.getMainAttributes() .getValue(header); if (launcher != null) { Class<?> clz = getClass(launcher, c.getFile()); if (clz != null) { if (!target.isAssignableFrom(clz)) { msgs.IncompatibleHandler_For_(launcher, defaultHandler); } else { logger.debug("found handler {} from {}", defaultHandler, c); handlerClass = clz.asSubclass(target); Constructor<? extends T> constructor; try { constructor = handlerClass.getConstructor(Project.class, Container.class); } catch (NoSuchMethodException e) { constructor = handlerClass.getConstructor(Project.class); } try { return (constructor.getParameterCount() == 1) ? constructor.newInstance(this) : constructor.newInstance(this, c); } catch (InvocationTargetException e) { throw Exceptions.duck(e.getCause()); } } } } } } throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler); } /** * Make this project delay the calculation of the run dependencies. The run * dependencies calculation can be done in prepare or until the dependencies * are actually needed. */ public void setDelayRunDependencies(boolean x) { delayRunDependencies = x; } /** * bnd maintains a class path that is set by the environment, i.e. bnd is * not in charge of it. */ public void addClasspath(File f) { if (!f.isFile() && !f.isDirectory()) { msgs.AddingNonExistentFileToClassPath_(f); } Container container = new Container(f, null); classpath.add(container); } public void clearClasspath() { classpath.clear(); unreferencedClasspathEntries.clear(); } public Collection<Container> getClasspath() { return classpath; } /** * Pack the project (could be a bndrun file) and save it on disk. Report * errors if they happen. */ static List<String> ignore = new ExtList<>(BUNDLE_SPECIFIC_HEADERS); /** * Caller must close this JAR * * @param profile * @return a jar with the executable code * @throws Exception */ public Jar pack(String profile) throws Exception { try (ProjectBuilder pb = getBuilder(null)) { List<Builder> subBuilders = pb.getSubBuilders(); if (subBuilders.size() != 1) { error("Project has multiple bnd files, please select one of the bnd files").header(EXPORT) .context(profile); return null; } Builder b = subBuilders.iterator() .next(); ignore.remove(BUNDLE_SYMBOLICNAME); ignore.remove(BUNDLE_VERSION); ignore.add(SERVICE_COMPONENT); try (ProjectLauncher launcher = getProjectLauncher()) { launcher.getRunProperties() .put("profile", profile); // TODO // remove launcher.getRunProperties() .put(PROFILE, profile); Jar jar = launcher.executable(); Manifest m = jar.getManifest(); Attributes main = m.getMainAttributes(); for (String key : this) { if (Character.isUpperCase(key.charAt(0)) && !ignore.contains(key)) { String value = getProperty(key); if (value == null) continue; Name name = new Name(key); String trimmed = value.trim(); if (trimmed.isEmpty()) main.remove(name); else if (EMPTY_HEADER.equals(trimmed)) main.put(name, ""); else main.put(name, value); } } if (main.getValue(BUNDLE_SYMBOLICNAME) == null) main.putValue(BUNDLE_SYMBOLICNAME, b.getBsn()); if (main.getValue(BUNDLE_SYMBOLICNAME) == null) main.putValue(BUNDLE_SYMBOLICNAME, getName()); if (main.getValue(BUNDLE_VERSION) == null) { main.putValue(BUNDLE_VERSION, Version.LOWEST.toString()); warning("No version set, uses 0.0.0"); } jar.setManifest(m); jar.calcChecksums(new String[] { "SHA1", "MD5" }); launcher.removeClose(jar); return jar; } } } /** * Do a baseline for this project * * @throws Exception */ public void baseline() throws Exception { try (ProjectBuilder pb = getBuilder(null)) { for (Builder b : pb.getSubBuilders()) { @SuppressWarnings("resource") Jar build = b.build(); getInfo(b); } getInfo(pb); } } /** * Method to verify that the paths are correct, ie no missing dependencies * * @param test for test cases, also adds -testpath * @throws Exception */ public void verifyDependencies(boolean test) throws Exception { verifyDependencies(RUNBUNDLES, getRunbundles()); verifyDependencies(RUNPATH, getRunpath()); if (test) verifyDependencies(TESTPATH, getTestpath()); verifyDependencies(BUILDPATH, getBuildpath()); } private void verifyDependencies(String title, Collection<Container> path) throws Exception { List<String> msgs = new ArrayList<>(); for (Container c : new ArrayList<>(path)) { for (Container cc : c.getMembers()) { if (cc.getError() != null) msgs.add(cc + " - " + cc.getError()); else if (!cc.getFile() .isFile() && !cc.getFile() .equals(cc.getProject() .getOutput()) && !cc.getFile() .equals(cc.getProject() .getTestOutput())) msgs.add(cc + " file does not exists: " + cc.getFile()); } } if (msgs.isEmpty()) return; error("%s: has errors: %s", title, Strings.join(msgs)); } /** * Report detailed info from this project * * @throws Exception */ @Override public void report(Map<String, Object> table) throws Exception { super.report(table); report(table, true); } protected void report(Map<String, Object> table, boolean isProject) throws Exception { if (isProject) { table.put("Target", getTarget()); table.put("Source", getSrc()); table.put("Output", getOutput()); File[] buildFiles = getBuildFiles(); if (buildFiles != null) table.put("BuildFiles", Arrays.asList(buildFiles)); table.put("Classpath", getClasspath()); table.put("Actions", getActions()); table.put("AllSourcePath", getAllsourcepath()); table.put("BootClassPath", getBootclasspath()); table.put("BuildPath", getBuildpath()); table.put("Deliverables", getDeliverables()); table.put("DependsOn", getDependson()); table.put("SourcePath", getSourcePath()); } table.put("RunPath", getRunpath()); table.put("TestPath", getTestpath()); table.put("RunProgramArgs", getRunProgramArgs()); table.put("RunVM", getRunVM()); table.put("Runfw", getRunFw()); table.put("Runbundles", getRunbundles()); } // TODO test format parametsr public void compile(boolean test) throws Exception { Command javac = getCommonJavac(false); javac.add("-d", IO.absolutePath(getOutput())); StringBuilder buildpath = new StringBuilder(); String buildpathDel = ""; Collection<Container> bp = Container.flatten(getBuildpath()); logger.debug("buildpath {}", getBuildpath()); for (Container c : bp) { buildpath.append(buildpathDel) .append(IO.absolutePath(c.getFile())); buildpathDel = File.pathSeparator; } if (buildpath.length() != 0) { javac.add("-classpath", buildpath.toString()); } List<File> sp = new ArrayList<>(getSourcePath()); StringBuilder sourcepath = new StringBuilder(); String sourcepathDel = ""; for (File sourceDir : sp) { sourcepath.append(sourcepathDel) .append(IO.absolutePath(sourceDir)); sourcepathDel = File.pathSeparator; } javac.add("-sourcepath", sourcepath.toString()); Glob javaFiles = new Glob("*.java"); List<File> files = javaFiles.getFiles(getSrc(), true, false); for (File file : files) { javac.add(IO.absolutePath(file)); } if (files.isEmpty()) { logger.debug("Not compiled, no source files"); } else compile(javac, "src"); if (test) { javac = getCommonJavac(true); javac.add("-d", IO.absolutePath(getTestOutput())); Collection<Container> tp = Container.flatten(getTestpath()); for (Container c : tp) { buildpath.append(buildpathDel) .append(IO.absolutePath(c.getFile())); buildpathDel = File.pathSeparator; } if (buildpath.length() != 0) { javac.add("-classpath", buildpath.toString()); } sourcepath.append(sourcepathDel) .append(IO.absolutePath(getTestSrc())); javac.add("-sourcepath", sourcepath.toString()); javaFiles.getFiles(getTestSrc(), files, true, false); for (File file : files) { javac.add(IO.absolutePath(file)); } if (files.isEmpty()) { logger.debug("Not compiled for test, no test src files"); } else compile(javac, "test"); } } private void compile(Command javac, String what) throws Exception { logger.debug("compile {} {}", what, javac); StringBuilder stdout = new StringBuilder(); StringBuilder stderr = new StringBuilder(); int n = javac.execute(stdout, stderr); logger.debug("javac stdout: {}", stdout); logger.debug("javac stderr: {}", stderr); if (n != 0) { error("javac failed %s", stderr); } } private Command getCommonJavac(boolean test) throws Exception { Command javac = new Command(); javac.add(getProperty("javac", "javac")); String target = getProperty("javac.target", "1.6"); String profile = getProperty("javac.profile", ""); String source = getProperty("javac.source", "1.6"); String debug = getProperty("javac.debug"); if ("on".equalsIgnoreCase(debug) || "true".equalsIgnoreCase(debug)) debug = "vars,source,lines"; Parameters options = new Parameters(getProperty("java.options"), this); boolean deprecation = isTrue(getProperty("java.deprecation")); javac.add("-encoding", "UTF-8"); javac.add("-source", source); javac.add("-target", target); if (!profile.isEmpty()) javac.add("-profile", profile); if (deprecation) javac.add("-deprecation"); if (test || debug == null) { javac.add("-g:source,lines,vars"); } else { javac.add("-g:" + debug); } javac.addAll(options.keyList()); StringBuilder bootclasspath = new StringBuilder(); String bootclasspathDel = "-Xbootclasspath/p:"; Collection<Container> bcp = Container.flatten(getBootclasspath()); for (Container c : bcp) { bootclasspath.append(bootclasspathDel) .append(IO.absolutePath(c.getFile())); bootclasspathDel = File.pathSeparator; } if (bootclasspath.length() != 0) { javac.add(bootclasspath.toString()); } return javac; } public String _ide(String[] args) throws IOException { if (args.length < 2) { error("The ${ide;<>} macro needs an argument"); return null; } if (ide == null) { ide = new UTF8Properties(); File file = getFile(".settings/org.eclipse.jdt.core.prefs"); if (!file.isFile()) { error("The ${ide;<>} macro requires a .settings/org.eclipse.jdt.core.prefs file in the project"); return null; } try (InputStream in = IO.stream(file)) { ide.load(in); } } String deflt = args.length > 2 ? args[2] : null; if ("javac.target".equals(args[1])) { return ide.getProperty("org.eclipse.jdt.core.compiler.codegen.targetPlatform", deflt); } if ("javac.source".equals(args[1])) { return ide.getProperty("org.eclipse.jdt.core.compiler.source", deflt); } return null; } public Map<String, Version> getVersions() throws Exception { if (versionMap.isEmpty()) { try (ProjectBuilder pb = getBuilder(null)) { for (Builder builder : pb.getSubBuilders()) { String v = builder.getVersion(); if (v == null) v = "0"; else { v = Analyzer.cleanupVersion(v); if (!Verifier.isVersion(v)) continue; // skip } Version version = new Version(v); versionMap.put(builder.getBsn(), version); } } } return new LinkedHashMap<>(versionMap); } public Collection<String> getBsns() throws Exception { return new ArrayList<>(getVersions().keySet()); } public Version getVersion(String bsn) throws Exception { Version version = getVersions().get(bsn); if (version == null) { throw new IllegalArgumentException("Bsn " + bsn + " does not exist in project " + getName()); } return version; } /** * Get the exported packages form all builders calculated from the last * build */ public Packages getExports() { return exportedPackages; } /** * Get the imported packages from all builders calculated from the last * build */ public Packages getImports() { return importedPackages; } /** * Get the contained packages calculated from all builders from the last * build */ public Packages getContained() { return containedPackages; } public void remove() throws Exception { getWorkspace().removeProject(this); IO.delete(getBase()); } public boolean getRunKeep() { return is(Constants.RUNKEEP); } public void setPackageInfo(String packageName, Version newVersion) throws Exception { packageInfo.setPackageInfo(packageName, newVersion); } public Version getPackageInfo(String packageName) throws Exception { return packageInfo.getPackageInfo(packageName); } /** * Actions to perform before a full workspace release. This is executed for * projects that describe the distribution */ public void preRelease() { for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) { rp.begin(this); } } /** * Actions to perform after a full workspace release. This is executed for * projects that describe the distribution */ public void postRelease() { for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) { rp.end(this); } } /** * Copy a repository to another repository * * @throws Exception */ public void copy(RepositoryPlugin source, String filter, RepositoryPlugin destination) throws Exception { copy(source, filter == null ? null : new Instructions(filter), destination); } public void copy(RepositoryPlugin source, Instructions filter, RepositoryPlugin destination) throws Exception { assert source != null; assert destination != null; logger.info("copy from repo {} to {} with filter {}", source, destination, filter); for (String bsn : source.list(null)) { for (Version version : source.versions(bsn)) { if (filter == null || filter.matches(bsn)) { logger.info("copy {}:{}", bsn, version); File file = source.get(bsn, version, null); if (file.getName() .endsWith(".jar")) { try (InputStream in = IO.stream(file)) { PutOptions po = new PutOptions(); po.bsn = bsn; po.context = null; po.type = "bundle"; po.version = version; PutResult put = destination.put(in, po); } catch (Exception e) { logger.error("Failed to copy {}-{}", e, bsn, version); error("Failed to copy %s:%s from %s to %s, error: %s", bsn, version, source, destination, e); } } } } } } @Override public boolean isInteractive() { return getWorkspace().isInteractive(); } }
package SW9.model_canvas.locations; import SW9.Keybind; import SW9.KeyboardTracker; import SW9.MouseTracker; import SW9.model_canvas.IParent; import SW9.model_canvas.ModelCanvas; import SW9.model_canvas.ModelContainer; import SW9.model_canvas.Parent; import SW9.model_canvas.edges.Edge; import SW9.utility.BindingHelper; import SW9.utility.DragHelper; import SW9.utility.DropShadowHelper; import javafx.animation.Animation; import javafx.animation.Transition; import javafx.beans.binding.StringBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableDoubleValue; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.shape.Circle; import javafx.util.Duration; public class Location extends Parent implements DragHelper.Draggable { // Used to create the Location public final static double RADIUS = 25.0f; // Used to update the interaction with the mouse private BooleanProperty isOnMouse = new SimpleBooleanProperty(false); public final MouseTracker localMouseTracker; public Circle circle; public Label locationLabel; public BooleanProperty isUrgent = new SimpleBooleanProperty(false); public BooleanProperty isCommitted = new SimpleBooleanProperty(false); public enum Type { NORMAL, INITIAL, FINAL } public Type type; public Location(MouseTracker canvasMouseTracker) { this(canvasMouseTracker.getXProperty(), canvasMouseTracker.getYProperty(), canvasMouseTracker, Type.NORMAL); // It is initialize with the mouse, hence it is on the mouse isOnMouse.set(true); // Only locations following on the mouse is discardable (until placed) KeyboardTracker.registerKeybind(KeyboardTracker.DISCARD_NEW_LOCATION, removeOnEscape); } public Location(final ObservableDoubleValue centerX, final ObservableDoubleValue centerY, final MouseTracker canvasMouseTracker, Type type) { // Initialize the type property this.type = type; // Bind the mouse transparency to the boolean telling if the location is on the mouse this.mouseTransparentProperty().bind(isOnMouse); // Add the circle and add it at a child circle = new Circle(centerX.doubleValue(), centerY.doubleValue(), RADIUS); addChild(circle); // If the location is not a normal locations draw the visual cues if (type == Type.INITIAL) { addChild(new InitialLocationCircle(this)); } else if (type == Type.FINAL) { addChild(new FinalLocationCross(this)); } // Add a text which we will use as a label for urgent and committed locations locationLabel = new Label(); locationLabel.textProperty().bind(new StringBinding() { { super.bind(isUrgent, isCommitted); } @Override protected String computeValue() { if (isUrgent.get()) { return "U"; } else if (isCommitted.get()) { return "C"; } else { return ""; } } }); locationLabel.setMinWidth(2 * RADIUS); locationLabel.setMaxWidth(2 * RADIUS); locationLabel.setMinHeight(2 * RADIUS); locationLabel.setMaxHeight(2 * RADIUS); addChild(locationLabel); // Bind the label to the circle BindingHelper.bind(locationLabel, this); // Add style for the circle and label circle.getStyleClass().add("location"); locationLabel.getStyleClass().add("location-label"); locationLabel.getStyleClass().add("headline"); locationLabel.getStyleClass().add("white-text"); // Bind the Location to the property circle.centerXProperty().bind(centerX); circle.centerYProperty().bind(centerY); // Initialize the local mouse tracker this.localMouseTracker = new MouseTracker(this); // Register the handler for entering the location localMouseTracker.registerOnMouseEnteredEventHandler(event -> { ModelCanvas.setHoveredLocation(this); }); // Register the handler for existing the locations localMouseTracker.registerOnMouseExitedEventHandler(event -> { if (ModelCanvas.mouseIsHoveringLocation() && ModelCanvas.getHoveredLocation().equals(this)) { ModelCanvas.setHoveredLocation(null); } }); // Place the new location when the mouse is pressed (i.e. stop moving it) canvasMouseTracker.registerOnMousePressedEventHandler(mouseClickedEvent -> { if (isOnMouse.get() && ModelCanvas.mouseIsHoveringModelContainer()) { ModelContainer modelContainer = ModelCanvas.getHoveredModelContainer(); circle.centerXProperty().bind(modelContainer.xProperty().add(mouseClickedEvent.getX() - (modelContainer.xProperty().get()))); circle.centerYProperty().bind(modelContainer.yProperty().add(mouseClickedEvent.getY() - (modelContainer.yProperty().get()))); modelContainer.addLocation(this); // Tell the canvas that the mouse is no longer occupied ModelCanvas.setLocationOnMouse(null); // Disable discarding functionality for a location when it is placed on the canvas KeyboardTracker.unregisterKeybind(KeyboardTracker.DISCARD_NEW_LOCATION); // Animate the way the location is placed on the canvas Animation locationPlaceAnimation = new Transition() { { setCycleDuration(Duration.millis(50)); } protected void interpolate(double frac) { Location.this.setEffect(DropShadowHelper.generateElevationShadow(12 - 12 * frac)); } }; // When the animation is done ensure that we note that we are no longer on the mouse locationPlaceAnimation.setOnFinished(event -> { isOnMouse.set(false); }); locationPlaceAnimation.play(); } }); // Make the location draggable (if shift is not pressed, and there is no edge currently being drawn) DragHelper.makeDraggable(this, (event) -> { ModelContainer parent = (ModelContainer) getParent(); boolean allowX = event.getX() - RADIUS >= parent.xProperty().get() && event.getX() < parent.xProperty().get() + parent.getXLimit().get() - RADIUS; boolean allowY = event.getY() - RADIUS >= parent.yProperty().get() && event.getY() < parent.yProperty().get() + parent.getYLimit().get() - RADIUS; return !event.isShiftDown() && !ModelCanvas.edgeIsBeingDrawn() && !this.equals(ModelCanvas.getLocationOnMouse()) && type.equals(Type.NORMAL) && allowX && allowY; }); // Draw a new edge from the location localMouseTracker.registerOnMousePressedEventHandler(event -> { if (event.isShiftDown() && !ModelCanvas.edgeIsBeingDrawn()) { final Edge edge = new Edge(this, canvasMouseTracker); addChildToParent(edge); } }); // Register toggle urgent and committed keybinds when the locations is hovered, and unregister them when we are not localMouseTracker.registerOnMouseEnteredEventHandler(event -> { KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_URGENT, makeLocationUrgent); KeyboardTracker.registerKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED, makeLocationCommitted); }); localMouseTracker.registerOnMouseExitedEventHandler(event -> { KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_URGENT); KeyboardTracker.unregisterKeybind(KeyboardTracker.MAKE_LOCATION_COMMITTED); }); } private final Keybind removeOnEscape = new Keybind(new KeyCodeCombination(KeyCode.ESCAPE), () -> { // Get the parent and detach this Location IParent parent = (IParent) this.getParent(); if (parent == null) return; parent.removeChild(this); // Notify the canvas that we are no longer placing a location ModelCanvas.setLocationOnMouse(null); }); private final Keybind makeLocationUrgent = new Keybind(new KeyCodeCombination(KeyCode.U), () -> { // The location cannot be committed isCommitted.set(false); // Toggle the urgent boolean isUrgent.set(!isUrgent.get()); }); private final Keybind makeLocationCommitted = new Keybind(new KeyCodeCombination(KeyCode.C), () -> { // The location cannot be committed isUrgent.set(false); // Toggle the urgent boolean isCommitted.set(!isCommitted.get()); }); private void addChildToParent(final Node child) { // Get the parent from the source location IParent parent = (IParent) this.getParent(); if (parent == null) return; parent.addChild(child); } @Override public MouseTracker getMouseTracker() { return this.localMouseTracker; } @Override public DoubleProperty xProperty() { return circle.centerXProperty(); } @Override public DoubleProperty yProperty() { return circle.centerYProperty(); } }
package cn.lambdalib.util.datapart; import cn.lambdalib.networkcall.s11n.StorageOption.RangedTarget; import net.minecraft.entity.Entity; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import cn.lambdalib.annoreg.core.Registrant; import cn.lambdalib.networkcall.RegNetworkCall; import cn.lambdalib.networkcall.s11n.InstanceSerializer; import cn.lambdalib.networkcall.s11n.RegSerializable; import cn.lambdalib.networkcall.s11n.SerializationManager; import cn.lambdalib.networkcall.s11n.StorageOption.Data; import cpw.mods.fml.relauncher.Side; /** * DataPart represents a single tickable data-storage object attached on an Entity. * It is driven by the {@link EntityData} of this entity. <br> * * The DataPart is attached statically via {@link EntityData#register} * method or @RegDataPart annotation (This should be done at init stages), and is automatically constructed * on <em>first time querying</em>. At server, the {@link DataPart#fromNBT(NBTTagCompound)} * method will be called right away, and the NBT will be sync to client ASAP. <br> * * Also when the world is being saved, the {@link DataPart#toNBT()} will be called to save stuffs * in server. <br> * * A simple sync helper is provided. You can use sync() in both CLIENT and SERVER side to make a new NBT * synchronization. However, for complex syncs you might want to consider using NetworkCall. <br> * * DataPart supports ticking by nature. Use setTick() to enable it. <br> * * For DataPart of EntityPlayer, all DataParts are kept except for those who called {@link DataPart#clearOnDeath()} * in their ctor when player is respawned. * * @author WeAthFolD */ @Registrant @RegSerializable(instance = DataPart.Serializer.class) public abstract class DataPart<Ent extends Entity> { // API /** * The default constructor must be kept for subclasses, for using reflections to create instance. */ public DataPart() {} /** * Invoked every tick if setTick() is called */ public void tick() {} /** * Set this DataPart to need ticking. Called in ctor. */ public final void setTick() { tick = true; } /** * Set this DataPart to be reset when entity is dead. Effective for EntityPlayer only. Called in ctor. * (Other entities don't revive) */ public final void clearOnDeath() { keepOnDeath = false; } /** * Restore data of this DataPart from the NBT. Will be called externally only for world saving */ public abstract void fromNBT(NBTTagCompound tag); /** * Convert data of this DataPart to a NBT. Will be called externally only for world saving */ public abstract NBTTagCompound toNBT(); /** * Same as fromNBT, but only get called when synchronizing across network. */ public void fromNBTSync(NBTTagCompound tag) { fromNBT(tag); } /** * Same as toNBT, but only get called when synchronizing across network. */ public NBTTagCompound toNBTSync() { return toNBT(); } public Ent getEntity() { return data.entity; } public boolean isRemote() { return getEntity().worldObj.isRemote; } public <T extends DataPart> T getPart(String name) { return data.getPart(name); } public <T extends DataPart> T getPart(Class<T> type) { return data.getPart(type); } public String getName() { return data.getName(this); } // Internal /** * Internal sync flag, used to determine whether this part is init in client. */ boolean dirty = true; int tickUntilQuery = 0; /** * The player instance when this data is available. Do NOT modify this field! */ EntityData<Ent> data; boolean tick = false, keepOnDeath = true; /** * Return true if this data has received the initial sync. * ALWAYS true in server. */ protected boolean isSynced() { return !dirty; } protected void sync() { if(isRemote()) { syncFromClient(toNBTSync()); } else { syncFromServer(getEntity(), toNBTSync()); } } @RegNetworkCall(side = Side.SERVER) private void syncFromClient(@Data NBTTagCompound tag) { fromNBTSync(tag); } @RegNetworkCall(side = Side.CLIENT) private void syncFromServer(@RangedTarget(range = 10) Entity player, @Data NBTTagCompound tag) { fromNBTSync(tag); } protected void checkSide(boolean isRemote) { if(isRemote ^ isRemote()) { throw new IllegalStateException("Wrong side: " + isRemote()); } } public static class Serializer implements InstanceSerializer<DataPart> { InstanceSerializer entitySer = SerializationManager.INSTANCE.getInstanceSerializer(Entity.class); @Override public DataPart readInstance(NBTBase nbt) throws Exception { NBTTagCompound tag = (NBTTagCompound) nbt; NBTBase entityTag = tag.getTag("e"); if(entityTag != null) { Entity e = (Entity) entitySer.readInstance(entityTag); EntityData data = EntityData.get(e); if(data != null) { return data.getPart(tag.getString("n")); } } return null; } @Override public NBTBase writeInstance(DataPart obj) throws Exception { NBTTagCompound ret = new NBTTagCompound(); NBTBase entityTag = entitySer.writeInstance(obj.getEntity()); ret.setTag("e", entityTag); ret.setString("n", obj.getName()); return ret; } } }
package cn.net.openid.web; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.context.MessageSource; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import cn.net.openid.dao.DaoFacade; import cn.net.openid.domain.User; /** * @author Shutra * */ public class ProfileController extends SimpleFormController { private DaoFacade daoFacade; private MessageSource messageSource; private LocaleResolver localeResolver; private String formatOffset(int offset) { int m = offset / (1000 * 60); int h = m / 60; StringBuffer sb = new StringBuffer(); if (offset > 0) { sb.append('+'); } else { sb.append('-'); } if (Math.abs(h) < 10) { sb.append('0'); } sb.append(Math.abs(h)).append(":"); m = m - h * 60; if (m == 0) { sb.append("00"); } else { sb.append(Math.abs(m)); } return sb.toString(); } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest) */ @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); UserSession userSession = (UserSession) session .getAttribute("userSession"); String userId = userSession.getUserId(); User user = this.daoFacade.getUser(userId); return user; } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, * org.springframework.web.bind.ServletRequestDataBinder) */ @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor( new SimpleDateFormat("yyyy-MM-dd"), true)); } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, * java.lang.Object, org.springframework.validation.BindException) */ @Override protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception { super.onBindAndValidate(request, command, errors); } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object) */ @Override protected ModelAndView onSubmit(Object command) throws Exception { User user = (User) command; this.daoFacade.updateUser(user); return super.onSubmit(command); } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest) */ @SuppressWarnings("unchecked") @Override protected Map referenceData(HttpServletRequest request) throws Exception { Map map = super.referenceData(request); if (map == null) { map = new HashMap<Object, Object>(); } Locale locale = this.localeResolver.resolveLocale(request); final Map<String, String> timezones = new LinkedHashMap<String, String>(); final Map<String, String> countries = new LinkedHashMap<String, String>(); final Map<String, String> languages = new LinkedHashMap<String, String>(); Locale[] locales = Locale.getAvailableLocales(); countries.put("", " languages.put("", " for (Locale l : locales) { if (!StringUtils.isEmpty(l.getCountry()) && !countries.containsKey(l.getCountry())) { countries.put(l.getCountry(), l.getDisplayCountry(locale)); } if (!StringUtils.isEmpty(l.getLanguage()) && !languages.containsKey(l.getLanguage())) { languages.put(l.getLanguage(), l.getDisplayLanguage(locale)); } } map.put("countries", countries); map.put("languages", languages); String[] timezoneIds = TimeZone.getAvailableIDs(); timezones.put("", " for (String timeZoneId : timezoneIds) { TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); String longName = timeZone.getDisplayName(locale); int offset = timeZone.getRawOffset(); timezones.put(timeZone.getID(), String.format(this.messageSource .getMessage("timezone", new String[] {}, locale), this .formatOffset(offset), longName, timeZone.getID())); } map.put("timezones", timezones); return map; } /** * @param daoFacade * the daoFacade to set */ public void setDaoFacade(DaoFacade daoFacade) { this.daoFacade = daoFacade; } /** * @param localeResolver * the localeResolver to set */ public void setLocaleResolver(LocaleResolver localeResolver) { this.localeResolver = localeResolver; } /** * @param messageSource * the messageSource to set */ public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } }
package com.amee.domain.profile; import com.amee.domain.AMEEStatus; import com.amee.domain.Builder; import com.amee.domain.ObjectType; import com.amee.domain.data.DataCategory; import com.amee.domain.data.DataItem; import com.amee.domain.data.Item; import com.amee.domain.data.ItemValue; import com.amee.platform.science.ReturnValues; import com.amee.platform.science.StartEndDate; import org.hibernate.annotations.Index; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.annotation.Resource; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Transient; import java.util.Date; @Entity @DiscriminatorValue("PI") public class ProfileItem extends Item { @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "PROFILE_ID") private Profile profile; @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "DATA_ITEM_ID") private DataItem dataItem; @Column(name = "START_DATE") @Index(name = "START_DATE_IND") protected Date startDate = new Date(); @Column(name = "END_DATE") @Index(name = "END_DATE_IND") protected Date endDate; @Transient private ReturnValues amounts = new ReturnValues(); @Transient private Builder builder; @Transient @Resource private CO2CalculationService calculationService; public ProfileItem() { super(); } public ProfileItem(Profile profile, DataItem dataItem) { super(dataItem.getDataCategory(), dataItem.getItemDefinition()); setProfile(profile); setDataItem(dataItem); } public ProfileItem(Profile profile, DataCategory dataCategory, DataItem dataItem) { super(dataCategory, dataItem.getItemDefinition()); setProfile(profile); setDataItem(dataItem); } public void setBuilder(Builder builder) { this.builder = builder; } public ProfileItem getCopy() { log.debug("getCopy()"); ProfileItem profileItem = new ProfileItem(); copyTo(profileItem); return profileItem; } /** * Copy values from this instance to the supplied instance. * * @param o Object to copy values to */ protected void copyTo(ProfileItem o) { super.copyTo(o); o.profile = profile; o.dataItem = dataItem; o.startDate = (startDate != null) ? (Date) startDate.clone() : null; o.endDate = (endDate != null) ? (Date) endDate.clone() : null; o.amounts = amounts; o.builder = builder; o.calculationService = calculationService; } public String getPath() { return getUid(); } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public DataItem getDataItem() { return dataItem; } public void setDataItem(DataItem dataItem) { if (dataItem != null) { this.dataItem = dataItem; } } public StartEndDate getStartDate() { return new StartEndDate(startDate); } public void setStartDate(Date startDate) { this.startDate = startDate; } public StartEndDate getEndDate() { if (endDate != null) { return new StartEndDate(endDate); } else { return null; } } public void setEndDate(Date endDate) { // May be null. this.endDate = endDate; } public boolean isEnd() { return (endDate != null) && (startDate.compareTo(endDate) == 0); } /** * Get the GHG {@link com.amee.platform.science.ReturnValues ReturnValues} for this ProfileItem. * <p/> * If the ProfileItem does not support calculations (i.e. metadata) an empty ReturnValues object is returned. * * @param recalculate force recalculation of the amounts. If false, only calculate amounts if amounts is empty. * @return - the {@link com.amee.platform.science.ReturnValues ReturnValues} for this ProfileItem */ public ReturnValues getAmounts(boolean recalculate) { if (amounts.getReturnValues().isEmpty() || recalculate) { log.debug("getAmounts() - calculating amounts"); calculationService.calculate(this); } return amounts; } /** * Get the GHG {@link com.amee.platform.science.ReturnValues ReturnValues} for this ProfileItem. * <p/> * If the ProfileItem does not support calculations (i.e. metadata) an empty ReturnValues object is returned. * <p/> * Note: this method only calculates the amounts if amounts is empty, ie, has not already been calculated. * * @return - the {@link com.amee.platform.science.ReturnValues ReturnValues} for this ProfileItem */ public ReturnValues getAmounts() { return getAmounts(false); } /** * Returns the default GHG amount for this ProfileItem as a double. * This method is only included to provide backwards compatibility for existing Algorithms. * * @return the double value of the default GHG amount. */ @Deprecated public double getAmount() { return getAmounts().defaultValueAsDouble(); } public void setAmounts(ReturnValues amounts) { this.amounts = amounts; } @Override public JSONObject getJSONObject(boolean b) throws JSONException { return builder.getJSONObject(b); } public Element getElement(Document document, boolean b) { return builder.getElement(document, b); } public ObjectType getObjectType() { return ObjectType.PI; } public boolean hasNonZeroPerTimeValues() { for (ItemValue iv : getItemValues()) { if (iv.hasPerTimeUnit() && iv.isNonZero()) { return true; } } return false; } //TODO - TEMP HACK - will remove as soon we decide how to handle return units in V1 correctly. public boolean isSingleFlight() { for (ItemValue iv : getItemValues()) { if ((iv.getName().startsWith("IATA") && iv.getValue().length() > 0) || (iv.getName().startsWith("Lat") && !iv.getValue().equals("-999")) || (iv.getName().startsWith("Lon") && !iv.getValue().equals("-999"))) { return true; } } return false; } @Override public boolean isTrash() { return status.equals(AMEEStatus.TRASH) || getDataItem().isTrash() || getProfile().isTrash(); } }
package com.checkmarx.jenkins; import com.checkmarx.components.zipper.Zipper; import com.checkmarx.ws.CxJenkinsWebService.*; import com.thoughtworks.xstream.annotations.XStreamOmitField; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.ComboBoxModel; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.*; import org.jetbrains.annotations.NotNull; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.*; import java.net.MalformedURLException; import java.net.URLDecoder; import java.util.List; import java.util.Map; /** * The main entry point for Checkmarx plugin. This class implements the Builder * build stage that scans the source code. * * @author Denis Krivitski * @since 3/10/13 */ public class CxScanBuilder extends Builder { // Persistent plugin configuration parameters private boolean useOwnServerCredentials; private String serverUrl; private String username; private String password; private String projectName; private String groupId; private String preset; private boolean presetSpecified; private String excludeFolders; private String filterPattern; private boolean incremental; private boolean fullScansScheduled; private int fullScanCycle; private boolean isThisBuildIncremental; private String sourceEncoding; private String comment; private boolean waitForResultsEnabled; private boolean vulnerabilityThresholdEnabled; private int highThreshold; private boolean generatePdfReport; // Private variables static { BasicConfigurator.configure(); // Set the log4j system to log to console } private final static Logger staticLogger = Logger.getLogger(CxScanBuilder.class); @XStreamOmitField private Logger instanceLogger = staticLogger; // Instance logger redirects to static logger until // it is initialized in perform method @XStreamOmitField private FileAppender fileAppender; // Constructors @DataBoundConstructor public CxScanBuilder(boolean useOwnServerCredentials, String serverUrl, String username, String password, String projectName, String groupId, String preset, boolean presetSpecified, String excludeFolders, String filterPattern, boolean incremental, boolean fullScansScheduled, int fullScanCycle, String sourceEncoding, String comment, boolean waitForResultsEnabled, boolean vulnerabilityThresholdEnabled, int highThreshold, boolean generatePdfReport) { this.useOwnServerCredentials = useOwnServerCredentials; this.serverUrl = serverUrl; this.username = username; this.password = password; this.projectName = projectName; this.groupId = groupId; this.preset = preset; this.presetSpecified = presetSpecified; this.excludeFolders = excludeFolders; this.filterPattern = filterPattern; this.incremental = incremental; this.fullScansScheduled = fullScansScheduled; this.fullScanCycle = fullScanCycle; this.sourceEncoding = sourceEncoding; this.comment = comment; this.waitForResultsEnabled = waitForResultsEnabled; this.vulnerabilityThresholdEnabled = vulnerabilityThresholdEnabled; this.highThreshold = highThreshold; this.generatePdfReport = generatePdfReport; } // Configuration fields getters public boolean isUseOwnServerCredentials() { return useOwnServerCredentials; } public String getServerUrl() { return serverUrl; } public String getUsername() { return username; } public String getPassword() { return password; } public String getProjectName() { return projectName; } public String getGroupId() { return groupId; } public String getPreset() { return preset; } public boolean isPresetSpecified() { return presetSpecified; } public String getExcludeFolders() { return excludeFolders; } public String getFilterPattern() { return filterPattern; } public boolean isIncremental() { return incremental; } public boolean isFullScansScheduled(){ return fullScansScheduled; } public int getFullScanCycle(){ return fullScanCycle; } public String getSourceEncoding() { return sourceEncoding; } public String getComment() { return comment; } public boolean isWaitForResultsEnabled() { return waitForResultsEnabled; } public boolean isVulnerabilityThresholdEnabled() { return vulnerabilityThresholdEnabled; } public int getHighThreshold() { return highThreshold; } public boolean isGeneratePdfReport() { return generatePdfReport; } @Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { try { File checkmarxBuildDir = new File(build.getRootDir(),"checkmarx"); checkmarxBuildDir.mkdir(); initLogger(checkmarxBuildDir, listener, instanceLoggerSuffix(build)); listener.started(null); instanceLogger.info("Checkmarx Jenkins plugin version: " + CxConfig.version()); String serverUrlToUse = isUseOwnServerCredentials() ? getServerUrl() : getDescriptor().getServerUrl(); String usernameToUse = isUseOwnServerCredentials() ? getUsername() : getDescriptor().getUsername(); String passwordToUse = isUseOwnServerCredentials() ? getPassword() : getDescriptor().getPassword(); CxWebService cxWebService = new CxWebService(serverUrlToUse,instanceLoggerSuffix(build)); cxWebService.login(usernameToUse,passwordToUse); instanceLogger.info("Checkmarx server login successful"); CxWSResponseRunID cxWSResponseRunID = submitScan(build, cxWebService,listener); instanceLogger.info("\nScan job submitted successfully\n"); if (!isWaitForResultsEnabled()) { listener.finished(Result.SUCCESS); return true; } long scanId = cxWebService.trackScanProgress(cxWSResponseRunID); File xmlReportFile = new File(checkmarxBuildDir,"ScanReport.xml"); cxWebService.retrieveScanReport(scanId,xmlReportFile,CxWSReportType.XML); if (this.generatePdfReport) { File pdfReportFile = new File(checkmarxBuildDir, CxScanResult.PDF_REPORT_NAME); cxWebService.retrieveScanReport(scanId, pdfReportFile, CxWSReportType.PDF); } // Parse scan report and present results in Jenkins CxScanResult cxScanResult = new CxScanResult(build,instanceLoggerSuffix(build),serverUrlToUse); cxScanResult.readScanXMLReport(xmlReportFile); build.addAction(cxScanResult); instanceLogger.info("Number of high severity vulnerabilities: " + cxScanResult.getHighCount() + " stability threshold: " + this.getHighThreshold()); if (this.isVulnerabilityThresholdEnabled()) { if (cxScanResult.getHighCount() > this.getHighThreshold()) { build.setResult(Result.UNSTABLE); // Marks the build result as UNSTABLE listener.finished(Result.UNSTABLE); return true; } } listener.finished(Result.SUCCESS); return true; } catch (Error e) { instanceLogger.error(e.getMessage(),e); throw e; } catch (AbortException e) { instanceLogger.error(e.getMessage(),e); throw e; } catch (IOException e) { instanceLogger.error(e.getMessage(),e); throw e; } finally { closeLogger(); } } private String instanceLoggerSuffix(final AbstractBuild<?, ?> build) { return build.getProject().getDisplayName() + "-" + build.getDisplayName(); } private void initLogger(final File checkmarxBuildDir, final BuildListener listener, final String loggerSuffix) { instanceLogger = CxLogUtils.loggerWithSuffix(getClass(),loggerSuffix); final WriterAppender writerAppender = new WriterAppender(new PatternLayout("%m%n"),listener.getLogger()); writerAppender.setThreshold(Level.INFO); final Logger parentLogger = CxLogUtils.parentLoggerWithSuffix(loggerSuffix); parentLogger.addAppender(writerAppender); String logFileName = checkmarxBuildDir.getAbsolutePath() + File.separator + "checkmarx.log"; try { fileAppender = new FileAppender(new PatternLayout("%C: [%d] %-5p: %m%n"),logFileName); fileAppender.setThreshold(Level.DEBUG); parentLogger.addAppender(fileAppender); } catch (IOException e) { staticLogger.warn("Could not open log file for writing: " + logFileName); staticLogger.debug(e); } } private void closeLogger() { instanceLogger.removeAppender(fileAppender); fileAppender.close(); instanceLogger = staticLogger; // Redirect all logs back to static logger } private CxWSResponseRunID submitScan(final AbstractBuild<?, ?> build, final CxWebService cxWebService, final BuildListener listener) throws IOException { isThisBuildIncremental = isThisBuildIncremental(build.getNumber()); if(isThisBuildIncremental){ instanceLogger.info("\nScan job started in incremental scan mode\n"); } else{ instanceLogger.info("\nScan job started in full scan mode\n"); } instanceLogger.info("Started zipping the workspace"); try { // hudson.FilePath will work in distributed Jenkins installation FilePath baseDir = build.getWorkspace(); String combinedFilterPattern = this.getFilterPattern() + "," + processExcludeFolders(this.getExcludeFolders()); // Implementation of FilePath.FileCallable allows extracting a java.io.File from // hudson.FilePath and still working with it in remote mode CxZipperCallable zipperCallable = new CxZipperCallable(combinedFilterPattern); final CxZipResult zipResult = baseDir.act(zipperCallable); instanceLogger.info(zipResult.getLogMessage()); final FilePath tempFile = zipResult.getTempFile(); final int numOfZippedFiles = zipResult.getNumOfZippedFiles(); instanceLogger.info("Zipping complete with " + numOfZippedFiles + " files, total compressed size: " + FileUtils.byteCountToDisplaySize(tempFile.length() / 8 * 6)); // We print here the size of compressed sources before encoding to base 64 instanceLogger.info("Temporary file with zipped and base64 encoded sources was created at: " + tempFile.getRemote()); listener.getLogger().flush(); // Create cliScanArgs object with dummy byte array for zippedFile field // Streaming scan web service will nullify zippedFile filed and use tempFile // instead final CliScanArgs cliScanArgs = createCliScanArgs(new byte[]{}); final CxWSResponseRunID cxWSResponseRunID = cxWebService.scan(cliScanArgs, tempFile); tempFile.delete(); instanceLogger.info("Temporary file deleted"); return cxWSResponseRunID; } catch (Zipper.MaxZipSizeReached e) { throw new AbortException("Checkmarx Scan Failed: Reached maximum upload size limit of " + FileUtils.byteCountToDisplaySize(CxConfig.maxZipSize())); } catch (Zipper.NoFilesToZip e) { throw new AbortException("Checkmarx Scan Failed: No files to scan"); } catch (InterruptedException e) { throw new AbortException("Remote operation failed on slave node: " + e.getMessage()); } } @NotNull private String processExcludeFolders(String excludeFolders) { if (excludeFolders==null) { return ""; } StringBuilder result = new StringBuilder(); String[] patterns = StringUtils.split(excludeFolders, ",\n"); for(String p : patterns) { p = p.trim(); if (p.length()>0) { result.append("!**/"); result.append(p); result.append("*, "); } } instanceLogger.debug("Exclude folders converted to: " +result.toString()); return result.toString(); } private CliScanArgs createCliScanArgs(byte[] compressedSources) { ProjectSettings projectSettings = new ProjectSettings(); long presetLong = 0; // Default value to use in case of exception try { presetLong = Long.parseLong(getPreset()); } catch (Exception e) { instanceLogger.error("Encountered illegal preset value: " + getPreset() + ". Using default preset."); } projectSettings.setPresetID(presetLong); projectSettings.setProjectName(getProjectName()); projectSettings.setAssociatedGroupID(getGroupId()); long configuration = 0; // Default value to use in case of exception try { configuration = Long.parseLong(getSourceEncoding()); } catch (Exception e) { instanceLogger.error("Encountered illegal source encoding (configuration) value: " + getSourceEncoding() + ". Using default configuration."); } projectSettings.setScanConfigurationID(configuration); LocalCodeContainer localCodeContainer = new LocalCodeContainer(); localCodeContainer.setFileName("src.zip"); localCodeContainer.setZippedFile(compressedSources); SourceCodeSettings sourceCodeSettings = new SourceCodeSettings(); sourceCodeSettings.setSourceOrigin(SourceLocationType.LOCAL); sourceCodeSettings.setPackagedCode(localCodeContainer); String commentText = getComment().trim(); CliScanArgs args = new CliScanArgs(); args.setIsIncremental(isThisBuildIncremental); args.setIsPrivateScan(false); args.setPrjSettings(projectSettings); args.setSrcCodeSettings(sourceCodeSettings); args.setComment(commentText); return args; } private boolean isThisBuildIncremental(int buildNumber) { boolean askedForIncremental = isIncremental(); if(!askedForIncremental){ return false; } boolean askedForPeriodicFullScans = isFullScansScheduled(); if(!askedForPeriodicFullScans){ return true; } // if user entered invalid value for full scan cycle - all scans will be incremental if (fullScanCycle < DescriptorImpl.FULL_SCAN_CYCLE_MIN || fullScanCycle > DescriptorImpl.FULL_SCAN_CYCLE_MAX){ return true; } // If user asked to perform full scan after every 9 incremental scans - // it means that every 10th scan should be full, // that is the ordinal numbers of full scans will be "1", "11", "21" and so on... boolean shouldBeFullScan = (buildNumber % (fullScanCycle+1) == 1); return !shouldBeFullScan; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } /*public String getIconPath() { PluginWrapper wrapper = Hudson.getInstance().getPluginManager().getPlugin([YOUR-PLUGIN-MAIN-CLASS].class); return Hudson.getInstance().getRootUrl() + "plugin/"+ wrapper.getShortName()+"/"; }*/ @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public final static String DEFAULT_FILTER_PATTERNS = CxConfig.defaultFilterPattern(); public final static int FULL_SCAN_CYCLE_MIN = 1; public final static int FULL_SCAN_CYCLE_MAX = 99; private final static Logger logger = Logger.getLogger(DescriptorImpl.class); // Persistent plugin global configuration parameters private String serverUrl; private String username; private String password; public String getServerUrl() { return serverUrl; } public void setServerUrl(String serverUrl) { this.serverUrl = serverUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } public DescriptorImpl() { load(); } // Helper methods for jelly views // Provides a description string to be displayed near "Use default server credentials" // configuration option public String getCredentialsDescription() { if (getServerUrl()==null || getServerUrl().isEmpty() || getUsername()==null || getUsername().isEmpty()) { return "not set"; } return "Server URL: " + getServerUrl() + " username: " + getUsername(); } // Field value validators /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public FormValidation doCheckServerUrl(final @QueryParameter String value) { try { new CxWebService(value); return FormValidation.ok("Server Validated Successfully"); } catch (Exception e) { return FormValidation.error(e.getMessage()); } } /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public FormValidation doCheckPassword( final @QueryParameter String serverUrl, final @QueryParameter String password, final @QueryParameter String username) { CxWebService cxWebService = null; try { cxWebService = new CxWebService(serverUrl); } catch (Exception e) { return FormValidation.warning("Server URL not set"); } try { cxWebService.login(username,password); return FormValidation.ok("Login Successful"); } catch (Exception e) { return FormValidation.error(e.getMessage()); } } // Prepares a this.cxWebService object to be connected and logged in /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ private CxWebService prepareLoggedInWebservice(boolean useOwnServerCredentials, String serverUrl, String username, String password) throws AbortException, MalformedURLException { String serverUrlToUse = !useOwnServerCredentials ? serverUrl : getServerUrl(); String usernameToUse = !useOwnServerCredentials ? username : getUsername(); String passwordToUse = !useOwnServerCredentials ? password : getPassword(); logger.debug("prepareLoggedInWebservice: server: " + serverUrlToUse + " user: " + usernameToUse + " pass: " + passwordToUse); CxWebService cxWebService = new CxWebService(serverUrlToUse); logger.debug("prepareLoggedInWebservice: created cxWebService"); cxWebService.login(usernameToUse, passwordToUse); logger.debug("prepareLoggedInWebservice: logged in"); return cxWebService; } /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public ComboBoxModel doFillProjectNameItems( final @QueryParameter boolean useOwnServerCredentials, final @QueryParameter String serverUrl, final @QueryParameter String username, final @QueryParameter String password) { ComboBoxModel projectNames = new ComboBoxModel(); try { final CxWebService cxWebService = prepareLoggedInWebservice(useOwnServerCredentials,serverUrl,username,password); List<ProjectDisplayData> projectsDisplayData = cxWebService.getProjectsDisplayData(); for(ProjectDisplayData pd : projectsDisplayData) { projectNames.add(pd.getProjectName()); } logger.debug("Projects list: " + projectNames.size()); return projectNames; } catch (Exception e) { logger.debug("Projects list: empty"); return projectNames; // Return empty list of project names } } /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public FormValidation doCheckProjectName(final @QueryParameter String projectName, final @QueryParameter boolean useOwnServerCredentials, final @QueryParameter String serverUrl, final @QueryParameter String username, final @QueryParameter String password, final @QueryParameter String groupId) { try { final CxWebService cxWebService = prepareLoggedInWebservice(useOwnServerCredentials,serverUrl,username,password); CxWSBasicRepsonse cxWSBasicRepsonse = cxWebService.validateProjectName(projectName,groupId); if (cxWSBasicRepsonse.isIsSuccesfull()) { return FormValidation.ok("Project Name Validated Successfully"); } else { if (cxWSBasicRepsonse.getErrorMessage().startsWith("project name validation failed: duplicate name, project name") || cxWSBasicRepsonse.getErrorMessage().equalsIgnoreCase("Project name already exists")) { return FormValidation.ok("Scan will be added to existing project"); } else if (cxWSBasicRepsonse.getErrorMessage().equalsIgnoreCase("project name validation failed: unauthorized user")) { return FormValidation.error("The user is not authorized to create/run Checkmarx projects"); } else if (cxWSBasicRepsonse.getErrorMessage().startsWith("Exception occurred at IsValidProjectCreationRequest:")) { logger.warn("Couldn't validate project name with Checkmarx sever:\n" + cxWSBasicRepsonse.getErrorMessage()); return FormValidation.warning(cxWSBasicRepsonse.getErrorMessage()); } else { return FormValidation.error(cxWSBasicRepsonse.getErrorMessage()); } } } catch (Exception e) { logger.warn("Couldn't validate project name with Checkmarx sever:\n" + e.getLocalizedMessage()); return FormValidation.warning("Can't reach server to validate project name"); } } // Provides a list of presets from checkmarx server for dynamic drop-down list in configuration page /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public ListBoxModel doFillPresetItems( final @QueryParameter boolean useOwnServerCredentials, final @QueryParameter String serverUrl, final @QueryParameter String username, final @QueryParameter String password) { ListBoxModel listBoxModel = new ListBoxModel(); try { final CxWebService cxWebService = prepareLoggedInWebservice(useOwnServerCredentials,serverUrl,username,password); final List<Preset> presets = cxWebService.getPresets(); for(Preset p : presets) { listBoxModel.add(new ListBoxModel.Option(p.getPresetName(),Long.toString(p.getID()))); } logger.debug("Presets list: " + listBoxModel.size()); return listBoxModel; } catch (Exception e) { logger.debug("Presets list: empty"); String message = "Provide Checkmarx server credentials to see presets list"; listBoxModel.add(new ListBoxModel.Option(message,message)); return listBoxModel; // Return empty list of project names } } // Provides a list of source encodings from checkmarx server for dynamic drop-down list in configuration page /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public FormValidation doCheckFullScanCycle( final @QueryParameter int value) { if(value >= FULL_SCAN_CYCLE_MIN && value <= FULL_SCAN_CYCLE_MAX){ return FormValidation.ok(); } else{ return FormValidation.error("Number must be in the range " + FULL_SCAN_CYCLE_MIN + "-" + FULL_SCAN_CYCLE_MAX); } } public ListBoxModel doFillSourceEncodingItems( final @QueryParameter boolean useOwnServerCredentials, final @QueryParameter String serverUrl, final @QueryParameter String username, final @QueryParameter String password) { ListBoxModel listBoxModel = new ListBoxModel(); try { final CxWebService cxWebService = prepareLoggedInWebservice(useOwnServerCredentials,serverUrl,username,password); final List<ConfigurationSet> sourceEncodings = cxWebService.getSourceEncodings(); for(ConfigurationSet cs : sourceEncodings) { listBoxModel.add(new ListBoxModel.Option(cs.getConfigSetName(),Long.toString(cs.getID()))); } logger.debug("Source encodings list: " + listBoxModel.size()); return listBoxModel; } catch (Exception e) { logger.debug("Source encodings list: empty"); String message = "Provide Checkmarx server credentials to see source encodings list"; listBoxModel.add(new ListBoxModel.Option(message,message)); return listBoxModel; // Return empty list of project names } } // Provides a list of source encodings from checkmarx server for dynamic drop-down list in configuration page /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public ListBoxModel doFillGroupIdItems( final @QueryParameter boolean useOwnServerCredentials, final @QueryParameter String serverUrl, final @QueryParameter String username, final @QueryParameter String password) { ListBoxModel listBoxModel = new ListBoxModel(); try { final CxWebService cxWebService = prepareLoggedInWebservice(useOwnServerCredentials,serverUrl,username,password); final List<Group> groups = cxWebService.getAssociatedGroups(); for(Group group : groups) { listBoxModel.add(new ListBoxModel.Option(group.getGroupName(),group.getID())); } logger.debug("Associated groups list: " + listBoxModel.size()); return listBoxModel; } catch (Exception e) { logger.debug("Associated groups: empty"); String message = "Provide Checkmarx server credentials to see teams list"; listBoxModel.add(new ListBoxModel.Option(message,message)); return listBoxModel; // Return empty list of project names } } /* * Note: This method is called concurrently by multiple threads, refrain from using mutable * shared state to avoid synchronization issues. */ public FormValidation doCheckHighThreshold(final @QueryParameter int value) { if (value >= 0) { return FormValidation.ok(); } else { return FormValidation.error("Number must be non-negative"); } } public String getDefaultProjectName() { // Retrieves the job name from request URL, cleans it from special characters,\ // and returns as a default project name. final String url = getCurrentDescriptorByNameUrl(); String decodedUrl = null; try { decodedUrl = URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { decodedUrl = url; } final String[] urlComponents = decodedUrl.split("/"); if (urlComponents.length > 0) { final String jobName = urlComponents[urlComponents.length-1]; final String cleanJobName = jobName.replaceAll("[^\\w\\s_]", ""); return cleanJobName; } // This is a fallback if the above code fails return ""; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Execute Checkmarx Scan"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setUseFrench) req.bindJSON(this, formData.getJSONObject("checkmarx")); save(); return super.configure(req,formData); } } }
package com.constantcontact; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.constantcontact.components.accounts.VerifiedEmailAddress; import com.constantcontact.components.activities.contacts.request.AddContactsRequest; import com.constantcontact.components.activities.contacts.request.ClearListsRequest; import com.constantcontact.components.activities.contacts.request.ExportContactsRequest; import com.constantcontact.components.activities.contacts.request.RemoveContactsRequest; import com.constantcontact.components.activities.contacts.response.ContactsResponse; import com.constantcontact.components.activities.contacts.response.DetailedStatusReport; import com.constantcontact.components.activities.contacts.response.SummaryReport; import com.constantcontact.components.common.tracking.TrackingBase; import com.constantcontact.components.contacts.Contact; import com.constantcontact.components.contacts.ContactList; import com.constantcontact.components.contacts.tracking.TrackingContactsBase; import com.constantcontact.components.contacts.tracking.bounces.ContactTrackingBounce; import com.constantcontact.components.contacts.tracking.clicks.ContactTrackingClick; import com.constantcontact.components.contacts.tracking.forwards.ContactTrackingForward; import com.constantcontact.components.contacts.tracking.opens.ContactTrackingOpen; import com.constantcontact.components.contacts.tracking.reports.summary.ContactTrackingSummaryReport; import com.constantcontact.components.contacts.tracking.sends.ContactTrackingSend; import com.constantcontact.components.contacts.tracking.unsubscribes.ContactTrackingUnsubscribe; import com.constantcontact.components.emailcampaigns.EmailCampaignBase; import com.constantcontact.components.emailcampaigns.EmailCampaignRequest; import com.constantcontact.components.emailcampaigns.EmailCampaignResponse; import com.constantcontact.components.emailcampaigns.schedules.EmailCampaignSchedule; import com.constantcontact.components.emailcampaigns.tracking.bounces.EmailCampaignTrackingBounce; import com.constantcontact.components.emailcampaigns.tracking.clicks.EmailCampaignTrackingClick; import com.constantcontact.components.emailcampaigns.tracking.forwards.EmailCampaignTrackingForward; import com.constantcontact.components.emailcampaigns.tracking.opens.EmailCampaignTrackingOpen; import com.constantcontact.components.emailcampaigns.tracking.reports.summary.EmailCampaignTrackingSummary; import com.constantcontact.components.emailcampaigns.tracking.sends.EmailCampaignTrackingSend; import com.constantcontact.components.emailcampaigns.tracking.unsubscribes.EmailCampaignTrackingUnsubscribe; import com.constantcontact.components.generic.response.Pagination; import com.constantcontact.components.generic.response.ResultSet; import com.constantcontact.exceptions.ConstantContactException; import com.constantcontact.exceptions.service.ConstantContactServiceException; import com.constantcontact.pagination.PaginationHelperService; import com.constantcontact.services.accounts.AccountService; import com.constantcontact.services.accounts.IAccountService; import com.constantcontact.services.activities.BulkActivitiesService; import com.constantcontact.services.activities.IBulkActivitiesService; import com.constantcontact.services.contactlists.ContactListService; import com.constantcontact.services.contactlists.IContactListService; import com.constantcontact.services.contacts.ContactService; import com.constantcontact.services.contacts.IContactService; import com.constantcontact.services.contacts.tracking.ContactTrackingService; import com.constantcontact.services.contacts.tracking.IContactTrackingService; import com.constantcontact.services.emailcampaigns.EmailCampaignService; import com.constantcontact.services.emailcampaigns.IEmailCampaignService; import com.constantcontact.services.emailcampaigns.schedule.EmailCampaignScheduleService; import com.constantcontact.services.emailcampaigns.schedule.IEmailCampaignScheduleService; import com.constantcontact.services.emailcampaigns.tracking.EmailCampaignTrackingService; import com.constantcontact.services.emailcampaigns.tracking.IEmailCampaignTrackingService; import com.constantcontact.util.Config; import com.constantcontact.util.Config.Errors; import com.constantcontact.util.http.MultipartBody; import com.constantcontact.util.http.MultipartBuilder; /** * Main Constant Contact class.<br/> * This is meant to be used by users to access Constant Contact API functionality.<br/> * <ul> * <li>{@link ContactService}</li> * <li>{@link ContactListService}</li> * <li>{@link EmailCampaignService}</li> * <li>{@link AccountService}</li> * <li>{@link EmailCampaignScheduleService}</li> * <li>{@link EmailCampaignTrackingService}</li> * <li>{@link ContactTrackingService}</li> * <li>{@link BulkActivitiesService}</li> * </ul> * * @author ConstantContact */ public class ConstantContact { private String accessToken; public static String API_KEY; private IContactService contactService; private IContactListService contactListService; private IEmailCampaignService emailCampaignService; private IAccountService accountService; private IEmailCampaignScheduleService emailCampaignScheduleService; private IEmailCampaignTrackingService emailCampaignTrackingService; private IContactTrackingService contactTrackingService; private IBulkActivitiesService bulkActivitiesService; private PaginationHelperService paginationHelperService; /** * Custom Class constructor.<br/> * Initializes all Services; * * @param apiKey The API key provided by Constant Contact. * @param accessToken The access token provided by Constant Contact Authentication workflow. */ public ConstantContact(String apiKey, String accessToken) { this.accessToken = accessToken; ConstantContact.API_KEY = apiKey; this.setContactService(new ContactService()); this.setListService(new ContactListService()); this.setEmailCampaignService(new EmailCampaignService()); this.setAccountService(new AccountService()); this.setEmailCampaignScheduleService(new EmailCampaignScheduleService()); this.setEmailCampaignTrackingService(new EmailCampaignTrackingService()); this.setContactTrackingService(new ContactTrackingService()); this.setBulkActivitiesService(new BulkActivitiesService()); this.setPaginationHelperService(new PaginationHelperService()); } /** * Get the access token.<br/> * * @return The access token. */ public String getAccessToken() { return accessToken; } /** * Get the Contact service. * * @return The Contact service. */ public IContactService getContactService() { return contactService; } /** * Set the Contact service. * * @param contactService The Contact service. */ public void setContactService(IContactService contactService) { this.contactService = contactService; } /** * Get the List service. * * @return The List service. */ public IContactListService getListService() { return contactListService; } /** * Set the List service. * * @param contactListService The List service. */ public void setListService(IContactListService contactListService) { this.contactListService = contactListService; } /** * Set the {@link EmailCampaignService} * * @param emailCampaignService The {@link EmailCampaignService} */ public void setEmailCampaignService(IEmailCampaignService emailCampaignService) { this.emailCampaignService = emailCampaignService; } /** * Get the {@link EmailCampaignService} * * @return The {@link EmailCampaignService} */ public IEmailCampaignService getEmailCampaignService() { return emailCampaignService; } /** * Set the {@link AccountService} * * @param accountService The {@link AccountService} */ public void setAccountService(IAccountService accountService) { this.accountService = accountService; } /** * Get the {@link AccountService} * * @return The {@link AccountService} */ public IAccountService getAccountService() { return accountService; } /** * Set the {@link EmailCampaignScheduleService} * * @param emailCampaignScheduleService The {@link EmailCampaignScheduleService} */ public void setEmailCampaignScheduleService(IEmailCampaignScheduleService emailCampaignScheduleService) { this.emailCampaignScheduleService = emailCampaignScheduleService; } /** * Get the {@link EmailCampaignScheduleService} * * @return The {@link EmailCampaignScheduleService} */ public IEmailCampaignScheduleService getEmailCampaignScheduleService() { return emailCampaignScheduleService; } /** * Set the {@link EmailCampaignTrackingService} * * @param emailCampaignTrackingSummaryService The {@link EmailCampaignTrackingService} */ public void setEmailCampaignTrackingService(IEmailCampaignTrackingService emailCampaignTrackingSummaryService) { this.emailCampaignTrackingService = emailCampaignTrackingSummaryService; } /** * Get the {@link EmailCampaignTrackingService} * * @return The {@link EmailCampaignTrackingService} */ public IEmailCampaignTrackingService getEmailCampaignTrackingService() { return emailCampaignTrackingService; } /** * Set the {@link ContactTrackingService} * * @param contactTrackingService The {@link ContactTrackingService} */ public void setContactTrackingService(IContactTrackingService contactTrackingService) { this.contactTrackingService = contactTrackingService; } /** * Get the {@link ContactTrackingService} * * @return The {@link ContactTrackingService} */ public IContactTrackingService getContactTrackingService() { return contactTrackingService; } /** * Set the {@link BulkActivitiesService} * * @param bulkActivitiesService The {@link BulkActivitiesService} */ public void setBulkActivitiesService(IBulkActivitiesService bulkActivitiesService) { this.bulkActivitiesService = bulkActivitiesService; } /** * Get the {@link BulkActivitiesService} * * @return The {@link BulkActivitiesService} */ public IBulkActivitiesService getBulkActivitiesService() { return bulkActivitiesService; } /** * Get the {@link PaginationHelperService} * * @return The {@link PaginationHelperService} */ public PaginationHelperService getPaginationHelperService(){ return paginationHelperService; } /** * Set the {@link PaginationHelperService} * * @param paginationHelperService The {@link PaginationHelperService} */ public void setPaginationHelperService(PaginationHelperService paginationHelperService) { this.paginationHelperService = paginationHelperService; } /** * Get contacts API. <br/> * Details in : {@link ContactService#getContacts(String, Integer, String)} * * @param limit The maximum number of results to return - can be null. * @param modifiedSinceTimestamp This time stamp is an ISO-8601 ordinal date supporting offset. <br/> * It will return only the contacts modified since the supplied date. <br/> * If you want to bypass this filter set modifiedSinceTimestamp to null. * @param status Return only records with the given status. Does not support VISITOR or NON_SUBSCRIBER * @return The contacts. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public ResultSet<Contact> getContacts(Integer limit, String modifiedSinceTimestamp, Contact.Status status) throws ConstantContactServiceException { if (status != null && (status.equals(Contact.Status.VISITOR) || status.equals(Contact.Status.NON_SUBSCRIBER))){ throw new IllegalArgumentException(Config.Errors.STATUS + " ACTIVE, OPTOUT, REMOVED, UNCONFIRMED."); } return contactService.getContacts(this.getAccessToken(), limit, modifiedSinceTimestamp, status); } public ResultSet<Contact> getContacts(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Contact.class); } /** * Get contact API.<br/> * Details in : {@link ContactService#getContact(String, String)} * * @param contactId The contact id. * @return The contact. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public Contact getContact(String contactId) throws ConstantContactServiceException { return contactService.getContact(this.getAccessToken(), contactId); } /** * Get Contact By Email API.<br/> * Details in : {@link ContactService#getContactByEmail(String, String)} * * @param email The email address. * @return A {@link ResultSet} of {@link Contact}. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public ResultSet<Contact> getContactByEmail(String email) throws ConstantContactServiceException { return contactService.getContactByEmail(this.getAccessToken(), email); } /** * Add Contact API.<br/> * Details in : {@link ContactService#addContact(String, Contact, Boolean)} * * @param contact The {@link Contact} to add. * @return The added contact. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public Contact addContact(Contact contact, Boolean actionByVisitor) throws ConstantContactServiceException { return contactService.addContact(this.getAccessToken(), contact, actionByVisitor.booleanValue()); } /** * Add Contact API.<br/> * Details in : {@link ContactService#addContact(String, Contact, Boolean)} * * @param contact The {@link Contact} to add. * @return The added contact. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public Contact addContact(Contact contact) throws ConstantContactServiceException { return contactService.addContact(this.getAccessToken(), contact, false); } public boolean deleteContact(Contact contact) throws IllegalArgumentException, ConstantContactServiceException { if (contact == null) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } return deleteContact(contact.getId()); } public boolean deleteContact(String contactId) throws IllegalArgumentException, ConstantContactServiceException { try { int nContactId = Integer.parseInt(contactId); if (nContactId < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } return contactService.deleteContact(this.getAccessToken(), contactId); } public boolean deleteContactFromLists(String contactId) throws IllegalArgumentException, ConstantContactServiceException { try { int nContactId = Integer.parseInt(contactId); if (nContactId < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } return contactService.deleteContactFromLists(this.getAccessToken(), contactId); } /** * Delete Contact From Lists API.<br/> * Details in : {@link ContactService#deleteContactFromLists(String, String)} * * @param contact The Contact to delete. Match is done on id. * @return true in case of success, an exception is thrown otherwise. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public boolean deleteContactFromLists(Contact contact) throws ConstantContactServiceException { if (contact == null) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } return contactService.deleteContactFromLists(this.getAccessToken(), contact.getId()); } public boolean deleteContactFromList(Contact contact, ContactList list) throws IllegalArgumentException, ConstantContactServiceException { if (contact == null) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } if (list == null) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } return contactService.deleteContactFromList(this.getAccessToken(), contact.getId(), list.getId()); } public boolean deleteContactFromList(String contactId, String listId) throws IllegalArgumentException, ConstantContactServiceException { try { int nContactId = Integer.parseInt(contactId); if (nContactId < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } try { int nListId = Integer.parseInt(listId); if (nListId < 1) { throw new NumberFormatException(); } } catch (Exception e) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } return contactService.deleteContactFromList(this.getAccessToken(), contactId, listId); } public Contact updateContact(Contact contact) throws IllegalArgumentException, ConstantContactServiceException { if (contact == null) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } if (contact.getId() == null || !(contact.getId().length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactService.updateContact(this.getAccessToken(), contact, false); } public Contact updateContact(Contact contact, Boolean actionByVisitor) throws IllegalArgumentException, ConstantContactServiceException { if (contact == null) { throw new IllegalArgumentException(Config.Errors.CONTACT_OR_ID); } if (contact.getId() == null || !(contact.getId().length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactService.updateContact(this.getAccessToken(), contact, actionByVisitor.booleanValue()); } /** * Get Contact Lists API.<br/> * Details in : {@link ContactListService#getLists(String, String)} * * @param modifiedSinceTimestamp This time stamp is an ISO-8601 ordinal date supporting offset. <br/> * It will return only the contact lists modified since the supplied date. <br/> * If you want to bypass this filter set modifiedSinceTimestamp to null. * * @return The Contact Lists in case of success; an exception is thrown otherwise. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public List<ContactList> getLists(String modifiedSinceTimestamp) throws ConstantContactServiceException { return contactListService.getLists(this.getAccessToken(), modifiedSinceTimestamp); } public ContactList getList(String listId) throws IllegalArgumentException, ConstantContactServiceException { try { int nListId = Integer.parseInt(listId); if (nListId < 1) { throw new NumberFormatException(); } } catch (Exception e) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } return contactListService.getList(this.getAccessToken(), listId); } public ContactList addList(ContactList list) throws IllegalArgumentException, ConstantContactServiceException { try { return contactListService.addList(this.getAccessToken(), list); } catch (ConstantContactServiceException e) { throw new ConstantContactServiceException(e); } } public ResultSet<Contact> getContactsFromList(ContactList list) throws IllegalArgumentException, ConstantContactServiceException { if (list == null) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } return contactListService.getContactsFromList(this.getAccessToken(), list.getId(), null, null); } public ResultSet<Contact> getContactsFromList(String listId) throws IllegalArgumentException, ConstantContactServiceException { try { int nListId = Integer.parseInt(listId); if (nListId < 1) { throw new NumberFormatException(); } } catch (Exception e) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } try { return contactListService.getContactsFromList(this.getAccessToken(), listId, null, null); } catch (ConstantContactServiceException e) { throw new ConstantContactServiceException(e); } } public ResultSet<Contact> getContactsFromList(ContactList list, Integer limit, String modifiedSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (list == null) { throw new IllegalArgumentException(Config.Errors.LIST_OR_ID); } return contactListService.getContactsFromList(this.getAccessToken(), list.getId(), limit, modifiedSinceTimestamp); } public ResultSet<Contact> getContactsFromList(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, Contact.class); } public ResultSet<EmailCampaignResponse> getEmailCampaigns() throws IllegalArgumentException, ConstantContactServiceException { return emailCampaignService.getCampaigns(this.getAccessToken(), null, null); } public ResultSet<EmailCampaignResponse> getEmailCampaigns(Integer limit, String modifiedSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { return emailCampaignService.getCampaigns(this.getAccessToken(), limit, modifiedSinceTimestamp); } public ResultSet<EmailCampaignResponse> getEmailCampaigns(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException, IllegalArgumentException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignResponse.class); } public EmailCampaignResponse getEmailCampaign(String campaignId) throws IllegalArgumentException, ConstantContactServiceException { if (campaignId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignService.getCampaign(this.getAccessToken(), campaignId); } public EmailCampaignResponse updateEmailCampaign(EmailCampaignRequest emailCampaign) throws IllegalArgumentException, ConstantContactServiceException { if (emailCampaign == null || !(emailCampaign.getId().length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignService.updateCampaign(this.getAccessToken(), emailCampaign); } public EmailCampaignResponse addEmailCampaign(EmailCampaignRequest emailCampaign) throws IllegalArgumentException, ConstantContactServiceException { if (emailCampaign == null) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignService.addCampaign(this.getAccessToken(), emailCampaign); } public List<VerifiedEmailAddress> getVerifiedEmailAddresses(String status) throws IllegalArgumentException, ConstantContactServiceException { if (status != null && status.length() > 0) { if (!status.equals(VerifiedEmailAddress.Status.CONFIRMED) && !status.equals(VerifiedEmailAddress.Status.UNCONFIRMED)) throw new IllegalArgumentException(Config.Errors.STATUS + VerifiedEmailAddress.Status.CONFIRMED + ", " + VerifiedEmailAddress.Status.CONFIRMED); } return accountService.getVerifiedEmailAddresses(this.getAccessToken(), status); } public List<EmailCampaignSchedule> getEmailCampaignSchedules(String campaignId) throws IllegalArgumentException, ConstantContactServiceException { if (campaignId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignScheduleService.getSchedules(this.getAccessToken(), campaignId); } public EmailCampaignSchedule getEmailCampaignSchedule(String campaignId, String scheduleId) throws IllegalArgumentException, ConstantContactServiceException { if (campaignId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } if (scheduleId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignScheduleService.getSchedule(this.getAccessToken(), campaignId, scheduleId); } public boolean deleteEmailCampaignSchedule(String campaignId, String scheduleId) throws IllegalArgumentException, ConstantContactServiceException { if (campaignId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } if (scheduleId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignScheduleService.deleteSchedule(this.getAccessToken(), campaignId, scheduleId); } public EmailCampaignSchedule addEmailCampaignSchedule(String campaignId, EmailCampaignSchedule emailCampaignSchedule) throws IllegalArgumentException, ConstantContactServiceException { if (campaignId == null || !(campaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } if (emailCampaignSchedule == null) { throw new IllegalArgumentException(Config.Errors.EMAIL_CAMPAIGN_SCHEDULE_NULL); } return emailCampaignScheduleService.addSchedule(this.getAccessToken(), campaignId, emailCampaignSchedule); } public EmailCampaignSchedule updateEmailCampaignSchedule(String emailCampaignId, String scheduleId, EmailCampaignSchedule emailCampaignSchedule) throws IllegalArgumentException, ConstantContactServiceException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } if (emailCampaignSchedule == null) { throw new IllegalArgumentException(Config.Errors.EMAIL_CAMPAIGN_SCHEDULE_NULL); } return emailCampaignScheduleService.updateSchedule(this.getAccessToken(), emailCampaignId, scheduleId, emailCampaignSchedule); } public EmailCampaignTrackingSummary getEmailCampaignTrackingSummary(String emailCampaignId, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getSummary(this.getAccessToken(), emailCampaignId, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingBounce> getEmailCampaignTrackingBounces(String emailCampaignId, Integer limit) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getBounces(this.getAccessToken(), emailCampaignId, limit); } public ResultSet<EmailCampaignTrackingBounce> getEmailCampaignTrackingBounces(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingBounce.class); } public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicks(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getClicks(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicks(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingClick.class); } public ResultSet<EmailCampaignTrackingForward> getEmailCampaignTrackingForwards(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getForwards(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingForward> getEmailCampaignTrackingForwards(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingForward.class); } public ResultSet<EmailCampaignTrackingOpen> getEmailCampaignTrackingOpens(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getOpens(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingOpen> getEmailCampaignTrackingOpens(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingOpen.class); } public ResultSet<EmailCampaignTrackingSend> getEmailCampaignTrackingSends(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getSends(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingSend> getEmailCampaignTrackingSends(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingSend.class); } public ResultSet<EmailCampaignTrackingUnsubscribe> getEmailCampaignTrackingUnsubscribes(String emailCampaignId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getUnsubscribes(this.getAccessToken(), emailCampaignId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingUnsubscribe> getEmailCampaignTrackingUnsubscribes(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingUnsubscribe.class); } public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicksByLink(String emailCampaignId, String linkId, Integer limit, String createdSinceTimestamp) throws ConstantContactServiceException, IllegalArgumentException { if (emailCampaignId == null || !(emailCampaignId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return emailCampaignTrackingService.getClicksByLinkId(this.getAccessToken(), emailCampaignId, linkId, limit, createdSinceTimestamp); } public ResultSet<EmailCampaignTrackingClick> getEmailCampaignTrackingClicksByLink(Pagination pagination) throws ConstantContactServiceException, IllegalArgumentException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, EmailCampaignTrackingClick.class); } public ContactTrackingSummaryReport getContactTrackingSummary(String contactId, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getSummary(this.getAccessToken(), contactId, createdSinceTimestamp); } public ResultSet<? extends TrackingContactsBase> getContactTrackingActivities(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getActivities(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<TrackingContactsBase> getContactTrackingActivities(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, TrackingContactsBase.class); } public ResultSet<ContactTrackingBounce> getContactTrackingBounces(String contactId, Integer limit) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getBounces(this.getAccessToken(), contactId, limit); } public ResultSet<ContactTrackingBounce> getContactTrackingBounces(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingBounce.class); } public ResultSet<ContactTrackingClick> getContactTrackingClicks(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getClicks(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<ContactTrackingClick> getContactTrackingClicks(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingClick.class); } public ResultSet<ContactTrackingForward> getContactTrackingForwards(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getForwards(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<ContactTrackingForward> getContactTrackingForwards(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if (pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingForward.class); } public ResultSet<ContactTrackingOpen> getContactTrackingOpens(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getOpens(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<ContactTrackingOpen> getContactTrackingOpens(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingOpen.class); } public ResultSet<ContactTrackingSend> getContactTrackingSends(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getSends(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<ContactTrackingSend> getContactTrackingSends(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingSend.class); } public ResultSet<ContactTrackingUnsubscribe> getContactTrackingUnsubscribes(String contactId, Integer limit, String createdSinceTimestamp) throws IllegalArgumentException, ConstantContactServiceException { if (contactId == null || !(contactId.length() > 0)) { throw new IllegalArgumentException(Config.Errors.ID); } return contactTrackingService.getUnsubscribes(this.getAccessToken(), contactId, limit, createdSinceTimestamp); } public ResultSet<ContactTrackingUnsubscribe> getContactTrackingUnsubscribes(Pagination pagination) throws IllegalArgumentException, ConstantContactServiceException { if(pagination == null) { throw new IllegalArgumentException(Config.Errors.PAGINATION_NULL); } return getPaginationHelperService().getPage(this.getAccessToken(), pagination, ContactTrackingUnsubscribe.class); } public ContactsResponse addBulkContacts(AddContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException { if (request == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL); } return bulkActivitiesService.addContacts(this.getAccessToken(), request); } public ContactsResponse addBulkContactsMultipart(String fileName, File file, ArrayList<String> listIds) throws ConstantContactServiceException, IOException{ if (fileName == null || "".equals(fileName)){ throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_FILE_NAME_NULL); } else if (file == null){ throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_FILE_NULL); } else if (listIds == null){ throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_LIST_NULL); } Map<String,String> textParts = new HashMap<String,String>(); StringBuilder lists = new StringBuilder(); lists.append(listIds.remove(0)); for (String list : listIds){ lists.append(","); lists.append(list); } textParts.put("lists", lists.toString()); InputStream fileStream = new FileInputStream(file); MultipartBody request = MultipartBuilder.buildMultipartBody(textParts, fileName, fileStream); return bulkActivitiesService.addContacts(this.getAccessToken(), request); } public ContactsResponse removeBulkContactsFromLists(RemoveContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException { if (request == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL); } return bulkActivitiesService.removeContactsFromLists(this.getAccessToken(), request); } public ContactsResponse removeBulkContactsFromListsMultipart(String fileName, File file, ArrayList<String> listIds) throws ConstantContactServiceException, IOException { if (fileName == null || "".equals(fileName)) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_FILE_NAME_NULL); } else if (file == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_FILE_NULL); } else if (listIds == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_LIST_NULL); } Map<String, String> textParts = new HashMap<String, String>(); StringBuilder lists = new StringBuilder(); lists.append(listIds.remove(0)); for (String list : listIds) { lists.append(","); lists.append(list); } textParts.put("lists", lists.toString()); InputStream fileStream = new FileInputStream(file); MultipartBody request = MultipartBuilder.buildMultipartBody(textParts, fileName, fileStream); return bulkActivitiesService.removeContactsFromLists(this.getAccessToken(), request); } public ContactsResponse clearBulkContactsLists(ClearListsRequest request) throws IllegalArgumentException, ConstantContactServiceException { if (request == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL); } return bulkActivitiesService.clearLists(this.getAccessToken(), request); } public ContactsResponse exportBulkContacts(ExportContactsRequest request) throws IllegalArgumentException, ConstantContactServiceException { if (request == null) { throw new IllegalArgumentException(Config.Errors.BULK_CONTACTS_REQUEST_NULL); } return bulkActivitiesService.exportContacts(this.getAccessToken(), request); } /** * * Get Bulk Summary Report API.<br/> * Details in : {@link BulkActivitiesService#getSummaryReport(String)} * * @return A {@link List} of {@link SummaryReport} in case of success; an exception is thrown otherwise. * @throws ConstantContactServiceException Thrown when : * <ul> * <li>something went wrong either on the client side;</li> * <li>or an error message was received from the server side.</li> * </ul> * <br/> * To check if a detailed error message is present, call {@link ConstantContactException#hasErrorInfo()} <br/> * Detailed error message (if present) can be seen by calling {@link ConstantContactException#getErrorInfo()} */ public List<SummaryReport> getBulkSummaryReport() throws ConstantContactServiceException { return bulkActivitiesService.getSummaryReport(this.getAccessToken()); } public List<DetailedStatusReport> getBulkDetailedStatusReport(String status, String type, String id) throws IllegalArgumentException, ConstantContactServiceException { return bulkActivitiesService.getDetailedStatusReport(this.getAccessToken(), status, type, id); } }
package com.enow.storm.main; import com.enow.persistence.redis.RedisDB; import com.enow.storm.ActionTopology.*; import com.enow.storm.TriggerTopology.*; import org.apache.storm.Config; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.StormTopology; import org.apache.storm.kafka.*; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.UUID; public class RemoteSubmitter { private static final String[] TOPICS = new String[]{"event", "proceed", "order", "trigger", "status"}; private static final String[] SETTINGS = new String[]{"127.0.0.1", "27017", "127.0.0.1", "6379", "127.0.0.1:9092", "127.0.0.1:2181"}; // private static final String zkhost = "127.0.0.1:2181"; public static void main(String[] args) throws Exception { // RedisDB.getInstance(args[4], Integer.parseInt(args[5])).deleteAllNodes(); // RedisDB.getInstance(args[4], Integer.parseInt(args[5])).deleteAllStatus(); RedisDB.getInstance(SETTINGS[2], Integer.parseInt(SETTINGS[3])).deleteAllNodes(); RedisDB.getInstance(SETTINGS[2], Integer.parseInt(SETTINGS[3])).deleteAllStatus(); new RemoteSubmitter().runMain(args); } protected void runMain(String[] args) throws Exception { // submitTopologyRemoteCluster(args[0], getTriggerTopology(args[7]), getConfig(args)); // submitTopologyRemoteCluster(args[1], getActionTopology(args[7]), getConfig(args)); submitTopologyRemoteCluster(args[0], getTriggerTopology(SETTINGS[5]), getConfig(SETTINGS)); submitTopologyRemoteCluster(args[1], getActionTopology(SETTINGS[5]), getConfig(SETTINGS)); } protected void submitTopologyRemoteCluster(String arg, StormTopology topology, Config config) throws Exception { StormSubmitter.submitTopology(arg, config, topology); } protected void stopWaitingForInput() { try { System.out.println("PRESS ENTER TO STOP"); new BufferedReader(new InputStreamReader(System.in)).readLine(); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } protected Config getConfig(String[] SETTINGS) { Config config = new Config(); // config.put("mongodb.ip", args[2]); // config.put("mongodb.port", Integer.parseInt(args[3])); // config.put("redis.ip", args[4]); // config.put("redis.port", Integer.parseInt(args[5])); // config.put("kafka.properties", args[6]); config.put("mongodb.ip", SETTINGS[0]); config.put("mongodb.port", Integer.parseInt(SETTINGS[1])); config.put("redis.ip", SETTINGS[2]); config.put("redis.port", Integer.parseInt(SETTINGS[3])); config.put("kafka.properties", SETTINGS[4]); config.setDebug(true); config.setNumWorkers(2); return config; } protected StormTopology getTriggerTopology(String zkhost) { BrokerHosts hosts = new ZkHosts(zkhost); TopologyBuilder builder = new TopologyBuilder(); // event spouts setting SpoutConfig eventConfig = new SpoutConfig(hosts, TOPICS[0], "/" + TOPICS[0], UUID.randomUUID().toString()); eventConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); eventConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime(); eventConfig.ignoreZkOffsets = true; // proceed spouts setting SpoutConfig proceedConfig = new SpoutConfig(hosts, TOPICS[1], "/" + TOPICS[1], UUID.randomUUID().toString()); proceedConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); proceedConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime(); proceedConfig.ignoreZkOffsets = true; // order spouts setting SpoutConfig orderConfig = new SpoutConfig(hosts, TOPICS[2], "/" + TOPICS[2], UUID.randomUUID().toString()); orderConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); orderConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime(); orderConfig.ignoreZkOffsets = true; // Set spouts builder.setSpout("event-spout", new KafkaSpout(eventConfig)); builder.setSpout("proceed-spout", new KafkaSpout(proceedConfig)); builder.setSpout("order-spout", new KafkaSpout(orderConfig)); // Set bolts builder.setBolt("indexing-bolt", new IndexingBolt()).allGrouping("event-spout") .allGrouping("proceed-spout") .allGrouping("order-spout"); builder.setBolt("staging-bolt", new StagingBolt()).allGrouping("indexing-bolt"); builder.setBolt("calling-trigger-bolt", new CallingTriggerBolt()).allGrouping("staging-bolt"); return builder.createTopology(); } protected StormTopology getActionTopology(String zkhost) { BrokerHosts hosts = new ZkHosts(zkhost); TopologyBuilder builder = new TopologyBuilder(); // trigger spouts setting SpoutConfig triggerConfig = new SpoutConfig(hosts, TOPICS[3], "/" + TOPICS[3], UUID.randomUUID().toString()); triggerConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); triggerConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime(); triggerConfig.ignoreZkOffsets = true; // status spouts setting SpoutConfig statusConfig = new SpoutConfig(hosts, TOPICS[4], "/" + TOPICS[4], UUID.randomUUID().toString()); statusConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); statusConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime(); statusConfig.ignoreZkOffsets = true; // Set spouts builder.setSpout("trigger-spout", new KafkaSpout(triggerConfig)); builder.setSpout("status-spout", new KafkaSpout(statusConfig)); /* Set bolts */ builder.setBolt("scheduling-bolt", new SchedulingBolt()) .allGrouping("trigger-spout"); builder.setBolt("status-bolt", new StatusBolt(), 4) .allGrouping("status-spout"); builder.setBolt("execute-code-bolt", new ExecutingBolt()).allGrouping("scheduling-bolt"); builder.setBolt("provisioning-bolt", new ProvisioningBolt()).allGrouping("execute-code-bolt"); builder.setBolt("calling-feed-bolt", new CallingFeedBolt()).allGrouping("provisioning-bolt"); return builder.createTopology(); } }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.pm.ApplicationInfo; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.litho.displaylist.DisplayListException; import com.facebook.litho.reference.BorderColorDrawableReference; import com.facebook.litho.reference.Reference; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.M; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec; import static com.facebook.litho.Component.isMountSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentContext.NULL_LAYOUT; import static com.facebook.litho.ComponentLifecycle.MountType.NONE; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS; import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT; import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED; import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE; import static com.facebook.litho.MountState.ROOT_HOST_ID; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.litho.SizeSpec.EXACTLY; /** * The main role of {@link LayoutState} is to hold the output of layout calculation. This includes * mountable outputs and visibility outputs. A centerpiece of the class is {@link * #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs * based on the provided {@link InternalNode} for later use in {@link MountState}. */ class LayoutState { static final Comparator<LayoutOutput> sTopsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsTop = lhs.getBounds().top; final int rhsTop = rhs.getBounds().top; return lhsTop < rhsTop ? -1 : lhsTop > rhsTop ? 1 // Hosts should be higher for tops so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? -1 : 1; } }; static final Comparator<LayoutOutput> sBottomsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsBottom = lhs.getBounds().bottom; final int rhsBottom = rhs.getBounds().bottom; return lhsBottom < rhsBottom ? -1 : lhsBottom > rhsBottom ? 1 // Hosts should be lower for bottoms so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? 1 : -1; } }; private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled}; private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{}; private ComponentContext mContext; private TransitionContext mTransitionContext; private Component<?> mComponent; private int mWidthSpec; private int mHeightSpec; private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8); private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8); private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8); private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator; private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>(); private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>(); private final List<TestOutput> mTestOutputs; private InternalNode mLayoutRoot; private DiffNode mDiffTreeRoot; // Reference count will be initialized to 1 in init(). private final AtomicInteger mReferenceCount = new AtomicInteger(-1); private int mWidth; private int mHeight; private int mCurrentX; private int mCurrentY; private int mCurrentLevel = 0; // Holds the current host marker in the layout tree. private long mCurrentHostMarker = -1; private int mCurrentHostOutputPosition = -1; private boolean mShouldDuplicateParentState = true; private boolean mShouldGenerateDiffTree = false; private int mComponentTreeId = -1; private AccessibilityManager mAccessibilityManager; private boolean mAccessibilityEnabled = false; private StateHandler mStateHandler; LayoutState() { mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator(); mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null; } /** * Acquires a new layout output for the internal node and its associated component. It returns * null if there's no component associated with the node as the mount pass only cares about nodes * that will potentially mount content into the component host. */ @Nullable private static LayoutOutput createGenericLayoutOutput( InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); // Skip empty nodes and layout specs because they don't mount anything. if (component == null || component.getLifecycle().getMountType() == NONE) { return null; } return createLayoutOutput( component, layoutState, node, true /* useNodePadding */, node.getImportantForAccessibility(), layoutState.mShouldDuplicateParentState); } private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) { final LayoutOutput hostOutput = createLayoutOutput( HostComponent.create(), layoutState, node, false /* useNodePadding */, node.getImportantForAccessibility(), node.isDuplicateParentStateEnabled()); hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey()); return hostOutput; } private static LayoutOutput createDrawableLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node) { return createLayoutOutput( component, layoutState, node, false /* useNodePadding */, IMPORTANT_FOR_ACCESSIBILITY_NO, layoutState.mShouldDuplicateParentState); } private static LayoutOutput createLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node, boolean useNodePadding, int importantForAccessibility, boolean duplicateParentState) { final boolean isMountViewSpec = isMountViewSpec(component); final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput(); layoutOutput.setComponent(component); layoutOutput.setImportantForAccessibility(importantForAccessibility); // The mount operation will need both the marker for the target host and its matching // parent host to ensure the correct hierarchy when nesting the host views. layoutOutput.setHostMarker(layoutState.mCurrentHostMarker); if (layoutState.mCurrentHostOutputPosition >= 0) { final LayoutOutput hostOutput = layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition); final Rect hostBounds = hostOutput.getBounds(); layoutOutput.setHostTranslationX(hostBounds.left); layoutOutput.setHostTranslationY(hostBounds.top); } int l = layoutState.mCurrentX + node.getX(); int t = layoutState.mCurrentY + node.getY(); int r = l + node.getWidth(); int b = t + node.getHeight(); final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0; final int paddingTop = useNodePadding ? node.getPaddingTop() : 0; final int paddingRight = useNodePadding ? node.getPaddingRight() : 0; final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0; // View mount specs are able to set their own attributes when they're mounted. // Non-view specs (drawable and layout) always transfer their view attributes // to their respective hosts. // Moreover, if the component mounts a view, then we apply padding to the view itself later on. // Otherwise, apply the padding to the bounds of the layout output. if (isMountViewSpec) { layoutOutput.setNodeInfo(node.getNodeInfo()); // Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput. final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection()); viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b); layoutOutput.setViewNodeInfo(viewNodeInfo); viewNodeInfo.release(); } else { l += paddingLeft; t += paddingTop; r -= paddingRight; b -= paddingBottom; } layoutOutput.setBounds(l, t, r, b); int flags = 0; if (duplicateParentState) { flags |= FLAG_DUPLICATE_PARENT_STATE; } layoutOutput.setFlags(flags); return layoutOutput; } /** * Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information * stored in the {@link InternalNode}. */ private static VisibilityOutput createVisibilityOutput( InternalNode node, LayoutState layoutState) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final EventHandler visibleHandler = node.getVisibleHandler(); final EventHandler focusedHandler = node.getFocusedHandler(); final EventHandler fullImpressionHandler = node.getFullImpressionHandler(); final EventHandler invisibleHandler = node.getInvisibleHandler(); final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput(); final Component<?> handlerComponent; // Get the component from the handler that is not null. If more than one is not null, then // getting the component from any of them works. if (visibleHandler != null) { handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher; } else if (focusedHandler != null) { handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher; } else if (fullImpressionHandler != null) { handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher; } else { handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher; } visibilityOutput.setComponent(handlerComponent); visibilityOutput.setBounds(l, t, r, b); visibilityOutput.setVisibleEventHandler(visibleHandler); visibilityOutput.setFocusedEventHandler(focusedHandler); visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler); visibilityOutput.setInvisibleEventHandler(invisibleHandler); return visibilityOutput; } private static TestOutput createTestOutput( InternalNode node, LayoutState layoutState, LayoutOutput layoutOutput) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final TestOutput output = ComponentsPools.acquireTestOutput(); output.setTestKey(node.getTestKey()); output.setBounds(l, t, r, b); output.setHostMarker(layoutState.mCurrentHostMarker); if (layoutOutput != null) { output.setLayoutOutputId(layoutOutput.getId()); } return output; } private static boolean isLayoutDirectionRTL(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if ((SDK_INT >= JELLY_BEAN_MR1) && (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) { int layoutDirection = getLayoutDirection(context); return layoutDirection == View.LAYOUT_DIRECTION_RTL; } return false; } @TargetApi(JELLY_BEAN_MR1) private static int getLayoutDirection(Context context) { return context.getResources().getConfiguration().getLayoutDirection(); } /** * Determine if a given {@link InternalNode} within the context of a given {@link LayoutState} * requires to be wrapped inside a view. * * @see #needsHostView(InternalNode, LayoutState) */ private static boolean hasViewContent(InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); final NodeInfo nodeInfo = node.getNodeInfo(); final boolean implementsAccessibility = (nodeInfo != null && nodeInfo.hasAccessibilityHandlers()) || (component != null && component.getLifecycle().implementsAccessibility()); final int importantForAccessibility = node.getImportantForAccessibility(); // A component has accessibility content if: // 1. Accessibility is currently enabled. // 2. Accessibility hasn't been explicitly disabled on it // i.e. IMPORTANT_FOR_ACCESSIBILITY_NO. // 3. Any of these conditions are true: // - It implements accessibility support. // - It has a content description. // - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES // or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS. // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host // so that such flag is applied in the resulting view hierarchy after the component // tree is mounted. Click handling is also considered accessibility content but // this is already covered separately i.e. click handler is not null. final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled && importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO && (implementsAccessibility || (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription())) || importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO); final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers()); final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null); final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null); final boolean isFocusableSetTrue = (nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE); return hasTouchEventHandlers || hasViewTag || hasViewTags || hasAccessibilityContent || isFocusableSetTrue; } /** * Collects layout outputs and release the layout tree. The layout outputs hold necessary * information to be used by {@link MountState} to mount components into a {@link ComponentHost}. * <p/> * Whenever a component has view content (view tags, click handler, etc), a new host 'marker' * is added for it. The mount pass will use the markers to decide which host should be used * for each layout output. The root node unconditionally generates a layout output corresponding * to the root host. * <p/> * The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts * will be created at the right order when mounting. The host markers will be define which host * each mounted artifacts will be attached to. * <p/> * At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled * will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the * host and the contents (including background/foreground). In all other cases instead we'll only * try to re-use the hosts. In some cases the host's structure might change between two updates * even if the component is of the same type. This can happen for example when a click listener is * added. To avoid trying to re-use the wrong host type we explicitly check that after all the * children for a subtree have been added (this is when the actual host type is resolved). If the * host type changed compared to the one in the DiffNode we need to refresh the ids for the whole * subtree in order to ensure that the MountState will unmount the subtree and mount it again on * the correct host. * <p/> * * @param node InternalNode to process. * @param layoutState the LayoutState currently operating. * @param parentDiffNode whether this method also populates the diff tree and assigns the root * to mDiffTreeRoot. */ private static void collectResults( InternalNode node, LayoutState layoutState, DiffNode parentDiffNode) { if (node.hasNewLayout()) { node.markLayoutSeen(); } final Component<?> component = node.getComponent(); // Early return if collecting results of a node holding a nested tree. if (node.isNestedTreeHolder()) { // If the nested tree is defined, it has been resolved during a measure call during // layout calculation. InternalNode nestedTree = resolveNestedTree( node, SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY), SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY)); if (nestedTree == NULL_LAYOUT) { return; } // Account for position of the holder node. layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); collectResults(nestedTree, layoutState, parentDiffNode); layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); return; } final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree; final DiffNode currentDiffNode = node.getDiffNode(); final boolean shouldUseCachedOutputs = isMountSpec(component) && currentDiffNode != null; final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid(); final DiffNode diffNode; if (shouldGenerateDiffTree) { diffNode = createDiffNode(node, parentDiffNode); if (parentDiffNode == null) { layoutState.mDiffTreeRoot = diffNode; } } else { diffNode = null; } final boolean needsHostView = needsHostView(node, layoutState); final long currentHostMarker = layoutState.mCurrentHostMarker; final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition; int hostLayoutPosition = -1; // 1. Insert a host LayoutOutput if we have some interactive content to be attached to. if (needsHostView) { hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode); layoutState.mCurrentLevel++; layoutState.mCurrentHostMarker = layoutState.mMountableOutputs.get(hostLayoutPosition).getId(); layoutState.mCurrentHostOutputPosition = hostLayoutPosition; } // We need to take into account flattening when setting duplicate parent state. The parent after // flattening may no longer exist. Therefore the value of duplicate parent state should only be // true if the path between us (inclusive) and our inner/root host (exclusive) all are // duplicate parent state. final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState; layoutState.mShouldDuplicateParentState = needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled()); // Generate the layoutOutput for the given node. final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState); if (layoutOutput != null) { final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( layoutOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_CONTENT, previousId, isCachedOutputUpdated); } // If we don't need to update this output we can safely re-use the display list from the // previous output. if (isCachedOutputUpdated) { layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList()); } // 2. Add background if defined. final Reference<? extends Drawable> background = node.getBackground(); if (background != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) { layoutOutput.getViewNodeInfo().setBackground(background); } else { final LayoutOutput convertBackground = (currentDiffNode != null) ? currentDiffNode.getBackground() : null; final LayoutOutput backgroundOutput = addDrawableComponent( node, layoutState, convertBackground, background, LayoutOutput.TYPE_BACKGROUND); if (diffNode != null) { diffNode.setBackground(backgroundOutput); } } } // 3. Now add the MountSpec (either View or Drawable) to the Outputs. if (isMountSpec(component)) { // Notify component about its final size. component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component); addMountableOutput(layoutState, layoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, layoutOutput, layoutState.mMountableOutputs.size() - 1); if (diffNode != null) { diffNode.setContent(layoutOutput); } } // 4. Add border color if defined. if (node.shouldDrawBorders()) { final LayoutOutput convertBorder = (currentDiffNode != null) ? currentDiffNode.getBorder() : null; final LayoutOutput borderOutput = addDrawableComponent( node, layoutState, convertBorder, getBorderColorDrawable(node), LayoutOutput.TYPE_BORDER); if (diffNode != null) { diffNode.setBorder(borderOutput); } } // 5. Extract the Transitions. if (SDK_INT >= ICE_CREAM_SANDWICH) { if (node.getTransitionKey() != null) { layoutState .getOrCreateTransitionContext() .addTransitionKey(node.getTransitionKey()); } if (component != null) { Transition transition = component.getLifecycle().onLayoutTransition( layoutState.mContext, component); if (transition != null) { layoutState.getOrCreateTransitionContext().add(transition); } } } layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); // We must process the nodes in order so that the layout state output order is correct. for (int i = 0, size = node.getChildCount(); i < size; i++) { collectResults( node.getChildAt(i), layoutState, diffNode); } layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); // 6. Add foreground if defined. final Reference<? extends Drawable> foreground = node.getForeground(); if (foreground != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) { layoutOutput.getViewNodeInfo().setForeground(foreground); } else { final LayoutOutput convertForeground = (currentDiffNode != null) ? currentDiffNode.getForeground() : null; final LayoutOutput foregroundOutput = addDrawableComponent( node, layoutState, convertForeground, foreground, LayoutOutput.TYPE_FOREGROUND); if (diffNode != null) { diffNode.setForeground(foregroundOutput); } } } // 7. Add VisibilityOutputs if any visibility-related event handlers are present. if (node.hasVisibilityHandlers()) { final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState); final long previousId = shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId( visibilityOutput, layoutState.mCurrentLevel, previousId); layoutState.mVisibilityOutputs.add(visibilityOutput); if (diffNode != null) { diffNode.setVisibilityOutput(visibilityOutput); } } // 8. If we're in a testing environment, maintain an additional data structure with // information about nodes that we can query later. if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) { final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput); layoutState.mTestOutputs.add(testOutput); } // All children for the given host have been added, restore the previous // host, level, and duplicate parent state value in the recursive queue. if (layoutState.mCurrentHostMarker != currentHostMarker) { layoutState.mCurrentHostMarker = currentHostMarker; layoutState.mCurrentHostOutputPosition = currentHostOutputPosition; layoutState.mCurrentLevel } layoutState.mShouldDuplicateParentState = shouldDuplicateParentState; Collections.sort(layoutState.mMountableOutputTops, sTopsComparator); Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator); } private static void calculateAndSetHostOutputIdAndUpdateState( InternalNode node, LayoutOutput hostOutput, LayoutState layoutState, boolean isCachedOutputUpdated) { if (layoutState.isLayoutRoot(node)) { // The root host (ComponentView) always has ID 0 and is unconditionally // set as dirty i.e. no need to use shouldComponentUpdate(). hostOutput.setId(ROOT_HOST_ID); // Special case where the host marker of the root host is pointing to itself. hostOutput.setHostMarker(ROOT_HOST_ID); hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY); } else { layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( hostOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_HOST, -1, isCachedOutputUpdated); } } private static LayoutOutput addDrawableComponent( InternalNode node, LayoutState layoutState, LayoutOutput recycle, Reference<? extends Drawable> reference, @LayoutOutput.LayoutOutputType int type) { final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference); drawableComponent.setScopedContext( ComponentContext.withComponentScope(node.getContext(), drawableComponent)); final boolean isOutputUpdated; if (recycle != null) { isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate( recycle.getComponent(), drawableComponent); } else { isOutputUpdated = false; } final long previousId = recycle != null ? recycle.getId() : -1; final LayoutOutput output = addDrawableLayoutOutput( drawableComponent, layoutState, node, type, previousId, isOutputUpdated); return output; } private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) { if (!node.shouldDrawBorders()) { throw new RuntimeException("This node does not support drawing border color"); } return BorderColorDrawableReference.create(node.getContext()) .color(node.getBorderColor()) .borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT))) .borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP))) .borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT))) .borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM))) .build(); } private static void addLayoutOutputIdToPositionsMap( LongSparseArray outputsIdToPositionMap, LayoutOutput layoutOutput, int position) { if (outputsIdToPositionMap != null) { outputsIdToPositionMap.put(layoutOutput.getId(), position); } } private static LayoutOutput addDrawableLayoutOutput( Component<DrawableComponent> drawableComponent, LayoutState layoutState, InternalNode node, @LayoutOutput.LayoutOutputType int layoutOutputType, long previousId, boolean isCachedOutputUpdated) { drawableComponent.getLifecycle().onBoundsDefined( layoutState.mContext, node, drawableComponent); final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput( drawableComponent, layoutState, node); layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( drawableLayoutOutput, layoutState.mCurrentLevel, layoutOutputType, previousId, isCachedOutputUpdated); addMountableOutput(layoutState, drawableLayoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, drawableLayoutOutput, layoutState.mMountableOutputs.size() - 1); return drawableLayoutOutput; } static void releaseNodeTree(InternalNode node, boolean isNestedTree) { if (node == NULL_LAYOUT) { throw new IllegalArgumentException("Cannot release a null node tree"); } for (int i = node.getChildCount() - 1; i >= 0; i final InternalNode child = node.getChildAt(i); if (isNestedTree && node.hasNewLayout()) { node.markLayoutSeen(); } // A node must be detached from its parent *before* being released (otherwise the parent would // retain a reference to a node that may get re-used by another thread) node.removeChildAt(i); releaseNodeTree(child, isNestedTree); } if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) { releaseNodeTree(node.getNestedTree(), true); } ComponentsPools.release(node); } /** * If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an * HostComponent in the Outputs such as it will be used as a HostView at Mount time. View * MountSpec are not allowed. * * @return The position the HostLayoutOutput was inserted. */ private static int addHostLayoutOutput( InternalNode node, LayoutState layoutState, DiffNode diffNode) { final Component<?> component = node.getComponent(); // Only the root host is allowed to wrap view mount specs as a layout output // is unconditionally added for it. if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) { throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View"); } final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node); // The component of the hostLayoutOutput will be set later after all the // children got processed. addMountableOutput(layoutState, hostLayoutOutput); final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1; if (diffNode != null) { diffNode.setHost(hostLayoutOutput); } calculateAndSetHostOutputIdAndUpdateState( node, hostLayoutOutput, layoutState, false); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, hostLayoutOutput, hostOutputPosition); return hostOutputPosition; } static <T extends ComponentLifecycle> LayoutState calculate( ComponentContext c, Component<T> component, int componentTreeId, int widthSpec, int heightSpec, boolean shouldGenerateDiffTree, DiffNode previousDiffTreeRoot) { // Detect errors internal to components component.markLayoutStarted(); LayoutState layoutState = ComponentsPools.acquireLayoutState(c); layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree; layoutState.mComponentTreeId = componentTreeId; layoutState.mAccessibilityManager = (AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE); layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager); layoutState.mComponent = component; layoutState.mWidthSpec = widthSpec; layoutState.mHeightSpec = heightSpec; component.applyStateUpdates(c); final InternalNode root = createAndMeasureTreeForComponent( component.getScopedContext(), component, null, // nestedTreeHolder is null because this is measuring the root component tree. widthSpec, heightSpec, previousDiffTreeRoot); switch (SizeSpec.getMode(widthSpec)) { case SizeSpec.EXACTLY: layoutState.mWidth = SizeSpec.getSize(widthSpec); break; case SizeSpec.AT_MOST: layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mWidth = root.getWidth(); break; } switch (SizeSpec.getMode(heightSpec)) { case SizeSpec.EXACTLY: layoutState.mHeight = SizeSpec.getSize(heightSpec); break; case SizeSpec.AT_MOST: layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mHeight = root.getHeight(); break; } layoutState.mLayoutStateOutputIdCalculator.clear(); // Reset markers before collecting layout outputs. layoutState.mCurrentHostMarker = -1; final ComponentsLogger logger = c.getLogger(); if (root == NULL_LAYOUT) { return layoutState; } layoutState.mLayoutRoot = root; ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName()); if (logger != null) { logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag()); }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.pm.ApplicationInfo; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.litho.displaylist.DisplayListException; import com.facebook.litho.reference.BorderColorDrawableReference; import com.facebook.litho.reference.Reference; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.M; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec; import static com.facebook.litho.Component.isMountSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentContext.NULL_LAYOUT; import static com.facebook.litho.ComponentLifecycle.MountType.NONE; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS; import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT; import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED; import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE; import static com.facebook.litho.MountState.ROOT_HOST_ID; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.litho.SizeSpec.EXACTLY; /** * The main role of {@link LayoutState} is to hold the output of layout calculation. This includes * mountable outputs and visibility outputs. A centerpiece of the class is {@link * #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs * based on the provided {@link InternalNode} for later use in {@link MountState}. */ class LayoutState { static final Comparator<LayoutOutput> sTopsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsTop = lhs.getBounds().top; final int rhsTop = rhs.getBounds().top; return lhsTop < rhsTop ? -1 : lhsTop > rhsTop ? 1 // Hosts should be higher for tops so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? -1 : 1; } }; static final Comparator<LayoutOutput> sBottomsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsBottom = lhs.getBounds().bottom; final int rhsBottom = rhs.getBounds().bottom; return lhsBottom < rhsBottom ? -1 : lhsBottom > rhsBottom ? 1 // Hosts should be lower for bottoms so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? 1 : -1; } }; private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled}; private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{}; private ComponentContext mContext; private TransitionContext mTransitionContext; private Component<?> mComponent; private int mWidthSpec; private int mHeightSpec; private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8); private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8); private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8); private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator; private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>(); private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>(); private final List<TestOutput> mTestOutputs; private InternalNode mLayoutRoot; private DiffNode mDiffTreeRoot; // Reference count will be initialized to 1 in init(). private final AtomicInteger mReferenceCount = new AtomicInteger(-1); private int mWidth; private int mHeight; private int mCurrentX; private int mCurrentY; private int mCurrentLevel = 0; // Holds the current host marker in the layout tree. private long mCurrentHostMarker = -1; private int mCurrentHostOutputPosition = -1; private boolean mShouldDuplicateParentState = true; private boolean mShouldGenerateDiffTree = false; private int mComponentTreeId = -1; private AccessibilityManager mAccessibilityManager; private boolean mAccessibilityEnabled = false; private StateHandler mStateHandler; LayoutState() { mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator(); mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null; } /** * Acquires a new layout output for the internal node and its associated component. It returns * null if there's no component associated with the node as the mount pass only cares about nodes * that will potentially mount content into the component host. */ @Nullable private static LayoutOutput createGenericLayoutOutput( InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); // Skip empty nodes and layout specs because they don't mount anything. if (component == null || component.getLifecycle().getMountType() == NONE) { return null; } return createLayoutOutput( component, layoutState, node, true /* useNodePadding */, node.getImportantForAccessibility(), layoutState.mShouldDuplicateParentState); } private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) { final LayoutOutput hostOutput = createLayoutOutput( HostComponent.create(), layoutState, node, false /* useNodePadding */, node.getImportantForAccessibility(), node.isDuplicateParentStateEnabled()); hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey()); return hostOutput; } private static LayoutOutput createDrawableLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node) { return createLayoutOutput( component, layoutState, node, false /* useNodePadding */, IMPORTANT_FOR_ACCESSIBILITY_NO, layoutState.mShouldDuplicateParentState); } private static LayoutOutput createLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node, boolean useNodePadding, int importantForAccessibility, boolean duplicateParentState) { final boolean isMountViewSpec = isMountViewSpec(component); final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput(); layoutOutput.setComponent(component); layoutOutput.setImportantForAccessibility(importantForAccessibility); // The mount operation will need both the marker for the target host and its matching // parent host to ensure the correct hierarchy when nesting the host views. layoutOutput.setHostMarker(layoutState.mCurrentHostMarker); if (layoutState.mCurrentHostOutputPosition >= 0) { final LayoutOutput hostOutput = layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition); final Rect hostBounds = hostOutput.getBounds(); layoutOutput.setHostTranslationX(hostBounds.left); layoutOutput.setHostTranslationY(hostBounds.top); } int l = layoutState.mCurrentX + node.getX(); int t = layoutState.mCurrentY + node.getY(); int r = l + node.getWidth(); int b = t + node.getHeight(); final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0; final int paddingTop = useNodePadding ? node.getPaddingTop() : 0; final int paddingRight = useNodePadding ? node.getPaddingRight() : 0; final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0; // View mount specs are able to set their own attributes when they're mounted. // Non-view specs (drawable and layout) always transfer their view attributes // to their respective hosts. // Moreover, if the component mounts a view, then we apply padding to the view itself later on. // Otherwise, apply the padding to the bounds of the layout output. if (isMountViewSpec) { layoutOutput.setNodeInfo(node.getNodeInfo()); // Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput. final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection()); viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b); layoutOutput.setViewNodeInfo(viewNodeInfo); viewNodeInfo.release(); } else { l += paddingLeft; t += paddingTop; r -= paddingRight; b -= paddingBottom; } layoutOutput.setBounds(l, t, r, b); int flags = 0; if (duplicateParentState) { flags |= FLAG_DUPLICATE_PARENT_STATE; } layoutOutput.setFlags(flags); return layoutOutput; } /** * Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information * stored in the {@link InternalNode}. */ private static VisibilityOutput createVisibilityOutput( InternalNode node, LayoutState layoutState) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final EventHandler visibleHandler = node.getVisibleHandler(); final EventHandler focusedHandler = node.getFocusedHandler(); final EventHandler fullImpressionHandler = node.getFullImpressionHandler(); final EventHandler invisibleHandler = node.getInvisibleHandler(); final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput(); final Component<?> handlerComponent; // Get the component from the handler that is not null. If more than one is not null, then // getting the component from any of them works. if (visibleHandler != null) { handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher; } else if (focusedHandler != null) { handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher; } else if (fullImpressionHandler != null) { handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher; } else { handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher; } visibilityOutput.setComponent(handlerComponent); visibilityOutput.setBounds(l, t, r, b); visibilityOutput.setVisibleEventHandler(visibleHandler); visibilityOutput.setFocusedEventHandler(focusedHandler); visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler); visibilityOutput.setInvisibleEventHandler(invisibleHandler); return visibilityOutput; } private static TestOutput createTestOutput( InternalNode node, LayoutState layoutState, LayoutOutput layoutOutput) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final TestOutput output = ComponentsPools.acquireTestOutput(); output.setTestKey(node.getTestKey()); output.setBounds(l, t, r, b); output.setHostMarker(layoutState.mCurrentHostMarker); if (layoutOutput != null) { output.setLayoutOutputId(layoutOutput.getId()); } return output; } private static boolean isLayoutDirectionRTL(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if ((SDK_INT >= JELLY_BEAN_MR1) && (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) { int layoutDirection = getLayoutDirection(context); return layoutDirection == View.LAYOUT_DIRECTION_RTL; } return false; } @TargetApi(JELLY_BEAN_MR1) private static int getLayoutDirection(Context context) { return context.getResources().getConfiguration().getLayoutDirection(); } /** * Determine if a given {@link InternalNode} within the context of a given {@link LayoutState} * requires to be wrapped inside a view. * * @see #needsHostView(InternalNode, LayoutState) */ private static boolean hasViewContent(InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); final NodeInfo nodeInfo = node.getNodeInfo(); final boolean implementsAccessibility = (nodeInfo != null && nodeInfo.hasAccessibilityHandlers()) || (component != null && component.getLifecycle().implementsAccessibility()); final int importantForAccessibility = node.getImportantForAccessibility(); // A component has accessibility content if: // 1. Accessibility is currently enabled. // 2. Accessibility hasn't been explicitly disabled on it // i.e. IMPORTANT_FOR_ACCESSIBILITY_NO. // 3. Any of these conditions are true: // - It implements accessibility support. // - It has a content description. // - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES // or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS. // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host // so that such flag is applied in the resulting view hierarchy after the component // tree is mounted. Click handling is also considered accessibility content but // this is already covered separately i.e. click handler is not null. final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled && importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO && (implementsAccessibility || (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription())) || importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO); final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers()); final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null); final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null); final boolean isFocusableSetTrue = (nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE); return hasTouchEventHandlers || hasViewTag || hasViewTags || hasAccessibilityContent || isFocusableSetTrue; } /** * Collects layout outputs and release the layout tree. The layout outputs hold necessary * information to be used by {@link MountState} to mount components into a {@link ComponentHost}. * <p/> * Whenever a component has view content (view tags, click handler, etc), a new host 'marker' * is added for it. The mount pass will use the markers to decide which host should be used * for each layout output. The root node unconditionally generates a layout output corresponding * to the root host. * <p/> * The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts * will be created at the right order when mounting. The host markers will be define which host * each mounted artifacts will be attached to. * <p/> * At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled * will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the * host and the contents (including background/foreground). In all other cases instead we'll only * try to re-use the hosts. In some cases the host's structure might change between two updates * even if the component is of the same type. This can happen for example when a click listener is * added. To avoid trying to re-use the wrong host type we explicitly check that after all the * children for a subtree have been added (this is when the actual host type is resolved). If the * host type changed compared to the one in the DiffNode we need to refresh the ids for the whole * subtree in order to ensure that the MountState will unmount the subtree and mount it again on * the correct host. * <p/> * * @param node InternalNode to process. * @param layoutState the LayoutState currently operating. * @param parentDiffNode whether this method also populates the diff tree and assigns the root * to mDiffTreeRoot. */ private static void collectResults( InternalNode node, LayoutState layoutState, DiffNode parentDiffNode) { if (node.hasNewLayout()) { node.markLayoutSeen(); } final Component<?> component = node.getComponent(); // Early return if collecting results of a node holding a nested tree. if (node.isNestedTreeHolder()) { // If the nested tree is defined, it has been resolved during a measure call during // layout calculation. InternalNode nestedTree = resolveNestedTree( node, SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY), SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY)); if (nestedTree == NULL_LAYOUT) { return; } // Account for position of the holder node. layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); collectResults(nestedTree, layoutState, parentDiffNode); layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); return; } final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree; final DiffNode currentDiffNode = node.getDiffNode(); final boolean shouldUseCachedOutputs = isMountSpec(component) && currentDiffNode != null; final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid(); final DiffNode diffNode; if (shouldGenerateDiffTree) { diffNode = createDiffNode(node, parentDiffNode); if (parentDiffNode == null) { layoutState.mDiffTreeRoot = diffNode; } } else { diffNode = null; } final boolean needsHostView = needsHostView(node, layoutState); final long currentHostMarker = layoutState.mCurrentHostMarker; final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition; int hostLayoutPosition = -1; // 1. Insert a host LayoutOutput if we have some interactive content to be attached to. if (needsHostView) { hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode); layoutState.mCurrentLevel++; layoutState.mCurrentHostMarker = layoutState.mMountableOutputs.get(hostLayoutPosition).getId(); layoutState.mCurrentHostOutputPosition = hostLayoutPosition; } // We need to take into account flattening when setting duplicate parent state. The parent after // flattening may no longer exist. Therefore the value of duplicate parent state should only be // true if the path between us (inclusive) and our inner/root host (exclusive) all are // duplicate parent state. final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState; layoutState.mShouldDuplicateParentState = needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled()); // Generate the layoutOutput for the given node. final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState); if (layoutOutput != null) { final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( layoutOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_CONTENT, previousId, isCachedOutputUpdated); } // If we don't need to update this output we can safely re-use the display list from the // previous output. if (isCachedOutputUpdated) { layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList()); } // 2. Add background if defined. final Reference<? extends Drawable> background = node.getBackground(); if (background != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) { layoutOutput.getViewNodeInfo().setBackground(background); } else { final LayoutOutput convertBackground = (currentDiffNode != null) ? currentDiffNode.getBackground() : null; final LayoutOutput backgroundOutput = addDrawableComponent( node, layoutState, convertBackground, background, LayoutOutput.TYPE_BACKGROUND); if (diffNode != null) { diffNode.setBackground(backgroundOutput); } } } // 3. Now add the MountSpec (either View or Drawable) to the Outputs. if (isMountSpec(component)) { // Notify component about its final size. component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component); addMountableOutput(layoutState, layoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, layoutOutput, layoutState.mMountableOutputs.size() - 1); if (diffNode != null) { diffNode.setContent(layoutOutput); } } // 4. Add border color if defined. if (node.shouldDrawBorders()) { final LayoutOutput convertBorder = (currentDiffNode != null) ? currentDiffNode.getBorder() : null; final LayoutOutput borderOutput = addDrawableComponent( node, layoutState, convertBorder, getBorderColorDrawable(node), LayoutOutput.TYPE_BORDER); if (diffNode != null) { diffNode.setBorder(borderOutput); } } // 5. Extract the Transitions. if (SDK_INT >= ICE_CREAM_SANDWICH) { if (node.getTransitionKey() != null) { layoutState .getOrCreateTransitionContext() .addTransitionKey(node.getTransitionKey()); } if (component != null) { Transition transition = component.getLifecycle().onLayoutTransition( layoutState.mContext, component); if (transition != null) { layoutState.getOrCreateTransitionContext().add(transition); } } } layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); // We must process the nodes in order so that the layout state output order is correct. for (int i = 0, size = node.getChildCount(); i < size; i++) { collectResults( node.getChildAt(i), layoutState, diffNode); } layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); // 6. Add foreground if defined. final Reference<? extends Drawable> foreground = node.getForeground(); if (foreground != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) { layoutOutput.getViewNodeInfo().setForeground(foreground); } else { final LayoutOutput convertForeground = (currentDiffNode != null) ? currentDiffNode.getForeground() : null; final LayoutOutput foregroundOutput = addDrawableComponent( node, layoutState, convertForeground, foreground, LayoutOutput.TYPE_FOREGROUND); if (diffNode != null) { diffNode.setForeground(foregroundOutput); } } } // 7. Add VisibilityOutputs if any visibility-related event handlers are present. if (node.hasVisibilityHandlers()) { final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState); final long previousId = shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId( visibilityOutput, layoutState.mCurrentLevel, previousId); layoutState.mVisibilityOutputs.add(visibilityOutput); if (diffNode != null) { diffNode.setVisibilityOutput(visibilityOutput); } } // 8. If we're in a testing environment, maintain an additional data structure with // information about nodes that we can query later. if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) { final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput); layoutState.mTestOutputs.add(testOutput); } // All children for the given host have been added, restore the previous // host, level, and duplicate parent state value in the recursive queue. if (layoutState.mCurrentHostMarker != currentHostMarker) { layoutState.mCurrentHostMarker = currentHostMarker; layoutState.mCurrentHostOutputPosition = currentHostOutputPosition; layoutState.mCurrentLevel } layoutState.mShouldDuplicateParentState = shouldDuplicateParentState; Collections.sort(layoutState.mMountableOutputTops, sTopsComparator); Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator); } private static void calculateAndSetHostOutputIdAndUpdateState( InternalNode node, LayoutOutput hostOutput, LayoutState layoutState, boolean isCachedOutputUpdated) { if (layoutState.isLayoutRoot(node)) { // The root host (ComponentView) always has ID 0 and is unconditionally // set as dirty i.e. no need to use shouldComponentUpdate(). hostOutput.setId(ROOT_HOST_ID); // Special case where the host marker of the root host is pointing to itself. hostOutput.setHostMarker(ROOT_HOST_ID); hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY); } else { layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( hostOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_HOST, -1, isCachedOutputUpdated); } } private static LayoutOutput addDrawableComponent( InternalNode node, LayoutState layoutState, LayoutOutput recycle, Reference<? extends Drawable> reference, @LayoutOutput.LayoutOutputType int type) { final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference); drawableComponent.setScopedContext( ComponentContext.withComponentScope(node.getContext(), drawableComponent)); final boolean isOutputUpdated; if (recycle != null) { isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate( recycle.getComponent(), drawableComponent); } else { isOutputUpdated = false; } final long previousId = recycle != null ? recycle.getId() : -1; final LayoutOutput output = addDrawableLayoutOutput( drawableComponent, layoutState, node, type, previousId, isOutputUpdated); return output; } private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) { if (!node.shouldDrawBorders()) { throw new RuntimeException("This node does not support drawing border color"); } return BorderColorDrawableReference.create(node.getContext()) .color(node.getBorderColor()) .borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT))) .borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP))) .borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT))) .borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM))) .build(); } private static void addLayoutOutputIdToPositionsMap( LongSparseArray outputsIdToPositionMap, LayoutOutput layoutOutput, int position) { if (outputsIdToPositionMap != null) { outputsIdToPositionMap.put(layoutOutput.getId(), position); } } private static LayoutOutput addDrawableLayoutOutput( Component<DrawableComponent> drawableComponent, LayoutState layoutState, InternalNode node, @LayoutOutput.LayoutOutputType int layoutOutputType, long previousId, boolean isCachedOutputUpdated) { drawableComponent.getLifecycle().onBoundsDefined( layoutState.mContext, node, drawableComponent); final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput( drawableComponent, layoutState, node); layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( drawableLayoutOutput, layoutState.mCurrentLevel, layoutOutputType, previousId, isCachedOutputUpdated); addMountableOutput(layoutState, drawableLayoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, drawableLayoutOutput, layoutState.mMountableOutputs.size() - 1); return drawableLayoutOutput; } static void releaseNodeTree(InternalNode node, boolean isNestedTree) { if (node == NULL_LAYOUT) { throw new IllegalArgumentException("Cannot release a null node tree"); } for (int i = node.getChildCount() - 1; i >= 0; i final InternalNode child = node.getChildAt(i); if (isNestedTree && node.hasNewLayout()) { node.markLayoutSeen(); } // A node must be detached from its parent *before* being released (otherwise the parent would // retain a reference to a node that may get re-used by another thread) node.removeChildAt(i); releaseNodeTree(child, isNestedTree); } if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) { releaseNodeTree(node.getNestedTree(), true); } ComponentsPools.release(node); } /** * If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an * HostComponent in the Outputs such as it will be used as a HostView at Mount time. View * MountSpec are not allowed. * * @return The position the HostLayoutOutput was inserted. */ private static int addHostLayoutOutput( InternalNode node, LayoutState layoutState, DiffNode diffNode) { final Component<?> component = node.getComponent(); // Only the root host is allowed to wrap view mount specs as a layout output // is unconditionally added for it. if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) { throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View"); } final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node); // The component of the hostLayoutOutput will be set later after all the // children got processed. addMountableOutput(layoutState, hostLayoutOutput); final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1; if (diffNode != null) { diffNode.setHost(hostLayoutOutput); } calculateAndSetHostOutputIdAndUpdateState( node, hostLayoutOutput, layoutState, false); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, hostLayoutOutput, hostOutputPosition); return hostOutputPosition; } static <T extends ComponentLifecycle> LayoutState calculate( ComponentContext c, Component<T> component, int componentTreeId, int widthSpec, int heightSpec, boolean shouldGenerateDiffTree, DiffNode previousDiffTreeRoot) { // Detect errors internal to components component.markLayoutStarted(); LayoutState layoutState = ComponentsPools.acquireLayoutState(c); layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree; layoutState.mComponentTreeId = componentTreeId; layoutState.mAccessibilityManager = (AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE); layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager); layoutState.mComponent = component; layoutState.mWidthSpec = widthSpec; layoutState.mHeightSpec = heightSpec; component.applyStateUpdates(c); final InternalNode root = createAndMeasureTreeForComponent( component.getScopedContext(), component, null, // nestedTreeHolder is null because this is measuring the root component tree. widthSpec, heightSpec, previousDiffTreeRoot); switch (SizeSpec.getMode(widthSpec)) { case SizeSpec.EXACTLY: layoutState.mWidth = SizeSpec.getSize(widthSpec); break; case SizeSpec.AT_MOST: layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mWidth = root.getWidth(); break; } switch (SizeSpec.getMode(heightSpec)) { case SizeSpec.EXACTLY: layoutState.mHeight = SizeSpec.getSize(heightSpec); break; case SizeSpec.AT_MOST: layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mHeight = root.getHeight(); break; } layoutState.mLayoutStateOutputIdCalculator.clear(); // Reset markers before collecting layout outputs. layoutState.mCurrentHostMarker = -1; final ComponentsLogger logger = c.getLogger(); if (root == NULL_LAYOUT) { return layoutState; } layoutState.mLayoutRoot = root; ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName()); if (logger != null) { logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag()); } collectResults(root, layoutState, null); if (logger != null) { logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS); } ComponentsSystrace.endSection(); if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) { releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */); layoutState.mLayoutRoot = null; } if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) { collectDisplayLists(layoutState); } return layoutState; } void preAllocateMountContent() { if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) { for (int i = 0, size = mMountableOutputs.size(); i < size; i++) { final Component component = mMountableOutputs.get(i).getComponent(); if (Component.isMountViewSpec(component)) { final ComponentLifecycle lifecycle = component.getLifecycle(); if (!lifecycle.hasBeenPreallocated()) { final int poolSize = lifecycle.poolSize(); int insertedCount = 0; while (insertedCount < poolSize && ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) { ComponentsPools.release( mContext, lifecycle, lifecycle.createMountContent(mContext)); insertedCount++; } lifecycle.setWasPreallocated(); } } } } } private static void collectDisplayLists(LayoutState layoutState) { final Rect rect = new Rect(); final ComponentContext context = layoutState.mContext; final Activity activity = findActivityInContext(context); if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) { return; } for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) { final LayoutOutput output = layoutState.getMountableOutputAt(i); final Component component = output.getComponent(); final ComponentLifecycle lifecycle = component.getLifecycle(); if (lifecycle.shouldUseDisplayList()) { output.getMountBounds(rect); if (output.getDisplayList() != null && output.getDisplayList().isValid()) { // This output already has a valid DisplayList from diffing. No need to re-create it. // Just update its bounds. try { output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom); continue; } catch (DisplayListException e) { // Nothing to do here. } } final DisplayList displayList = DisplayList.createDisplayList( lifecycle.getClass().getSimpleName()); if (displayList != null) { Drawable drawable = (Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId()); if (drawable == null) { drawable = (Drawable) lifecycle.createMountContent(context); } final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output); boolean isStateEnabled = false; if (clickableOutput != null && clickableOutput.getNodeInfo() != null) { final NodeInfo nodeInfo = clickableOutput.getNodeInfo(); if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) { isStateEnabled = true; } } if (isStateEnabled) { drawable.setState(DRAWABLE_STATE_ENABLED); } else { drawable.setState(DRAWABLE_STATE_NOT_ENABLED); } lifecycle.mount( context, drawable, component); lifecycle.bind(context, drawable, component); output.getMountBounds(rect); drawable.setBounds(0, 0, rect.width(), rect.height()); try { final Canvas canvas = displayList.start(rect.width(), rect.height()); drawable.draw(canvas); displayList.end(canvas); displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom); output.setDisplayList(displayList); } catch (DisplayListException e) { // Display list creation failed. Make sure the DisplayList for this output is set // to null. output.setDisplayList(null); } lifecycle.unbind(context, drawable, component); lifecycle.unmount(context, drawable, component); ComponentsPools.release(context, lifecycle, drawable); } } } } private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) { if (output.getId() == ROOT_HOST_ID) { return output; } if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) { final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker()); if (parentPosition >= 0) { final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition); if (parent == null) { return null; } return findInteractiveRoot(layoutState, parent); } return null; } return output; } private static boolean isActivityDestroyed(Activity activity) { if (SDK_INT >= JELLY_BEAN_MR1) { return activity.isDestroyed(); } return false; } private static Activity findActivityInContext(Context context) { if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return findActivityInContext(((ContextWrapper) context).getBaseContext()); } return null; } @VisibleForTesting static <T extends ComponentLifecycle> InternalNode createTree( Component<T> component, ComponentContext context) { final ComponentsLogger logger = context.getLogger(); if (logger != null) { logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag()); logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName()); } final InternalNode root = (InternalNode) component.getLifecycle().createLayout( context, component, true /* resolveNestedTree */); if (logger != null) { logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS); } return root; } @VisibleForTesting static void measureTree( InternalNode root, int widthSpec, int heightSpec, DiffNode previousDiffTreeRoot) { final ComponentContext context = root.getContext(); final Component component = root.getComponent(); ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName()); if (YogaConstants.isUndefined(root.getStyleWidth())) { root.setStyleWidthFromSpec(widthSpec); } if (YogaConstants.isUndefined(root.getStyleHeight())) { root.setStyleHeightFromSpec(heightSpec); } if (previousDiffTreeRoot != null) { ComponentsSystrace.beginSection("applyDiffNode"); applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot); ComponentsSystrace.endSection(/* applyDiffNode */); } final ComponentsLogger logger = context.getLogger(); if (logger != null) { logger.eventStart(EVENT_CSS_LAYOUT, component, PARAM_LOG_TAG, context.getLogTag()); logger.eventAddParam( EVENT_CSS_LAYOUT, component, PARAM_TREE_DIFF_ENABLED, String.valueOf(previousDiffTreeRoot != null)); } root.calculateLayout( SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED ? YogaConstants.UNDEFINED : SizeSpec.getSize(widthSpec), SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED ? YogaConstants.UNDEFINED : SizeSpec.getSize(heightSpec)); if (logger != null) { logger.eventEnd(EVENT_CSS_LAYOUT, component, ACTION_SUCCESS); } ComponentsSystrace.endSection(/* measureTree */); } /** * Create and measure the nested tree or return the cached one for the same size specs. */ static InternalNode resolveNestedTree( InternalNode nestedTreeHolder, int widthSpec, int heightSpec) { final ComponentContext context = nestedTreeHolder.getContext(); final Component<?> component = nestedTreeHolder.getComponent(); InternalNode nestedTree = nestedTreeHolder.getNestedTree(); if (nestedTree == null || !hasCompatibleSizeSpec( nestedTree.getLastWidthSpec(), nestedTree.getLastHeightSpec(), widthSpec, heightSpec, nestedTree.getLastMeasuredWidth(), nestedTree.getLastMeasuredHeight())) { if (nestedTree != null) { if (nestedTree != NULL_LAYOUT) { releaseNodeTree(nestedTree, true /* isNestedTree */); } nestedTree = null; } if (component.hasCachedLayout()) { final InternalNode cachedLayout = component.getCachedLayout(); final boolean hasCompatibleLayoutDirection = InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout); // Transfer the cached layout to the node without releasing it if it's compatible. if (hasCompatibleLayoutDirection && hasCompatibleSizeSpec( cachedLayout.getLastWidthSpec(), cachedLayout.getLastHeightSpec(), widthSpec, heightSpec, cachedLayout.getLastMeasuredWidth(), cachedLayout.getLastMeasuredHeight())) { nestedTree = cachedLayout; component.clearCachedLayout(); } else { component.releaseCachedLayout(); } } if (nestedTree == null) { nestedTree = createAndMeasureTreeForComponent( context, component, nestedTreeHolder, widthSpec, heightSpec, nestedTreeHolder.getDiffNode()); // Previously set while traversing the holder's tree. nestedTree.setLastWidthSpec(widthSpec); nestedTree.setLastHeightSpec(heightSpec); nestedTree.setLastMeasuredHeight(nestedTree.getHeight()); nestedTree.setLastMeasuredWidth(nestedTree.getWidth()); } nestedTreeHolder.setNestedTree(nestedTree); } // This is checking only nested tree roots however it will be moved to check all the tree roots. InternalNode.assertContextSpecificStyleNotSet(nestedTree); return nestedTree; } /** * Create and measure a component with the given size specs. */ static InternalNode createAndMeasureTreeForComponent( ComponentContext c, Component component, int widthSpec, int heightSpec) { return createAndMeasureTreeForComponent(c, component, null, widthSpec, heightSpec, null); } private static InternalNode createAndMeasureTreeForComponent( ComponentContext c, Component component, InternalNode nestedTreeHolder, // This will be set only if we are resolving a nested tree. int widthSpec, int heightSpec, DiffNode diffTreeRoot) { // Account for the size specs in ComponentContext in case the tree is a NestedTree. final int previousWidthSpec = c.getWidthSpec(); final int previousHeightSpec = c.getHeightSpec(); final boolean hasNestedTreeHolder = nestedTreeHolder != null; c.setWidthSpec(widthSpec); c.setHeightSpec(heightSpec); if (hasNestedTreeHolder) { c.setTreeProps(nestedTreeHolder.getPendingTreeProps()); } final InternalNode root = createTree( component, c); if (hasNestedTreeHolder) { c.setTreeProps(null); } c.setWidthSpec(previousWidthSpec); c.setHeightSpec(previousHeightSpec); if (root == NULL_LAYOUT) { return root; } // If measuring a ComponentTree with a LayoutSpecWithSizeSpec at the root, the nested tree // holder argument will be null. if (hasNestedTreeHolder && isLayoutSpecWithSizeSpec(component)) { // Transfer information from the holder node to the nested tree root before measurement. nestedTreeHolder.copyInto(root); diffTreeRoot = nestedTreeHolder.getDiffNode(); } else if (root.getStyleDirection() == com.facebook.yoga.YogaDirection.INHERIT && LayoutState.isLayoutDirectionRTL(c)) { root.layoutDirection(YogaDirection.RTL); } measureTree( root, widthSpec, heightSpec, diffTreeRoot); return root; } static DiffNode createDiffNode(InternalNode node, DiffNode parent) { ComponentsSystrace.beginSection("diff_node_creation"); DiffNode diffNode = ComponentsPools.acquireDiffNode(); diffNode.setLastWidthSpec(node.getLastWidthSpec()); diffNode.setLastHeightSpec(node.getLastHeightSpec()); diffNode.setLastMeasuredWidth(node.getLastMeasuredWidth()); diffNode.setLastMeasuredHeight(node.getLastMeasuredHeight()); diffNode.setComponent(node.getComponent()); if (parent != null) { parent.addChild(diffNode); } ComponentsSystrace.endSection(); return diffNode; } boolean isCompatibleSpec(int widthSpec, int heightSpec) { final boolean widthIsCompatible = MeasureComparisonUtils.isMeasureSpecCompatible( mWidthSpec, widthSpec, mWidth); final boolean heightIsCompatible = MeasureComparisonUtils.isMeasureSpecCompatible( mHeightSpec, heightSpec, mHeight); return widthIsCompatible && heightIsCompatible; } boolean isCompatibleAccessibility() { return isAccessibilityEnabled(mAccessibilityManager) == mAccessibilityEnabled; } private static boolean isAccessibilityEnabled(AccessibilityManager accessibilityManager) { return accessibilityManager.isEnabled() && AccessibilityManagerCompat.isTouchExplorationEnabled(accessibilityManager); } /** * Traverses the layoutTree and the diffTree recursively. If a layoutNode has a compatible host * type {@link LayoutState#hostIsCompatible} it assigns the DiffNode to the layout node in order * to try to re-use the LayoutOutputs that will be generated by {@link * LayoutState#collectResults(InternalNode, LayoutState, DiffNode)}. If a layoutNode * component returns false when shouldComponentUpdate is called with the DiffNode Component it * also tries to re-use the old measurements and therefore marks as valid the cachedMeasures for * the whole component subtree. * * @param layoutNode the root of the LayoutTree * @param diffNode the root of the diffTree * * @return true if the layout node requires updating, false if it can re-use the measurements * from the diff node. */ static boolean applyDiffNodeToUnchangedNodes(InternalNode layoutNode, DiffNode diffNode) { // Root of the main tree or of a nested tree. final boolean isTreeRoot = layoutNode.getParent() == null; if (isLayoutSpecWithSizeSpec(layoutNode.getComponent()) && !isTreeRoot) { layoutNode.setDiffNode(diffNode); return true; } if (!hostIsCompatible(layoutNode, diffNode)) { return true; } layoutNode.setDiffNode(diffNode); final int layoutCount = layoutNode.getChildCount(); final int diffCount = diffNode.getChildCount(); // Layout node needs to be updated if: // - it has a different number of children. // - one of its children needs updating. // - the node itself declares that it needs updating. boolean shouldUpdate = layoutCount != diffCount; for (int i = 0; i < layoutCount && i < diffCount; i++) { // ensure that we always run for all children. boolean shouldUpdateChild = applyDiffNodeToUnchangedNodes( layoutNode.getChildAt(i), diffNode.getChildAt(i)); shouldUpdate |= shouldUpdateChild; } shouldUpdate |= shouldComponentUpdate(layoutNode, diffNode); if (!shouldUpdate) { applyDiffNodeToLayoutNode(layoutNode, diffNode); } return shouldUpdate; } /** * Copies the inter stage state (if any) from the DiffNode's component to the layout node's * component, and declares that the cached measures on the diff node are valid for the layout * node. */ private static void applyDiffNodeToLayoutNode(InternalNode layoutNode, DiffNode diffNode) { final Component component = layoutNode.getComponent(); if (component != null) { component.copyInterStageImpl(diffNode.getComponent()); } layoutNode.setCachedMeasuresValid(true); } /** * Returns true either if the two nodes have the same Component type or if both don't have a * Component. */ private static boolean hostIsCompatible(InternalNode node, DiffNode diffNode) { if (diffNode == null) { return false; } return isSameComponentType(node.getComponent(), diffNode.getComponent()); } private static boolean isSameComponentType(Component a, Component b) { if (a == b) { return true; } else if (a == null || b == null) { return false; } return a.getLifecycle().getClass().equals(b.getLifecycle().getClass()); } private static boolean shouldComponentUpdate(InternalNode layoutNode, DiffNode diffNode) { if (diffNode == null) { return true; } final Component component = layoutNode.getComponent(); if (component != null) { return component.getLifecycle().shouldComponentUpdate(component, diffNode.getComponent()); } return true; } boolean isCompatibleComponentAndSpec( int componentId, int widthSpec, int heightSpec) { return mComponent.getId() == componentId && isCompatibleSpec(widthSpec, heightSpec); } boolean isCompatibleSize(int width, int height) { return mWidth == width && mHeight == height; } boolean isComponentId(int componentId) { return mComponent.getId() == componentId; } int getMountableOutputCount() { return mMountableOutputs.size(); } LayoutOutput getMountableOutputAt(int index) { return mMountableOutputs.get(index); } ArrayList<LayoutOutput> getMountableOutputTops() { return mMountableOutputTops; } ArrayList<LayoutOutput> getMountableOutputBottoms() { return mMountableOutputBottoms; } int getVisibilityOutputCount() { return mVisibilityOutputs.size(); } VisibilityOutput getVisibilityOutputAt(int index) { return mVisibilityOutputs.get(index); } int getTestOutputCount() { return mTestOutputs == null ? 0 : mTestOutputs.size(); } TestOutput getTestOutputAt(int index) { return mTestOutputs == null ? null : mTestOutputs.get(index); } public DiffNode getDiffTree() { return mDiffTreeRoot; } int getWidth() { return mWidth; } int getHeight() { return mHeight; } /** * @return The id of the {@link ComponentTree} that generated this {@link LayoutState} */ int getComponentTreeId() { return mComponentTreeId; } /** * See {@link LayoutState#acquireRef} Call this when you are done using the reference to the * LayoutState. */ @ThreadSafe(enableChecks = false) void releaseRef() { int count = mReferenceCount.decrementAndGet(); if (count < 0) { throw new IllegalStateException("Trying to releaseRef a recycled LayoutState"); } if (count == 0) { mContext = null; mComponent = null; mWidth = 0; mHeight = 0; mCurrentX = 0; mCurrentY = 0; mCurrentHostMarker = -1; mCurrentHostOutputPosition = -1; mComponentTreeId = -1; mShouldDuplicateParentState = true; for (int i = 0, size = mMountableOutputs.size(); i < size; i++) { ComponentsPools.release(mMountableOutputs.get(i)); } mMountableOutputs.clear(); mMountableOutputTops.clear(); mMountableOutputBottoms.clear(); mOutputsIdToPositionMap.clear(); for (int i = 0, size = mVisibilityOutputs.size(); i < size; i++) { ComponentsPools.release(mVisibilityOutputs.get(i)); } mVisibilityOutputs.clear(); if (mTestOutputs != null) { for (int i = 0, size = mTestOutputs.size(); i < size; i++) { ComponentsPools.release(mTestOutputs.get(i)); } mTestOutputs.clear(); } mShouldGenerateDiffTree = false; mAccessibilityManager = null; mAccessibilityEnabled = false; if (mDiffTreeRoot != null) { ComponentsPools.release(mDiffTreeRoot); mDiffTreeRoot = null; } mLayoutStateOutputIdCalculator.clear(); if (mTransitionContext != null) { ComponentsPools.release(mTransitionContext); mTransitionContext = null; } // This should only ever be true in non-release builds as we need this for Stetho integration. // In release builds the node tree is released in calculateLayout(). if (mLayoutRoot != null) { releaseNodeTree(mLayoutRoot, false /* isNestedTree */); mLayoutRoot = null; } ComponentsPools.release(this); } } /** * The lifecycle of LayoutState is generally controlled by ComponentTree. Since sometimes we need * an old LayoutState to be passed to a new LayoutState to implement Tree diffing, We use * reference counting to avoid releasing a LayoutState that is not used by ComponentTree anymore * but could be used by another LayoutState. The rule is that whenever you need to pass the * LayoutState outside of ComponentTree, you acquire a reference and then you release it as soon * as you are done with it * * @return The same LayoutState instance with an higher reference count. */ LayoutState acquireRef() { if (mReferenceCount.getAndIncrement() == 0) { throw new IllegalStateException("Trying to use a released LayoutState"); } return this; } void init(ComponentContext context) { mContext = context; mStateHandler = mContext.getStateHandler();
package com.facebook.litho; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.pm.ApplicationInfo; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.litho.displaylist.DisplayListException; import com.facebook.litho.reference.BorderColorDrawableReference; import com.facebook.litho.reference.Reference; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.M; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec; import static com.facebook.litho.Component.isMountSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentContext.NULL_LAYOUT; import static com.facebook.litho.ComponentLifecycle.MountType.NONE; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS; import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT; import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED; import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE; import static com.facebook.litho.MountState.ROOT_HOST_ID; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.litho.SizeSpec.EXACTLY; /** * The main role of {@link LayoutState} is to hold the output of layout calculation. This includes * mountable outputs and visibility outputs. A centerpiece of the class is {@link * #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs * based on the provided {@link InternalNode} for later use in {@link MountState}. */ class LayoutState { static final Comparator<LayoutOutput> sTopsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsTop = lhs.getBounds().top; final int rhsTop = rhs.getBounds().top; return lhsTop < rhsTop ? -1 : lhsTop > rhsTop ? 1 // Hosts should be higher for tops so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? -1 : 1; } }; static final Comparator<LayoutOutput> sBottomsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsBottom = lhs.getBounds().bottom; final int rhsBottom = rhs.getBounds().bottom; return lhsBottom < rhsBottom ? -1 : lhsBottom > rhsBottom ? 1 // Hosts should be lower for bottoms so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? 1 : -1; } }; private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled}; private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{}; private ComponentContext mContext; private TransitionContext mTransitionContext; private Component<?> mComponent; private int mWidthSpec; private int mHeightSpec; private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8); private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8); private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8); private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator; private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>(); private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>(); private final List<TestOutput> mTestOutputs; private InternalNode mLayoutRoot; private DiffNode mDiffTreeRoot; // Reference count will be initialized to 1 in init(). private final AtomicInteger mReferenceCount = new AtomicInteger(-1); private int mWidth; private int mHeight; private int mCurrentX; private int mCurrentY; private int mCurrentLevel = 0; // Holds the current host marker in the layout tree. private long mCurrentHostMarker = -1; private int mCurrentHostOutputPosition = -1; private boolean mShouldDuplicateParentState = true; private boolean mShouldGenerateDiffTree = false; private int mComponentTreeId = -1; private AccessibilityManager mAccessibilityManager; private boolean mAccessibilityEnabled = false; private StateHandler mStateHandler; LayoutState() { mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator(); mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null; } /** * Acquires a new layout output for the internal node and its associated component. It returns * null if there's no component associated with the node as the mount pass only cares about nodes * that will potentially mount content into the component host. */ @Nullable private static LayoutOutput createGenericLayoutOutput( InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); // Skip empty nodes and layout specs because they don't mount anything. if (component == null || component.getLifecycle().getMountType() == NONE) { return null; } return createLayoutOutput( component, layoutState, node, true /* useNodePadding */, node.getImportantForAccessibility(), layoutState.mShouldDuplicateParentState); } private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) { final LayoutOutput hostOutput = createLayoutOutput( HostComponent.create(), layoutState, node, false /* useNodePadding */, node.getImportantForAccessibility(), node.isDuplicateParentStateEnabled()); hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey()); return hostOutput; } private static LayoutOutput createDrawableLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node) { return createLayoutOutput( component, layoutState, node, false /* useNodePadding */, IMPORTANT_FOR_ACCESSIBILITY_NO, layoutState.mShouldDuplicateParentState); } private static LayoutOutput createLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node, boolean useNodePadding, int importantForAccessibility, boolean duplicateParentState) { final boolean isMountViewSpec = isMountViewSpec(component); final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput(); layoutOutput.setComponent(component); layoutOutput.setImportantForAccessibility(importantForAccessibility); // The mount operation will need both the marker for the target host and its matching // parent host to ensure the correct hierarchy when nesting the host views. layoutOutput.setHostMarker(layoutState.mCurrentHostMarker); if (layoutState.mCurrentHostOutputPosition >= 0) { final LayoutOutput hostOutput = layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition); final Rect hostBounds = hostOutput.getBounds(); layoutOutput.setHostTranslationX(hostBounds.left); layoutOutput.setHostTranslationY(hostBounds.top); } int l = layoutState.mCurrentX + node.getX(); int t = layoutState.mCurrentY + node.getY(); int r = l + node.getWidth(); int b = t + node.getHeight(); final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0; final int paddingTop = useNodePadding ? node.getPaddingTop() : 0; final int paddingRight = useNodePadding ? node.getPaddingRight() : 0; final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0; // View mount specs are able to set their own attributes when they're mounted. // Non-view specs (drawable and layout) always transfer their view attributes // to their respective hosts. // Moreover, if the component mounts a view, then we apply padding to the view itself later on. // Otherwise, apply the padding to the bounds of the layout output. if (isMountViewSpec) { layoutOutput.setNodeInfo(node.getNodeInfo()); // Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput. final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection()); viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b); layoutOutput.setViewNodeInfo(viewNodeInfo); viewNodeInfo.release(); } else { l += paddingLeft; t += paddingTop; r -= paddingRight; b -= paddingBottom; } layoutOutput.setBounds(l, t, r, b); int flags = 0; if (duplicateParentState) { flags |= FLAG_DUPLICATE_PARENT_STATE; } layoutOutput.setFlags(flags); return layoutOutput; } /** * Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information * stored in the {@link InternalNode}. */ private static VisibilityOutput createVisibilityOutput( InternalNode node, LayoutState layoutState) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final EventHandler visibleHandler = node.getVisibleHandler(); final EventHandler focusedHandler = node.getFocusedHandler(); final EventHandler fullImpressionHandler = node.getFullImpressionHandler(); final EventHandler invisibleHandler = node.getInvisibleHandler(); final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput(); final Component<?> handlerComponent; // Get the component from the handler that is not null. If more than one is not null, then // getting the component from any of them works. if (visibleHandler != null) { handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher; } else if (focusedHandler != null) { handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher; } else if (fullImpressionHandler != null) { handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher; } else { handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher; } visibilityOutput.setComponent(handlerComponent); visibilityOutput.setBounds(l, t, r, b); visibilityOutput.setVisibleEventHandler(visibleHandler); visibilityOutput.setFocusedEventHandler(focusedHandler); visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler); visibilityOutput.setInvisibleEventHandler(invisibleHandler); return visibilityOutput; } private static TestOutput createTestOutput( InternalNode node, LayoutState layoutState, LayoutOutput layoutOutput) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final TestOutput output = ComponentsPools.acquireTestOutput(); output.setTestKey(node.getTestKey()); output.setBounds(l, t, r, b); output.setHostMarker(layoutState.mCurrentHostMarker); if (layoutOutput != null) { output.setLayoutOutputId(layoutOutput.getId()); } return output; } private static boolean isLayoutDirectionRTL(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if ((SDK_INT >= JELLY_BEAN_MR1) && (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) { int layoutDirection = getLayoutDirection(context); return layoutDirection == View.LAYOUT_DIRECTION_RTL; } return false; } @TargetApi(JELLY_BEAN_MR1) private static int getLayoutDirection(Context context) { return context.getResources().getConfiguration().getLayoutDirection(); } /** * Determine if a given {@link InternalNode} within the context of a given {@link LayoutState} * requires to be wrapped inside a view. * * @see #needsHostView(InternalNode, LayoutState) */ private static boolean hasViewContent(InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); final NodeInfo nodeInfo = node.getNodeInfo(); final boolean implementsAccessibility = (nodeInfo != null && nodeInfo.hasAccessibilityHandlers()) || (component != null && component.getLifecycle().implementsAccessibility()); final int importantForAccessibility = node.getImportantForAccessibility(); // A component has accessibility content if: // 1. Accessibility is currently enabled. // 2. Accessibility hasn't been explicitly disabled on it // i.e. IMPORTANT_FOR_ACCESSIBILITY_NO. // 3. Any of these conditions are true: // - It implements accessibility support. // - It has a content description. // - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES // or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS. // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host // so that such flag is applied in the resulting view hierarchy after the component // tree is mounted. Click handling is also considered accessibility content but // this is already covered separately i.e. click handler is not null. final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled && importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO && (implementsAccessibility || (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription())) || importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO); final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers()); final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null); final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null); final boolean isFocusableSetTrue = (nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE); return hasTouchEventHandlers || hasViewTag || hasViewTags || hasAccessibilityContent || isFocusableSetTrue; } /** * Collects layout outputs and release the layout tree. The layout outputs hold necessary * information to be used by {@link MountState} to mount components into a {@link ComponentHost}. * <p/> * Whenever a component has view content (view tags, click handler, etc), a new host 'marker' * is added for it. The mount pass will use the markers to decide which host should be used * for each layout output. The root node unconditionally generates a layout output corresponding * to the root host. * <p/> * The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts * will be created at the right order when mounting. The host markers will be define which host * each mounted artifacts will be attached to. * <p/> * At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled * will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the * host and the contents (including background/foreground). In all other cases instead we'll only * try to re-use the hosts. In some cases the host's structure might change between two updates * even if the component is of the same type. This can happen for example when a click listener is * added. To avoid trying to re-use the wrong host type we explicitly check that after all the * children for a subtree have been added (this is when the actual host type is resolved). If the * host type changed compared to the one in the DiffNode we need to refresh the ids for the whole * subtree in order to ensure that the MountState will unmount the subtree and mount it again on * the correct host. * <p/> * * @param node InternalNode to process. * @param layoutState the LayoutState currently operating. * @param parentDiffNode whether this method also populates the diff tree and assigns the root * to mDiffTreeRoot. */ private static void collectResults( InternalNode node, LayoutState layoutState, DiffNode parentDiffNode) { if (node.hasNewLayout()) { node.markLayoutSeen(); } final Component<?> component = node.getComponent(); // Early return if collecting results of a node holding a nested tree. if (node.isNestedTreeHolder()) { // If the nested tree is defined, it has been resolved during a measure call during // layout calculation. InternalNode nestedTree = resolveNestedTree( node, SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY), SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY)); if (nestedTree == NULL_LAYOUT) { return; } // Account for position of the holder node. layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); collectResults(nestedTree, layoutState, parentDiffNode); layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); return; } final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree; final DiffNode currentDiffNode = node.getDiffNode(); final boolean shouldUseCachedOutputs = isMountSpec(component) && currentDiffNode != null; final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid(); final DiffNode diffNode; if (shouldGenerateDiffTree) { diffNode = createDiffNode(node, parentDiffNode); if (parentDiffNode == null) { layoutState.mDiffTreeRoot = diffNode; } } else { diffNode = null; } final boolean needsHostView = needsHostView(node, layoutState); final long currentHostMarker = layoutState.mCurrentHostMarker; final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition; int hostLayoutPosition = -1; // 1. Insert a host LayoutOutput if we have some interactive content to be attached to. if (needsHostView) { hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode); layoutState.mCurrentLevel++; layoutState.mCurrentHostMarker = layoutState.mMountableOutputs.get(hostLayoutPosition).getId(); layoutState.mCurrentHostOutputPosition = hostLayoutPosition; } // We need to take into account flattening when setting duplicate parent state. The parent after // flattening may no longer exist. Therefore the value of duplicate parent state should only be // true if the path between us (inclusive) and our inner/root host (exclusive) all are // duplicate parent state. final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState; layoutState.mShouldDuplicateParentState = needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled()); // Generate the layoutOutput for the given node. final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState); if (layoutOutput != null) { final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( layoutOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_CONTENT, previousId, isCachedOutputUpdated); } // If we don't need to update this output we can safely re-use the display list from the // previous output. if (isCachedOutputUpdated) { layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList()); } // 2. Add background if defined. final Reference<? extends Drawable> background = node.getBackground(); if (background != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) { layoutOutput.getViewNodeInfo().setBackground(background); } else { final LayoutOutput convertBackground = (currentDiffNode != null) ? currentDiffNode.getBackground() : null; final LayoutOutput backgroundOutput = addDrawableComponent( node, layoutState, convertBackground, background, LayoutOutput.TYPE_BACKGROUND); if (diffNode != null) { diffNode.setBackground(backgroundOutput); } } } // 3. Now add the MountSpec (either View or Drawable) to the Outputs. if (isMountSpec(component)) { // Notify component about its final size. component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component); addMountableOutput(layoutState, layoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, layoutOutput, layoutState.mMountableOutputs.size() - 1); if (diffNode != null) { diffNode.setContent(layoutOutput); } } // 4. Add border color if defined. if (node.shouldDrawBorders()) { final LayoutOutput convertBorder = (currentDiffNode != null) ? currentDiffNode.getBorder() : null; final LayoutOutput borderOutput = addDrawableComponent( node, layoutState, convertBorder, getBorderColorDrawable(node), LayoutOutput.TYPE_BORDER); if (diffNode != null) { diffNode.setBorder(borderOutput); } } // 5. Extract the Transitions. if (SDK_INT >= ICE_CREAM_SANDWICH) { if (node.getTransitionKey() != null) { layoutState .getOrCreateTransitionContext() .addTransitionKey(node.getTransitionKey()); } if (component != null) { Transition transition = component.getLifecycle().onLayoutTransition( layoutState.mContext, component); if (transition != null) { layoutState.getOrCreateTransitionContext().add(transition); } } } layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); // We must process the nodes in order so that the layout state output order is correct. for (int i = 0, size = node.getChildCount(); i < size; i++) { collectResults( node.getChildAt(i), layoutState, diffNode); } layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); // 6. Add foreground if defined. final Reference<? extends Drawable> foreground = node.getForeground(); if (foreground != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) { layoutOutput.getViewNodeInfo().setForeground(foreground); } else { final LayoutOutput convertForeground = (currentDiffNode != null) ? currentDiffNode.getForeground() : null; final LayoutOutput foregroundOutput = addDrawableComponent( node, layoutState, convertForeground, foreground, LayoutOutput.TYPE_FOREGROUND); if (diffNode != null) { diffNode.setForeground(foregroundOutput); } } } // 7. Add VisibilityOutputs if any visibility-related event handlers are present. if (node.hasVisibilityHandlers()) { final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState); final long previousId = shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId( visibilityOutput, layoutState.mCurrentLevel, previousId); layoutState.mVisibilityOutputs.add(visibilityOutput); if (diffNode != null) { diffNode.setVisibilityOutput(visibilityOutput); } } // 8. If we're in a testing environment, maintain an additional data structure with // information about nodes that we can query later. if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) { final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput); layoutState.mTestOutputs.add(testOutput); } // All children for the given host have been added, restore the previous // host, level, and duplicate parent state value in the recursive queue. if (layoutState.mCurrentHostMarker != currentHostMarker) { layoutState.mCurrentHostMarker = currentHostMarker; layoutState.mCurrentHostOutputPosition = currentHostOutputPosition; layoutState.mCurrentLevel } layoutState.mShouldDuplicateParentState = shouldDuplicateParentState; Collections.sort(layoutState.mMountableOutputTops, sTopsComparator); Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator); } private static void calculateAndSetHostOutputIdAndUpdateState( InternalNode node, LayoutOutput hostOutput, LayoutState layoutState, boolean isCachedOutputUpdated) { if (layoutState.isLayoutRoot(node)) { // The root host (ComponentView) always has ID 0 and is unconditionally // set as dirty i.e. no need to use shouldComponentUpdate(). hostOutput.setId(ROOT_HOST_ID); // Special case where the host marker of the root host is pointing to itself. hostOutput.setHostMarker(ROOT_HOST_ID); hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY); } else { layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( hostOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_HOST, -1, isCachedOutputUpdated); } } private static LayoutOutput addDrawableComponent( InternalNode node, LayoutState layoutState, LayoutOutput recycle, Reference<? extends Drawable> reference, @LayoutOutput.LayoutOutputType int type) { final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference); drawableComponent.setScopedContext( ComponentContext.withComponentScope(node.getContext(), drawableComponent)); final boolean isOutputUpdated; if (recycle != null) { isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate( recycle.getComponent(), drawableComponent); } else { isOutputUpdated = false; } final long previousId = recycle != null ? recycle.getId() : -1; final LayoutOutput output = addDrawableLayoutOutput( drawableComponent, layoutState, node, type, previousId, isOutputUpdated); return output; } private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) { if (!node.shouldDrawBorders()) { throw new RuntimeException("This node does not support drawing border color"); } return BorderColorDrawableReference.create(node.getContext()) .color(node.getBorderColor()) .borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT))) .borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP))) .borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT))) .borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM))) .build(); } private static void addLayoutOutputIdToPositionsMap( LongSparseArray outputsIdToPositionMap, LayoutOutput layoutOutput, int position) { if (outputsIdToPositionMap != null) { outputsIdToPositionMap.put(layoutOutput.getId(), position); } } private static LayoutOutput addDrawableLayoutOutput( Component<DrawableComponent> drawableComponent, LayoutState layoutState, InternalNode node, @LayoutOutput.LayoutOutputType int layoutOutputType, long previousId, boolean isCachedOutputUpdated) { drawableComponent.getLifecycle().onBoundsDefined( layoutState.mContext, node, drawableComponent); final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput( drawableComponent, layoutState, node); layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( drawableLayoutOutput, layoutState.mCurrentLevel, layoutOutputType, previousId, isCachedOutputUpdated); addMountableOutput(layoutState, drawableLayoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, drawableLayoutOutput, layoutState.mMountableOutputs.size() - 1); return drawableLayoutOutput; } static void releaseNodeTree(InternalNode node, boolean isNestedTree) { if (node == NULL_LAYOUT) { throw new IllegalArgumentException("Cannot release a null node tree"); } for (int i = node.getChildCount() - 1; i >= 0; i final InternalNode child = node.getChildAt(i); if (isNestedTree && node.hasNewLayout()) { node.markLayoutSeen(); } // A node must be detached from its parent *before* being released (otherwise the parent would // retain a reference to a node that may get re-used by another thread) node.removeChildAt(i); releaseNodeTree(child, isNestedTree); } if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) { releaseNodeTree(node.getNestedTree(), true); } ComponentsPools.release(node); } /** * If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an * HostComponent in the Outputs such as it will be used as a HostView at Mount time. View * MountSpec are not allowed. * * @return The position the HostLayoutOutput was inserted. */ private static int addHostLayoutOutput( InternalNode node, LayoutState layoutState, DiffNode diffNode) { final Component<?> component = node.getComponent(); // Only the root host is allowed to wrap view mount specs as a layout output // is unconditionally added for it. if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) { throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View"); } final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node); // The component of the hostLayoutOutput will be set later after all the // children got processed. addMountableOutput(layoutState, hostLayoutOutput); final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1; if (diffNode != null) { diffNode.setHost(hostLayoutOutput); } calculateAndSetHostOutputIdAndUpdateState( node, hostLayoutOutput, layoutState, false); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, hostLayoutOutput, hostOutputPosition); return hostOutputPosition; } static <T extends ComponentLifecycle> LayoutState calculate( ComponentContext c, Component<T> component, int componentTreeId, int widthSpec, int heightSpec, boolean shouldGenerateDiffTree, DiffNode previousDiffTreeRoot) { // Detect errors internal to components component.markLayoutStarted(); LayoutState layoutState = ComponentsPools.acquireLayoutState(c); layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree; layoutState.mComponentTreeId = componentTreeId; layoutState.mAccessibilityManager = (AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE); layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager); layoutState.mComponent = component; layoutState.mWidthSpec = widthSpec; layoutState.mHeightSpec = heightSpec; component.applyStateUpdates(c); final InternalNode root = createAndMeasureTreeForComponent( component.getScopedContext(), component, null, // nestedTreeHolder is null because this is measuring the root component tree. widthSpec, heightSpec, previousDiffTreeRoot); switch (SizeSpec.getMode(widthSpec)) { case SizeSpec.EXACTLY: layoutState.mWidth = SizeSpec.getSize(widthSpec); break; case SizeSpec.AT_MOST: layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mWidth = root.getWidth(); break; } switch (SizeSpec.getMode(heightSpec)) { case SizeSpec.EXACTLY: layoutState.mHeight = SizeSpec.getSize(heightSpec); break; case SizeSpec.AT_MOST: layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mHeight = root.getHeight(); break; } layoutState.mLayoutStateOutputIdCalculator.clear(); // Reset markers before collecting layout outputs. layoutState.mCurrentHostMarker = -1; final ComponentsLogger logger = c.getLogger(); if (root == NULL_LAYOUT) { return layoutState; } layoutState.mLayoutRoot = root; ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName()); if (logger != null) { logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag()); } collectResults(root, layoutState, null); if (logger != null) { logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS); } ComponentsSystrace.endSection(); if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) { releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */); layoutState.mLayoutRoot = null; } if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) { collectDisplayLists(layoutState); } return layoutState; } void preAllocateMountContent() { if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) { for (int i = 0, size = mMountableOutputs.size(); i < size; i++) { final Component component = mMountableOutputs.get(i).getComponent(); if (Component.isMountViewSpec(component)) { final ComponentLifecycle lifecycle = component.getLifecycle(); if (!lifecycle.hasBeenPreallocated()) { final int poolSize = lifecycle.poolSize(); int insertedCount = 0; while (insertedCount < poolSize && ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) { ComponentsPools.release( mContext, lifecycle, lifecycle.createMountContent(mContext)); insertedCount++; } lifecycle.setWasPreallocated(); } } } } } private static void collectDisplayLists(LayoutState layoutState) { final Rect rect = new Rect(); final ComponentContext context = layoutState.mContext; final Activity activity = findActivityInContext(context); if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) { return; } for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) { final LayoutOutput output = layoutState.getMountableOutputAt(i); final Component component = output.getComponent(); final ComponentLifecycle lifecycle = component.getLifecycle(); if (lifecycle.shouldUseDisplayList()) { output.getMountBounds(rect); if (output.getDisplayList() != null && output.getDisplayList().isValid()) { // This output already has a valid DisplayList from diffing. No need to re-create it. // Just update its bounds. try { output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom); continue; } catch (DisplayListException e) { // Nothing to do here. } } final DisplayList displayList = DisplayList.createDisplayList( lifecycle.getClass().getSimpleName()); if (displayList != null) { Drawable drawable = (Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId()); if (drawable == null) { drawable = (Drawable) lifecycle.createMountContent(context); } final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output); boolean isStateEnabled = false; if (clickableOutput != null && clickableOutput.getNodeInfo() != null) { final NodeInfo nodeInfo = clickableOutput.getNodeInfo(); if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) { isStateEnabled = true; } } if (isStateEnabled) { drawable.setState(DRAWABLE_STATE_ENABLED); } else { drawable.setState(DRAWABLE_STATE_NOT_ENABLED); } lifecycle.mount( context, drawable, component); lifecycle.bind(context, drawable, component); output.getMountBounds(rect); drawable.setBounds(0, 0, rect.width(), rect.height()); try { final Canvas canvas = displayList.start(rect.width(), rect.height()); drawable.draw(canvas); displayList.end(canvas); displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom); output.setDisplayList(displayList); } catch (DisplayListException e) { // Display list creation failed. Make sure the DisplayList for this output is set // to null. output.setDisplayList(null); } lifecycle.unbind(context, drawable, component); lifecycle.unmount(context, drawable, component); ComponentsPools.release(context, lifecycle, drawable); } } } } private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) { if (output.getId() == ROOT_HOST_ID) { return output; } if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) { final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker()); if (parentPosition >= 0) { final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition); if (parent == null) { return null; } return findInteractiveRoot(layoutState, parent); } return null; } return output; } private static boolean isActivityDestroyed(Activity activity) { if (SDK_INT >= JELLY_BEAN_MR1) { return activity.isDestroyed(); } return false; } private static Activity findActivityInContext(Context context) { if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return findActivityInContext(((ContextWrapper) context).getBaseContext()); } return null; } @VisibleForTesting static <T extends ComponentLifecycle> InternalNode createTree( Component<T> component, ComponentContext context) { final ComponentsLogger logger = context.getLogger(); if (logger != null) { logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag()); logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName()); } final InternalNode root = (InternalNode) component.getLifecycle().createLayout( context, component, true /* resolveNestedTree */); if (logger != null) { logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS);
package com.github.dozedoff.commonj.gui; import java.text.DateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.JTextArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class outputs Strings sent to it to a TextField. The class also maintains the TextFied, limiting the amount of text displayed on it. */ public class Log { static private JTextArea logArea; static private int logNr = 0; static private final Logger logger = LoggerFactory.getLogger(Log.class); /** * Set the {@link JTextArea} that will be used for logging. * * @param logArea * text area to use */ public static void setLogArea(JTextArea logArea) { Log.logArea = logArea; } /** * Set the number of log lines. * * @param nr * number to set */ public static void setLogNr(int nr) { Log.logNr = nr; } /** * Clear the log, removing all text from the {@link JTextArea} and setting * the line count to 0. */ public static void clear() { Log.logArea.setText(""); Log.logNr = 0; } /** * Get the number of displayed log entries. * * @return number of log entries */ public static int getLogNr() { return logNr; } /** * Will output a message to the GUI log. The message will have the current date and time as a prefix. * * @param add * message to add to log */ public static void add(String add) { if (logArea == null) { logger.warn("No output textfield set for GUI log"); return; } Calendar cal = new GregorianCalendar(); DateFormat df; df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); logArea.append(df.format(cal.getTime()) + " " + add + "\n"); if (logNr > 50) { logArea.replaceRange("", 0, 1 + logArea.getText().indexOf("\n")); } else { logNr++; // to avoid overflow } // logArea.setCaretPosition(logArea.getText().length()); } }
package com.hankcs.hanlp.model.crf; import com.hankcs.hanlp.collection.trie.DoubleArrayTrie; import com.hankcs.hanlp.collection.trie.ITrie; import com.hankcs.hanlp.corpus.io.ByteArray; import com.hankcs.hanlp.corpus.io.ICacheAble; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.utility.Predefine; import com.hankcs.hanlp.utility.TextUtility; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.util.*; import static com.hankcs.hanlp.utility.Predefine.BIN_EXT; import static com.hankcs.hanlp.utility.Predefine.logger; /** * @author hankcs */ public class CRFModel implements ICacheAble { Map<String, Integer> tag2id; protected String[] id2tag; ITrie<FeatureFunction> featureFunctionTrie; List<FeatureTemplate> featureTemplateList; /** * tagBiGram Feature */ protected double[][] matrix; public CRFModel() { featureFunctionTrie = new DoubleArrayTrie<FeatureFunction>(); } /** * trie * @param featureFunctionTrie */ public CRFModel(ITrie<FeatureFunction> featureFunctionTrie) { this.featureFunctionTrie = featureFunctionTrie; } protected void onLoadTxtFinished() { // do nothing } /** * TxtCRF++ * @param path * @param instance CRFModel * @return */ public static CRFModel loadTxt(String path, CRFModel instance) { CRFModel CRFModel = instance; // bin if (CRFModel.load(ByteArray.createByteArray(path + Predefine.BIN_EXT))) return CRFModel; IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(path); if (!lineIterator.hasNext()) return null; logger.info(lineIterator.next()); // verson logger.info(lineIterator.next()); // cost-factor int maxid = Integer.parseInt(lineIterator.next().substring("maxid:".length()).trim()); logger.info(lineIterator.next()); // xsize lineIterator.next(); // blank String line; int id = 0; CRFModel.tag2id = new HashMap<String, Integer>(); while ((line = lineIterator.next()).length() != 0) { CRFModel.tag2id.put(line, id); ++id; } CRFModel.id2tag = new String[CRFModel.tag2id.size()]; final int size = CRFModel.id2tag.length; for (Map.Entry<String, Integer> entry : CRFModel.tag2id.entrySet()) { CRFModel.id2tag[entry.getValue()] = entry.getKey(); } TreeMap<String, FeatureFunction> featureFunctionMap = new TreeMap<String, FeatureFunction>(); // trie List<FeatureFunction> featureFunctionList = new LinkedList<FeatureFunction>(); CRFModel.featureTemplateList = new LinkedList<FeatureTemplate>(); while ((line = lineIterator.next()).length() != 0) { if (!"B".equals(line)) { FeatureTemplate featureTemplate = FeatureTemplate.create(line); CRFModel.featureTemplateList.add(featureTemplate); } else { CRFModel.matrix = new double[size][size]; } } if (CRFModel.matrix != null) { lineIterator.next(); // 0 B } while ((line = lineIterator.next()).length() != 0) { String[] args = line.split(" ", 2); char[] charArray = args[1].toCharArray(); FeatureFunction featureFunction = new FeatureFunction(charArray, size); featureFunctionMap.put(args[1], featureFunction); featureFunctionList.add(featureFunction); } if (CRFModel.matrix != null) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { CRFModel.matrix[i][j] = Double.parseDouble(lineIterator.next()); } } } for (FeatureFunction featureFunction : featureFunctionList) { for (int i = 0; i < size; i++) { featureFunction.w[i] = Double.parseDouble(lineIterator.next()); } } if (lineIterator.hasNext()) { logger.warning("" + path); } lineIterator.close(); logger.info("trie"); CRFModel.featureFunctionTrie.build(featureFunctionMap); // bin try { logger.info("" + path + Predefine.BIN_EXT); DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path + Predefine.BIN_EXT)); CRFModel.save(out); out.close(); } catch (Exception e) { logger.warning("" + path + Predefine.BIN_EXT + "" + TextUtility.exceptionToString(e)); } CRFModel.onLoadTxtFinished(); return CRFModel; } /** * * * @param table */ public void tag(Table table) { int size = table.size(); if (size == 0) return; int tagSize = id2tag.length; double[][] net = new double[size][tagSize]; for (int i = 0; i < size; ++i) { LinkedList<double[]> scoreList = computeScoreList(table, i); for (int tag = 0; tag < tagSize; ++tag) { net[i][tag] = computeScore(scoreList, tag); } } if (size == 1) { double maxScore = -1e10; int bestTag = 0; for (int tag = 0; tag < net[0].length; ++tag) { if (net[0][tag] > maxScore) { maxScore = net[0][tag]; bestTag = tag; } } table.setLast(0, id2tag[bestTag]); return; } int[][] from = new int[size][tagSize]; double[][] maxScoreAt = new double[2][tagSize]; System.arraycopy(net[0], 0, maxScoreAt[0], 0, tagSize); // preI=0, maxScoreAt[preI][pre] = net[0][pre] int curI = 0; for (int i = 1; i < size; ++i) { curI = i & 1; int preI = 1 - curI; for (int now = 0; now < tagSize; ++now) { double maxScore = -1e10; for (int pre = 0; pre < tagSize; ++pre) { double score = maxScoreAt[preI][pre] + matrix[pre][now] + net[i][now]; if (score > maxScore) { maxScore = score; from[i][now] = pre; maxScoreAt[curI][now] = maxScore; } } net[i][now] = maxScore; } } double maxScore = -1e10; int maxTag = 0; for (int tag = 0; tag < tagSize; ++tag) { if (maxScoreAt[curI][tag] > maxScore) { maxScore = maxScoreAt[curI][tag]; maxTag = tag; } } table.setLast(size - 1, id2tag[maxTag]); maxTag = from[size - 1][maxTag]; for (int i = size - 2; i > 0; --i) { table.setLast(i, id2tag[maxTag]); maxTag = from[i][maxTag]; } table.setLast(0, id2tag[maxTag]); } /** * * @param table * @param current * @return */ protected LinkedList<double[]> computeScoreList(Table table, int current) { LinkedList<double[]> scoreList = new LinkedList<double[]>(); for (FeatureTemplate featureTemplate : featureTemplateList) { char[] o = featureTemplate.generateParameter(table, current); FeatureFunction featureFunction = featureFunctionTrie.get(o); if (featureFunction == null) continue; scoreList.add(featureFunction.w); } return scoreList; } /** * tag * * @param scoreList * @param tag * @return */ protected static double computeScore(LinkedList<double[]> scoreList, int tag) { double score = 0; for (double[] w : scoreList) { score += w[tag]; } return score; } @Override public void save(DataOutputStream out) throws Exception { out.writeInt(id2tag.length); for (String tag : id2tag) { out.writeUTF(tag); } FeatureFunction[] valueArray = featureFunctionTrie.getValueArray(new FeatureFunction[0]); out.writeInt(valueArray.length); for (FeatureFunction featureFunction : valueArray) { featureFunction.save(out); } featureFunctionTrie.save(out); out.writeInt(featureTemplateList.size()); for (FeatureTemplate featureTemplate : featureTemplateList) { featureTemplate.save(out); } if (matrix != null) { out.writeInt(matrix.length); for (double[] line : matrix) { for (double v : line) { out.writeDouble(v); } } } else { out.writeInt(0); } } @Override public boolean load(ByteArray byteArray) { if (byteArray == null) return false; try { int size = byteArray.nextInt(); id2tag = new String[size]; tag2id = new HashMap<String, Integer>(size); for (int i = 0; i < id2tag.length; i++) { id2tag[i] = byteArray.nextUTF(); tag2id.put(id2tag[i], i); } FeatureFunction[] valueArray = new FeatureFunction[byteArray.nextInt()]; for (int i = 0; i < valueArray.length; i++) { valueArray[i] = new FeatureFunction(); valueArray[i].load(byteArray); } featureFunctionTrie.load(byteArray, valueArray); size = byteArray.nextInt(); featureTemplateList = new ArrayList<FeatureTemplate>(size); for (int i = 0; i < size; ++i) { FeatureTemplate featureTemplate = new FeatureTemplate(); featureTemplate.load(byteArray); featureTemplateList.add(featureTemplate); } size = byteArray.nextInt(); if (size == 0) return true; matrix = new double[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { matrix[i][j] = byteArray.nextDouble(); } } } catch (Exception e) { logger.warning("\n" + TextUtility.exceptionToString(e)); return false; } return true; } /** * TxtCRF++<br> * path.bin * @param path * @return */ public static CRFModel loadTxt(String path) { return loadTxt(path, new CRFModel(new DoubleArrayTrie<FeatureFunction>())); } /** * CRF++<br> * txt * @param path txt.txt.bintxt.bin * @return */ public static CRFModel load(String path) { CRFModel model = loadBin(path + BIN_EXT); if (model != null) return model; return loadTxt(path, new CRFModel(new DoubleArrayTrie<FeatureFunction>())); } /** * BinCRF++<br> * BinCRF++,HanLPCRF++ * @param path * @return */ public static CRFModel loadBin(String path) { ByteArray byteArray = ByteArray.createByteArray(path); if (byteArray == null) return null; CRFModel model = new CRFModel(); if (model.load(byteArray)) return model; return null; } /** * tagID * @param tag * @return */ public Integer getTagId(String tag) { return tag2id.get(tag); } }
package com.laxture.lib.util; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Environment; import android.os.FileObserver; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.widget.Toast; import com.laxture.lib.R; import com.laxture.lib.RuntimeContext; import com.laxture.lib.cache.men.BitmapCache; import java.io.File; import java.util.Vector; public class CameraLauncher { private static final String PHOTO_FILE = "PhotoFile"; private static final String OUTPUT_DIR = "OutputDir"; private static final String OUTPUT_FILE = "OutputFile"; private static final String WIDTH_LIMIT = "WidthLimit"; private static final String HEIGHT_LIMIT = "HeightLimit"; private static final String QUALITY = "Quality"; private Activity mActivity; private Fragment mFragment; private CameraLauncherListener mCameraLauncherListener; public File mPhotoFile; public static final int DEFAULT_CAPTURED_QUALITY = 85; public File mOutputFile; public void setOutputFile(File file) { mOutputFile = file; } public File mOutputDir; public void setOutputDir(File file) { mOutputDir = file; } private int mWidthLimit; public void setWidthLimit(int widthLimit) { mWidthLimit = widthLimit; } public int getWidthLimit() { return mWidthLimit > 0 ? mWidthLimit : RuntimeContext.getConfig().getMaxCaptureImageSize(); } private int mHeightLimit; public void setHeightLimit(int heightLimit) { mHeightLimit = heightLimit; } public int getHeightLimit() { return mHeightLimit > 0 ? mHeightLimit : RuntimeContext.getConfig().getMaxCaptureImageSize(); } private int mQuality; public void setQuality(int quality) { mQuality = quality; } public int getQuality() { return mQuality > 0 ? mQuality : DEFAULT_CAPTURED_QUALITY; } private String mCameraRollObservingPath = Environment.DIRECTORY_DCIM; public String getCameraRollObservingPath() { return mCameraRollObservingPath; } public void setCameraRollObservingPath(String cameraRollObservingPath) { this.mCameraRollObservingPath = cameraRollObservingPath; } public void onSaveInstanceState(Bundle outState) { outState.putSerializable(PHOTO_FILE, mPhotoFile); outState.putSerializable(OUTPUT_DIR, mOutputDir); outState.putSerializable(OUTPUT_FILE, mOutputFile); outState.putInt(WIDTH_LIMIT, mWidthLimit); outState.putInt(HEIGHT_LIMIT, mHeightLimit); outState.putInt(QUALITY, mQuality); } public void onRestoreInstanceState(Bundle inState) { mPhotoFile = (File) inState.getSerializable(PHOTO_FILE); mOutputDir = (File) inState.getSerializable(OUTPUT_DIR); mOutputFile = (File) inState.getSerializable(OUTPUT_FILE); mWidthLimit = inState.getInt(WIDTH_LIMIT); mHeightLimit = inState.getInt(HEIGHT_LIMIT); mQuality = inState.getInt(QUALITY); } private Vector<File> mNewAddedImageFiles = new Vector<>(); private FileObserver mCameraRollObserver; public CameraLauncher(Activity activity, int resultCode, CameraLauncherListener listener) { mActivity = activity; mCameraLauncherListener = listener; } public CameraLauncher(Fragment fragment, int resultCode, CameraLauncherListener listener) { mFragment = fragment; mActivity = fragment.getActivity(); mCameraLauncherListener = listener; } public void launchCamera(int resultCode) { launchCamera(null, resultCode); } public void launchCamera(Intent cameraIntent, int resultCode) { mOutputFile = null; mPhotoFile = IntentUtil.getOutputImageFile(); if (cameraIntent == null) cameraIntent = IntentUtil.getCameraIntent(mPhotoFile, 0); startCameraRollWatching(); if (mFragment != null) { IntentUtil.startActivityWrapper(mFragment, cameraIntent, resultCode); } else { IntentUtil.startActivityWrapper(mActivity, cameraIntent, resultCode); } } public void onCameraCancel() { mCameraRollObserver.stopWatching(); mNewAddedImageFiles.clear(); if (Checker.isExistedFile(mPhotoFile)) mPhotoFile.delete(); } public File onCameraReturn() { mCameraRollObserver.stopWatching(); if (Checker.isEmpty(mPhotoFile)) { LLog.w("Cannot found captured image file, try to load from new added files (size=%s).", mNewAddedImageFiles.size()); if (mNewAddedImageFiles.size() == 1) mPhotoFile = mNewAddedImageFiles.get(0); } mNewAddedImageFiles.clear(); if (Checker.isEmpty(mPhotoFile)) { LLog.e("Failed to found photo file captured by camera."); Toast.makeText(mActivity, R.string.msg_cannotFoundPhoto, Toast.LENGTH_SHORT).show(); return null; } // create output file based on output dir if (mOutputFile == null && mOutputDir != null) { mOutputFile = getOutputFile(mPhotoFile); } // copy a scaled image to home dir. if (mOutputFile != null && getWidthLimit() > 0 && getHeightLimit() > 0) { compressImageFile(mOutputFile, mPhotoFile); mCameraLauncherListener.onImageReady(mOutputFile); return mOutputFile; } else { mCameraLauncherListener.onImageReady(mPhotoFile); return mPhotoFile; } } public interface CameraLauncherListener { void onImageReady(File imageFile); } public File getOutputFile(@NonNull File inputFile) { if (mOutputDir != null) { if (!mOutputDir.exists()) mOutputDir.mkdirs(); if (mOutputDir.isDirectory()) { return new File(mOutputDir, inputFile.getName()); } } return null; } public File compressImageFile(File outputFile, @NonNull File inputFile) { BitmapUtil.Size imageSize = BitmapUtil.getImageSizeFromFile(inputFile); if (imageSize.width > getWidthLimit() || imageSize.height > getHeightLimit()) { BitmapCache.prepareMemoryBeforeLoadBitmap(getWidthLimit(), getHeightLimit()); // resize image to limit size Bitmap documentedBitmap = BitmapUtil.loadBitmapFromFile( inputFile, getWidthLimit(), getHeightLimit(), BitmapUtil.ResizeMode.Fit); if (documentedBitmap == null) { LLog.e("Failed to read captured photo data."); return null; } // Save captured photo data to documented photo file with scaled size. BitmapUtil.storeBitmapToFile(documentedBitmap, outputFile, getQuality()); documentedBitmap.recycle(); // no need resize, copy directly. be careful of loading full size image that cause OOM. } else FileUtil.copyFile(inputFile, outputFile); if (Checker.isEmpty(outputFile)) { LLog.e("Failed to save documented photo file %s.", outputFile); return null; } return outputFile; } private void startCameraRollWatching() { if (mCameraRollObserver != null) mCameraRollObserver.stopWatching(); mCameraRollObserver = new FileObserver(mCameraRollObservingPath, FileObserver.CREATE) { @Override public void onEvent(int event, String fileName) { if (Checker.isEmpty(fileName)) return; File newAddedFile = new File(mCameraRollObservingPath, fileName); if (!FileUtil.getFileExtName(newAddedFile).equalsIgnoreCase("jpg")) return; mNewAddedImageFiles.add(newAddedFile); LLog.d("Detected a image file captured by camera", fileName); } }; mCameraRollObserver.startWatching(); } }
package com.mattcorallo.relaynode; import com.google.bitcoin.core.*; import com.google.bitcoin.networkabstraction.NioClientManager; import com.google.bitcoin.networkabstraction.NioServer; import com.google.bitcoin.networkabstraction.StreamParser; import com.google.bitcoin.networkabstraction.StreamParserFactory; import com.google.bitcoin.params.MainNetParams; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.BlockStoreException; import com.google.bitcoin.store.MemoryBlockStore; import com.google.bitcoin.utils.Threading; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.Uninterruptibles; import javax.annotation.Nullable; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Keeps a peer and a set of invs which it has told us about (ie that it has data for) */ class PeerAndInvs { Peer p; Set<InventoryItem> invs = new LinkedHashSet<InventoryItem>() { @Override public boolean add(InventoryItem e) { boolean res = super.add(e); if (size() > 5000) super.remove(super.iterator().next()); return res; } }; public PeerAndInvs(Peer p) { this.p = p; p.addEventListener(new AbstractPeerEventListener() { @Override public Message onPreMessageReceived(Peer p, Message m) { if (m instanceof InventoryMessage) { for (InventoryItem item : ((InventoryMessage) m).getItems()) invs.add(item); } else if (m instanceof Transaction) invs.add(new InventoryItem(InventoryItem.Type.Transaction, m.getHash())); else if (m instanceof Block) invs.add(new InventoryItem(InventoryItem.Type.Block, m.getHash())); return m; } }, Threading.SAME_THREAD); } public void maybeRelay(Message m) { Preconditions.checkArgument(m instanceof Block || m instanceof Transaction); InventoryItem item; if (m instanceof Block) item = new InventoryItem(InventoryItem.Type.Block, m.getHash()); else item = new InventoryItem(InventoryItem.Type.Transaction, m.getHash()); if (!invs.contains(item)) { p.sendMessage(m); invs.add(item); } } } /** * Keeps track of a set of PeerAndInvs */ class Peers { public final Set<PeerAndInvs> peers = Collections.synchronizedSet(new HashSet<PeerAndInvs>()); public PeerAndInvs add(Peer p) { PeerAndInvs peerAndInvs = new PeerAndInvs(p); add(peerAndInvs); return peerAndInvs; } public boolean add(final PeerAndInvs peerAndInvs) { peerAndInvs.p.addEventListener(new AbstractPeerEventListener() { @Override public void onPeerDisconnected(Peer peer, int peerCount) { peers.remove(peerAndInvs); } }, Threading.SAME_THREAD); return peers.add(peerAndInvs); } public int size() { return peers.size(); } public void relayObject(Message m) { synchronized (peers) { for (PeerAndInvs p : peers) p.maybeRelay(m); } } } /** * Keeps track of the set of known blocks and transactions for relay */ abstract class Pool<Type extends Message> { abstract int relayedCacheSize(); Map<Sha256Hash, Type> objects = new HashMap<Sha256Hash, Type>(); Set<Sha256Hash> objectsRelayed = new LinkedHashSet<Sha256Hash>() { @Override public boolean add(Sha256Hash e) { boolean res = super.add(e); if (size() > relayedCacheSize()) super.remove(super.iterator().next()); //TODO: right order, or inverse? return res; } }; Peers trustedOutboundPeers; public Pool(Peers trustedOutboundPeers) { this.trustedOutboundPeers = trustedOutboundPeers; } public synchronized boolean shouldRequestInv(Sha256Hash hash) { return !objectsRelayed.contains(hash) && !objects.containsKey(hash); } public synchronized void provideObject(Type m) { if (!objectsRelayed.contains(m.getHash())) objects.put(m.getHash(), m); trustedOutboundPeers.relayObject(m); } public synchronized void invGood(Peers clients, Sha256Hash hash) { if (!objectsRelayed.contains(hash)) { Type o = objects.get(hash); Preconditions.checkState(o != null); clients.relayObject(o); objectsRelayed.add(hash); } objects.remove(hash); } } class BlockPool extends Pool<Block> { public BlockPool(Peers trustedOutboundPeers) { super(trustedOutboundPeers); } @Override int relayedCacheSize() { return 100; } } class TransactionPool extends Pool<Transaction> { public TransactionPool(Peers trustedOutboundPeers) { super(trustedOutboundPeers); } @Override int relayedCacheSize() { return 10000; } } /** * A RelayNode which is designed to relay blocks/txn from a set of untrusted peers, through a trusted bitcoind, to the * rest of the untrusted peers. It does no verification and trusts everything that comes from the trusted bitcoind is * good to relay. */ public class RelayNode { public static void main(String[] args) throws BlockStoreException { new RelayNode().run(8334, 8335); } NetworkParameters params = MainNetParams.get(); VersionMessage versionMessage = new VersionMessage(params, 0); Peers trustedOutboundPeers = new Peers(); TransactionPool txPool = new TransactionPool(trustedOutboundPeers); BlockPool blockPool = new BlockPool(trustedOutboundPeers); BlockStore blockStore = new MemoryBlockStore(params); BlockChain blockChain; PeerGroup trustedOutboundPeerGroup; volatile boolean chainDownloadDone = false; final Peers txnClients = new Peers(); final Peers blocksClients = new Peers(); PeerEventListener clientPeerListener = new AbstractPeerEventListener() { @Override public Message onPreMessageReceived(Peer p, Message m) { if (m instanceof InventoryMessage) { GetDataMessage getDataMessage = new GetDataMessage(params); for (InventoryItem item : ((InventoryMessage)m).getItems()) { if (item.type == InventoryItem.Type.Block) { if (blockPool.shouldRequestInv(item.hash)) getDataMessage.addBlock(item.hash); } else if (item.type == InventoryItem.Type.Transaction) { if (txPool.shouldRequestInv(item.hash)) getDataMessage.addTransaction(item.hash); } } if (!getDataMessage.getItems().isEmpty()) p.sendMessage(getDataMessage); } else if (m instanceof Block) { blockPool.provideObject((Block) m); // This will relay to trusted peers, just in case we reject something we shouldn't try { if (blockChain.add((Block) m)) { LogBlockRelay(m.getHash(), "SPV check, from " + p.getAddress()); blockPool.invGood(blocksClients, m.getHash()); } } catch (Exception e) { /* Invalid block, don't relay it */ } } else if (m instanceof Transaction) txPool.provideObject((Transaction) m); return m; } }; /** Manages reconnecting to trusted peers and relay nodes, often sleeps */ private static Executor reconnectExecutor = Executors.newSingleThreadExecutor(); /** Keeps track of a trusted peer connection (two connections per peer) */ class TrustedPeerConnections { /** We only receive messages here (listen for invs of validated data) */ public Peer inbound; /** We only send messages here (send unvalidated data) */ public Peer outbound; /** The address to (re)connect to */ public InetSocketAddress addr; public volatile boolean inboundConnected = false; // Flag for UI only, very racy, often wrong public volatile boolean outboundConnected = false; // Flag for UI only, very racy, often wrong private void makeInboundPeer() { if (inbound != null) inbound.close(); // Double-check closed inbound = new Peer(params, versionMessage, null, addr); inbound.addEventListener(trustedPeerInboundListener, Threading.SAME_THREAD); inbound.addEventListener(trustedPeerDisconnectListener); inbound.addEventListener(new AbstractPeerEventListener() { @Override public void onPeerConnected(Peer p, int peerCount) { inboundConnected = true; } }); trustedPeerManager.openConnection(addr, inbound); } private void makeOutboundPeer() { if (outbound != null) outbound.close(); // Double-check closed outbound = trustedOutboundPeerGroup.connectTo(addr); trustedOutboundPeers.add(outbound); trustedOutboundPeerGroup.startBlockChainDownload(new DownloadListener() { @Override protected void doneDownload() { chainDownloadDone = true; } }); outboundConnected = true; // Ehhh...assume we got through... } public void onDisconnect(final Peer p) { if (p == inbound) inboundConnected = false; else if (p == outbound) outboundConnected = false; reconnectExecutor.execute(new Runnable() { @Override public void run() { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); if (p == inbound) makeInboundPeer(); else if (p == outbound) makeOutboundPeer(); } }); } public TrustedPeerConnections(InetSocketAddress addr) { this.addr = addr; makeInboundPeer(); makeOutboundPeer(); trustedPeerConnectionsMap.put(addr.getAddress(), this); } } final Map<InetAddress, TrustedPeerConnections> trustedPeerConnectionsMap = Collections.synchronizedMap(new HashMap<InetAddress, TrustedPeerConnections>()); NioClientManager trustedPeerManager = new NioClientManager(); PeerEventListener trustedPeerInboundListener = new AbstractPeerEventListener() { @Override public Message onPreMessageReceived(Peer p, Message m) { if (m instanceof InventoryMessage) { GetDataMessage getDataMessage = new GetDataMessage(params); for (InventoryItem item : ((InventoryMessage)m).getItems()) { if (item.type == InventoryItem.Type.Block) { if (blockPool.shouldRequestInv(item.hash)) getDataMessage.addBlock(item.hash); else { LogBlockRelay(item.hash, "inv from node " + p.getAddress()); blockPool.invGood(blocksClients, item.hash); } } else if (item.type == InventoryItem.Type.Transaction) { if (txPool.shouldRequestInv(item.hash)) getDataMessage.addTransaction(item.hash); else txPool.invGood(txnClients, item.hash); } } if (!getDataMessage.getItems().isEmpty()) p.sendMessage(getDataMessage); } else if (m instanceof Transaction) { txPool.provideObject((Transaction) m); txPool.invGood(txnClients, m.getHash()); } else if (m instanceof Block) { blockPool.provideObject((Block) m); LogBlockRelay(m.getHash(), "block from node " + p.getAddress()); blockPool.invGood(blocksClients, m.getHash()); } return m; } }; PeerEventListener trustedPeerDisconnectListener = new AbstractPeerEventListener() { @Override public void onPeerDisconnected(Peer peer, int peerCount) { TrustedPeerConnections connections = trustedPeerConnectionsMap.get(peer.getAddress().getAddr()); if (connections == null) { return; } connections.onDisconnect(peer); } }; Peers trustedRelayPeers = new Peers(); // Just used to keep a list of relay peers Set<InetSocketAddress> relayPeersWaitingOnReconnection = Collections.synchronizedSet(new HashSet<InetSocketAddress>()); PeerEventListener trustedRelayPeerListener = new AbstractPeerEventListener() { @Override public Message onPreMessageReceived(Peer p, Message m) { if (m instanceof Block) { blockPool.provideObject((Block) m); LogBlockRelay(m.getHash(), "block from relay peer " + p.getAddress()); blockPool.invGood(blocksClients, m.getHash()); } return m; } }; public RelayNode() throws BlockStoreException { String version = "reliable rhinoceros"; versionMessage.appendToSubVer("RelayNode", version, null); // Fudge a few flags so that we can connect to other relay nodes versionMessage.localServices = VersionMessage.NODE_NETWORK; versionMessage.bestHeight = 1; trustedPeerManager.startAndWait(); blockChain = new BlockChain(params, blockStore); trustedOutboundPeerGroup = new PeerGroup(params, blockChain); trustedOutboundPeerGroup.setUserAgent("RelayNode", version); trustedOutboundPeerGroup.addEventListener(trustedPeerDisconnectListener); trustedOutboundPeerGroup.setFastCatchupTimeSecs(Long.MAX_VALUE); // We'll revert to full blocks after catchup, but oh well trustedOutboundPeerGroup.startAndWait(); } public void run(int onlyBlocksListenPort, int bothListenPort) { // Listen for incoming client connections try { NioServer onlyBlocksServer = new NioServer(new StreamParserFactory() { @Nullable @Override public StreamParser getNewParser(InetAddress inetAddress, int port) { Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port)); blocksClients.add(p); // Should come first to avoid relaying back to the sender p.addEventListener(clientPeerListener, Threading.SAME_THREAD); return p; } }, new InetSocketAddress(onlyBlocksListenPort)); NioServer bothServer = new NioServer(new StreamParserFactory() { @Nullable @Override public StreamParser getNewParser(InetAddress inetAddress, int port) { Peer p = new Peer(params, versionMessage, null, new InetSocketAddress(inetAddress, port)); txnClients.add(blocksClients.add(p)); // Should come first to avoid relaying back to the sender p.addEventListener(clientPeerListener, Threading.SAME_THREAD); return p; } }, new InetSocketAddress(bothListenPort)); onlyBlocksServer.startAndWait(); bothServer.startAndWait(); } catch (IOException e) { System.err.println("Failed to bind to port"); System.exit(1); } // Print stats new Thread(new Runnable() { @Override public void run() { printStats(); } }).start(); WatchForUserInput(); } public void WatchForUserInput() { // Get user input Scanner scanner = new Scanner(System.in); String line; while (true) { line = scanner.nextLine(); if (line.equals("q")) { synchronized (printLock) { System.out.println("Quitting..."); // Wait...cleanup? naaaaa System.exit(0); } } else if (line.startsWith("t ")) { String[] hostPort = line.substring(2).split(":"); if (hostPort.length != 2) { LogLine("Invalid argument"); continue; } try { int port = Integer.parseInt(hostPort[1]); InetSocketAddress addr = new InetSocketAddress(hostPort[0], port); if (addr.isUnresolved()) LogLine("Unable to resolve host"); else { if (trustedPeerConnectionsMap.containsKey(addr)) { LogLine("Already had trusted peer " + addr); } else { new TrustedPeerConnections(addr); LogLine("Added trusted peer " + addr); } } } catch (NumberFormatException e) { LogLine("Invalid argument"); } } else if (line.startsWith("r ")) { String[] hostPort = line.substring(2).split(":"); if (hostPort.length != 2) { LogLine("Invalid argument"); continue; } try { int port = Integer.parseInt(hostPort[1]); InetSocketAddress addr = new InetSocketAddress(hostPort[0], port); if (addr.isUnresolved()) LogLine("Unable to resolve host"); else { ConnectToTrustedRelayPeer(addr); LogLine("Added trusted relay peer " + addr); } } catch (NumberFormatException e) { LogLine("Invalid argument"); } } else { LogLine("Invalid command"); } } } public void ConnectToTrustedRelayPeer(final InetSocketAddress address) { final Peer p = new Peer(params, versionMessage, null, address); p.addEventListener(trustedRelayPeerListener, Threading.SAME_THREAD); p.addEventListener(new AbstractPeerEventListener() { @Override public void onPeerDisconnected(Peer peer, int peerCount) { Preconditions.checkState(peer == p); relayPeersWaitingOnReconnection.add(address); reconnectExecutor.execute(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } relayPeersWaitingOnReconnection.remove(address); ConnectToTrustedRelayPeer(address); } }); } }); trustedRelayPeers.add(p); trustedPeerManager.openConnection(address, p); } final Queue<String> logLines = new LinkedList<String>(); public void LogLine(String line) { synchronized (logLines) { logLines.add(line); } } Set<Sha256Hash> blockRelayedSet = Collections.synchronizedSet(new HashSet<Sha256Hash>()); public void LogBlockRelay(Sha256Hash blockHash, String reason) { if (blockRelayedSet.contains(blockHash)) return; blockRelayedSet.add(blockHash); LogLine(blockHash.toString().substring(4, 32) + " relayed (" + reason + ")"); } // Wouldn't want to print from multiple threads, would we? final Object printLock = new Object(); public void printStats() { // Things may break if your column count is too small boolean firstIteration = true; int linesPrinted = 1; for (int iter = 0; true; iter++) { int prevLinesPrinted = linesPrinted; linesPrinted = 1; synchronized (printLock) { if (!firstIteration) { synchronized (logLines) { System.out.print("\033[s\033[1000D"); // Save cursor position + move to first char for (String ignored : logLines) System.out.println(); // Move existing log lines up for (int i = 0; i < prevLinesPrinted; i++) System.out.print("\033[1A\033[K"); // Up+clear linesPrinted lines for (String ignored : logLines) System.out.print("\033[1A\033[K"); // Up and make sure we're at the beginning, clear line for (String line : logLines) System.out.println(line); logLines.clear(); } } if (trustedPeerConnectionsMap.isEmpty()) { System.out.println("\nNo trusted nodes (no transaction relay)"); linesPrinted += 2; } else { System.out.println("\nTrusted nodes: "); linesPrinted += 2; synchronized (trustedPeerConnectionsMap) { for (Map.Entry<InetAddress, TrustedPeerConnections> entry : trustedPeerConnectionsMap.entrySet()) { System.out.println(" " + entry.getValue().addr + ((entry.getValue().inboundConnected && entry.getValue().outboundConnected) ? " connected" : " not connected")); linesPrinted++; } } } Set<InetAddress> relayPeers = new HashSet<InetAddress>(); if (trustedRelayPeers.peers.isEmpty()) { System.out.println("\nNo relay peers"); linesPrinted += 2; } else { System.out.println("\nRelay peers:"); linesPrinted += 2; synchronized (trustedRelayPeers.peers) { for (PeerAndInvs peer : trustedRelayPeers.peers) { // If its not connected, its not in the set System.out.println(" " + peer.p.getAddress() + " connected"); linesPrinted++; relayPeers.add(peer.p.getAddress().getAddr()); } } synchronized (relayPeersWaitingOnReconnection) { for (InetSocketAddress a : relayPeersWaitingOnReconnection) { System.out.println(" " + a + " not connected"); linesPrinted++; relayPeers.add(a.getAddress()); } } } int relayClients = 0; synchronized (blocksClients.peers) { for (PeerAndInvs p : blocksClients.peers) if (relayPeers.contains(p.p.getAddress().getAddr())) relayClients++; } System.out.println(); linesPrinted++; System.out.println("Connected block+transaction clients: " + txnClients.size()); linesPrinted++; System.out.println("Connected block-only clients: " + (blocksClients.size() - txnClients.size() - relayClients)); linesPrinted++; System.out.println("Connected relay node clients: " + relayClients); linesPrinted++; System.out.println(chainDownloadDone ? "Chain download done (relaying SPV-checked blocks)" : ("Chain download at " + blockChain.getBestChainHeight())); linesPrinted++; System.out.println(); linesPrinted++; System.out.println("Commands:"); linesPrinted++; System.out.println("q \t\tquit"); linesPrinted++; System.out.println("t IP:port\t\tadd node IP:port as a trusted peer"); linesPrinted++; System.out.println("r IP:port\t\tadd trusted relay node (via its block-only port) to relay from"); linesPrinted++; if (firstIteration) System.out.println(); else System.out.print("\033[u"); firstIteration = false; } try { Thread.sleep(100); } catch (InterruptedException e) { System.err.println("Stats printing thread interrupted"); System.exit(1); } } } }
package com.myjeeva.digitalocean.pojo; import java.util.Date; import java.util.List; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.myjeeva.digitalocean.common.ImageType; /** * Represents Droplet Image (also public images aka Distribution) attributes of DigitalOcean * (distribution, snapshots or backups). Revised as per v2 API data structure. * * @author Jeevanandam M. (jeeva@myjeeva.com) */ public class Image extends RateLimitBase { private static final long serialVersionUID = 1321111459154107563L; private Integer id; @Expose private String name; private String distribution; private String slug; @SerializedName("public") private boolean availablePublic; private List<String> regions; @SerializedName("created_at") private Date createdDate; @SerializedName("min_disk_size") private Integer minDiskSize; @SerializedName("size_gigabytes") private Double size; private ImageType type; public Image() { // Default constructor } public Image(Integer id) { this.id = id; } public Image(String slug) { this.slug = slug; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } /** * @return true if image is snapshot */ public boolean isSnapshot() { return ImageType.SNAPSHOT == type; } /** * @return true if image is backup */ public boolean isBackup() { return ImageType.BACKUP == type; } @Deprecated public boolean isTemporary() { return ImageType.TEMPORARY == type; } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the distribution */ public String getDistribution() { return distribution; } /** * @param distribution the distribution to set */ public void setDistribution(String distribution) { this.distribution = distribution; } /** * @return the slug */ public String getSlug() { return slug; } /** * @param slug the slug to set */ public void setSlug(String slug) { this.slug = slug; } /** * @return the availablePublic */ public boolean isAvailablePublic() { return availablePublic; } /** * @param availablePublic the availablePublic to set */ public void setAvailablePublic(boolean availablePublic) { this.availablePublic = availablePublic; } /** * @return the regions */ public List<String> getRegions() { return regions; } /** * @param regions the regions to set */ public void setRegions(List<String> regions) { this.regions = regions; } /** * @return the createdDate */ public Date getCreatedDate() { return createdDate; } /** * @param createdDate the createdDate to set */ public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } /** * @return the type */ public ImageType getType() { return type; } /** * @param type the type to set */ public void setType(ImageType type) { this.type = type; } /** * @return the min Disk Size */ public Integer getMinDiskSize() { return minDiskSize; } /** * @param minDiskSize the minDiskSize to set */ public void setMinDiskSize(Integer minDiskSize) { this.minDiskSize = minDiskSize; } }
package com.ninty.nativee.sun.misc; import com.ninty.nativee.INativeMethod; import com.ninty.nativee.NaMethodManager; import com.ninty.runtime.LocalVars; import com.ninty.runtime.NiFrame; import com.ninty.runtime.heap.NiObject; import sun.misc.Unsafe; import java.lang.reflect.Field; public class NaUnsafe { private static Unsafe unsafe; static { Field field; try { field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } private final static String className = "sun/misc/Unsafe"; public static void init() { NaMethodManager.register(className, "arrayBaseOffset", "(Ljava/lang/Class;)I", new arrayBaseOffset()); NaMethodManager.register(className, "arrayIndexScale", "(Ljava/lang/Class;)I", new arrayIndexScale()); NaMethodManager.register(className, "addressSize", "()I", new addressSize()); NaMethodManager.register(className, "allocateMemory", "(J)J", new allocateMemory()); NaMethodManager.register(className, "putLong", "(JJ)V", new putLong()); NaMethodManager.register(className, "getByte", "(J)B", new getByte()); NaMethodManager.register(className, "freeMemory", "(J)V", new freeMemory()); NaMethodManager.register(className, "objectFieldOffset", "(Ljava/lang/reflect/Field;)J", new objectFieldOffset()); NaMethodManager.register(className, "compareAndSwapObject", "(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z", new compareAndSwapObject()); NaMethodManager.register(className, "compareAndSwapInt", "(Ljava/lang/Object;JII)Z", new compareAndSwapInt()); NaMethodManager.register(className, "getIntVolatile", "(Ljava/lang/Object;J)I", new getIntVolatile()); } public static class arrayBaseOffset implements INativeMethod { @Override public void invoke(NiFrame frame) { frame.getOperandStack().pushInt(0); } } public static class arrayIndexScale implements INativeMethod { @Override public void invoke(NiFrame frame) { frame.getOperandStack().pushInt(1); } } public static class addressSize implements INativeMethod { @Override public void invoke(NiFrame frame) { frame.getOperandStack().pushInt(unsafe.addressSize()); } } public static class allocateMemory implements INativeMethod { @Override public void invoke(NiFrame frame) { long size = frame.getLocalVars().getLong(1); long addr = unsafe.allocateMemory(size); frame.getOperandStack().pushLong(addr); } } public static class putLong implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); long l1 = localVars.getLong(1); long l2 = localVars.getLong(3); unsafe.putLong(l1, l2); } } public static class getByte implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); long addr = localVars.getLong(1); byte data = unsafe.getByte(addr); frame.getOperandStack().pushInt(data); } } public static class freeMemory implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); long addr = localVars.getLong(1); unsafe.freeMemory(addr); } } public static class objectFieldOffset implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); NiObject fieldObj = localVars.getRef(1); frame.getOperandStack().pushLong(fieldObj.getFieldInt("slot")); } } // TODO: CAS public static class compareAndSwapObject implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); NiObject obj = localVars.getRef(1); int offset = (int) localVars.getLong(2); NiObject expect = localVars.getRef(4); NiObject update = localVars.getRef(5); if (obj.getFields().getRef(offset) == expect) { obj.getFields().setRef(offset, update); frame.getOperandStack().pushBoolean(true); } else { frame.getOperandStack().pushBoolean(false); } } } public static class compareAndSwapInt implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); NiObject obj = localVars.getRef(1); int offset = (int) localVars.getLong(2); int expect = localVars.getInt(4); int update = localVars.getInt(5); if (obj.getFields().getInt(offset) == expect) { obj.getFields().setInt(offset, update); frame.getOperandStack().pushBoolean(true); } else { frame.getOperandStack().pushBoolean(false); } } } public static class getIntVolatile implements INativeMethod { @Override public void invoke(NiFrame frame) { LocalVars localVars = frame.getLocalVars(); NiObject obj = localVars.getRef(1); long offset = localVars.getLong(2); LocalVars fields = obj.getFields(); int result = fields.getInt((int) offset); frame.getOperandStack().pushInt(result); } } }
package com.nirmata.workflow.details; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.nirmata.workflow.details.internalmodels.DenormalizedWorkflowModel; import com.nirmata.workflow.models.ScheduleId; import com.nirmata.workflow.models.TaskId; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import static com.nirmata.workflow.details.InternalJsonSerializer.getDenormalizedWorkflow; import static com.nirmata.workflow.spi.JsonSerializer.fromBytes; class Cacher implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final PathChildrenCache scheduleCache; private final ConcurrentMap<ScheduleId, PathChildrenCache> completedTasksCaches; private final CuratorFramework curator; private final CacherListener cacherListener; private final ExecutorService executorService = ThreadUtils.newSingleThreadExecutor("Cacher"); private final PathChildrenCacheListener scheduleListener = new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch ( event.getType() ) { default: { break; // NOP } case CHILD_ADDED: { ScheduleId scheduleId = new ScheduleId(ZooKeeperConstants.getScheduleIdFromSchedulePath(event.getData().getPath())); log.debug("Schedule added: " + scheduleId); PathChildrenCache taskCache = new PathChildrenCache(curator, ZooKeeperConstants.getCompletedTasksParentPath(scheduleId), false); if ( completedTasksCaches.putIfAbsent(scheduleId, taskCache) == null ) { taskCache.getListenable().addListener(completedTasksListener, executorService); taskCache.start(PathChildrenCache.StartMode.NORMAL); } DenormalizedWorkflowModel workflow = getDenormalizedWorkflow(fromBytes(event.getData().getData())); cacherListener.updateAndQueueTasks(Cacher.this, workflow); break; } case CHILD_REMOVED: { ScheduleId scheduleId = new ScheduleId(ZooKeeperConstants.getScheduleIdFromSchedulePath(event.getData().getPath())); log.debug("Schedule removed: " + scheduleId); PathChildrenCache cache = completedTasksCaches.remove(scheduleId); if ( cache != null ) { CloseableUtils.closeQuietly(cache); } break; } case CHILD_UPDATED: { ScheduleId scheduleId = new ScheduleId(ZooKeeperConstants.getScheduleIdFromSchedulePath(event.getData().getPath())); log.debug("Schedule updated: " + scheduleId); DenormalizedWorkflowModel workflow = getDenormalizedWorkflow(fromBytes(event.getData().getData())); cacherListener.updateAndQueueTasks(Cacher.this, workflow); } } } }; private final PathChildrenCacheListener completedTasksListener = new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) { String taskId = ZooKeeperConstants.getTaskIdFromCompletedTaskPath(event.getData().getPath()); String scheduleId = ZooKeeperConstants.getScheduleIdFromCompletedTaskPath(event.getData().getPath()); log.info("Task completed: " + taskId); String schedulePath = ZooKeeperConstants.getSchedulePath(new ScheduleId(scheduleId)); ChildData scheduleData = scheduleCache.getCurrentData(schedulePath); if ( scheduleData == null ) { String message = "Expected schedule not found at path " + schedulePath; log.error(message); throw new Exception(message); } DenormalizedWorkflowModel workflow = getDenormalizedWorkflow(fromBytes(scheduleData.getData())); cacherListener.updateAndQueueTasks(Cacher.this, workflow); } } }; Cacher(CuratorFramework curator, CacherListener cacherListener) { this.curator = Preconditions.checkNotNull(curator, "curator cannot be null"); this.cacherListener = Preconditions.checkNotNull(cacherListener, "cacherListener cannot be null"); scheduleCache = new PathChildrenCache(curator, ZooKeeperConstants.getScheduleParentPath(), true); completedTasksCaches = Maps.newConcurrentMap(); } void start() { scheduleCache.getListenable().addListener(scheduleListener, executorService); try { scheduleCache.start(PathChildrenCache.StartMode.NORMAL); } catch ( Exception e ) { log.error("Could not start schedule cache", e); throw new RuntimeException(e); } } @Override public void close() { for ( PathChildrenCache cache : completedTasksCaches.values() ) { CloseableUtils.closeQuietly(cache); } CloseableUtils.closeQuietly(scheduleCache); } void updateSchedule(DenormalizedWorkflowModel workflow) { try { String schedulePath = ZooKeeperConstants.getSchedulePath(workflow.getScheduleId()); curator.setData().forPath(schedulePath, Scheduler.toJson(log, workflow)); } catch ( Exception e ) { log.error("Could not updateSchedule for workflow: " + workflow, e); throw new RuntimeException(e); } } boolean scheduleIsActive(ScheduleId scheduleId) { return scheduleCache.getCurrentData(ZooKeeperConstants.getSchedulePath(scheduleId)) != null; } boolean taskIsComplete(ScheduleId scheduleId, TaskId taskId) { PathChildrenCache taskCache = completedTasksCaches.get(scheduleId); if ( taskCache != null ) { String path = ZooKeeperConstants.getCompletedTaskPath(scheduleId, taskId); return taskCache.getCurrentData(path) != null; } return false; } }
package com.notnoop.mpns.internal; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import com.notnoop.mpns.MpnsDelegate; import com.notnoop.mpns.MpnsNotification; import com.notnoop.mpns.MpnsResponse; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; public final class Utilities { private Utilities() { throw new AssertionError("Uninstantiable class"); } /** * The content type "text/xml" */ public static String XML_CONTENT_TYPE = "text/xml"; public static ThreadSafeClientConnManager poolManager(int maxConnections) { ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); cm.setMaxTotal(maxConnections); cm.setDefaultMaxPerRoute(maxConnections); return cm; } /** * Returns {@cond value} is the {@code cond} is non-null; otherwise * returns an empty String. */ public static String ifNonNull(Object cond, String value) { return cond != null ? value : ""; } public static String escapeXml(String value) { if (value == null) { return null; } StringBuilder sb = new StringBuilder(value.length()); for (int i = 0; i < value.length(); ++i) { char ch = value.charAt(i); switch (ch) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(ch); } } return sb.toString(); } public static byte[] toUTF8(String content) { try { return content.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("The world is coming to an end! No UTF-8 support"); } } private static String headerValue(HttpResponse response, String name) { Header header = response.getFirstHeader(name); return header == null ? null: header.getValue(); } private static MpnsResponse[] logicalResponses = MpnsResponse.values(); public static MpnsResponse logicalResponseFor(HttpResponse response) { for (MpnsResponse r: logicalResponses) { if (r.getResponseCode() != response.getStatusLine().getStatusCode()) { continue; } if (r.getNotificationStatus() != null && !r.getNotificationStatus().equals(headerValue(response, "X-NotificationStatus"))) { continue; } if (r.getDeviceConnectionStatus() != null && !r.getNotificationStatus().equals(headerValue(response, "X-DeviceConnectionStatus"))) { continue; } if (r.getSubscriptionStatus() != null && !r.getSubscriptionStatus().equals(headerValue(response, "X-SubscriptionStatus"))) { continue; } return r; } // Didn't find anything assert false; return null; } public static void fireDelegate(MpnsNotification message, HttpResponse response, MpnsDelegate delegate) { if (delegate != null) { MpnsResponse r = Utilities.logicalResponseFor(response); if (r.isSuccessful()) { delegate.messageSent(message, r); } else { delegate.messageFailed(message, r); } } } }
package com.pump.swing; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; 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.concurrent.Semaphore; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.pump.awt.DescendantListener; import com.pump.icon.RotatedIcon; import com.pump.icon.TriangleIcon; import com.pump.plaf.AnimationManager; import com.pump.plaf.AnimationManager.Ticket; import com.pump.plaf.QPanelUI; import com.pump.plaf.UIEffect; import com.pump.plaf.button.ButtonState; import com.pump.plaf.button.GradientButtonUI; import com.pump.plaf.button.QButtonUI; import com.pump.plaf.button.QButtonUI.HorizontalPosition; import com.pump.plaf.button.QButtonUI.PaintFocus; import com.pump.plaf.button.QButtonUI.VerticalPosition; import com.pump.util.WeakSet; public class CollapsibleContainer extends SectionContainer { private static final long serialVersionUID = 1L; /** * A property name for a Section that maps to the JButton used as a header * for that Section. */ protected static final String HEADER = CollapsibleContainer.class.getName() + ".header"; /** * A property name for a Section that identifies its vertical weight. When * it is absent the vertical weight is assumed to be zero. */ public static final String VERTICAL_WEIGHT = CollapsibleContainer.class .getName() + ".vertical-weight"; /** * A client property name for the JButton header of a <code>Section</code> * that determines whether a the user can collapse/expand a section. */ public static final String COLLAPSIBLE = CollapsibleContainer.class .getName() + ".collapsible"; /** * A client property name for the JButton header of a <code>Section</code> * that determines whether a Section is collapsed. */ public static final String COLLAPSED = CollapsibleContainer.class.getName() + ".collapsed"; /** * A client property name for the JButton header of a <code>Section</code> * that determines the current rotation of the triangle. (This will vary a * lot during animation.) */ protected static final String ROTATION = CollapsibleContainer.class .getName() + ".rotation"; /** * A client property name for the JButton header of a <code>Section</code> * that determines the target rotation of the triangle. (This is generally 1 * of 2 values: open or closed.) */ protected static final String TARGET_ROTATION = CollapsibleContainer.class .getName() + ".target-rotation"; /** * A client property name for the JButton header that maps to the * <code>Section</code> this header relates to. */ protected static final String SECTION = CollapsibleContainer.class .getName() + ".section"; /** * The duration in seconds for animating section heights */ private static float ANIMATION_DURATION = .2f; /** * This contains the preferred layout of this container at a given instant. * This layout can be installed in one instant or incrementally (for * animation) */ class LayoutBlueprint extends AnimationManager.Adjuster<Float> { List<JComponent> components = new ArrayList<JComponent>(); Map<JComponent, Integer> heightMap = new HashMap<JComponent, Integer>(); Map<JComponent, Integer> originalHeightMap = new HashMap<JComponent, Integer>(); Set<JComponent> visibleComponents = new HashSet<JComponent>(); boolean initialPermitLocked; protected LayoutBlueprint(boolean initialPermitLocked) { super(ANIMATION_DURATION, 1F); this.initialPermitLocked = initialPermitLocked; Insets insets = getInsets(); int height = getHeight() - insets.top - insets.bottom; int remainingHeight = height; float totalVerticalWeight = 0; Map<JComponent, Number> verticalWeightMap = new HashMap<JComponent, Number>(); for (int a = 0; a < sections.size(); a++) { Section section = sections.get(a); JPanel body = section.getBody(); JButton header = getHeader(section); Boolean collapsed = (Boolean) header .getClientProperty(COLLAPSED); if (collapsed == null) collapsed = Boolean.FALSE; if (!header.isVisible()) collapsed = true; components.add(header); components.add(body); if (header.isVisible()) visibleComponents.add(header); if ((!collapsed)) visibleComponents.add(body); Number n = (Number) section.getProperty(VERTICAL_WEIGHT); if (n == null) n = 0; if (visibleComponents.contains(body)) { totalVerticalWeight += n.floatValue(); if (n.floatValue() != 0) verticalWeightMap.put(body, n); } if (visibleComponents.contains(header)) { Dimension headerSize = header.getPreferredSize(); heightMap.put(header, headerSize.height); remainingHeight -= headerSize.height; } else { heightMap.put(header, 0); } originalHeightMap.put(header, header.getHeight()); if (visibleComponents.contains(body) && n.floatValue() == 0) { Dimension bodySize = body.getPreferredSize(); heightMap.put(body, bodySize.height); remainingHeight -= bodySize.height; } else { heightMap.put(body, 0); } originalHeightMap.put(body, body.getHeight()); } if (remainingHeight > 0 && totalVerticalWeight > 0) { // divide the remaining height based on the vertical weight int designatedHeight = 0; JComponent lastC = null; for (JComponent jc : verticalWeightMap.keySet()) { Number weight = verticalWeightMap.get(jc); int i = (int) (weight.floatValue() / totalVerticalWeight * remainingHeight); heightMap.put(jc, heightMap.get(jc) + i); designatedHeight += i; lastC = jc; } // due to rounding error, we may have a few extra pixels: int remainingPixels = remainingHeight - designatedHeight; // tack them on to someone. anyone. heightMap.put(lastC, heightMap.get(lastC) + remainingPixels); } } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("LayoutBlueprint["); for (int a = 0; a < components.size(); a++) { JComponent jc = components.get(a); int height = heightMap.get(jc); boolean visible = visibleComponents.contains(jc); if (a != 0) sb.append(", "); sb.append(height + " (" + jc.getClass().getName()); if (!visible) { sb.append(" - hidden"); } sb.append(")"); } sb.append("]"); return sb.toString(); } protected void install() { midanimation.acquireUninterruptibly(); try { Insets insets = getInsets(); int x = insets.left; int y = insets.top; int width = getWidth() - insets.right - insets.left; for (int a = 0; a < components.size(); a++) { JComponent jc = components.get(a); if (visibleComponents.contains(jc)) { int h = heightMap.get(jc); jc.setBounds(x, y, width, h); jc.validate(); y += h; jc.setVisible(true); } else { jc.setBounds(0, 0, 0, 0); jc.setVisible(false); } } } finally { midanimation.release(); } } @Override public void increment(Ticket ticket, double fraction) { try { Insets insets = getInsets(); int x = insets.left; int y = insets.top; int width = getWidth() - insets.right - insets.left; boolean moreChanges = false; boolean requiresValidation = false; for (JComponent jc : components) { if (visibleComponents.contains(jc)) { if (!jc.isVisible()) { jc.setSize(width, 0); jc.setVisible(true); requiresValidation = true; } } } for (int a = 0; a < components.size(); a++) { JComponent jc = components.get(a); int originalHeight = originalHeightMap.get(jc); int targetHeight = heightMap.get(jc); int newHeight = (int) (targetHeight * (fraction) + originalHeight * (1 - fraction) + .5); if (Math.abs(targetHeight - newHeight) <= 1) newHeight = targetHeight; jc.setBounds(x, y, width, newHeight); jc.validate(); y += newHeight; if (newHeight != targetHeight) moreChanges = true; } if (!moreChanges) { for (JComponent jc : components) { if (!visibleComponents.contains(jc)) { if (jc.isVisible()) { jc.setVisible(false); requiresValidation = true; } } } } if (requiresValidation) { CollapsibleContainer.this.invalidate(); CollapsibleContainer.this.validate(); } } finally { if (fraction >= 1 && initialPermitLocked) midanimation.release(); } } } private class CollapsibleLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) { } public void removeLayoutComponent(Component comp) { } public Dimension preferredLayoutSize(Container parent) { return calculateSize(parent, true); } /** * * @param usePreferred * true for preferred size, false for minimum size */ private Dimension calculateSize(Container parent, boolean usePreferred) { Dimension size = new Dimension(); for (int a = 0; a < parent.getComponentCount(); a++) { Component comp = parent.getComponent(a); Dimension d = usePreferred ? comp.getPreferredSize() : comp .getMinimumSize(); size.width = Math.max(size.width, d.width); size.height += d.height; } Insets insets = getInsets(); size.width += insets.left + insets.right; size.height += insets.top + insets.bottom; return size; } public Dimension minimumLayoutSize(Container parent) { return calculateSize(parent, false); } public void layoutContainer(Container parent) { if (midanimation.availablePermits() == 0) return; LayoutBlueprint blueprint = new LayoutBlueprint(false); blueprint.install(); } } private Set<JButton> headers = new HashSet<JButton>(); ChangeListener sectionListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { // add new headers & bodies if necessary: for (Section section : sections) { getHeader(section); JPanel body = section.getBody(); if (body.getParent() != CollapsibleContainer.this) { add(body); } } // remove unused headers/bodies from this panel: Iterator<JButton> iter = headers.iterator(); while (iter.hasNext()) { JButton header = iter.next(); Section section = (Section) header.getClientProperty(SECTION); if (section.getBody().getParent() != CollapsibleContainer.this) { iter.remove(); section.setProperty(HEADER, null); remove(header); remove(section.getBody()); } } revalidate(); } }; public CollapsibleContainer() { setLayout(new CollapsibleLayout()); sections.addChangeListener(sectionListener, false); sections.addChangeListener(new ChangeListener() { Set<Section> mySections = new WeakSet<>(); @Override public void stateChanged(ChangeEvent e) { for (Section s : sections) { if (mySections.add(s)) { final JPanel body = s.getBody(); new DescendantListener(s.getBody(), false) { @Override public void register(Component c) { refreshSectionBody(body); } @Override public void unregister(Component c) { refreshSectionBody(body); } }; } } } private void refreshSectionBody(JPanel container) { JPanel p = container; QPanelUI ui; if (!(p.getUI() instanceof QPanelUI)) { ui = new QPanelUI(); p.setUI(ui); } else { ui = (QPanelUI) p.getUI(); } ui.assign(QPanelUI.createBoxUI()); if (p.getComponentCount() == 1) { Component child = p.getComponent(0); if (child instanceof JList || child instanceof JTree) { JComponent jc = (JComponent) child; Border b = jc.getBorder(); Insets i = b == null ? null : b.getBorderInsets(jc); boolean hasBorder = i != null && i.left > 0 && i.right > 0 && i.top > 0 && i.bottom > 0; ui.setFillColor(child.getBackground()); ui.setCornerSize(0); ui.setShadowSize(0); if (!hasBorder) { ui.setStrokeColor(Color.gray); } } else if (child instanceof JScrollPane) { ui.setFillColor(child.getBackground()); ui.setCornerSize(0); ui.setShadowSize(0); ui.setStrokeColor(new Color(0, 0, 0, 0)); } else if (child.isOpaque() && child.getBackground().getAlpha() > 0) { ui.setCornerSize(1); } } } }, false); } protected JButton createHeader(Section s) { return createCollapsibleButton("", true); } LayoutBlueprint animatingBlueprint; protected Semaphore midanimation = new Semaphore(1); /** Return the header button associated with a Section. */ public JButton getHeader(final Section section) { JButton header = (JButton) section.getProperty(HEADER); if (header == null) { header = createHeader(section); final JButton headerRef = header; PropertyChangeListener nameListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt == null || NAME.equals(evt.getPropertyName())) { headerRef.setText(section.getName()); } } }; section.addPropertyChangeListener(nameListener); nameListener.propertyChange(null); header.addPropertyChangeListener(COLLAPSED, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { midanimation.acquireUninterruptibly(); animatingBlueprint = new LayoutBlueprint(true); String p = CollapsibleContainer.class.getName() + "#temp"; putClientProperty(p, 0f); AnimationManager.setTargetProperty( CollapsibleContainer.this, p, animatingBlueprint); } }); section.setProperty(HEADER, header); headers.add(header); header.putClientProperty(SECTION, section); add(header); } return header; } /** * @return a button that can toggle the property <code>COLLAPSED</code> if * the property <code>COLLAPSIBLE</code> is <code>true</code>. * <p> * This button (by default) uses a <code>QButtonUI</code>, so if you * configure it's position then you can toggle off certain parts of * the border. * <p> * The following property of this button are automatically * maintained through a set of listeners: * <ul> * <li>Request Focus Enabled</li> * <li>Focusable</li> * <li>Icon</li> * <li>COLLAPSED</li> * <li>Internal properties including ROTATION and TARGET_ROTATION</li> * </ul> */ public static JButton createCollapsibleButton() { return createCollapsibleButton("", true); } /** * * @param text * the text in this button * @param includeLeftAndRightEdges * whether the left and right edges should be visible * @param collapsible * whether this button should initially be collapsible. * @return a button that can toggle the property <code>COLLAPSED</code> if * the property <code>COLLAPSIBLE</code> is <code>true</code>. * <p> * This button (by default) uses a <code>QButtonUI</code>, so if you * configure it's position then you can toggle off certain parts of * the border. * <p> * The following property of this button are automatically * maintained through a set of listeners: * <ul> * <li>Request Focus Enabled</li> * <li>Focusable</li> * <li>Icon</li> * <li>COLLAPSED</li> * <li>Internal properties including ROTATION and TARGET_ROTATION</li> * </ul> */ public static JButton createCollapsibleButton(String text, boolean collapsible) { final JButton button = new JButton(); QButtonUI ui = new GradientButtonUI(); button.setContentAreaFilled(false); button.setUI(ui); button.putClientProperty(QButtonUI.PROPERTY_STROKE_PAINTED, Boolean.FALSE); button.setFont(UIManager.getFont("Label.font")); button.setText(text); button.putClientProperty(QButtonUI.PROPERTY_HORIZONTAL_POSITION, HorizontalPosition.MIDDLE); // TODO: the focus ring is 1 pixel off when the stroke is not painted. // Setting the vertical position to middle helps hide this a little, but // it's still a bug. button.putClientProperty(QButtonUI.PROPERTY_VERTICAL_POSITION, VerticalPosition.MIDDLE); ui.setPaintFocus(PaintFocus.INSIDE); button.setHorizontalAlignment(SwingConstants.LEFT); button.setIconTextGap(2); button.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if ((Boolean) button.getClientProperty(COLLAPSIBLE)) { if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_UP) { button.putClientProperty(COLLAPSED, true); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_DOWN) { button.putClientProperty(COLLAPSED, false); e.consume(); } } } }); button.setOpaque(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Boolean b = (Boolean) button.getClientProperty(COLLAPSED); button.putClientProperty(COLLAPSED, !b); } }); // this is always rendered as enabled, whether it is or not button.putClientProperty(QButtonUI.PROPERTY_BOOLEAN_BUTTON_STATE, new ButtonState.Boolean(true, false, false, false, false)); button.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (COLLAPSIBLE.equals(evt.getPropertyName())) { boolean collapsible = ((Boolean) evt.getNewValue()); button.setEnabled(collapsible); updateIcon(); } else if (COLLAPSED.equals(evt.getPropertyName())) { boolean collapsed = ((Boolean) evt.getNewValue()); if (collapsed) { button.putClientProperty(TARGET_ROTATION, new Double(0)); } else { button.putClientProperty(TARGET_ROTATION, new Double( Math.PI / 2.0)); } } else if (ROTATION.equals(evt.getPropertyName())) { updateIcon(); } } private Icon triangleIcon = new TriangleIcon(SwingConstants.EAST, 10, 10); private void updateIcon() { if ((Boolean) button.getClientProperty(COLLAPSIBLE)) { Number n = (Number) button.getClientProperty(ROTATION); if (n == null) n = 0; float rotation = n.floatValue(); button.setIcon(new RotatedIcon(triangleIcon, rotation)); } else { button.setIcon(null); } } }); button.putClientProperty(COLLAPSIBLE, collapsible); button.putClientProperty(COLLAPSED, false); UIEffect.installTweenEffect(button, TARGET_ROTATION, ROTATION, .15f, 20); return button; } }
package com.realcomp.data.conversion; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.logging.Logger; /** * * @author krenfro */ @com.realcomp.data.annotation.Converter("lookup") public class Lookup extends StringConverter{ private static final Logger logger = Logger.getLogger(Lookup.class.getName()); private String source; private String delimiter = "\t"; private Map<String,String> table; private void initializeTable() throws IOException{ table = new HashMap<>(); try( BufferedReader reader = new BufferedReader(new FileReader(source))){ String s = reader.readLine(); while (s != null){ String[] tokens = s.split(delimiter); if (tokens.length >= 2){ table.put(tokens[0], tokens[1]); } s = reader.readLine(); } } } @Override public Object convert(Object value) throws ConversionException{ if (table == null){ try{ initializeTable(); } catch (IOException ex){ throw new ConversionException(ex); } } Object result = value; if (value != null){ String key = value.toString(); String found = table.get(key); if (found != null){ result = found; } } return result; } public String getSource(){ return source; } public void setSource(String source){ this.source = source; } public String getDelimiter(){ return delimiter; } public void setDelimiter(String delimiter){ this.delimiter = delimiter; } @Override public Lookup copyOf(){ Lookup copy = new Lookup(); copy.setSource(source); copy.setDelimiter(delimiter); return copy; } @Override public int hashCode(){ int hash = 5; hash = 67 * hash + Objects.hashCode(this.source); hash = 67 * hash + Objects.hashCode(this.delimiter); return hash; } @Override public boolean equals(Object obj){ if (obj == null){ return false; } if (getClass() != obj.getClass()){ return false; } final Lookup other = (Lookup) obj; if (!Objects.equals(this.source, other.source)){ return false; } if (!Objects.equals(this.delimiter, other.delimiter)){ return false; } return true; } }
package com.sandwell.JavaSimulation3D; import java.util.ArrayList; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.FormatInput; import com.jaamsim.input.OutputListInput; import com.jaamsim.input.ValueInput; import com.jaamsim.input.ValueListInput; import com.jaamsim.math.Color4d; import com.jaamsim.ui.FrameBox; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; import com.sandwell.JavaSimulation.ColorListInput; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleListInput; import com.sandwell.JavaSimulation.DoubleVector; import com.sandwell.JavaSimulation.EntityInput; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.IntegerInput; import com.sandwell.JavaSimulation.Keyword; import com.sandwell.JavaSimulation.Process; import com.sandwell.JavaSimulation.StringInput; import com.jaamsim.input.OutputHandle; public class Graph extends DisplayEntity { /** * A struct containing all the information pertaining to a specific series */ public static class SeriesInfo { public double[] values; public int numPoints; // The first point to draw from the start (used to be confusingly called index) public OutputHandle out; // The source of the data for the series public double lineWidth; public Color4d lineColour; } protected final ArrayList<SeriesInfo> primarySeries; protected final ArrayList<SeriesInfo> secondarySeries; private Class<? extends Unit> dataUnitType; // unit type for the graphed lines plotted against the y-axis private Class<? extends Unit> secondaryDataUnitType; // unit type for the graphed lines plotted against the secondary y-axis static int ENTITY_ONLY = 0; static int PARAMETER_ONLY = 1; static int ENTITY_PARAMETER = 2; // Data category @Keyword(description= "Text for the graph title.", example = "Graph1 Title { 'Title of the Graph' }") private final StringInput title; @Keyword(description = "The number of data points that can be displayed on the graph.\n" + " This parameter determines the resolution of the graph.", example = "Graph1 NumberOfPoints { 200 }") protected final IntegerInput numberOfPoints; @Keyword(description = "One or more sources of data to be graphed on the primary y-axis.\n" + "Each source is graphed as a separate line and is specified by an Entity and its Output.", example = "Graph1 DataSource { { Entity-1 Output-1 } { Entity-2 Output-2 } }") protected final OutputListInput<Double> dataSource; @Keyword(description = "A list of colors for the line series to be displayed.\n" + "Each color can be specified by either a color keyword or an RGB value.\n" + "For multiple lines, each color must be enclosed in braces.\n" + "If only one color is provided, it is used for all the lines.", example = "Graph1 LineColors { { red } { green } }") protected final ColorListInput lineColorsList; @Keyword(description = "A list of line widths (in pixels) for the line series to be displayed.\n" + "If only one line width is provided, it is used for all the lines.", example = "Graph1 LineWidths { 2 1 }") protected final DoubleListInput lineWidths; @Keyword(description = "One or more sources of data to be graphed on the secondary y-axis.\n" + "Each source is graphed as a separate line and is specified by an Entity and its Output.", example = "Graph1 SecondaryDataSource { { Entity-1 Output-1 } { Entity-2 Output-2 } }") protected final OutputListInput<Double> secondaryDataSource; @Keyword(description = "A list of colors for the secondary line series to be displayed.\n" + "Each color can be specified by either a color keyword or an RGB value.\n" + "For multiple lines, each color must be enclosed in braces.\n" + "If only one color is provided, it is used for all the lines.", example = "Graph1 SecondaryLineColors { { red } { green } }") protected final ColorListInput secondaryLineColorsList; @Keyword(description = "A list of line widths (in pixels) for the seconardy line series to be displayed.\n" + "If only one line width is provided, it is used for all the lines.", example = "Graph1 SecondaryLineWidths { 2 1 }") protected final DoubleListInput secondaryLineWidths; // X-Axis category @Keyword(description = "The time unit to be used for the x-axis.", example = "Graph1 XAxisUnit { h }") private final EntityInput<TimeUnit> xAxisUnit; @Keyword(description = "The start time for the x-axis relative to the present time.\n" + "The present time is 0 for this axis.", example = "Graph1 StartTime { -48 h }") protected final ValueInput startTime; @Keyword(description = "The end time for the x-axis relative to the present time.\n" + "The present time is 0 for this axis.", example = "Graph1 EndTime { 8 h }") protected final ValueInput endTime; @Keyword(description = "The time increment between the tick marks on the x-axis.", example = "Graph1 TimeInterval { 8 h }") private final ValueInput timeInterval; @Keyword(description = "The Java format to be used for the tick mark values on the x-axis.\n" + "For example, the format %.1fs would dispaly the value 5 as 5.0s.", example = "Graph1 XAxisLabelFormat { %.1fs }") private final FormatInput xAxisLabelFormat; @Keyword(description = "A list of time values between StartTime and EndTime where vertical gridlines are inserted.", example = "Graph1 XLines { -48 -40 -32 -24 -16 -8 0 h }") private final ValueListInput xLines; @Keyword(description = "The color of the vertical gridlines (or a list corresponding to the colour of each " + "gridline defined in XLines), defined using a colour keyword or RGB values.", example = "Graph1 XLinesColor { gray76 }") private final ColorListInput xLinesColor; // Y-Axis category @Keyword(description = "Title of the y-axis, enclosed in single quotes, rotated by 90 degrees counter-clockwise.", example = "Graph1 YAxisTitle { 'Water Height (m)' }") private final StringInput yAxisTitle; @Keyword(description = "The unit to be used for the y-axis.\n" + "The unit chosen must be consistent with the unit type for the DataSource value,\n" + "i.e. if the data has units of distance, then unit must be a distance unit such as meters.", example = "Graph1 YAxisUnit { t/h }") private final EntityInput<? extends Unit> yAxisUnit; @Keyword(description = "The minimum value for the y-axis.", example = "Graph1 YAxisStart { 0 t/h }") private final ValueInput yAxisStart; @Keyword(description = "The maximum value for the y-axis.", example = "Graph1 YAxisEnd { 5 t/h }") private final ValueInput yAxisEnd; @Keyword(description = "The interval between y-axis labels.", example = "Graph1 YAxisInterval { 1 t/h }") private final ValueInput yAxisInterval; @Keyword(description = "The Java format to be used for the tick mark values on the y-axis.\n" + "For example, the format %.1f would dispaly the value 5 as 5.0.", example = "Graph1 YAxisLabelFormat { %.1f }") private final FormatInput yAxisLabelFormat; @Keyword(description = "A list of values at which to insert horizontal gridlines.", example ="Graph1 YLines { 0 0.5 1 1.5 2 2.5 3 t/h }") private final ValueListInput yLines; @Keyword(description = "The colour of the horizontal gridlines (or a list corresponding to the colour of each " + "gridline defined in YLines), defined using a colour keyword or RGB values.", example = "Graph1 YLinesColor { gray76 }") private final ColorListInput yLinesColor; // Secondary Y-Axis category @Keyword(description = "Title of the secondary y-axis, enclosed in single quotes, rotated by 90 degrees clockwise.", example = "Graph1 SecondaryYAxisTitle { 'Water Height (m)' }") private final StringInput secondaryYAxisTitle; @Keyword(description = "The unit to be used for the secondary y-axis.\n" + "The unit chosen must be consistent with the unit type for the DataSource value,\n" + "i.e. if the data has units of distance, then unit must be a distance unit such as meters.", example = "Graph1 SecondaryYAxisUnit { m }") private final EntityInput<? extends Unit> secondaryYAxisUnit; @Keyword(description = "The minimum value for the secondary y-axis.", example = "Graph1 SecondaryYAxisStart { 0 m }") private final ValueInput secondaryYAxisStart; @Keyword(description = "The maximum value for the secondary y-axis.", example = "Graph1 SecondaryYAxisEnd { 5 m }") private final ValueInput secondaryYAxisEnd; @Keyword(description = "The interval between secondary y-axis labels.", example = "Graph1 SecondaryYAxisInterval { 1 m }") private final ValueInput secondaryYAxisInterval; @Keyword(description = "The Java format to be used for the tick mark values on the secondary y-axis.\n" + "For example, the format %.1f would dispaly the value 5 as 5.0.", example = "Graph1 SecondaryYAxisLabelFormat { %.1f }") private final FormatInput secondaryYAxisLabelFormat; { // Data category title = new StringInput("Title", "Data", "Graph Title"); this.addInput(title, true); numberOfPoints = new IntegerInput("NumberOfPoints", "Data", 100); numberOfPoints.setValidRange(0, Integer.MAX_VALUE); this.addInput(numberOfPoints, true); dataSource = new OutputListInput<Double>(Double.class, "DataSource", "Data", null); this.addInput(dataSource, true); ArrayList<Color4d> defLineColor = new ArrayList<Color4d>(0); defLineColor.add(ColourInput.getColorWithName("red")); lineColorsList = new ColorListInput("LineColours", "Data", defLineColor); lineColorsList.setValidCountRange(1, Integer.MAX_VALUE); this.addInput(lineColorsList, true, "LineColors"); DoubleVector defLineWidths = new DoubleVector(); defLineWidths.add(1.0); lineWidths = new DoubleListInput("LineWidths", "Data", defLineWidths); lineWidths.setValidCountRange(1, Integer.MAX_VALUE); this.addInput(lineWidths, true); secondaryDataSource = new OutputListInput<Double>(Double.class, "SecondaryDataSource", "Data", null); this.addInput(secondaryDataSource, true); ArrayList<Color4d> defSecondaryLineColor = new ArrayList<Color4d>(0); defSecondaryLineColor.add(ColourInput.getColorWithName("black")); secondaryLineColorsList = new ColorListInput("SecondaryLineColours", "Data", defSecondaryLineColor); secondaryLineColorsList.setValidCountRange(1, Integer.MAX_VALUE); this.addInput(secondaryLineColorsList, true, "SecondaryLineColors"); DoubleVector defSecondaryLineWidths = new DoubleVector(); defSecondaryLineWidths.add(1.0); secondaryLineWidths = new DoubleListInput("SecondaryLineWidths", "Data", defSecondaryLineWidths); secondaryLineWidths.setValidCountRange(1, Integer.MAX_VALUE); this.addInput(secondaryLineWidths, true); // X-Axis category xAxisUnit = new EntityInput<TimeUnit>(TimeUnit.class, "XAxisUnit", "X-Axis", null); this.addInput(xAxisUnit, true); startTime = new ValueInput("StartTime", "X-Axis", -60.0d); startTime.setUnitType(TimeUnit.class); startTime.setValidRange(Double.NEGATIVE_INFINITY, 1.0e-6); this.addInput(startTime, true); endTime = new ValueInput("EndTime", "X-Axis", 0.0d); endTime.setUnitType(TimeUnit.class); endTime.setValidRange(0.0, Double.POSITIVE_INFINITY); this.addInput(endTime, true); timeInterval = new ValueInput("TimeInterval", "X-Axis", 10.0d); timeInterval.setUnitType(TimeUnit.class); timeInterval.setValidRange(1.0e-6, Double.POSITIVE_INFINITY); this.addInput(timeInterval, true); xAxisLabelFormat = new FormatInput("XAxisLabelFormat", "X-Axis", "%.0fs"); this.addInput(xAxisLabelFormat, true); DoubleVector defXLines = new DoubleVector(); defXLines.add(-20.0); defXLines.add(-40.0); xLines = new ValueListInput("XLines", "X-Axis", defXLines); xLines.setUnitType(TimeUnit.class); this.addInput(xLines, true); ArrayList<Color4d> defXlinesColor = new ArrayList<Color4d>(0); defXlinesColor.add(ColourInput.getColorWithName("gray50")); xLinesColor = new ColorListInput("XLinesColor", "X-Axis", defXlinesColor); this.addInput(xLinesColor, true, "XLinesColour"); // Y-Axis category yAxisTitle = new StringInput("YAxisTitle", "Y-Axis", "Y-Axis Title"); this.addInput(yAxisTitle, true); yAxisUnit = new EntityInput<Unit>(Unit.class, "YAxisUnit", "Y-Axis", null); this.addInput(yAxisUnit, true); yAxisStart = new ValueInput("YAxisStart", "Y-Axis", 0.0); yAxisStart.setUnitType(UserSpecifiedUnit.class); this.addInput(yAxisStart, true); yAxisEnd = new ValueInput("YAxisEnd", "Y-Axis", 5.0d); yAxisEnd.setUnitType(UserSpecifiedUnit.class); this.addInput(yAxisEnd, true); yAxisInterval = new ValueInput("YAxisInterval", "Y-Axis", 1.0d); yAxisInterval.setUnitType(UserSpecifiedUnit.class); yAxisInterval.setValidRange(1.0e-10, Double.POSITIVE_INFINITY); this.addInput(yAxisInterval, true); yAxisLabelFormat = new FormatInput("YAxisLabelFormat", "Y-Axis", "%.1f"); this.addInput(yAxisLabelFormat, true); DoubleVector defYLines = new DoubleVector(); defYLines.add(1.0); defYLines.add(2.0); defYLines.add(3.0); defYLines.add(4.0); yLines = new ValueListInput("YLines", "Y-Axis", defYLines); yLines.setUnitType(UserSpecifiedUnit.class); this.addInput(yLines, true); ArrayList<Color4d> defYlinesColor = new ArrayList<Color4d>(0); defYlinesColor.add(ColourInput.getColorWithName("gray50")); yLinesColor = new ColorListInput("YLinesColor", "Y-Axis", defYlinesColor); this.addInput(yLinesColor, true, "YLinesColour"); // Secondary Y-Axis category secondaryYAxisTitle = new StringInput("SecondaryYAxisTitle", "Secondary Y-Axis", "Secondary Y-Axis Title"); this.addInput(secondaryYAxisTitle, true); secondaryYAxisUnit = new EntityInput<Unit>(Unit.class, "SecondaryYAxisUnit", "Secondary Y-Axis", null); this.addInput(secondaryYAxisUnit, true); secondaryYAxisStart = new ValueInput("SecondaryYAxisStart", "Secondary Y-Axis", 0.0); secondaryYAxisStart.setUnitType(UserSpecifiedUnit.class); this.addInput(secondaryYAxisStart, true); secondaryYAxisEnd = new ValueInput("SecondaryYAxisEnd", "Secondary Y-Axis", 5.0); secondaryYAxisEnd.setUnitType(UserSpecifiedUnit.class); this.addInput(secondaryYAxisEnd, true); secondaryYAxisInterval = new ValueInput("SecondaryYAxisInterval", "Secondary Y-Axis", 1.0); secondaryYAxisInterval.setUnitType(UserSpecifiedUnit.class); secondaryYAxisInterval.setValidRange(1.0e-10, Double.POSITIVE_INFINITY); this.addInput(secondaryYAxisInterval, true); secondaryYAxisLabelFormat = new FormatInput("SecondaryYAxisLabelFormat", "Secondary Y-Axis", "%.1f"); this.addInput(secondaryYAxisLabelFormat, true); } public Graph() { primarySeries = new ArrayList<SeriesInfo>(); secondarySeries = new ArrayList<SeriesInfo>(); } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if (in == dataSource) { ArrayList<OutputHandle> outs = dataSource.getValue(); if (outs.isEmpty()) return; Class<? extends Unit> temp = outs.get(0).getUnitType(); for (int i=1; i<outs.size(); i++) { if( outs.get(i).getUnitType() != temp ) throw new InputErrorException("All inputs for keyword DataSource must have the same unit type./n" + "The unit type for the first source is %s", temp); } dataUnitType = temp; yAxisStart.setUnitType(dataUnitType); yAxisEnd.setUnitType(dataUnitType); yAxisInterval.setUnitType(dataUnitType); yLines.setUnitType(dataUnitType); FrameBox.valueUpdate(); // show the new units in the Input Editor } if (in == secondaryDataSource) { ArrayList<OutputHandle> outs = secondaryDataSource.getValue(); if (outs.isEmpty()) return; Class<? extends Unit> temp = outs.get(0).getUnitType(); for (int i=1; i<outs.size(); i++) { if( outs.get(i).getUnitType() != temp ) throw new InputErrorException("All inputs for keyword SecondaryDataSource must have the same unit type./n" + "The unit type for the first source is %s", temp); } secondaryDataUnitType = temp; secondaryYAxisStart.setUnitType(secondaryDataUnitType); secondaryYAxisEnd.setUnitType(secondaryDataUnitType); secondaryYAxisInterval.setUnitType(secondaryDataUnitType); FrameBox.valueUpdate(); // show the new units in the Input Editor } if (in == lineColorsList) { for (int i = 0; i < primarySeries.size(); ++ i) { SeriesInfo info = primarySeries.get(i); info.lineColour = getLineColor(i, lineColorsList.getValue()); } } if (in == lineWidths) { for (int i = 0; i < primarySeries.size(); ++ i) { SeriesInfo info = primarySeries.get(i); info.lineWidth = getLineWidth(i, lineWidths.getValue()); } } if (in == secondaryLineColorsList) { for (int i = 0; i < secondarySeries.size(); ++ i) { SeriesInfo info = secondarySeries.get(i); info.lineColour = getLineColor(i, secondaryLineColorsList.getValue()); } } if (in == secondaryLineWidths) { for (int i = 0; i < secondarySeries.size(); ++ i) { SeriesInfo info = secondarySeries.get(i); info.lineWidth = getLineWidth(i, secondaryLineWidths.getValue()); } } } @Override public void validate() throws InputErrorException { super.validate(); if(yLinesColor.getValue().size() > 1) { Input.validateIndexedLists(yLines.getValue(), yLinesColor.getValue(), "YLines", "YLinesColor"); } if(xLinesColor.getValue().size() > 1) { Input.validateIndexedLists(xLines.getValue(), xLinesColor.getValue(), "XLines", "XLinesColor"); } if(lineColorsList.getValue().size() > 1){ Input.validateIndexedLists(dataSource.getValue(), lineColorsList.getValue(), "DataSource", "LinesColor"); } if(secondaryLineColorsList.getValue().size() > 1){ Input.validateIndexedLists(secondaryDataSource.getValue(), secondaryLineColorsList.getValue(), "SecondaryTargetEntityList", "SecondaryLinesColor"); } if(lineWidths.getValue().size() > 1) Input.validateIndexedLists(dataSource.getValue(), lineWidths.getValue(), "DataSource", "LineWidths"); if(secondaryLineWidths.getValue().size() > 1) Input.validateIndexedLists(secondaryDataSource.getValue(), secondaryLineWidths.getValue(), "SecondaryDataSource", "SecondaryLineWidths"); for( int i = 0; i < yLines.getValue().size(); i++ ) { double y = yLines.getValue().get( i ); if( y > yAxisEnd.getValue() || y < yAxisStart.getValue() ) { throw new InputErrorException("value for yLines should be in (%f, %f) range -- it is (%f)", yAxisStart.getValue(), yAxisEnd.getValue(), y); } } for( int i = 0; i < xLines.getValue().size(); i++ ) { double x = xLines.getValue().get( i ); if( x < startTime.getValue() || x > endTime.getValue() ) { throw new InputErrorException("value for xLines should be in (%f, %f) range -- it is (%f)", startTime.getValue(), endTime.getValue(), x); } } } @Override public void earlyInit(){ super.earlyInit(); primarySeries.clear(); secondarySeries.clear(); // Populate the primary series data structures populateSeriesInfo(primarySeries, dataSource); populateSeriesInfo(secondarySeries, secondaryDataSource); } private void populateSeriesInfo(ArrayList<SeriesInfo> infos, OutputListInput<Double> data) { ArrayList<OutputHandle> outs = data.getValue(); if( outs == null ) return; for (int outInd = 0; outInd < outs.size(); ++outInd) { SeriesInfo info = new SeriesInfo(); info.out = outs.get(outInd); info.values = new double[numberOfPoints.getValue()]; infos.add(info); } } private static class ProcessGraphTarget extends ProcessTarget { final Graph graph; ProcessGraphTarget(Graph graph) { this.graph = graph; } @Override public String getDescription() { return graph.getInputName() + ".processGraph"; } @Override public void process() { graph.processGraph(); } } @Override public void startUp() { super.startUp(); extraStartGraph(); for (int i = 0; i < primarySeries.size(); ++ i) { SeriesInfo info = primarySeries.get(i); info.lineColour = getLineColor(i, lineColorsList.getValue()); info.lineWidth = getLineWidth(i, lineWidths.getValue()); } for (int i = 0; i < secondarySeries.size(); ++i) { SeriesInfo info = secondarySeries.get(i); info.lineColour = getLineColor(i, secondaryLineColorsList.getValue()); info.lineWidth = getLineWidth(i, secondaryLineWidths.getValue()); } Process.start(new ProcessGraphTarget(this)); } /** * Hook for sub-classes to do some processing at startup */ protected void extraStartGraph() {} protected Color4d getLineColor(int index, ArrayList<Color4d> colorList) { if (colorList.size() == 1) return colorList.get(0); return colorList.get(index); } protected double getLineWidth(int index, DoubleVector widthList) { if (widthList.size() == 1) return widthList.get(0); return widthList.get(index); } /** * Initialize the data for the specified series */ private void setupSeriesData(SeriesInfo info, double xLength, double xInterval) { info.numPoints = 0; for( int i = 0; i * xInterval < endTime.getValue(); i++ ) { double presentValue = this.getCurrentValue( i * xInterval, info); info.values[info.numPoints++] = presentValue; } } /** * A hook method for descendant graph types to grab some processing time */ protected void extraProcessing() {} /** * Calculate values for the data series on the graph */ public void processGraph() { if( traceFlag ) this.trace( "processGraph()" ); double xLength = endTime.getValue() - startTime.getValue(); double xInterval = xLength/(numberOfPoints.getValue() -1); for (SeriesInfo info : primarySeries) { setupSeriesData(info, xLength, xInterval); } for (SeriesInfo info : secondarySeries) { setupSeriesData(info, xLength, xInterval); } while ( true ) { // Give processing time to sub-classes extraProcessing(); // Calculate values for the primary y-axis for (SeriesInfo info : primarySeries) { processGraph(info); } // Calculate values for the secondary y-axis for (SeriesInfo info : secondarySeries) { processGraph(info); } simWait( xInterval, 7 ); } } /** * Calculate values for the data series on the graph * @param info - the information for the series to be rendered */ public void processGraph(SeriesInfo info) { // Entity has been removed if(info.out == null) { return; } double t = getSimTime() + endTime.getValue(); double presentValue = this.getCurrentValue(t, info); if (info.numPoints < info.values.length) { info.values[info.numPoints++] = presentValue; } else { System.arraycopy(info.values, 1, info.values, 0, info.values.length - 1); info.values[info.values.length - 1] = presentValue; } } /** * Return the current value for the series * @return double */ protected double getCurrentValue(double simTime, SeriesInfo info) { return info.out.getValueAsDouble(simTime, 0.0); } public ArrayList<SeriesInfo> getPrimarySeries() { return primarySeries; } public ArrayList<SeriesInfo> getSecondarySeries() { return secondarySeries; } public String getTitle() { return title.getValue(); } public int getNumberOfPoints() { return numberOfPoints.getValue(); } public TimeUnit getXAxisUnit() { return xAxisUnit.getValue(); } public double getStartTime() { return startTime.getValue(); } public double getEndTime() { return endTime.getValue(); } public double getTimeInterval() { return timeInterval.getValue(); } public String getXAxisLabelFormat() { return xAxisLabelFormat.getValue(); } public String getYAxisTitle() { return yAxisTitle.getValue(); } public Unit getYAxisUnit() { return yAxisUnit.getValue(); } public double getYAxisStart() { return yAxisStart.getValue(); } public double getYAxisEnd() { return yAxisEnd.getValue(); } public double getYAxisInterval() { return yAxisInterval.getValue(); } public String getYAxisLabelFormat() { return yAxisLabelFormat.getValue(); } public String getSecondaryYAxisTitle() { return secondaryYAxisTitle.getValue(); } public Unit getSecondaryYAxisUnit() { return secondaryYAxisUnit.getValue(); } public double getSecondaryYAxisStart() { return secondaryYAxisStart.getValue(); } public double getSecondaryYAxisEnd() { return secondaryYAxisEnd.getValue(); } public double getSecondaryYAxisInterval() { return secondaryYAxisInterval.getValue(); } public String getSecondaryYAxisLabelFormat() { return secondaryYAxisLabelFormat.getValue(); } public DoubleVector getXLines() { return xLines.getValue(); } public ArrayList<Color4d> getXLineColours() { return xLinesColor.getValue(); } public DoubleVector getYLines() { return yLines.getValue(); } public ArrayList<Color4d> getYLineColours() { return yLinesColor.getValue(); } // OUTPUT METHODS /** * Return the value for the given data point index for the given series index. * @param seriesIndex - the index of the data series (starting from 1) * @param pointIndex - the index of the data point (starting from 1) */ public double Series_Point( Integer seriesIndex, Integer pointIndex ) { return primarySeries.get(seriesIndex).values[pointIndex - 1]; } }
package com.sdl.selenium.extjs6.panel; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Panel extends WebLocator { private static final Logger LOGGER = LoggerFactory.getLogger(Panel.class); public Panel() { withClassName("Panel"); withBaseCls("x-panel"); WebLocator header = new WebLocator().withClasses("x-title").withRoot(" withTemplateTitle(new WebLocator(header)); } public Panel(WebLocator container) { this(); withContainer(container); } public Panel(WebLocator container, String title) { this(container); withTitle(title, SearchType.EQUALS); } private WebLocator getCollapseEl(String type) {
package com.verisign.getdns; /** * This class contains important constants for keys and values for GetDNS request and responses. * @author Prithvi * */ public interface GetDNSConstants { /** * Possible keys to be used in the request for extensions. */ public static final String DNSSEC_RETURN_VALIDATION_CHAIN = "dnssec_return_validation_chain"; public static final String DNSSEC_RETURN_ONLY_SECURE = "dnssec_return_only_secure"; public static final String DNSSEC_RETURN_STATUS = "dnssec_return_status"; public static final String RETURN_BOTH_V4_AND_V6 = "return_both_v4_and_v6"; public static final String RETURN_CALL_DEBUGGING = "return_call_debugging"; public static final String SPECIFY_CLASS = "specify_class"; public static final String ADD_WARNING_FOR_BAD_DNS = "add_warning_for_bad_dns"; public static final String ADD_OPT_PARAMETERS = "add_opt_parameters"; /** * Possible values for enabling GetDNS extensions. */ public static final int GETDNS_EXTENSION_TRUE = 1000; public static final int GETDNS_EXTENSION_FALSE = 1001; /** * Constants related to passing address. */ public static final String IPV6 = "IPv6"; public static final String IPV4 = "IPv4"; public static final String ADDRESS_DATA = "address_data"; public static final String ADDRESS_TYPE = "address_type"; }
package de.bmoth.backend.z3; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.microsoft.z3.Context; import com.microsoft.z3.Sort; import com.microsoft.z3.Symbol; import de.bmoth.parser.ast.AbstractVisitor; import de.bmoth.parser.ast.nodes.*; import de.bmoth.parser.ast.types.*; public class Z3TypeInference { Map<TypedNode, Z3Type> types = new HashMap<>(); Map<DeclarationNode, Z3Type> declarationNodesTypes = new HashMap<>(); public void visitMachineNode(MachineNode machineNode) { Visitor visitor = new Visitor(); if (machineNode.getProperties() != null) { visitor.visitPredicateNode(machineNode.getProperties(), null); } if (machineNode.getInitialisation() != null) { visitor.visitSubstitutionNode(machineNode.getInitialisation(), null); } machineNode.getOperations().forEach(op -> visitor.visitSubstitutionNode(op.getSubstitution(), null)); if (machineNode.getInvariant() != null) { visitor.visitPredicateNode(machineNode.getInvariant(), null); } } public void visitPredicateNode(PredicateNode node) { Visitor visitor = new Visitor(); visitor.visitPredicateNode(node, null); } interface Z3Type { } enum Basic { INTEGER, BOOL } class Z3BasicType implements Z3Type { Basic kind; public Z3BasicType(Basic kind) { this.kind = kind; } } class Z3SequenceType implements Z3Type { Z3Type subtype; Z3SequenceType(Z3Type type) { subtype = type; } public Z3Type getSubtype() { return this.subtype; } } class Z3SetType implements Z3Type { Z3Type subtype; Z3SetType(Z3Type type) { subtype = type; } public Z3Type getSubtype() { return this.subtype; } } class Z3DeferredType implements Z3Type { String name; Z3DeferredType(String name) { this.name = name; } public String getSetName() { return name; } } class Z3EnumeratedSetType implements Z3Type { String name; List<String> elements; Z3EnumeratedSetType(String name, List<String> elements) { this.name = name; this.elements = elements; } public String getSetName() { return name; } public List<String> getElements() { return elements; } } class Z3CoupleType implements Z3Type { Z3Type left; Z3Type right; Z3CoupleType(Z3Type left, Z3Type right) { this.left = left; this.right = right; } public Z3Type getLeftType() { return this.left; } public Z3Type getRightType() { return this.right; } } public Sort getZ3Sort(TypedNode node, Context z3Context) { if (declarationNodesTypes.containsKey(node)) { Z3Type z3Type = declarationNodesTypes.get(node); return getZ3Sort(z3Type, z3Context); } else if (types.containsKey(node)) { Z3Type z3Type = types.get(node); return getZ3Sort(z3Type, z3Context); } else { return getZ3Sort(convertBTypeToZ3Type(node.getType()), z3Context); } } public Sort getZ3Sort(BType bType, Context z3Context) { return getZ3Sort(convertBTypeToZ3Type(bType), z3Context); } public Sort getZ3Sort(Z3Type t, Context z3Context) { if (t instanceof Z3BasicType) { switch (((Z3BasicType) t).kind) { case INTEGER: return z3Context.getIntSort(); case BOOL: return z3Context.getBoolSort(); default: break; } } else if (t instanceof Z3SetType) { Sort subSort = getZ3Sort(((Z3SetType) t).subtype, z3Context); return z3Context.mkSetSort(subSort); } else if (t instanceof Z3CoupleType) { Z3CoupleType couple = (Z3CoupleType) t; Sort left = getZ3Sort(couple.left, z3Context); Sort right = getZ3Sort(couple.right, z3Context); Sort[] subSorts = new Sort[2]; subSorts[0] = left; subSorts[1] = right; return z3Context.mkTupleSort(z3Context.mkSymbol("couple"), new Symbol[] { z3Context.mkSymbol("left"), z3Context.mkSymbol("right") }, subSorts); } else if (t instanceof Z3SequenceType) { Sort subSort = getZ3Sort(((Z3SequenceType) t).subtype, z3Context); Sort intType = z3Context.getIntSort(); Sort[] subSorts = new Sort[2]; subSorts[0] = z3Context.mkArraySort(intType, subSort); subSorts[1] = intType; return z3Context.mkTupleSort(z3Context.mkSymbol("sequence"), new Symbol[] { z3Context.mkSymbol("array"), z3Context.mkSymbol("size") }, subSorts); } else if (t instanceof Z3DeferredType) { return z3Context.mkUninterpretedSort(((Z3DeferredType) t).name); } else if (t instanceof Z3EnumeratedSetType) { List<String> elements = ((Z3EnumeratedSetType) t).elements; String[] array = elements.toArray(new String[elements.size()]); return z3Context.mkEnumSort(((Z3EnumeratedSetType) t).name, array); } throw new AssertionError("Missing Type Conversion: " + t.getClass()); } protected Z3Type updateDeclarationType(DeclarationNode node, Z3Type newZ3Type) { if (declarationNodesTypes.containsKey(node)) { Z3Type z3Type = declarationNodesTypes.get(node); Z3Type unification = unify(z3Type, newZ3Type); declarationNodesTypes.put(node, unification); return unification; } else { declarationNodesTypes.put(node, newZ3Type); return newZ3Type; } } private Z3Type unify(Z3Type z3Type, Z3Type newZ3Type) { if (z3Type instanceof Z3SequenceType && newZ3Type instanceof Z3SetType) { return newZ3Type; } else if (newZ3Type instanceof Z3SequenceType && z3Type instanceof Z3SetType) { return z3Type; } else return newZ3Type; } protected Z3Type setSubType(TypedNode node, Z3Type subType) { types.put(node, subType); return subType; } protected Z3Type getZ3TypeOfNode(TypedNode node) { if (types.containsKey(node)) { return types.get(node); } else { return convertBTypeToZ3Type(node.getType()); } } protected Z3Type convertBTypeToZ3Type(BType bType) { if (bType instanceof IntegerType) { return new Z3BasicType(Basic.INTEGER); } else if (bType instanceof BoolType) { return new Z3BasicType(Basic.BOOL); } else if (bType instanceof de.bmoth.parser.ast.types.SetType) { BType subtype = ((de.bmoth.parser.ast.types.SetType) bType).getSubtype(); return new Z3SetType(convertBTypeToZ3Type(subtype)); } else if (bType instanceof CoupleType) { de.bmoth.parser.ast.types.CoupleType couple = (de.bmoth.parser.ast.types.CoupleType) bType; return new Z3CoupleType(convertBTypeToZ3Type(couple.getLeft()), convertBTypeToZ3Type(couple.getRight())); } else if (bType instanceof UserDefinedElementType) { UserDefinedElementType userType = (UserDefinedElementType) bType; if (null == userType.getElements()) { return new Z3DeferredType(userType.getSetName()); } else { return new Z3EnumeratedSetType(userType.getSetName(), userType.getElements()); } } throw new AssertionError(bType); } class Visitor implements AbstractVisitor<Z3Type, Void> { @Override public Z3Type visitExprOperatorNode(ExpressionOperatorNode node, Void expected) { List<ExprNode> arguments = node.getExpressionNodes(); arguments.forEach(e -> visitExprNode(e, expected)); switch (node.getOperator()) { case FRONT: case TAIL: case CONCAT: case INSERT_TAIL: case RESTRICT_FRONT: case RESTRICT_TAIL: return setSubType(node, getZ3TypeOfNode(arguments.get(0))); case INSERT_FRONT: return setSubType(node, getZ3TypeOfNode(arguments.get(1))); case SEQ_ENUMERATION: return setSubType(node, new Z3SequenceType(getZ3TypeOfNode(arguments.get(0)))); case EMPTY_SEQUENCE: { de.bmoth.parser.ast.types.SetType setType = (de.bmoth.parser.ast.types.SetType) node.getType(); de.bmoth.parser.ast.types.CoupleType c = (de.bmoth.parser.ast.types.CoupleType) setType.getSubtype(); return setSubType(node, new Z3SequenceType(convertBTypeToZ3Type(c.getRight()))); } default: return setSubType(node, convertBTypeToZ3Type(node.getType())); } } @Override public Z3Type visitIdentifierExprNode(IdentifierExprNode node, Void expected) { return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitCastPredicateExpressionNode(CastPredicateExpressionNode node, Void expected) { return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitNumberNode(NumberNode node, Void expected) { return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitQuantifiedExpressionNode(QuantifiedExpressionNode node, Void expected) { AbstractVisitor.super.visitPredicateNode(node.getPredicateNode(), expected); if (node.getExpressionNode() != null) { visitExprNode(node.getExpressionNode(), expected); } return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitIdentifierPredicateNode(IdentifierPredicateNode node, Void expected) { return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitPredicateOperatorNode(PredicateOperatorNode node, Void expected) { node.getPredicateArguments().forEach(e -> AbstractVisitor.super.visitPredicateNode(e, expected)); return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitPredicateOperatorWithExprArgs(PredicateOperatorWithExprArgsNode node, Void expected) { List<ExprNode> arguments = node.getExpressionNodes(); switch (node.getOperator()) { case EQUAL: case NOT_EQUAL: ExprNode left = arguments.get(0); ExprNode right = arguments.get(1); if (left instanceof IdentifierExprNode) { return updateDeclarationType(((IdentifierExprNode) left).getDeclarationNode(), visitExprNode(right, expected)); } else if (right instanceof IdentifierExprNode) { return updateDeclarationType(((IdentifierExprNode) right).getDeclarationNode(), visitExprNode(left, expected)); } else { break; } default: break; } arguments.forEach(a -> visitExprNode(a, expected)); return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitQuantifiedPredicateNode(QuantifiedPredicateNode node, Void expected) { AbstractVisitor.super.visitPredicateNode(node.getPredicateNode(), expected); return setSubType(node, convertBTypeToZ3Type(node.getType())); } @Override public Z3Type visitSkipSubstitutionNode(SkipSubstitutionNode node, Void expected) { return null; } @Override public Z3Type visitIfSubstitutionNode(IfSubstitutionNode node, Void expected) { node.getConditions().forEach(t -> AbstractVisitor.super.visitPredicateNode(t, expected)); node.getSubstitutions().forEach(t -> visitSubstitutionNode(t, expected)); if (node.getElseSubstitution() != null) { visitSubstitutionNode(node.getElseSubstitution(), expected); } return null; } @Override public Z3Type visitConditionSubstitutionNode(ConditionSubstitutionNode node, Void expected) { AbstractVisitor.super.visitPredicateNode(node.getCondition(), expected); visitSubstitutionNode(node.getSubstitution(), expected); return null; } @Override public Z3Type visitAnySubstitution(AnySubstitutionNode node, Void expected) { AbstractVisitor.super.visitPredicateNode(node.getWherePredicate(), expected); visitSubstitutionNode(node.getThenSubstitution(), expected); return null; } @Override public Z3Type visitSelectSubstitutionNode(SelectSubstitutionNode node, Void expected) { node.getConditions().forEach(t -> AbstractVisitor.super.visitPredicateNode(t, expected)); node.getSubstitutions().forEach(t -> visitSubstitutionNode(t, expected)); if (node.getElseSubstitution() != null) { visitSubstitutionNode(node.getElseSubstitution(), expected); } return null; } @Override public Z3Type visitSingleAssignSubstitution(SingleAssignSubstitutionNode node, Void expected) { IdentifierExprNode identifier = node.getIdentifier(); DeclarationNode declarationNode = identifier.getDeclarationNode(); Z3Type exprType = visitExprNode(node.getValue(), expected); return updateDeclarationType(declarationNode, exprType); } @Override public Z3Type visitParallelSubstitutionNode(ParallelSubstitutionNode node, Void expected) { node.getSubstitutions().forEach(s -> visitSubstitutionNode(s, null)); return null; } @Override public Z3Type visitBecomesElementOfSubstitutionNode(BecomesElementOfSubstitutionNode node, Void expected) { Z3SetType setType = (Z3SetType) visitExprNode(node.getExpression(), expected); Z3Type type = setType.getSubtype(); if (node.getIdentifiers().size() == 1) { updateDeclarationType(node.getIdentifiers().get(0).getDeclarationNode(), type); } else { List<Z3Type> typesList = new ArrayList<>(); Z3CoupleType couple = (Z3CoupleType) type; while (node.getIdentifiers().size() - 1 > typesList.size()) { typesList.add(0, couple.getRightType()); couple = (Z3CoupleType) couple.getLeftType(); } typesList.add(0, couple); for (int i = 0; i < node.getIdentifiers().size(); i++) { updateDeclarationType(node.getIdentifiers().get(i).getDeclarationNode(), typesList.get(i)); } } return null; } @Override public Z3Type visitBecomesSuchThatSubstitutionNode(BecomesSuchThatSubstitutionNode node, Void expected) { AbstractVisitor.super.visitPredicateNode(node.getPredicate(), expected); return null; } } }
package de.galan.commons.bootstrap; /** * daniel should have written a comment here. * * @author daniel */ public class Launcher { public static void main(String[] args) { // TODO Snake, Guice, dirs, Application, JMX, Logging. } }
package core.kibana; import core.util.JSON; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static core.kibana.KibanaObject.visualization; /** * @author neo */ public class KibanaObjectBuilder { private static final String[] COLOR_PALETTE = new String[]{ "#F94144", "#F3722C", "#F8961E", "#F9844A", "#F9C74F", "#90BE6D", "#43AA8B", "#4D908E", "#577590", "#277DA1" }; final List<KibanaObject> objects = new ArrayList<>(); private int colorIndex; public String build() { buildVisualization(); return JSON.toJSON(objects); } private void buildVisualization() { objects.add(visualization(splitByTerm("action-count-by-response_code", "context.response_code"))); objects.add(visualization(splitByTerm("action-count-by-app", "app"))); objects.add(visualization(splitByTerm("action-count-by-action", "action"))); objects.add(visualization(elapsedByAction())); objects.add(visualization(percentile("action-elapsed", "elapsed", "elapsed", color(), new String[]{"99", "90", "50"}))); objects.add(visualization(percentile("action-cpu_time", "stats.cpu_time", "cpu time", color(), new String[]{"99", "90", "50"}))); objects.add(visualization(maxAvg("stat-sys_load", "stat", "stats.sys_load_avg", "sys load", color(), "number"))); objects.add(visualization(maxAvg("stat-cpu_usage", "stat", "stats.cpu_usage", "cpu usage", color(), "percent"))); objects.add(visualization(statMem())); objects.add(visualization(maxAvg("stat-thread", "stat", "stats.thread_count", "thread count", color(), "number"))); objects.add(visualization(heap("jvm"))); objects.add(visualization(gc("jvm"))); objects.add(visualization(maxAvg("stat-http_active_requests", "stat", "stats.http_active_requests", "active http requests", color(), "number"))); objects.add(visualization(valueTemplate(maxAvg("action-http_delay", "action", "stats.http_delay", "http delay", color(), "number"), "{{value}} ns"))); objects.add(visualization(actionHTTPIO())); objects.add(visualization(percentile("perf-http_client", "perf_stats.http.total_elapsed", "total elapsed", color(), new String[]{"99", "90", "50"}))); objects.add(visualization(percentile("perf-http_client_dns", "perf_stats.http_dns.total_elapsed", "total elapsed", color(), new String[]{"99", "90", "50"}))); objects.add(visualization(percentile("perf-http_client_conn", "perf_stats.http_conn.total_elapsed", "total elapsed", color(), new String[]{"99", "90", "50"}))); objects.add(visualization(perfHTTPIO())); objects.add(visualization(httpRetries())); addPerf("db", "rows", "db"); objects.add(visualization(poolCount("db"))); objects.add(visualization(dbQueries())); addPerf("redis", "keys", "redis"); objects.add(visualization(poolCount("redis"))); objects.add(visualization(max("stat-redis_keys", "stat", "stats.redis_keys", "keys", "number", color()))); objects.add(visualization(usedMax("stat-redis_mem", "stats.redis_mem_max", "stats.redis_mem_used", "memory"))); objects.add(visualization(poolCount("redis-cache"))); objects.add(visualization(poolCount("redis-session"))); objects.add(visualization(cacheHitRate())); objects.add(visualization(maxAvg("stat-cache_size", "stat", "stats.cache_size", "cache size", color(), "number"))); objects.add(visualization(valueTemplate(maxAvg("action-consumer_delay", "action", "stats.consumer_delay", "consumer delay", color(), "number"), "{{value}} ns"))); objects.add(visualization(valueTemplate(maxAvg("action-task_delay", "action", "stats.task_delay", "task delay", color(), "number"), "{{value}} ns"))); objects.add(visualization(kafkaConsumerConsumedRate())); objects.add(visualization(kafkaConsumerFetchRate(color()))); objects.add(visualization(max("stat-kafka_consumer_max_lag", "stat", "stats.kafka_consumer_records_max_lag", "max lag", "number", color()))); objects.add(visualization(kafkaProducerProducedRate(null))); objects.add(visualization(kafkaProducerRequestSize(null))); objects.add(visualization(kafkaProducerProducedRate("log-forwarder"))); objects.add(visualization(kafkaProducerRequestSize("log-forwarder"))); addPerf("kafka", "msgs", "kafka"); objects.add(visualization(heap("kafka"))); objects.add(visualization(gc("kafka"))); objects.add(visualization(kafkaBytesRate())); objects.add(visualization(max("stat-kafka_disk", "stat", "stats.kafka_disk_used", "used disk size", "bytes", color()))); addPerf("es", "docs", "elasticsearch"); objects.add(visualization(usedMax("stat-es_disk", "stats.es_disk_max", "stats.es_disk_used", "disk"))); objects.add(visualization(heap("es"))); objects.add(visualization(gc("es"))); objects.add(visualization(max("stat-es_docs", "stat", "stats.es_docs", "docs", "number", color()))); addPerf("mongo", "docs", "mongo"); objects.add(visualization(traceCountByResult())); objects.add(visualization(businessUniqueVisitor())); objects.add(visualization(metric("business-customer_registered", "stats.customer_registered", "Customer Registered"))); objects.add(visualization(metric("business-order_amount", "stats.order_amount", "Total Order Amount"))); objects.add(visualization(metric("business-order_placed", "stats.order_placed", "Order Placed"))); } private void addPerf(String name, String unit, String key) { objects.add(visualization(percentile("perf-" + name, "perf_stats." + key + ".total_elapsed", "total elapsed", color(), new String[]{"99", "90", "50"}))); var tsvb = new TSVB("perf-" + name + "_io", "action"); var write = series("sum", "perf_stats." + key + ".write_entries", "write " + unit, "number", color()); write.value_template = "{{value}} " + unit; tsvb.params.series.add(write); var read = series("sum", "perf_stats." + key + ".read_entries", "read " + unit, "number", color()); read.value_template = write.value_template; tsvb.params.series.add(read); var operations = series("sum", "perf_stats." + key + ".count", "operations", "number", color()); operations.separate_axis = 1; operations.axis_position = "right"; operations.fill = 0; tsvb.params.series.add(operations); objects.add(visualization(tsvb)); } private TSVB perfHTTPIO() { var tsvb = new TSVB("perf-http_client_io", "action"); tsvb.params.show_grid = 0; tsvb.params.series.add(series("sum", "perf_stats.http.read_entries", "response body length", "bytes", color())); tsvb.params.series.add(series("sum", "perf_stats.http.write_entries", "request body length", "bytes", color())); var s1 = series("sum", "perf_stats.http.count", "http", "number", color()); s1.separate_axis = 1; s1.axis_position = "right"; s1.fill = 0; tsvb.params.series.add(s1); return tsvb; } private TSVB httpRetries() { var tsvb = new TSVB("action-http_client_retries", "action"); TSVB.Series s1 = series("sum", "stats.http_retries", "http retries", "number", color()); s1.chart_type = "bar"; tsvb.params.series.add(s1); return tsvb; } private TSVB dbQueries() { var tsvb = new TSVB("action-db_queries", "action"); tsvb.params.series.add(series("sum", "stats.db_queries", "db queries", "number", color())); return tsvb; } private TSVB actionHTTPIO() { var tsvb = new TSVB("action-http_io", "action"); tsvb.params.series.add(series("sum", "stats.request_body_length", "request body length", "bytes", color())); tsvb.params.series.add(series("sum", "stats.response_body_length", "response body length", "bytes", color())); return tsvb; } private TSVB max(String id, String index, String field, String label, String formatter, String color) { var tsvb = new TSVB(id, index); tsvb.params.series.add(series("max", field, label, formatter, color)); return tsvb; } private TSVB usedMax(String id, String maxField, String usedField, String label) { String color = color(); TSVB tsvb = max(id, "stat", maxField, "max " + label, "bytes", color); tsvb.params.series.add(series("max", usedField, "used " + label, "bytes", color)); return tsvb; } private TSVB cacheHitRate() { // hard code color to make miss/hit contrast var tsvb = new TSVB("action-cache_hit_rate", "action"); var hits = series("sum", "stats.cache_hits", "cache hits", "number", "#43AA8B"); hits.chart_type = "bar"; hits.stacked = "stacked"; tsvb.params.series.add(hits); var misses = series("sum", "stats.cache_misses", "cache misses", "number", "#F94144"); misses.chart_type = "bar"; misses.stacked = "stacked"; tsvb.params.series.add(misses); return tsvb; } private TSVB kafkaConsumerFetchRate(String color) { var tsvb = new TSVB("stat-kafka_consumer_fetch_rate", "stat"); var s1 = series("avg", "stats.kafka_consumer_fetch_rate", "avg fetch rate", "number", color); s1.value_template = "{{value}} req/s"; tsvb.params.series.add(s1); var s2 = series("min", "stats.kafka_consumer_fetch_rate", "min fetch rate", "number", color); s2.value_template = "{{value}} req/s"; tsvb.params.series.add(s2); return tsvb; } private TSVB kafkaConsumerConsumedRate() { var tsvb = new TSVB("stat-kafka_consumer_consumed_rate", "stat"); tsvb.params.show_grid = 0; var s1 = series("avg", "stats.kafka_consumer_bytes_consumed_rate", "bytes consumed rate", "bytes", color()); s1.value_template = "{{value}}/s"; s1.separate_axis = 1; s1.axis_position = "left"; // seems only separate axis respect value_template s1.fill = 0; tsvb.params.series.add(s1); var s2 = series("avg", "stats.kafka_consumer_records_consumed_rate", "records consumed rate", "number", color()); s2.value_template = "{{value}}/s"; s2.separate_axis = 1; s2.axis_position = "right"; s2.fill = 0; tsvb.params.series.add(s2); return tsvb; } private TSVB kafkaProducerProducedRate(String name) { String postfix = name == null ? "" : "_" + name; var tsvb = new TSVB("stat-kafka_producer" + postfix + "_produced_rate", "stat"); tsvb.params.show_grid = 0; var s1 = series("avg", "stats.kafka_producer" + postfix + "_outgoing_byte_rate", "outgoing bytes rate", "bytes", color()); s1.value_template = "{{value}}/s"; s1.separate_axis = 1; s1.axis_position = "left"; // seems only separate axis respect value_template s1.fill = 0; tsvb.params.series.add(s1); var s2 = series("avg", "stats.kafka_producer" + postfix + "_request_rate", "request rate", "number", color()); s2.value_template = "{{value}}/s"; s2.separate_axis = 1; s2.axis_position = "right"; s2.fill = 0; tsvb.params.series.add(s2); return tsvb; } private TSVB kafkaProducerRequestSize(String name) { String postfix = name == null ? "" : "_" + name; var tsvb = new TSVB("stat-kafka_producer" + postfix + "_request_size_avg", "stat"); tsvb.params.series.add(series("avg", "stats.kafka_producer" + postfix + "_request_size_avg", "avg request size", "bytes", color())); return tsvb; } private TSVB kafkaBytesRate() { var tsvb = new TSVB("stat-kafka_bytes_rate", "stat"); var s1 = series("avg", "stats.kafka_bytes_in_rate", "bytes in rate", "bytes", color()); s1.value_template = "{{value}}/s"; s1.fill = 0; tsvb.params.series.add(s1); var s2 = series("avg", "stats.kafka_bytes_out_rate", "bytes out rate", "bytes", color()); s2.value_template = "{{value}}/s"; s2.fill = 0; tsvb.params.series.add(s2); return tsvb; } private TSVB businessUniqueVisitor() { var tsvb = new TSVB("business-unique_visitor", "action"); tsvb.params.series.add(series("cardinality", "context.session_hash", "unique sessions", "number", color())); tsvb.params.series.add(series("cardinality", "context.client_ip", "unique client ips", "number", color())); return tsvb; } private TSVB statMem() { String color = color(); TSVB tsvb = max("stat-mem", "stat", "stats.mem_max", "max mem", "bytes", color); tsvb.params.series.add(series("max", "stats.vm_rss", "vm rss", "bytes", color)); return tsvb; } private TSVB poolCount(String name) { TSVB tsvb = max("stat-pool_" + name + "_count", "stat", "stats.pool_" + name + "_total_count", "total count", "number", color()); tsvb.params.series.add(series("max", "stats.pool_" + name + "_active_count", "active count", "number", color())); return tsvb; } private TSVB heap(String name) { var tsvb = new TSVB("stat-" + name + "_heap", "stat"); String color = color(); tsvb.params.series.add(series("max", "stats." + name + "_heap_max", "max heap", "bytes", color)); tsvb.params.series.add(series("max", "stats." + name + "_heap_used", "used heap", "bytes", color)); var series = series("max", "stats." + name + "_non_heap_used", "used non heap", "bytes", color()); series.fill = 0; tsvb.params.series.add(series); return tsvb; } private TSVB gc(String name) { var tsvb = new TSVB("stat-" + name + "_gc", "stat"); tsvb.params.show_grid = 0; var youngElapsed = series("sum", "stats." + name + "_gc_young_elapsed", "young gc elapsed", "number", color()); youngElapsed.value_template = "{{value}} ns"; var youngCount = series("sum", "stats." + name + "_gc_young_count", "young gc count", "number", color()); youngCount.separate_axis = 1; youngCount.axis_position = "right"; youngCount.fill = 0; var oldElapsed = series("sum", "stats." + name + "_gc_old_elapsed", "old gc elapsed", "number", color()); oldElapsed.value_template = "{{value}} ns"; var oldCount = series("sum", "stats." + name + "_gc_old_count", "old gc count", "number", color()); oldCount.separate_axis = 1; oldCount.axis_position = "right"; oldCount.fill = 0; tsvb.params.series.add(youngElapsed); tsvb.params.series.add(youngCount); tsvb.params.series.add(oldElapsed); tsvb.params.series.add(oldCount); return tsvb; } private TSVB splitByTerm(String id, String term) { var tsvb = new TSVB(id, "action"); tsvb.params.show_legend = 1; var series = new TSVB.Series(); series.color = "#000000"; series.id = "count"; series.label = "count"; series.split_mode = "terms"; series.split_color_mode = "rainbow"; series.terms_field = term; series.terms_order_by = "count"; series.chart_type = "bar"; series.stacked = "stacked"; series.metrics.add(new TSVB.Metric("count", null)); tsvb.params.series.add(series); return tsvb; } private TSVB traceCountByResult() { var tsvb = new TSVB("trace-count-by-result", "trace"); tsvb.params.show_legend = 1; var series = new TSVB.Series(); series.color = "#000000"; series.id = "count"; series.label = "count"; series.split_mode = "terms"; series.split_color_mode = "rainbow"; series.terms_field = "result"; series.terms_order_by = "count"; series.chart_type = "bar"; series.stacked = "stacked"; series.metrics.add(new TSVB.Metric("count", null)); tsvb.params.series.add(series); return tsvb; } private TSVB elapsedByAction() { var tsvb = new TSVB("action-elapsed-by-action", "action"); tsvb.params.show_legend = 1; var series = new TSVB.Series(); series.color = "#000000"; series.id = "elapsed"; series.label = "elapsed"; series.split_mode = "terms"; series.split_color_mode = "rainbow"; series.terms_field = "action"; series.terms_order_by = "sum"; series.chart_type = "bar"; series.value_template = "{{value}} ns"; series.stacked = "stacked"; series.metrics.add(new TSVB.Metric("sum", "elapsed")); tsvb.params.series.add(series); return tsvb; } private TSVB percentile(String id, String field, String label, String color, String[] percentiles) { var tsvb = new TSVB(id, "action"); var series = new TSVB.Series(); series.id = "percentile"; series.label = label; series.color = color; series.value_template = "{{value}} ns"; var metric = new TSVB.Metric("percentile", field); metric.percentiles = Arrays.stream(percentiles).map(TSVB.Percentile::new).collect(Collectors.toList()); series.metrics.add(metric); tsvb.params.series.add(series); return tsvb; } private TSVB maxAvg(String id, String index, String field, String label, String color, String formatter) { var tsvb = new TSVB(id, index); tsvb.params.series.add(series("max", field, "max " + label, formatter, color)); tsvb.params.series.add(series("avg", field, "avg " + label, formatter, color)); return tsvb; } private TSVB valueTemplate(TSVB tsvb, String template) { for (TSVB.Series series : tsvb.params.series) { series.value_template = template; } return tsvb; } private TSVB.Series series(String type, String field, String label, String formatter, String color) { var avg = new TSVB.Series(); avg.id = type + "-" + field.replace('.', '-'); avg.label = label; avg.color = color; avg.formatter = formatter; avg.metrics.add(new TSVB.Metric(type, field)); return avg; } private TSVB metric(String id, String field, String label) { var tsvb = new TSVB(id, "action"); tsvb.params.time_range_mode = "entire_time_range"; tsvb.params.type = "metric"; var series = new TSVB.Series(); series.id = id; series.label = label; series.metrics.add(new TSVB.Metric("sum", field)); tsvb.params.series.add(series); return tsvb; } private String color() { return COLOR_PALETTE[colorIndex++ % COLOR_PALETTE.length]; } }
package de.lessvoid.nifty.effects.impl; import de.lessvoid.nifty.EndNotify; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyIdCreator; import de.lessvoid.nifty.builder.ControlBuilder; import de.lessvoid.nifty.builder.LayerBuilder; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.effects.EffectImpl; import de.lessvoid.nifty.effects.EffectProperties; import de.lessvoid.nifty.effects.Falloff; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.tools.SizeValue; /** * Hint - show a hint, a nifty hint! * @author void */ public class Hint implements EffectImpl { private Nifty nifty; private String hintLayerId; private String hintPanelId; private int hintDelay; public void activate(final Nifty niftyParam, final Element element, final EffectProperties parameter) { this.nifty = niftyParam; final String hintControl = parameter.getProperty("hintControl", "nifty-default-hint"); final String hintStyle = parameter.getProperty("hintStyle", null); final String hintText = parameter.getProperty("hintText", "hint: add a 'hintText' attribute to the hint effect :)"); hintDelay = Integer.valueOf(parameter.getProperty("hintDelay", "0")); // we'll create a new layer on the fly for the hint and because we could really // have lots of hints we'll generate a unique id for this new layer this.hintLayerId = NiftyIdCreator.generate(); this.hintPanelId = hintLayerId + "-hint-panel"; new LayerBuilder(hintLayerId) {{ childLayoutAbsolute(); visible(false); control(new ControlBuilder(hintPanelId, hintControl) {{ parameter("hintText", hintText); if (hintStyle != null) { style(hintStyle); } }}); }}.build(niftyParam, niftyParam.getCurrentScreen(), niftyParam.getCurrentScreen().getRootElement()); } public void execute( final Element element, final float normalizedTime, final Falloff falloff, final NiftyRenderEngine r) { if (normalizedTime > 0.0) { final Element hintLayer = nifty.getCurrentScreen().findElementByName(hintLayerId); if (!hintLayer.isVisible()) { // decide if we can already show the hint if (nifty.getNiftyMouse().getNoMouseMovementTime() > hintDelay) { Element hintPanel = hintLayer.findElementByName(hintPanelId); if (hintPanel != null) { hintPanel.setConstraintX(new SizeValue(element.getX() + 20 + "px")); hintPanel.setConstraintY(new SizeValue(element.getY() + 20 + "px")); hintLayer.layoutElements(); hintLayer.show(); } } } } } public void deactivate() { final Element hintLayer = nifty.getCurrentScreen().findElementByName(hintLayerId); if (hintLayer == null) { return; } if (hintLayer.isVisible()) { hintLayer.startEffect(EffectEventId.onCustom, new EndNotify() { @Override public void perform() { hintLayer.markForRemoval(); } }); } else { hintLayer.markForRemoval(); } } }
package kikaha.urouting; import java.lang.annotation.Annotation; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeMirror; import lombok.RequiredArgsConstructor; import lombok.val; import trip.spi.Singleton; import trip.spi.Stateless; import trip.spi.helpers.filter.Condition; import trip.spi.helpers.filter.Filter; public class AnnotationProcessorUtil { final static String METHOD_PARAM_EOL = "\n\t\t\t"; @SuppressWarnings( "unchecked" ) public static Iterable<Element> retrieveMethodsAnnotatedWith( final RoundEnvironment roundEnv, final Class<? extends Annotation> annotation ) { return (Iterable<Element>)Filter.filter( roundEnv.getElementsAnnotatedWith( annotation ), new MethodsOnlyCondition() ); } public static ExecutableElement retrieveFirstMethodAnnotatedWith( final TypeElement typeElement, final Class<? extends Annotation> annotation ) { return (ExecutableElement)Filter.first( typeElement.getEnclosedElements(), new AnnotatedMethodsCondition( annotation ) ); } public static String extractServiceInterfaceFrom( final ExecutableElement method ) { final TypeElement classElement = (TypeElement)method.getEnclosingElement(); return extractServiceInterfaceFrom( classElement ); } public static String extractServiceInterfaceFrom( final TypeElement classElement ) { final String canonicalName = getServiceInterfaceProviderClass( classElement ).toString(); if ( Singleton.class.getCanonicalName().equals( canonicalName ) || Stateless.class.getCanonicalName().equals( canonicalName ) ) return classElement.asType().toString(); return canonicalName; } public static TypeMirror getServiceInterfaceProviderClass( final TypeElement service ) { try { final Singleton singleton = service.getAnnotation( Singleton.class ); if ( singleton != null ) singleton.exposedAs(); final Stateless stateless = service.getAnnotation( Stateless.class ); if ( stateless != null ) stateless.exposedAs(); return service.asType(); } catch ( final MirroredTypeException cause ) { return cause.getTypeMirror(); } } public static String extractCanonicalName( final Element element ) { return element.asType().toString(); } public static String extractPackageName( final Element element ) { final String canonicalName = extractCanonicalName( element ); return canonicalName.replaceAll( "^(.*)\\.[^\\.]+", "$1" ); } public static String extractMethodParamsFrom( final ExecutableElement method, final MethodParameterParser parser ) { final StringBuilder buffer = new StringBuilder().append( METHOD_PARAM_EOL ); boolean first = true; for ( final VariableElement parameter : method.getParameters() ) { if ( !first ) buffer.append( ',' ); buffer.append( parser.parse( method, parameter ) ).append( METHOD_PARAM_EOL ); first = false; } return buffer.toString(); } public interface MethodParameterParser { String parse( final ExecutableElement method, final VariableElement variable ); } } class MethodsOnlyCondition implements Condition<Element> { @Override public boolean check( final Element object ) { val parentClass = object.getEnclosingElement(); return object.getKind().equals( ElementKind.METHOD ) && isNotAbstract( parentClass ); } private boolean isNotAbstract( Element clazz ) { for ( val modifier : clazz.getModifiers() ) if ( Modifier.ABSTRACT.equals( modifier ) ) return false; return true; } } @RequiredArgsConstructor class AnnotatedMethodsCondition implements Condition<Element> { final Class<? extends Annotation> annotationType; @Override public boolean check( final Element element ) { final MethodsOnlyCondition methodsOnlyCondition = new MethodsOnlyCondition(); return methodsOnlyCondition.check( element ) && element.getAnnotation( annotationType ) != null; } }
package de.neuland.jade4j; import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; import de.neuland.jade4j.Jade4J.Mode; import de.neuland.jade4j.exceptions.JadeCompilerException; import de.neuland.jade4j.exceptions.JadeException; import de.neuland.jade4j.expression.ExpressionHandler; import de.neuland.jade4j.filter.*; import de.neuland.jade4j.model.JadeModel; import de.neuland.jade4j.parser.Parser; import de.neuland.jade4j.parser.node.Node; import de.neuland.jade4j.template.FileTemplateLoader; import de.neuland.jade4j.template.JadeTemplate; import de.neuland.jade4j.template.TemplateLoader; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class JadeConfiguration { private static final String FILTER_CDATA = "cdata"; private static final String FILTER_PLAIN = "plain"; private static final String FILTER_STYLE = "css"; private static final String FILTER_SCRIPT = "js"; private static final String FILTER_SVG = "svg"; private boolean prettyPrint = false; private boolean caching = true; private Mode mode = Jade4J.Mode.HTML; private Map<String, Filter> filters = new HashMap<String, Filter>(); private Map<String, Object> sharedVariables = new HashMap<String, Object>(); private TemplateLoader templateLoader = new FileTemplateLoader("", "UTF-8"); protected static final int MAX_ENTRIES = 1000; public JadeConfiguration() { setFilter(FILTER_PLAIN, new PlainFilter()); setFilter(FILTER_CDATA, new CDATAFilter()); setFilter(FILTER_SCRIPT, new JsFilter()); setFilter(FILTER_STYLE, new CssFilter()); setFilter(FILTER_SVG, new PlainFilter()); } private Map<String, JadeTemplate> cache = new ConcurrentLinkedHashMap.Builder<String, JadeTemplate>().maximumWeightedCapacity( MAX_ENTRIES + 1).build(); public JadeTemplate getTemplate(String name) throws IOException, JadeException { if (caching) { long lastModified = templateLoader.getLastModified(name); String key = name + "-" + lastModified; JadeTemplate template = cache.get(key); if (template != null) { return template; } else { JadeTemplate newTemplate = createTemplate(name); cache.put(key, newTemplate); return newTemplate; } } return createTemplate(name); } public void renderTemplate(JadeTemplate template, Map<String, Object> model, Writer writer) throws JadeCompilerException { JadeModel jadeModel = new JadeModel(sharedVariables); for (String filterName : filters.keySet()) { jadeModel.addFilter(filterName, filters.get(filterName)); } jadeModel.putAll(model); template.process(jadeModel, writer); } public String renderTemplate(JadeTemplate template, Map<String, Object> model) throws JadeCompilerException { StringWriter writer = new StringWriter(); renderTemplate(template, model, writer); return writer.toString(); } private JadeTemplate createTemplate(String name) throws JadeException, IOException { JadeTemplate template = new JadeTemplate(); Parser parser = new Parser(name, templateLoader); Node root = parser.parse(); template.setTemplateLoader(templateLoader); template.setRootNode(root); template.setPrettyPrint(prettyPrint); template.setMode(getMode()); return template; } public boolean isPrettyPrint() { return prettyPrint; } public void setPrettyPrint(boolean prettyPrint) { this.prettyPrint = prettyPrint; } public void setFilter(String name, Filter filter) { filters.put(name, filter); } public void removeFilter(String name) { filters.remove(name); } public Map<String, Object> getSharedVariables() { return sharedVariables; } public void setSharedVariables(Map<String, Object> sharedVariables) { this.sharedVariables = sharedVariables; } public TemplateLoader getTemplateLoader() { return templateLoader; } public void setTemplateLoader(TemplateLoader templateLoader) { this.templateLoader = templateLoader; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } public boolean templateExists(String url) { try { return templateLoader.getReader(url) != null; } catch (IOException e) { return false; } } public boolean isCaching() { return caching; } public void setCaching(boolean cache) { if (cache != this.caching) { ExpressionHandler.setCache(cache); this.caching = cache; } } public void clearCache() { ExpressionHandler.clearCache(); cache.clear(); } }
package de.prob2.ui.consoles.b; import java.util.Collections; import java.util.Objects; import java.util.ResourceBundle; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.inject.Inject; import de.be4.classicalb.core.parser.exceptions.BCompoundException; import de.be4.classicalb.core.parser.exceptions.BException; import de.be4.classicalb.core.parser.exceptions.BLexerException; import de.be4.classicalb.core.parser.exceptions.BParseException; import de.be4.classicalb.core.parser.exceptions.CheckException; import de.be4.classicalb.core.parser.exceptions.PreParseException; import de.be4.classicalb.core.parser.parser.ParserException; import de.be4.eventbalg.core.parser.EventBLexerException; import de.be4.eventbalg.core.parser.EventBParseException; import de.hhu.stups.sablecc.patch.SourcePosition; import de.prob.animator.domainobjects.AbstractEvalResult; import de.prob.animator.domainobjects.EvaluationException; import de.prob.animator.domainobjects.FormulaExpand; import de.prob.animator.domainobjects.IEvalElement; import de.prob.exception.ProBError; import de.prob.statespace.Trace; import de.prob2.ui.consoles.ConsoleExecResult; import de.prob2.ui.consoles.ConsoleExecResultType; import de.prob2.ui.consoles.ConsoleInstruction; import de.prob2.ui.consoles.Executable; import de.prob2.ui.prob2fx.CurrentTrace; import de.prob2.ui.project.MachineLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BInterpreter implements Executable { private static final class ParseError { private final int line; private final int column; private final String message; private ParseError(final int line, final int column, final String message) { super(); Objects.requireNonNull(message); this.line = line; this.column = column; this.message = message; } private int getLine() { return this.line; } private int getColumn() { return this.column; } private String getMessage() { return this.message; } } private static final Logger logger = LoggerFactory.getLogger(BInterpreter.class); private static final Pattern MESSAGE_WITH_POSITIONS_PATTERN = Pattern.compile("^\\[(\\d+),(\\d+)\\] (.*)$"); private final CurrentTrace currentTrace; private final Trace defaultTrace; private final int promptLength; @Inject public BInterpreter(final MachineLoader machineLoader, final CurrentTrace currentTrace, final ResourceBundle bundle) { this.currentTrace = currentTrace; this.defaultTrace = new Trace(machineLoader.getEmptyStateSpace(Collections.emptyMap())); this.promptLength = bundle.getString("consoles.prompt.default").length(); } // The exceptions thrown while parsing are not standardized in any way. // This method tries to extract line/column info from an exception. // First it checks if the exception has programmatically readable position info and uses that if possible. // If that fails, it tries to parse SableCC-style position info from the exception message. // If that also fails, null is returned. private ParseError getParseErrorFromException(final Exception e) { if (( e instanceof EvaluationException || e instanceof BException || e instanceof de.be4.eventbalg.core.parser.BException ) && e.getCause() instanceof Exception) { // Check for known "wrapper exceptions" and look at their cause instead. return this.getParseErrorFromException((Exception)e.getCause()); } else if (e instanceof BCompoundException && !((BCompoundException)e).getBExceptions().isEmpty()) { return this.getParseErrorFromException(((BCompoundException)e).getBExceptions().get(0)); } else if (e instanceof PreParseException && ((PreParseException)e).getTokens().length > 0) { final PreParseException ex = (PreParseException)e; return new ParseError(ex.getTokens()[0].getLine(), ex.getTokens()[0].getPos(), e.getMessage()); } else if (e instanceof BLexerException) { final BLexerException ex = (BLexerException)e; return new ParseError(ex.getLastLine(), ex.getLastPos(), e.getMessage()); } else if (e instanceof EventBLexerException) { final EventBLexerException ex = (EventBLexerException)e; return new ParseError(ex.getLastLine(), ex.getLastPos(), e.getMessage()); } else if (e instanceof BParseException) { final BParseException ex = (BParseException)e; return new ParseError(ex.getToken().getLine(), ex.getToken().getPos(), ex.getRealMsg()); } else if (e instanceof EventBParseException) { final EventBParseException ex = (EventBParseException)e; return new ParseError(ex.getToken().getLine(), ex.getToken().getPos(), e.getMessage()); } else if (e instanceof de.be4.classicalb.core.preparser.parser.ParserException) { final de.be4.classicalb.core.preparser.parser.ParserException ex = (de.be4.classicalb.core.preparser.parser.ParserException)e; return new ParseError(ex.getToken().getLine(), ex.getToken().getPos(), ex.getRealMsg()); } else if (e instanceof ParserException) { final ParserException ex = (ParserException)e; return new ParseError(ex.getToken().getLine(), ex.getToken().getPos(), ex.getRealMsg()); } else if (e instanceof de.be4.eventbalg.core.parser.parser.ParserException) { final de.be4.eventbalg.core.parser.parser.ParserException ex = (de.be4.eventbalg.core.parser.parser.ParserException)e; return new ParseError(ex.getToken().getLine(), ex.getToken().getPos(), ex.getRealMsg()); } else if (e instanceof CheckException && ((CheckException)e).getNodes().length > 0) { final SourcePosition pos = ((CheckException)e).getNodes()[0].getStartPos(); return new ParseError(pos.getLine(), pos.getPos(), e.getMessage() ); } else { // The exception doesn't have any accessible position info. // Look for SableCC-style position info in the error message and try to parse it. final Matcher matcher = MESSAGE_WITH_POSITIONS_PATTERN.matcher(e.getMessage()); return matcher.find() ? new ParseError( Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), matcher.group(3) ) : null; } } private String formatParseException(final Exception e) { final ParseError error = this.getParseErrorFromException(e); if (error != null) { return String.format("%" + (error.getColumn() + this.promptLength) + "s\n%s", '^', error.getMessage()); } else { return String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage()); } } @Override public ConsoleExecResult exec(final ConsoleInstruction instruction) { final String source = instruction.getInstruction(); if ("clear".equals(source)) { return new ConsoleExecResult("clear","", ConsoleExecResultType.PASSED); } final Trace trace = currentTrace.exists() ? currentTrace.get() : defaultTrace; final IEvalElement formula; try { formula = trace.getModel().parseFormula(source, FormulaExpand.EXPAND); } catch (EvaluationException e) { logger.info("Failed to parse B console user input", e); return new ConsoleExecResult("", this.formatParseException(e), ConsoleExecResultType.ERROR); } try { AbstractEvalResult res = trace.evalCurrent(formula); // noinspection ObjectToString return new ConsoleExecResult("", res.toString(), ConsoleExecResultType.PASSED); } catch (ProBError e) { logger.info("B evaluation failed", e); return new ConsoleExecResult("", e.getMessage(), ConsoleExecResultType.ERROR); } } }
package edu.brandeis.cs.steele.wn; import java.util.*; import edu.brandeis.cs.steele.util.Utils; /** A <code>WordSense</code> represents the lexical information related to a specific sense of a {@link Word}. * * <code>WordSense</code>'s are linked by {@link Pointer}s into a network of lexically related <code>Synset</code>s * and <code>WordSense</code>s. * {@link WordSense#getTargets WordSense.getTargets()} retrieves the targets of these links, and * {@link WordSense#getPointers WordSense.getPointers()} retrieves the pointers themselves. * * @see Pointer * @see Synset * @see Word * @author Oliver Steele, steele@cs.brandeis.edu * @version 1.0 */ public class WordSense implements PointerTarget, Comparable<WordSense> { /** * <i>Optional</i> restrictions for the position(s) an adjective can take * relative to the noun it modifies. aka "adjclass". */ public enum AdjPosition { NONE(0), /** * of adjectives; relating to or occurring within the predicate of a sentence */ PREDICATIVE(1), /** * of adjectives; placed before the nouns they modify */ ATTRIBUTIVE(2), // synonymous with PRENOMINAL //PRENOMINAL(2), // synonymous with ATTRIBUTIVE IMMEDIATE_POSTNOMINAL(4), ; final int flag; AdjPosition(final int flag) { this.flag = flag; } static boolean isActive(final AdjPosition adjPosFlag, final int flags) { return 0 != (adjPosFlag.flag & flags); } } // end enum AdjPosition // Instance implementation private final Synset synset; private final String lemma; private final int lexid; // only needs to be a byte since there are only 3 bits of flag values private final byte flags; // represents up to 64 different verb frames are possible (as of now, 35 exist) private long verbFrameFlags; private short senseNumber; WordSense(final Synset synset, final String lemma, final int lexid, final int flags) { this.synset = synset; this.lemma = lemma; this.lexid = lexid; assert flags < Byte.MAX_VALUE; this.flags = (byte)flags; this.senseNumber = -1; } void setVerbFrameFlag(final int fnum) { verbFrameFlags |= 1L << (fnum - 1); } // Accessors public Synset getSynset() { return synset; } public POS getPOS() { return synset.getPOS(); } /** Returns the natural-cased lemma representation of this <code>WordSense</code> * Its lemma is its orthographic representation, for example <tt>"dog"</tt> * or <tt>"U.S.A."</tt> or <tt>"George Washington"</tt>. Contrast to the * canonical lemma provided by {@link Word#getLemma()}. */ public String getLemma() { return lemma; } /** {@inheritDoc} */ public Iterator<WordSense> iterator() { return Collections.singleton(this).iterator(); } String flagsToString() { if(flags == 0) { return "NONE"; } final StringBuilder flagString = new StringBuilder(); if(AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) { flagString.append("predicative"); } if(AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) { if(flagString.length() != 0) { flagString.append(","); } // synonymous with attributive - WordNet browser seems to use this // while the database files seem to indicate it as attributive flagString.append("prenominal"); } if(AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) { if(flagString.length() != 0) { flagString.append(","); } flagString.append("immediate_postnominal"); } return flagString.toString(); } /** * 1-indexed value. */ public int getSenseNumber() { if(senseNumber < 1) { // Ordering of Word's Synsets (combo(Word, Synset)=Word) // is defined by sense tagged frequency, but this is implicit) // Use lemma as key to find Word and then scan this WordSense's // Synsets and find the one with this Synset final FileBackedDictionary dictionary = FileBackedDictionary.getInstance(); final Word word = dictionary.lookupWord(getPOS(), lemma); assert word != null : "lookupWord failed for \""+lemma+"\" "+getPOS(); int senseNumber = 0; for (final Synset syn : word.getSynsets()) { senseNumber if(syn.equals(synset)) { senseNumber = -senseNumber; break; } } assert senseNumber > 0 : "Word lemma: "+lemma+" "+getPOS(); assert senseNumber < Short.MAX_VALUE; this.senseNumber = (short)senseNumber; } return senseNumber; } String getSenseKey() { final String searchWord; final int headSense; if (synset.isAdjectiveCluster()) { final PointerTarget[] adjsses = synset.getTargets(PointerType.SIMILAR_TO); assert adjsses.length == 1; final Synset adjss = (Synset)adjsses[0]; // if satellite, key lemma in cntlist.rev // is adjss's first word (no case) and // adjss's lexid (aka lexfilenum) otherwise searchWord = adjss.getWords()[0].getLemma(); headSense = adjss.getWords()[0].lexid; } else { searchWord = getLemma(); headSense = lexid; } int synsetIndex; for (synsetIndex = 0; synsetIndex < getSynset().getWords().length; synsetIndex++) { if (getSynset().getWords()[synsetIndex].getLemma().equals(getLemma())) { break; } } assert synsetIndex != getSynset().getWords().length; final String senseKey; if (synset.isAdjectiveCluster()) { senseKey = String.format("%s%%%d:%02d:%02d:%s:%02d", getLemma().toLowerCase(), POS.SAT_ADJ.getWordNetCode(), getSynset().lexfilenum(), getSynset().getWords()[synsetIndex].lexid, searchWord.toLowerCase(), headSense); } else { senseKey = String.format("%s%%%d:%02d:%02d::", getLemma().toLowerCase(), getPOS().getWordNetCode(), getSynset().lexfilenum(), getSynset().getWords()[synsetIndex].lexid ); } return senseKey; } public int getSensesTaggedFrequency() { //TODO cache this value //TODO we could use this Word's getTaggedSenseCount() to determine if //there were any tagged senses for *any* sense of it (including this one) //and really we wouldn't need to look at sense (numbers) exceeding that value //as an optimization final String senseKey = getSenseKey(); final FileBackedDictionary dictionary = FileBackedDictionary.getInstance(); final String line = dictionary.lookupCntlistDotRevLine(senseKey); int count = 0; if (line != null) { // cntlist.rev line format: // <sense_key> <sense_number> tag_cnt final int lastSpace = line.lastIndexOf(" "); assert lastSpace > 0; count = CharSequenceTokenizer.parseInt(line, lastSpace + 1, line.length()); // sanity check final int firstSpace = line.indexOf(" "); // sanity check assert firstSpace > 0 && firstSpace != lastSpace; // sanity check final int mySenseNumber = getSenseNumber(); // sanity check final int foundSenseNumber = // sanity check CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace); // sanity check if (mySenseNumber != foundSenseNumber) { // sanity check System.err.println(this+" foundSenseNumber: "+foundSenseNumber+" count: "+count); // sanity check } else { // sanity check //System.err.println(this+" OK"); // sanity check } //[WordSense 9465459@[POS noun]:"unit"#5] foundSenseNumber: 7 //assert getSenseNumber() == // CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace); } return count; } /** * FIXME this should only have 1 value (ie not be a Set)! */ public Set<AdjPosition> getAdjPositions() { if (flags == 0) { return Collections.emptySet(); } assert getPOS() == POS.ADJ; final EnumSet<AdjPosition> adjPosFlagSet = EnumSet.noneOf(AdjPosition.class); //FIXME check and add the apropos flags if (AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) { adjPosFlagSet.add(AdjPosition.PREDICATIVE); } if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) { adjPosFlagSet.add(AdjPosition.ATTRIBUTIVE); } if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) { adjPosFlagSet.add(AdjPosition.IMMEDIATE_POSTNOMINAL); } return adjPosFlagSet; } //FIXME publish as EnumSet (though store set as a byte for max efficiency long getFlags() { return flags; } //TODO expert only. maybe publish as EnumSet long getVerbFrameFlags() { return verbFrameFlags; } public List<String> getVerbFrames() { if (getPOS() != POS.VERB) { return Collections.emptyList(); } final String senseKey = getSenseKey(); final FileBackedDictionary dictionary = FileBackedDictionary.getInstance(); final String sentenceNumbers = dictionary.lookupVerbSentencesNumbers(senseKey); List<String> frames = Collections.emptyList(); if (sentenceNumbers != null) { frames = new ArrayList<String>(); // fetch the illustrative sentences indicated in sentenceNumbers //TODO consider substibuting in lemma for "%s" in each //FIXME this logic is a bit too complex/duplicated!! int s = 0; int e = sentenceNumbers.indexOf(","); final int n = sentenceNumbers.length(); e = e > 0 ? e : n; for ( ; s < n; // e = next comma OR if no more commas, e = n s = e + 1, e = sentenceNumbers.indexOf(",", s), e = e > 0 ? e : n) { final String sentNum = sentenceNumbers.substring(s, e); final String sentence = dictionary.lookupVerbSentence(sentNum); assert sentence != null; frames.add(sentence); } } else { //assert verbFrameFlags == 0L : "not mutually exclusive for "+this; } if (verbFrameFlags != 0L) { final int numGenericFrames = Long.bitCount(verbFrameFlags); if (frames.isEmpty()) { frames = new ArrayList<String>(); } else { ((ArrayList<String>)frames).ensureCapacity(frames.size() + numGenericFrames); } // fetch any generic verb frames indicated by verbFrameFlags // numberOfLeadingZeros (leftmost), numberOfTrailingZeros (rightmost) // 001111111111100 // ^-lead ^-trail // simple scan between these (inclusive) should cover rest for (int fn = Long.numberOfTrailingZeros(verbFrameFlags), lfn = Long.SIZE - Long.numberOfLeadingZeros(verbFrameFlags); fn < lfn; fn++) { if ((verbFrameFlags & (1L << fn)) != 0L) { final String frame = dictionary.lookupGenericFrame(fn + 1); assert frame != null : "this: "+this+" fn: "+fn+ " shift: "+((1L << fn)+ " verbFrameFlags: "+Long.toBinaryString(verbFrameFlags))+ " verbFrameFlags: "+verbFrameFlags; frames.add(frame); } } } return frames; } public String getDescription() { if (getPOS() != POS.ADJ && getPOS() != POS.SAT_ADJ) { return lemma; } final StringBuilder description = new StringBuilder(lemma); if (flags != 0) { description.append("("); description.append(flagsToString()); description.append(")"); } final PointerTarget[] targets = getTargets(PointerType.ANTONYM); if (targets.length > 0) { // adj acidic has more than 1 antonym (alkaline and amphoteric) for (final PointerTarget target : targets) { description.append(" (vs. "); final WordSense antonym = (WordSense)target; description.append(antonym.getLemma()); description.append(")"); } } return description.toString(); } public String getLongDescription() { final StringBuilder buffer = new StringBuilder(); //buffer.append(getSenseNumber()); //buffer.append(". "); //final int sensesTaggedFrequency = getSensesTaggedFrequency(); //if (sensesTaggedFrequency != 0) { // buffer.append("("); // buffer.append(sensesTaggedFrequency); // buffer.append(") "); buffer.append(getLemma()); if (flags != 0) { buffer.append("("); buffer.append(flagsToString()); buffer.append(")"); } final String gloss = getSynset().getGloss(); if (gloss != null) { buffer.append(" buffer.append(gloss); buffer.append(")"); } return buffer.toString(); } // Pointers private Pointer[] restrictPointers(final Pointer[] source) { List<Pointer> vector = null; for (int i = 0; i < source.length; ++i) { final Pointer pointer = source[i]; if (pointer.getSource().equals(this)) { assert pointer.getSource() == this; if (vector == null) { vector = new ArrayList<Pointer>(); } vector.add(pointer); } } if (vector == null) { return NO_POINTERS; } return vector.toArray(new Pointer[vector.size()]); } private static final Pointer[] NO_POINTERS = new Pointer[0]; public Pointer[] getPointers() { return restrictPointers(synset.getPointers()); } public Pointer[] getPointers(final PointerType type) { //TODO could be a little more efficient (no need for intermediate Pointer[]) return restrictPointers(synset.getPointers(type)); } public PointerTarget[] getTargets() { return Synset.collectTargets(getPointers()); } public PointerTarget[] getTargets(final PointerType type) { //TODO could be a little more efficient (no need for intermediate Pointer[]) return Synset.collectTargets(getPointers(type)); } // Object methods @Override public boolean equals(Object object) { return (object instanceof WordSense) && ((WordSense) object).synset.equals(synset) && ((WordSense) object).lemma.equals(lemma); } @Override public int hashCode() { return synset.hashCode() ^ lemma.hashCode(); } @Override public String toString() { return new StringBuilder("[WordSense "). append(synset.getOffset()). append("@"). append(synset.getPOS()). append(":\""). append(getLemma()). append("\" append(getSenseNumber()). append("]").toString(); } /** * {@inheritDoc} */ public int compareTo(final WordSense that) { int result; result = Utils.WordNetLexicalComparator.TO_LOWERCASE_INSTANCE.compare(this.getLemma(), that.getLemma()); if (result == 0) { result = this.getSenseNumber() - that.getSenseNumber(); if (result == 0) { result = this.getSynset().compareTo(that.getSynset()); } } return result; } }
package fi.csc.microarray.config; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.UUID; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import fi.csc.microarray.util.XmlUtil; /** * Simple tool for centrally changing configuration of the Chipster server environment. * * @author Aleksi Kallio * */ public class ConfigTool { static final String CURRENT_R_VERSION = "R-2.9"; private final String brokerDir = "activemq"; private final String webstartDir = "webstart"; private final static String[] componentDirsWithConfig = new String[] { "comp", "auth", "fileserver", "manager", "client", "webstart" }; private String[][] configs = new String[][] { {"message broker (ActiveMQ) host", "myhost.mydomain"}, {"message broker protocol", "tcp"}, {"message broker port", "61616"}, {"file broker host", "myhost.mydomain"}, {"file broker port", "8080"}, {"URL of Web Start files", "http://myhost.mydomain"}, {"Web Start www-server port", "8081"}, {"manager www-console port", "8082"}, {"R-2.6.1 command", "R"}, {"max. simultanous jobs (more recommended when compute service on separate node)", "3"} }; private final int KEY_INDEX = 0; private final int VAL_INDEX = 1; private final int BROKER_HOST_INDEX = 0; private final int BROKER_PROTOCOL_INDEX = 1; private final int BROKER_PORT_INDEX = 2; private final int FILEBROKER_HOST_INDEX = 3; private final int FILEBROKER_PORT_INDEX = 4; private final int WS_CODEBASE_INDEX = 5; private final int WS_PORT = 6; private final int MANAGER_PORT = 7; private final int R_COMMAND_INDEX = 8; private final int MAX_JOBS_INDEX = 9; private String[][] passwords = new String[][] { {"comp", ""}, {"auth", ""}, {"filebroker", ""}, {"manager", ""} }; private HashMap<String, Document> documentsToWrite = new HashMap<String, Document>(); public ConfigTool() throws ParserConfigurationException { System.out.println("Chipster ConfigTool"); System.out.println(""); System.out.println("No changes are written before you verify them"); System.out.println(""); } public static void main(String[] args) throws Exception { ConfigTool configTool = new ConfigTool(); UpgradeTool upgradeTool = new UpgradeTool(); SetupTool setupTool = new SetupTool(); if (args.length == 0) { fail(); } else if ("configure".equals(args[0])) { configTool.configure(); } else if ("genpasswd".equals(args[0])) { configTool.genpasswd(); } else if ("setup".equals(args[0])) { setupTool.setup(); } else if ("upgrade".equals(args[0])) { if (args.length > 1) { upgradeTool.upgrade(new File(args[1])); } else { System.out.println("Please specify location of the old installation directory as an argument (e.g., \"./upgrade.sh /opt/chipster-1.2.3\")"); } } else { fail(); } } private static void fail() { System.out.println("Illegal arguments! Please specify one of: configure, genpasswd, upgrade"); } private void genpasswd() throws Exception { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // STEP 1. GATHER DATA // generate passwords for (int i = 0; i < passwords.length; i++) { passwords[i][VAL_INDEX] = UUID.randomUUID().toString(); } // STEP 2. UPDATE CONFIGS // update all Chipster configs for (String componentDir : getComponentDirsWithConfig()) { if (new File(componentDir).exists()) { File configFile = new File(componentDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + Configuration.CONFIG_FILENAME); updateChipsterConfigFilePasswords(configFile); } } // update ActiveMQ config File activemqConfigFile = new File(brokerDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + "activemq.xml"); if (activemqConfigFile.exists()) { updateActivemqConfigFilePasswords(activemqConfigFile); } verifyChanges(in); } catch (Throwable t) { t.printStackTrace(); System.err.println("\nQuitting, no changes written to disk!"); return; } // STEP 3. WRITE CHANGES writeChangesToDisk(); } private void writeChangesToDisk() throws TransformerException, UnsupportedEncodingException, FileNotFoundException { // write out files for (String file : documentsToWrite.keySet()) { System.out.println("Writing changes to " + file + "..."); XmlUtil.printXml(documentsToWrite.get(file), new OutputStreamWriter(new FileOutputStream(file))); } System.out.println("\nAll changes successfully written!"); } public static void verifyChanges(BufferedReader in) throws Exception { verifyChanges(in, "Please verify changes. Should changes be written to disk"); } public static void verifyChanges(BufferedReader in, String question) throws Exception { System.out.println(question + " [yes/no]?"); String answer = in.readLine(); if (!"yes".equals(answer)) { throw new Exception("User decided to abort"); } } public void configure() throws Exception { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // STEP 1. GATHER DATA // sniff current host try { String host = InetAddress.getLocalHost().getHostName(); configs[BROKER_HOST_INDEX][VAL_INDEX] = host; configs[FILEBROKER_HOST_INDEX][VAL_INDEX] = host; configs[WS_CODEBASE_INDEX][VAL_INDEX] = "http://" + host + ":8081"; } catch (UnknownHostException e) { // ignore, sniffing failed } // gather required data for (int i = 0; i < configs.length; i++) { System.out.println("Please specify " + configs[i][KEY_INDEX] + " [" + configs[i][VAL_INDEX] + "]: "); String line = in.readLine(); if (!line.trim().equals("")) { configs[i][VAL_INDEX] = line; } } // STEP 2. UPDATE CONFIGS // update all Chipster configs for (String componentDir : getComponentDirsWithConfig()) { if (new File(componentDir).exists()) { File configFile = new File(componentDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + Configuration.CONFIG_FILENAME); updateChipsterConfigFile(configFile); } } File wsClientConfigFile = new File("webstart" + File.separator + DirectoryLayout.WEB_ROOT + File.separator + Configuration.CONFIG_FILENAME); if (wsClientConfigFile.exists()) { updateChipsterConfigFile(wsClientConfigFile); } File runtimesConfigFile = new File("comp" + File.separator + DirectoryLayout.CONF_DIR + File.separator + "runtimes.xml"); if (runtimesConfigFile.exists()) { updateRuntimesConfigFile(runtimesConfigFile); } // update ActiveMQ config File activemqConfigFile = new File(brokerDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + "activemq.xml"); if (activemqConfigFile.exists()) { updateActivemqConfigFile(activemqConfigFile); } // update Web Start config File wsConfigFile = new File(webstartDir + File.separator + DirectoryLayout.WEB_ROOT + File.separator + "chipster.jnlp"); if (wsConfigFile.exists()) { updateWsConfigFile(wsConfigFile); } verifyChanges(in); } catch (Throwable t) { t.printStackTrace(); System.err.println("\nQuitting, no changes written to disk!"); return; } // STEP 3. WRITE CHANGES writeChangesToDisk(); } private void updateWsConfigFile(File configFile) throws Exception { Document doc = openForUpdating("Web Start", configFile); Element jnlp = (Element)doc.getDocumentElement(); updateElementAttribute(jnlp, "codebase", configs[WS_CODEBASE_INDEX][VAL_INDEX]); Element applicationDesc = (Element)jnlp.getElementsByTagName("application-desc").item(0); NodeList arguments = applicationDesc.getElementsByTagName("argument"); Element lastArgument = (Element)arguments.item(arguments.getLength() - 1); String url = "http://" + configs[BROKER_HOST_INDEX][VAL_INDEX] + ":" + configs[WS_PORT][VAL_INDEX] + "/" + Configuration.CONFIG_FILENAME; updateElementValue(lastArgument, "configuration URL (for Web Start)", url); writeLater(configFile, doc); } private void updateActivemqConfigFile(File configFile) throws Exception { Document doc = openForUpdating("ActiveMQ", configFile); Element broker = (Element)doc.getDocumentElement().getElementsByTagName("broker").item(0); Element transportConnectors = (Element)broker.getElementsByTagName("transportConnectors").item(0); Element transportConnector = (Element)transportConnectors.getElementsByTagName("transportConnector").item(0); // edit first in the list (could use attribute name to decide right one).. String uri = configs[BROKER_PROTOCOL_INDEX][VAL_INDEX] + "://" + configs[BROKER_HOST_INDEX][VAL_INDEX] + ":" + configs[BROKER_PORT_INDEX][VAL_INDEX]; updateElementAttribute(transportConnector, "uri", uri); writeLater(configFile, doc); } private void updateActivemqConfigFilePasswords(File configFile) throws Exception { Document doc = openForUpdating("ActiveMQ", configFile); Element broker = (Element)doc.getDocumentElement().getElementsByTagName("broker").item(0); NodeList users = ((Element)((Element)((Element)broker.getElementsByTagName("plugins").item(0)).getElementsByTagName("simpleAuthenticationPlugin").item(0)).getElementsByTagName("users").item(0)).getElementsByTagName("authenticationUser"); for (int i = 0; i < users.getLength(); i++) { for (int p = 0; p < passwords.length; p++) { Element user = (Element)users.item(i); if (user.getAttribute("username").equals(passwords[p][KEY_INDEX])) { updateElementAttribute(user, "password for " + passwords[p][KEY_INDEX], "password", passwords[p][VAL_INDEX]); break; } } } writeLater(configFile, doc); } private void updateChipsterConfigFilePasswords(File configFile) throws Exception { Document doc = openForUpdating("Chipster", configFile); Element securityModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "security"); Element usernameElement = XmlUtil.getChildWithAttributeValue(securityModule, "entryKey", "username"); String username = ((Element)usernameElement.getElementsByTagName("value").item(0)).getTextContent(); for (int i = 0; i < passwords.length; i++) { if (username.equals(passwords[i][KEY_INDEX])) { updateConfigEntryValue(securityModule, "password", passwords[i][VAL_INDEX]); break; } } writeLater(configFile, doc); } private void updateChipsterConfigFile(File configFile) throws Exception { Document doc = openForUpdating("Chipster", configFile); Element messagingModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "messaging"); updateConfigEntryValue(messagingModule, "broker-host", configs[BROKER_HOST_INDEX][VAL_INDEX]); updateConfigEntryValue(messagingModule, "broker-protocol", configs[BROKER_PROTOCOL_INDEX][VAL_INDEX]); updateConfigEntryValue(messagingModule, "broker-port", configs[BROKER_PORT_INDEX][VAL_INDEX]); Element filebrokerModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "filebroker"); if (filebrokerModule != null) { updateConfigEntryValue(filebrokerModule, "port", configs[FILEBROKER_PORT_INDEX][VAL_INDEX]); updateConfigEntryValue(filebrokerModule, "url", createFilebrokerUrl()); } Element analyserModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "comp"); if (analyserModule != null) { updateConfigEntryValue(analyserModule, "max-jobs", configs[MAX_JOBS_INDEX][VAL_INDEX]); } Element webstartModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "webstart"); if (webstartModule != null) { updateConfigEntryValue(webstartModule, "port", configs[WS_PORT][VAL_INDEX]); } Element managerModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "manager"); if (managerModule != null) { updateConfigEntryValue(managerModule, "web-console-port", configs[MANAGER_PORT][VAL_INDEX]); } writeLater(configFile, doc); } private void updateRuntimesConfigFile(File configFile) throws Exception { boolean ok = false; Document doc = openForUpdating("Runtimes", configFile); Element runtimesElement = (Element)doc.getElementsByTagName("runtimes").item(0); for (Element runtimeElement: XmlUtil.getChildElements(runtimesElement, "runtime")) { String runtimeName = XmlUtil.getChildElement(runtimeElement, "name").getTextContent(); if (runtimeName.equals(CURRENT_R_VERSION)) { Element handlerElement = XmlUtil.getChildElement(runtimeElement, "handler"); for (Element parameterElement: XmlUtil.getChildElements(handlerElement, "parameter")) { String paramName = XmlUtil.getChildElement(parameterElement, "name").getTextContent(); if (paramName.equals("command")) { Element commandValueElement = XmlUtil.getChildElement(parameterElement, "value"); updateElementValue(commandValueElement, "R-2.6.1 command", configs[R_COMMAND_INDEX][VAL_INDEX]); ok = true; } } } } if (ok) { writeLater(configFile, doc); } else { throw new RuntimeException("Could not update R-2.6.1 command to runtimes.xml"); } } private String createFilebrokerUrl() { return "http://" + configs[FILEBROKER_HOST_INDEX][VAL_INDEX]; } private void updateConfigEntryValue(Element module, String name, String newValue) { Element entry = XmlUtil.getChildWithAttributeValue(module, "entryKey", name); Element value = (Element)entry.getElementsByTagName("value").item(0); updateElementValue(value, name, newValue); } private void updateElementValue(Element element, String logicalName, String newValue) { System.out.println(" changing " + logicalName + ": " + element.getTextContent() + " -> " + newValue); element.setTextContent(newValue); } private void updateElementAttribute(Element element, String attrName, String attrValue) { updateElementAttribute(element, attrName, attrName, attrValue); } private void updateElementAttribute(Element element, String logicalName, String attrName, String attrValue) { System.out.println(" changing " + logicalName + ": " + element.getAttribute(attrName) + " -> " + attrValue); element.setAttribute(attrName, attrValue); } private void writeLater(File configFile, Document doc) throws TransformerException, UnsupportedEncodingException, FileNotFoundException { documentsToWrite.put(configFile.getAbsolutePath(), doc); System.out.println(""); } private Document openForUpdating(String name, File configFile) throws SAXException, IOException, ParserConfigurationException { System.out.println("Updating " + name + " config in " + configFile.getAbsolutePath()); Document doc = XmlUtil.parseFile(configFile); return doc; } public static String[] getComponentDirsWithConfig() { return componentDirsWithConfig; } }
package graphql.schema; import graphql.GraphQLException; import graphql.Internal; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; import static graphql.Assert.assertShouldNeverHappen; import static graphql.Scalars.GraphQLBoolean; import static graphql.schema.GraphQLTypeUtil.isNonNull; import static graphql.schema.GraphQLTypeUtil.unwrapOne; /** * A re-usable class that can fetch from POJOs */ @Internal public class PropertyFetchingImpl { private final AtomicBoolean USE_SET_ACCESSIBLE = new AtomicBoolean(true); private final AtomicBoolean USE_NEGATIVE_CACHE = new AtomicBoolean(true); private final ConcurrentMap<CacheKey, CachedMethod> METHOD_CACHE = new ConcurrentHashMap<>(); private final ConcurrentMap<CacheKey, Field> FIELD_CACHE = new ConcurrentHashMap<>(); private final ConcurrentMap<CacheKey, CacheKey> NEGATIVE_CACHE = new ConcurrentHashMap<>(); private final Class<?> singleArgumentType; public PropertyFetchingImpl(Class<?> singleArgumentType) { this.singleArgumentType = singleArgumentType; } private class CachedMethod { Method method; boolean takesSingleArgumentTypeAsOnlyArgument; CachedMethod(Method method) { this.method = method; this.takesSingleArgumentTypeAsOnlyArgument = takesSingleArgumentTypeAsOnlyArgument(method); } } public Object getPropertyValue(String propertyName, Object object, GraphQLType graphQLType, Object singleArgumentValue) { if (object instanceof Map) { return ((Map<?, ?>) object).get(propertyName); } CacheKey cacheKey = mkCacheKey(object, propertyName); // lets try positive cache mechanisms first. If we have seen the method or field before // then we invoke it directly without burning any cycles doing reflection. CachedMethod cachedMethod = METHOD_CACHE.get(cacheKey); if (cachedMethod != null) { try { return invokeMethod(object, singleArgumentValue, cachedMethod.method, cachedMethod.takesSingleArgumentTypeAsOnlyArgument); } catch (NoSuchMethodException ignored) { assertShouldNeverHappen("A method cached as '%s' is no longer available??", cacheKey); } } Field cachedField = FIELD_CACHE.get(cacheKey); if (cachedField != null) { return invokeField(object, cachedField); } // if we have tried all strategies before and they have all failed then we negatively cache // the cacheKey and assume that its never going to turn up. This shortcuts the property lookup // in systems where there was a `foo` graphql property but they never provided an POJO // version of `foo`. // we do this second because we believe in the positive cached version will mostly prevail // but if we then look it up and negatively cache it then lest do that look up next if (isNegativelyCached(cacheKey)) { return null; } // ok we haven't cached it and we haven't negatively cached it so we have to find the POJO method which is the most // expensive operation here boolean dfeInUse = singleArgumentValue != null; try { MethodFinder methodFinder = (root, methodName) -> findPubliclyAccessibleMethod(cacheKey, root, methodName, dfeInUse); return getPropertyViaGetterMethod(object, propertyName, graphQLType, methodFinder, singleArgumentValue); } catch (NoSuchMethodException ignored) { try { MethodFinder methodFinder = (aClass, methodName) -> findViaSetAccessible(cacheKey, aClass, methodName, dfeInUse); return getPropertyViaGetterMethod(object, propertyName, graphQLType, methodFinder, singleArgumentValue); } catch (NoSuchMethodException ignored2) { try { return getPropertyViaFieldAccess(cacheKey, object, propertyName); } catch (FastNoSuchMethodException e) { // we have nothing to ask for and we have exhausted our lookup strategies putInNegativeCache(cacheKey); return null; } } } } private boolean isNegativelyCached(CacheKey key) { if (USE_NEGATIVE_CACHE.get()) { return NEGATIVE_CACHE.containsKey(key); } return false; } private void putInNegativeCache(CacheKey key) { if (USE_NEGATIVE_CACHE.get()) { NEGATIVE_CACHE.put(key, key); } } private interface MethodFinder { Method apply(Class<?> aClass, String s) throws NoSuchMethodException; } private Object getPropertyViaGetterMethod(Object object, String propertyName, GraphQLType graphQLType, MethodFinder methodFinder, Object singleArgumentValue) throws NoSuchMethodException { if (isBooleanProperty(graphQLType)) { try { return getPropertyViaGetterUsingPrefix(object, propertyName, "is", methodFinder, singleArgumentValue); } catch (NoSuchMethodException e) { return getPropertyViaGetterUsingPrefix(object, propertyName, "get", methodFinder, singleArgumentValue); } } else { return getPropertyViaGetterUsingPrefix(object, propertyName, "get", methodFinder, singleArgumentValue); } } private Object getPropertyViaGetterUsingPrefix(Object object, String propertyName, String prefix, MethodFinder methodFinder, Object singleArgumentValue) throws NoSuchMethodException { String getterName = prefix + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); Method method = methodFinder.apply(object.getClass(), getterName); return invokeMethod(object, singleArgumentValue, method, takesSingleArgumentTypeAsOnlyArgument(method)); } /** * Invoking public methods on package-protected classes via reflection * causes exceptions. This method searches a class's hierarchy for * public visibility parent classes with the desired getter. This * particular case is required to support AutoValue style data classes, * which have abstract public interfaces implemented by package-protected * (generated) subclasses. */ private Method findPubliclyAccessibleMethod(CacheKey cacheKey, Class<?> rootClass, String methodName, boolean dfeInUse) throws NoSuchMethodException { Class<?> currentClass = rootClass; while (currentClass != null) { if (Modifier.isPublic(currentClass.getModifiers())) { if (dfeInUse) { // try a getter that takes singleArgumentType first (if we have one) try { Method method = currentClass.getMethod(methodName, singleArgumentType); if (Modifier.isPublic(method.getModifiers())) { METHOD_CACHE.putIfAbsent(cacheKey, new CachedMethod(method)); return method; } } catch (NoSuchMethodException e) { // ok try the next approach } } Method method = currentClass.getMethod(methodName); if (Modifier.isPublic(method.getModifiers())) { METHOD_CACHE.putIfAbsent(cacheKey, new CachedMethod(method)); return method; } } currentClass = currentClass.getSuperclass(); } assert rootClass != null; return rootClass.getMethod(methodName); } private Method findViaSetAccessible(CacheKey cacheKey, Class<?> aClass, String methodName, boolean dfeInUse) throws NoSuchMethodException { if (!USE_SET_ACCESSIBLE.get()) { throw new FastNoSuchMethodException(methodName); } Class<?> currentClass = aClass; while (currentClass != null) { Predicate<Method> whichMethods = mth -> { if (dfeInUse) { return hasZeroArgs(mth) || takesSingleArgumentTypeAsOnlyArgument(mth); } return hasZeroArgs(mth); }; Method[] declaredMethods = currentClass.getDeclaredMethods(); Optional<Method> m = Arrays.stream(declaredMethods) .filter(mth -> methodName.equals(mth.getName())) .filter(whichMethods) .min(mostMethodArgsFirst()); if (m.isPresent()) { try { // few JVMs actually enforce this but it might happen Method method = m.get(); method.setAccessible(true); METHOD_CACHE.putIfAbsent(cacheKey, new CachedMethod(method)); return method; } catch (SecurityException ignored) { } } currentClass = currentClass.getSuperclass(); } throw new FastNoSuchMethodException(methodName); } private Object getPropertyViaFieldAccess(CacheKey cacheKey, Object object, String propertyName) throws FastNoSuchMethodException { Class<?> aClass = object.getClass(); try { Field field = aClass.getField(propertyName); FIELD_CACHE.putIfAbsent(cacheKey, field); return field.get(object); } catch (NoSuchFieldException e) { if (!USE_SET_ACCESSIBLE.get()) { throw new FastNoSuchMethodException(cacheKey.toString()); } // if not public fields then try via setAccessible try { Field field = aClass.getDeclaredField(propertyName); field.setAccessible(true); FIELD_CACHE.putIfAbsent(cacheKey, field); return field.get(object); } catch (SecurityException | NoSuchFieldException ignored2) { throw new FastNoSuchMethodException(cacheKey.toString()); } catch (IllegalAccessException e1) { throw new GraphQLException(e); } } catch (IllegalAccessException e) { throw new GraphQLException(e); } } private Object invokeMethod(Object object, Object singleArgumentValue, Method method, boolean takesSingleArgument) throws FastNoSuchMethodException { try { if (takesSingleArgument) { if (singleArgumentValue == null) { throw new FastNoSuchMethodException(method.getName()); } return method.invoke(object, singleArgumentValue); } else { return method.invoke(object); } } catch (IllegalAccessException | InvocationTargetException e) { throw new GraphQLException(e); } } private Object invokeField(Object object, Field field) { try { return field.get(object); } catch (IllegalAccessException e) { throw new GraphQLException(e); } } @SuppressWarnings("SimplifiableIfStatement") private boolean isBooleanProperty(GraphQLType graphQLType) { if (graphQLType == GraphQLBoolean) { return true; } if (isNonNull(graphQLType)) { return unwrapOne(graphQLType) == GraphQLBoolean; } return false; } public void clearReflectionCache() { METHOD_CACHE.clear(); FIELD_CACHE.clear(); NEGATIVE_CACHE.clear(); } public boolean setUseSetAccessible(boolean flag) { return USE_SET_ACCESSIBLE.getAndSet(flag); } public boolean setUseNegativeCache(boolean flag) { return USE_NEGATIVE_CACHE.getAndSet(flag); } private CacheKey mkCacheKey(Object object, String propertyName) { Class<?> clazz = object.getClass(); ClassLoader classLoader = clazz.getClassLoader(); return new CacheKey(classLoader, clazz.getName(), propertyName); } private static final class CacheKey { private final ClassLoader classLoader; private final String className; private final String propertyName; private CacheKey(ClassLoader classLoader, String className, String propertyName) { this.classLoader = classLoader; this.className = className; this.propertyName = propertyName; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CacheKey)) return false; CacheKey cacheKey = (CacheKey) o; return Objects.equals(classLoader, cacheKey.classLoader) && Objects.equals(className, cacheKey.className) && Objects.equals(propertyName, cacheKey.propertyName); } @Override public int hashCode() { return Objects.hash(classLoader, className, propertyName); } @Override public String toString() { return "CacheKey{" + "classLoader=" + classLoader + ", className='" + className + '\'' + ", propertyName='" + propertyName + '\'' + '}'; } } // by not filling out the stack trace, we gain speed when using the exception as flow control private boolean hasZeroArgs(Method mth) { return mth.getParameterCount() == 0; } private boolean takesSingleArgumentTypeAsOnlyArgument(Method mth) { return mth.getParameterCount() == 1 && mth.getParameterTypes()[0].equals(singleArgumentType); } private static Comparator<? super Method> mostMethodArgsFirst() { return Comparator.comparingInt(Method::getParameterCount).reversed(); } @SuppressWarnings("serial") private static class FastNoSuchMethodException extends NoSuchMethodException { public FastNoSuchMethodException(String methodName) { super(methodName); } @Override public synchronized Throwable fillInStackTrace() { return this; } } }
package hr.vsite.hive.services; import java.io.InputStream; import javax.inject.Inject; import javax.inject.Singleton; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.xml.XmlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import hr.vsite.hive.HiveConfiguration; @Singleton public class JettyService extends AbstractService { public static final String Key = "jetty"; @Inject public JettyService(HiveConfiguration conf) { super(conf, Key); } @Override public void doInit() throws Exception { try (InputStream istream = ClassLoader.getSystemResourceAsStream("jetty.xml")) { XmlConfiguration jettyConf = new XmlConfiguration(istream); server = Server.class.cast(jettyConf.configure()); } log.info("Jetty service initialized"); } @Override public void doStart() throws Exception { server.start(); log.info("Jetty service started"); } @Override public void doStop() { try { server.stop(); log.info("Jetty service stopped"); } catch (Exception e) { log.error("Error stopping jetty", e); } } @Override public void doDestroy() { server.destroy(); log.info("Jetty service destroyed"); } private static final Logger log = LoggerFactory.getLogger(JettyService.class); private Server server = null; }
package hu.karsany.hunlib4j.name; import hu.karsany.hunlib4j.exceptions.Hunlib4jException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; class TitulusSet implements Set<String> { private static final String ERR_CANNOT_ADD = "Titulusokhoz futás közben hozzáadni nem lehet."; private static final String ERR_CANNOT_DELETE = "Titulusok közül futás közben törölni nem lehet."; private static TitulusSet titulusSet; private Set<String> titulusok; private TitulusSet() throws IOException { InputStream resourceAsStream = this.getClass().getResourceAsStream("/name/TITULUS.txt"); InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream, Charset.forName("UTF-8")); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); titulusok = new HashSet<String>(); String line; while ((line = bufferedReader.readLine()) != null) { titulusok.add(line.toUpperCase().trim()); } } public static TitulusSet getInstance() { if (titulusSet == null) { try { titulusSet = new TitulusSet(); } catch (IOException e) { throw new Hunlib4jException("Cannot open resource TITULUS.txt", e); } } return titulusSet; } @Override public int size() { return titulusok.size(); } @Override public boolean isEmpty() { return titulusok.isEmpty(); } @Override public boolean contains(Object o) { return titulusok.contains(o); } @Override public Iterator<String> iterator() { return titulusok.iterator(); } @Override public Object[] toArray() { return titulusok.toArray(); } @Override public <T> T[] toArray(T[] a) { return titulusok.toArray(a); } @Override public boolean add(String s) { throw new UnsupportedOperationException(ERR_CANNOT_ADD); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(ERR_CANNOT_DELETE); } @Override public boolean containsAll(Collection<?> c) { return titulusok.containsAll(c); } @Override public boolean addAll(Collection<? extends String> c) { throw new UnsupportedOperationException(ERR_CANNOT_ADD); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(ERR_CANNOT_DELETE); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(ERR_CANNOT_DELETE); } @Override public void clear() { throw new UnsupportedOperationException(ERR_CANNOT_DELETE); } }
package io.mikekennedy.camel; import org.apache.camel.Endpoint; import org.apache.camel.impl.DefaultComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class SlackComponent extends DefaultComponent { private static final transient Logger LOG = LoggerFactory.getLogger(SlackComponent.class); private String webhookUrl; /** * Create a slack endpoint * * @param uri the full URI of the endpoint * @param channelName the channel or username that the message should be sent to * @param parameters the optional parameters passed in * @return the camel endpoint * @throws Exception */ @Override protected Endpoint createEndpoint(String uri, String channelName, Map<String, Object> parameters) throws Exception { Endpoint endpoint = new SlackEndpoint(uri, channelName, this); setProperties(endpoint, parameters); return endpoint; } /** * Getter for the incoming webhook URL * * @return String containing the incoming webhook URL */ public String getWebhookUrl() { return webhookUrl; } /** * Setter for the incoming webhook URL * * @param webhookUrl the incoming webhook URL */ public void setWebhookUrl(String webhookUrl) { this.webhookUrl = webhookUrl; } }
package io.strimzi.kafka.bridge; import io.netty.handler.codec.http.HttpResponseStatus; import io.strimzi.kafka.bridge.amqp.AmqpBridge; import io.strimzi.kafka.bridge.amqp.AmqpBridgeConfig; import io.strimzi.kafka.bridge.http.HttpBridge; import io.strimzi.kafka.bridge.http.HttpBridgeConfig; import io.vertx.config.ConfigRetriever; import io.vertx.config.ConfigRetrieverOptions; import io.vertx.config.ConfigStoreOptions; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Apache Kafka bridge main application class */ public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); private static final String HEALTH_SERVER_PORT = "HEALTH_SERVER_PORT"; private static final int DEFAULT_HEALTH_SERVER_PORT = 8081; @SuppressWarnings("checkstyle:NPathComplexity") public static void main(String[] args) { Vertx vertx = Vertx.vertx(); if (args.length == 0) { log.error("Please specify a cofiguration file using the '--config-file` option. For example 'bin/run_bridge.sh --config-file config/application.properties'."); System.exit(1); } String path = args[0]; if (args.length > 1) { path = args[0] + "=" + args[1]; } ConfigStoreOptions fileStore = new ConfigStoreOptions() .setType("file") .setOptional(true) .setFormat("properties") .setConfig(new JsonObject().put("path", getFilePath(path)).put("raw-data", true)); ConfigStoreOptions envStore = new ConfigStoreOptions() .setType("env") .setConfig(new JsonObject().put("raw-data", true)); ConfigRetrieverOptions options = new ConfigRetrieverOptions() .addStore(fileStore) .addStore(envStore); ConfigRetriever retriever = ConfigRetriever.create(vertx, options); retriever.getConfig(ar -> { Map<String, Object> config = ar.result().getMap(); AmqpBridgeConfig amqpBridgeConfig = AmqpBridgeConfig.fromMap(config); HttpBridgeConfig httpBridgeConfig = HttpBridgeConfig.fromMap(config); int healthServerPort = Integer.valueOf(config.getOrDefault(HEALTH_SERVER_PORT, DEFAULT_HEALTH_SERVER_PORT).toString()); if (amqpBridgeConfig.getEndpointConfig().getPort() == healthServerPort || httpBridgeConfig.getEndpointConfig().getPort() == healthServerPort) { log.error("Health server port {} conflicts with enabled protocols ports", healthServerPort); System.exit(1); } List<Future> futures = new ArrayList<>(); Future<Void> amqpFuture = Future.future(); futures.add(amqpFuture); if (amqpBridgeConfig.getEndpointConfig().isEnabled()) { AmqpBridge amqpBridge = new AmqpBridge(amqpBridgeConfig); vertx.deployVerticle(amqpBridge, done -> { if (done.succeeded()) { log.info("AMQP verticle instance deployed [{}]", done.result()); amqpFuture.complete(); } else { log.error("Failed to deploy AMQP verticle instance", done.cause()); amqpFuture.fail(done.cause()); } }); } else { amqpFuture.complete(); } Future<Void> httpFuture = Future.future(); futures.add(httpFuture); if (httpBridgeConfig.getEndpointConfig().isEnabled()) { HttpBridge httpBridge = new HttpBridge(httpBridgeConfig); vertx.deployVerticle(httpBridge, done -> { if (done.succeeded()) { log.info("HTTP verticle instance deployed [{}]", done.result()); httpFuture.complete(); } else { log.error("Failed to deploy HTTP verticle instance", done.cause()); httpFuture.fail(done.cause()); } }); } else { httpFuture.complete(); } CompositeFuture.join(futures).setHandler(done -> { if (done.succeeded()) { startHealthServer(vertx, healthServerPort); } }); }); } /** * Start an HTTP health server */ private static void startHealthServer(Vertx vertx, int port) { vertx.createHttpServer() .requestHandler(request -> { if (request.path().equals("/healthy")) { request.response().setStatusCode(HttpResponseStatus.OK.code()).end(); } else if (request.path().equals("/ready")) { request.response().setStatusCode(HttpResponseStatus.OK.code()).end(); } }) .listen(port, done -> { if (done.succeeded()) { log.info("Health server started, listening on port {}", port); } else { log.error("Failed to start Health server", done.cause()); } }); } private static String getFilePath(String arg) { String[] confFileArg = arg.split("="); String path = ""; if (confFileArg[0].equals("--config-file")) { if (confFileArg[1].startsWith(File.separator)) { // absolute path path = confFileArg[1]; } else { // relative path path = System.getProperty("user.dir") + File.separator + confFileArg[1]; } return path; } return null; } }