lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
mit
4e4c9e4adaf9a954403d819092d3623e9db619d8
0
EPiCS/soundgates,EPiCS/soundgates,EPiCS/soundgates,EPiCS/soundgates,EPiCS/soundgates
package de.upb.soundgates.atomicbuilder; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class AtomicBuilder { static boolean folder = false; public static void main(String[] args) { if (args.length > 0 && args[0].equals("--folder")){ folder = true; } if (args.length == 0){ System.out.println("Usage:"); System.out.println("\t --folder <sourceFolder> <destinationFolder>"); System.out.println("or"); System.out.println("\t <pdFile> <templateFile> <destinationFile>"); } if (folder){ File sourceFolder = new File(args[1]); File destinationFolder = new File(args[2]); for (final File sub : sourceFolder.listFiles()){ if (sub.isDirectory()){ File pdFile = getFileFromFolder(sub, "_patch.pd"); File xmlFile = getFileFromFolder(sub, "xml"); try { generate(new File(destinationFolder, xmlFile.getName().replaceAll("(\\..*)$", "") + ".xml"), pdFile, xmlFile); } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { File pdFile = new File(args[0]); File templateFile = new File(args[0]); File destinationFile = new File(args[1]); try { generate(destinationFile, pdFile, templateFile); } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private static void generate(File destinationFile, File pdFile, File templateFile) throws ParserConfigurationException, SAXException, IOException, TransformerException{ Document templateDoc = readTemplateFile(templateFile); PureDataInfo pureDataInfo = readPureDataCode(pdFile); insert(templateDoc, pureDataInfo); output(templateDoc, destinationFile); } private static File getFileFromFolder(File folder, final String suffix) { for (final File sub : folder.listFiles()) { if (sub.getName().endsWith(suffix)) return sub; } return null; } private static void output(Document templateDoc, File destination) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(templateDoc); StreamResult result = new StreamResult(destination); transformer.transform(source, result); } private static void insert(Document templateDoc, PureDataInfo pureDataInfo) { NodeList simulationNodes = templateDoc.getElementsByTagName("Simulation"); for (int i = 0; i < simulationNodes.getLength(); i++){ if (simulationNodes.item(i).getParentNode().getNodeName().equals("Code")){ createPortMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getInputDefinitions()); createPortMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getOutputDefinitions()); createPropMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getProperties()); createCode(templateDoc, simulationNodes.item(i), pureDataInfo.getCode()); } } } private static void createCode(Document doc, Node parent, String code){ Element codeNode = doc.createElement("PD"); parent.appendChild(codeNode); codeNode.appendChild(doc.createTextNode(code)); } private static void createPropMappings(Document doc, Node parent, List<String> properties) { for (String property : properties){ Element propMapping = doc.createElement("PropMapping"); parent.appendChild(propMapping); propMapping.setAttribute("PropName", property); propMapping.setAttribute("Tag", "@" + property); } } private static void createPortMappings(Document doc, Node parent, List<String> ports){ for (String port : ports){ Element portMapping = doc.createElement("PortMapping"); parent.appendChild(portMapping); portMapping.setAttribute("PortName", port); portMapping.setAttribute("PortNumber", "" + ports.indexOf(port)); } } private static Document readTemplateFile(File templateFile) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return dBuilder.parse(templateFile); } private static void executeReplacements(List<String> codeLines, PureDataInfo pdInfo){ List<String> connects = new ArrayList<String>(); List<String> onlyObjects = new ArrayList<String>(); //find counted pd code lines for (String line : codeLines){ onlyObjects.add(line); } //find connections for (String line : codeLines){ if (line.contains("#X connect")){ connects.add(line); } } //find messages with no outgoing links for(String connectLine : connects){ String [] connect = connectLine.split(" "); int sourceObjectNumber = Integer.parseInt(connect[2]); int targetObjectNumber = Integer.parseInt(connect[4]); String targetObject = getObject(codeLines, targetObjectNumber); if (targetObject.contains("#X msg")){ String [] message = targetObject.split(" "); //find only messages with no links to them boolean hasOutgoingLinks = false; for(String tmpConnectLine : connects){ String [] tmpConnect = tmpConnectLine.split(" "); if (Integer.parseInt(tmpConnect[2]) == targetObjectNumber){ hasOutgoingLinks = true; break; } } if (!hasOutgoingLinks){ String selector = message [4]; if (selector.equals("replace")){ int atomToReplace = Integer.parseInt(message[5]); String replacement = "@" + message[6]; String [] toManipulate = getObject(codeLines, sourceObjectNumber).split(" "); int offset = 3; //TODO: check if other offsets are needed, 3 is correct for messages, objects and comments toManipulate[atomToReplace + offset] = replacement; String manipulatedLine = ""; for (String part : toManipulate) manipulatedLine += part + " "; pdInfo.addProperty(message[6]); setObject(codeLines, sourceObjectNumber, manipulatedLine); } } } } } private static void setObject(List<String> pdCodeLines, int objectId, String object){ int counter = 0; int lineNumber = 0; for (String line : pdCodeLines){ if (!line.contains("#N")){ if (counter == objectId){ pdCodeLines.set(lineNumber, object); return; } counter++; } lineNumber++; } } private static String getObject(List<String> pdCodeLines, int objectId){ int counter = 0; for (String line : pdCodeLines){ if (!line.contains("#N")){ if (counter == objectId){ return line; } counter++; } } return null; } private static PureDataInfo readPureDataCode(File pdFile) throws IOException { FileReader fileReader = new FileReader(pdFile); BufferedReader bufferedReader = new BufferedReader(fileReader); String read = ""; PureDataInfo result = new PureDataInfo(); List<String> codeLines = new ArrayList<String>(); while((read = bufferedReader.readLine()) != null){ if (!read.contains(";")){ read += bufferedReader.readLine(); } read = read.split(";")[0]; if (read.contains("#X text")){ String [] splitLine = read.split(" "); if (splitLine.length >= 5 && splitLine[4].equals("inports")){ for (int i = 5; i < splitLine.length; i++){ result.addInputDefinition(splitLine[i]); } } else if (splitLine.length >= 5 && splitLine[4].equals("outports")){ for (int i = 5; i < splitLine.length; i++){ result.addOutputDefinition(splitLine[i]); } } } codeLines.add(read); } bufferedReader.close(); StringBuilder resultingCode = new StringBuilder(); executeReplacements(codeLines, result); for (String line : codeLines){ resultingCode.append(line + ";" + System.lineSeparator()); } result.setCode(resultingCode.toString()); return result; } }
software/editor/AtomicBuilder/src/de/upb/soundgates/atomicbuilder/AtomicBuilder.java
package de.upb.soundgates.atomicbuilder; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class AtomicBuilder { static boolean folder = false; public static void main(String[] args) { if (args.length > 0 && args[0].equals("--folder")){ folder = true; } if (args.length == 0){ System.out.println("Usage:"); System.out.println("\t -r <sourceFolder> <destinationFolder>"); System.out.println("or"); System.out.println("\t <pdFile> <templateFile> <destinationFile>"); } if (folder){ File sourceFolder = new File(args[1]); File destinationFolder = new File(args[2]); for (final File sub : sourceFolder.listFiles()){ if (sub.isDirectory()){ File pdFile = getFileFromFolder(sub, "_patch.pd"); File xmlFile = getFileFromFolder(sub, "xml"); try { generate(new File(destinationFolder, xmlFile.getName().replaceAll("(\\..*)$", "") + ".xml"), pdFile, xmlFile); } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { File pdFile = new File(args[0]); File templateFile = new File(args[0]); File destinationFile = new File(args[1]); try { generate(destinationFile, pdFile, templateFile); } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private static void generate(File destinationFile, File pdFile, File templateFile) throws ParserConfigurationException, SAXException, IOException, TransformerException{ Document templateDoc = readTemplateFile(templateFile); PureDataInfo pureDataInfo = readPureDataCode(pdFile); insert(templateDoc, pureDataInfo); output(templateDoc, destinationFile); } private static File getFileFromFolder(File folder, final String suffix) { for (final File sub : folder.listFiles()) { if (sub.getName().endsWith(suffix)) return sub; } return null; } private static void output(Document templateDoc, File destination) throws TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(templateDoc); StreamResult result = new StreamResult(destination); transformer.transform(source, result); } private static void insert(Document templateDoc, PureDataInfo pureDataInfo) { NodeList simulationNodes = templateDoc.getElementsByTagName("Simulation"); for (int i = 0; i < simulationNodes.getLength(); i++){ if (simulationNodes.item(i).getParentNode().getNodeName().equals("Code")){ createPortMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getInputDefinitions()); createPortMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getOutputDefinitions()); createPropMappings(templateDoc, simulationNodes.item(i), pureDataInfo.getProperties()); createCode(templateDoc, simulationNodes.item(i), pureDataInfo.getCode()); } } } private static void createCode(Document doc, Node parent, String code){ Element codeNode = doc.createElement("PD"); parent.appendChild(codeNode); codeNode.appendChild(doc.createTextNode(code)); } private static void createPropMappings(Document doc, Node parent, List<String> properties) { for (String property : properties){ Element propMapping = doc.createElement("PropMapping"); parent.appendChild(propMapping); propMapping.setAttribute("PropName", property); propMapping.setAttribute("Tag", "@" + property); } } private static void createPortMappings(Document doc, Node parent, List<String> ports){ for (String port : ports){ Element portMapping = doc.createElement("PortMapping"); parent.appendChild(portMapping); portMapping.setAttribute("PortName", port); portMapping.setAttribute("PortNumber", "" + ports.indexOf(port)); } } private static Document readTemplateFile(File templateFile) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return dBuilder.parse(templateFile); } private static void executeReplacements(List<String> codeLines, PureDataInfo pdInfo){ List<String> connects = new ArrayList<String>(); List<String> onlyObjects = new ArrayList<String>(); //find counted pd code lines for (String line : codeLines){ onlyObjects.add(line); } //find connections for (String line : codeLines){ if (line.contains("#X connect")){ connects.add(line); } } //find messages with no outgoing links for(String connectLine : connects){ String [] connect = connectLine.split(" "); int sourceObjectNumber = Integer.parseInt(connect[2]); int targetObjectNumber = Integer.parseInt(connect[4]); String targetObject = getObject(codeLines, targetObjectNumber); if (targetObject.contains("#X msg")){ String [] message = targetObject.split(" "); //find only messages with no links to them boolean hasOutgoingLinks = false; for(String tmpConnectLine : connects){ String [] tmpConnect = tmpConnectLine.split(" "); if (Integer.parseInt(tmpConnect[2]) == targetObjectNumber){ hasOutgoingLinks = true; break; } } if (!hasOutgoingLinks){ String selector = message [4]; if (selector.equals("replace")){ int atomToReplace = Integer.parseInt(message[5]); String replacement = "@" + message[6]; String [] toManipulate = getObject(codeLines, sourceObjectNumber).split(" "); int offset = 3; //TODO: check if other offsets are needed, 3 is correct for messages, objects and comments toManipulate[atomToReplace + offset] = replacement; String manipulatedLine = ""; for (String part : toManipulate) manipulatedLine += part + " "; pdInfo.addProperty(message[6]); setObject(codeLines, sourceObjectNumber, manipulatedLine); } } } } } private static void setObject(List<String> pdCodeLines, int objectId, String object){ int counter = 0; int lineNumber = 0; for (String line : pdCodeLines){ if (!line.contains("#N")){ if (counter == objectId){ pdCodeLines.set(lineNumber, object); return; } counter++; } lineNumber++; } } private static String getObject(List<String> pdCodeLines, int objectId){ int counter = 0; for (String line : pdCodeLines){ if (!line.contains("#N")){ if (counter == objectId){ return line; } counter++; } } return null; } private static PureDataInfo readPureDataCode(File pdFile) throws IOException { FileReader fileReader = new FileReader(pdFile); BufferedReader bufferedReader = new BufferedReader(fileReader); String read = ""; PureDataInfo result = new PureDataInfo(); List<String> codeLines = new ArrayList<String>(); while((read = bufferedReader.readLine()) != null){ if (!read.contains(";")){ read += bufferedReader.readLine(); } read = read.split(";")[0]; if (read.contains("#X text")){ String [] splitLine = read.split(" "); if (splitLine.length >= 5 && splitLine[4].equals("inports")){ for (int i = 5; i < splitLine.length; i++){ result.addInputDefinition(splitLine[i]); } } else if (splitLine.length >= 5 && splitLine[4].equals("outports")){ for (int i = 5; i < splitLine.length; i++){ result.addOutputDefinition(splitLine[i]); } } } codeLines.add(read); } bufferedReader.close(); StringBuilder resultingCode = new StringBuilder(); executeReplacements(codeLines, result); for (String line : codeLines){ resultingCode.append(line + ";" + System.lineSeparator()); } result.setCode(resultingCode.toString()); return result; } }
fixed usage message
software/editor/AtomicBuilder/src/de/upb/soundgates/atomicbuilder/AtomicBuilder.java
fixed usage message
Java
mit
7ba1f78bb646de3be7b8f9665eb588d937cc3590
0
douglasjunior/android-simple-tooltip
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Douglas Nassif Roma Junior * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.douglasjunior.androidSimpleTooltip; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; /** * <p class='pt'>Um tooltip que pode ser utilizado para exibição de dicas.</p> * <p class='en'>A tooltip that can be used to display tips on the screen.</p> * * @author Created by douglas on 05/05/16. * @see android.widget.PopupWindow */ @SuppressWarnings("SameParameterValue") public class SimpleTooltip implements PopupWindow.OnDismissListener { // Default Resources private static final int mDefaultPopupWindowStyleRes = android.R.attr.popupWindowStyle; private static final int mDefaultTextAppearanceRes = R.style.simpletooltip_default; private static final int mDefaultBackgroundColorRes = R.color.simpletooltip_background; private static final int mDefaultTextColorRes = R.color.simpletooltip_text; private static final int mDefaultArrowColorRes = R.color.simpletooltip_arrow; private static final int mDefaultMarginRes = R.dimen.simpletooltip_margin; private static final int mDefaultPaddingRes = R.dimen.simpletooltip_padding; private static final int mDefaultAnimationPaddingRes = R.dimen.simpletooltip_animation_padding; private static final int mDefaultAnimationDurationRes = R.integer.simpletooltip_animation_duration; private static final int mDefaultArrowWidthRes = R.dimen.simpletooltip_arrow_width; private static final int mDefaultArrowHeightRes = R.dimen.simpletooltip_arrow_height; private final Context mContext; private OnDismissListener mOnDismissListener; private OnShowListener mOnShowListener; private PopupWindow mPopupWindow; private final int mGravity; private final boolean mDismissOnInsideTouch; private final boolean mDismissOnOutsideTouch; private final boolean mModal; private final View mContentView; private View mContentLayout; @IdRes private final int mTextViewId; private final CharSequence mText; private final View mAnchorView; private final boolean mTransparentOverlay; private final float mMaxWidth; private View mOverlay; private ViewGroup mRootView; private final boolean mShowArrow; private ImageView mArrowView; private final Drawable mArrowDrawable; private final boolean mAnimated; private AnimatorSet mAnimator; private final float mMargin; private final float mPadding; private final float mAnimationPadding; private final long mAnimationDuration; private final float mArrowWidth; private final float mArrowHeight; private boolean dismissed = false; private SimpleTooltip(Builder builder) { mContext = builder.context; mGravity = builder.gravity; mDismissOnInsideTouch = builder.dismissOnInsideTouch; mDismissOnOutsideTouch = builder.dismissOnOutsideTouch; mModal = builder.modal; mContentView = builder.contentView; mTextViewId = builder.textViewId; mText = builder.text; mAnchorView = builder.anchorView; mTransparentOverlay = builder.transparentOverlay; mMaxWidth = builder.maxWidth; mShowArrow = builder.showArrow; mArrowWidth = builder.arrowWidth; mArrowHeight = builder.arrowHeight; mArrowDrawable = builder.arrowDrawable; mAnimated = builder.animated; mMargin = builder.margin; mPadding = builder.padding; mAnimationPadding = builder.animationPadding; mAnimationDuration = builder.animationDuration; mOnDismissListener = builder.onDismissListener; mOnShowListener = builder.onShowListener; mRootView = (ViewGroup) mAnchorView.getRootView(); init(); } private void init() { configPopupWindow(); configContentView(); } private void configPopupWindow() { mPopupWindow = new PopupWindow(mContext, null, mDefaultPopupWindowStyleRes); mPopupWindow.setOnDismissListener(this); mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); mPopupWindow.setClippingEnabled(false); } public void show() { verifyDismissed(); mContentLayout.getViewTreeObserver().addOnGlobalLayoutListener(mLocationLayoutListener); mContentLayout.getViewTreeObserver().addOnGlobalLayoutListener(mAutoDismissLayoutListener); mRootView.post(new Runnable() { @Override public void run() { mPopupWindow.showAtLocation(mRootView, Gravity.NO_GRAVITY, mRootView.getWidth(), mRootView.getHeight()); } }); } private void verifyDismissed() { if (dismissed) { throw new IllegalArgumentException("Tooltip has ben dismissed."); } } private void createOverlay() { mOverlay = mTransparentOverlay ? new View(mContext) : new OverlayView(mContext, mAnchorView); mOverlay.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mOverlay.setOnTouchListener(mOverlayTouchListener); mRootView.addView(mOverlay); } private PointF calculePopupLocation() { PointF location = new PointF(); final RectF anchorRect = SimpleTooltipUtils.calculeRectInWindow(mAnchorView); final PointF anchorCenter = new PointF(anchorRect.centerX(), anchorRect.centerY()); switch (mGravity) { case Gravity.START: location.x = anchorRect.left - mPopupWindow.getContentView().getWidth() - mMargin; location.y = anchorCenter.y - mPopupWindow.getContentView().getHeight() / 2f; break; case Gravity.END: location.x = anchorRect.right + mMargin; location.y = anchorCenter.y - mPopupWindow.getContentView().getHeight() / 2f; break; case Gravity.TOP: location.x = anchorCenter.x - mPopupWindow.getContentView().getWidth() / 2f; location.y = anchorRect.top - mPopupWindow.getContentView().getHeight() - mMargin; break; case Gravity.BOTTOM: location.x = anchorCenter.x - mPopupWindow.getContentView().getWidth() / 2f; location.y = anchorRect.bottom + mMargin; break; default: throw new IllegalArgumentException("Gravity must have be START, END, TOP or BOTTOM."); } return location; } private void configContentView() { if (mContentView instanceof TextView) { TextView tv = (TextView) mContentView; tv.setText(mText); } else { TextView tv = (TextView) mContentView.findViewById(mTextViewId); if (tv != null) tv.setText(mText); } mContentView.setPadding((int) mPadding, (int) mPadding, (int) mPadding, (int) mPadding); LinearLayout linearLayout = new LinearLayout(mContext); linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(mGravity == Gravity.START || mGravity == Gravity.END ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); int layoutPadding = (int) (mAnimated ? mAnimationPadding : 0); linearLayout.setPadding(layoutPadding, layoutPadding, layoutPadding, layoutPadding); if (mShowArrow) { mArrowView = new ImageView(mContext); mArrowView.setImageDrawable(mArrowDrawable); LinearLayout.LayoutParams arrowLayoutParams; if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) { arrowLayoutParams = new LinearLayout.LayoutParams((int) mArrowWidth, (int) mArrowHeight, 0); } else { arrowLayoutParams = new LinearLayout.LayoutParams((int) mArrowHeight, (int) mArrowWidth, 0); } arrowLayoutParams.gravity = Gravity.CENTER; mArrowView.setLayoutParams(arrowLayoutParams); if (mGravity == Gravity.TOP || mGravity == Gravity.START) { linearLayout.addView(mContentView); linearLayout.addView(mArrowView); } else { linearLayout.addView(mArrowView); linearLayout.addView(mContentView); } } else { linearLayout.addView(mContentView); } LinearLayout.LayoutParams contentViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); contentViewParams.gravity = Gravity.CENTER; mContentView.setLayoutParams(contentViewParams); if (mDismissOnInsideTouch || mDismissOnOutsideTouch) mContentView.setOnTouchListener(mPopupWindowTouchListener); mContentLayout = linearLayout; mContentLayout.setVisibility(View.INVISIBLE); mPopupWindow.setContentView(mContentLayout); } public void dismiss() { if (dismissed) return; dismissed = true; if (mPopupWindow != null) { mPopupWindow.dismiss(); } } /** * <div class="pt">Indica se o tooltip está sendo exibido na tela.</div> * <div class=en">Indicate whether this tooltip is showing on screen.</div> * * @return <div class="pt"><tt>true</tt> se o tooltip estiver sendo exibido, <tt>false</tt> caso contrário</div> * <div class="en"><tt>true</tt> if the popup is showing, <tt>false</tt> otherwise</div> */ public boolean isShowing() { return mPopupWindow != null && mPopupWindow.isShowing(); } public <T extends View> T findViewById(int id) { //noinspection unchecked return (T) mContentLayout.findViewById(id); } @Override public void onDismiss() { dismissed = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (mAnimator != null) { mAnimator.removeAllListeners(); mAnimator.end(); mAnimator.cancel(); mAnimator = null; } } if (mRootView != null && mOverlay != null) { mRootView.removeView(mOverlay); } mRootView = null; mOverlay = null; if (mOnDismissListener != null) mOnDismissListener.onDismiss(this); mOnDismissListener = null; SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), mLocationLayoutListener); SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), mArrowLayoutListener); SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), mShowLayoutListener); SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), mAnimationLayoutListener); SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), mAutoDismissLayoutListener); mPopupWindow = null; } private final View.OnTouchListener mPopupWindowTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) { if (mDismissOnInsideTouch) { dismiss(); return mModal; } return false; } if (event.getAction() == MotionEvent.ACTION_UP) { v.performClick(); } return mModal; } }; private final View.OnTouchListener mOverlayTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mDismissOnOutsideTouch) { dismiss(); } if (event.getAction() == MotionEvent.ACTION_UP) { v.performClick(); } return mModal; } }; private final ViewTreeObserver.OnGlobalLayoutListener mLocationLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (dismissed) { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); return; } if (mMaxWidth > 0 && mContentView.getWidth() > mMaxWidth) { SimpleTooltipUtils.setWidth(mContentView, mMaxWidth); mPopupWindow.update(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); return; } SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mArrowLayoutListener); PointF location = calculePopupLocation(); mPopupWindow.setClippingEnabled(true); mPopupWindow.update((int) location.x, (int) location.y, mPopupWindow.getWidth(), mPopupWindow.getHeight()); mPopupWindow.getContentView().requestLayout(); createOverlay(); } }; private final ViewTreeObserver.OnGlobalLayoutListener mArrowLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mAnimationLayoutListener); mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mShowLayoutListener); if (mShowArrow) { RectF achorRect = SimpleTooltipUtils.calculeRectOnScreen(mAnchorView); RectF contentViewRect = SimpleTooltipUtils.calculeRectOnScreen(mContentLayout); float x, y; if (mGravity == Gravity.BOTTOM || mGravity == Gravity.TOP) { x = mContentLayout.getPaddingLeft() + SimpleTooltipUtils.pxFromDp(2); float centerX = (contentViewRect.width() / 2f) - (mArrowView.getWidth() / 2f); float newX = centerX - (contentViewRect.centerX() - achorRect.centerX()); if (newX > x) { if (newX + mArrowView.getWidth() + x > contentViewRect.width()) { x = contentViewRect.width() - mArrowView.getWidth() - x; } else { x = newX; } } y = mArrowView.getTop(); y = y + (mGravity == Gravity.TOP ? -1 : +1); } else { y = mContentLayout.getPaddingTop() + SimpleTooltipUtils.pxFromDp(2); float centerY = (contentViewRect.height() / 2f) - (mArrowView.getHeight() / 2f); float newY = centerY - (contentViewRect.centerY() - achorRect.centerY()); if (newY > y) { if (newY + mArrowView.getHeight() + y > contentViewRect.height()) { y = contentViewRect.height() - mArrowView.getHeight() - y; } else { y = newY; } } x = mArrowView.getLeft(); x = x + (mGravity == Gravity.START ? -1 : +1); } SimpleTooltipUtils.setX(mArrowView, (int) x); SimpleTooltipUtils.setY(mArrowView, (int) y); } mPopupWindow.getContentView().requestLayout(); } }; private final ViewTreeObserver.OnGlobalLayoutListener mShowLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; if (mOnShowListener != null) mOnShowListener.onShow(SimpleTooltip.this); mOnShowListener = null; mContentLayout.setVisibility(View.VISIBLE); } }; private final ViewTreeObserver.OnGlobalLayoutListener mAnimationLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; if (mAnimated) { startAnimation(); } mPopupWindow.getContentView().requestLayout(); } }; @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void startAnimation() { final String property = mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM ? "translationY" : "translationX"; final ObjectAnimator anim1 = ObjectAnimator.ofFloat(mContentLayout, property, -mAnimationPadding, mAnimationPadding); anim1.setDuration(mAnimationDuration); anim1.setInterpolator(new AccelerateDecelerateInterpolator()); final ObjectAnimator anim2 = ObjectAnimator.ofFloat(mContentLayout, property, mAnimationPadding, -mAnimationPadding); anim2.setDuration(mAnimationDuration); anim2.setInterpolator(new AccelerateDecelerateInterpolator()); mAnimator = new AnimatorSet(); mAnimator.playSequentially(anim1, anim2); mAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (!dismissed && isShowing()) { animation.start(); } } }); mAnimator.start(); } /** * <div class="pt">Listener utilizado para chamar o <tt>SimpleTooltip#dismiss()</tt> quando a <tt>View</tt> root é encerrada sem que a tooltip seja fechada. * Pode ocorrer quando a tooltip é utilizada dentro de Dialogs.</div> */ private final ViewTreeObserver.OnGlobalLayoutListener mAutoDismissLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (dismissed) { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); return; } if (!mRootView.isShown()) dismiss(); } }; public interface OnDismissListener { void onDismiss(SimpleTooltip tooltip); } public interface OnShowListener { void onShow(SimpleTooltip tooltip); } /** * <div class="pt">Classe responsável por facilitar a criação do objeto <tt>SimpleTooltip</tt>.</div> * <div class="en">Class responsible for making it easier to build the object <tt>SimpleTooltip</tt>.</div> * * @author Created by douglas on 05/05/16. */ @SuppressWarnings({"SameParameterValue", "unused"}) public static class Builder { private final Context context; private boolean dismissOnInsideTouch = true; private boolean dismissOnOutsideTouch = true; private boolean modal = false; private View contentView; @IdRes private int textViewId = android.R.id.text1; private CharSequence text = ""; private View anchorView; private int gravity = Gravity.BOTTOM; private boolean transparentOverlay = true; private float maxWidth; private boolean showArrow = true; private Drawable arrowDrawable; private boolean animated = false; private float margin = -1; private float padding = -1; private float animationPadding = -1; private OnDismissListener onDismissListener; private OnShowListener onShowListener; private long animationDuration; private int backgroundColor; private int textColor; private int arrowColor; private float arrowHeight; private float arrowWidth; public Builder(Context context) { this.context = context; } public SimpleTooltip build() throws IllegalArgumentException { validateArguments(); if (backgroundColor == 0) { backgroundColor = SimpleTooltipUtils.getColor(context, mDefaultBackgroundColorRes); } if (textColor == 0) { textColor = SimpleTooltipUtils.getColor(context, mDefaultTextColorRes); } if (contentView == null) { TextView tv = new TextView(context); SimpleTooltipUtils.setTextAppearance(tv, mDefaultTextAppearanceRes); tv.setBackgroundColor(backgroundColor); tv.setTextColor(textColor); contentView = tv; } if (arrowColor == 0) { arrowColor = SimpleTooltipUtils.getColor(context, mDefaultArrowColorRes); } if (arrowDrawable == null) { int arrowDirection = SimpleTooltipUtils.tooltipGravityToArrowDirection(gravity); arrowDrawable = new ArrowDrawable(arrowColor, arrowDirection); } if (margin < 0) { margin = context.getResources().getDimension(mDefaultMarginRes); } if (padding < 0) { padding = context.getResources().getDimension(mDefaultPaddingRes); } if (animationPadding < 0) { animationPadding = context.getResources().getDimension(mDefaultAnimationPaddingRes); } if (animationDuration == 0) { animationDuration = context.getResources().getInteger(mDefaultAnimationDurationRes); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { animated = false; } if (showArrow) { if (arrowWidth == 0) arrowWidth = context.getResources().getDimension(mDefaultArrowWidthRes); if (arrowHeight == 0) arrowHeight = context.getResources().getDimension(mDefaultArrowHeightRes); } return new SimpleTooltip(this); } private void validateArguments() throws IllegalArgumentException { if (context == null) { throw new IllegalArgumentException("Context not specified."); } if (anchorView == null) { throw new IllegalArgumentException("Anchor view not specified."); } } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param textView <div class="pt">novo conteúdo para o tooltip.</div> * @return this * @see Builder#contentView(int, int) * @see Builder#contentView(View, int) * @see Builder#contentView(int) */ public Builder contentView(TextView textView) { this.contentView = textView; this.textViewId = 0; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentView <div class="pt">novo conteúdo para o tooltip, pode ser um <tt>ViewGroup</tt> ou qualquer componente customizado.</div> * @param textViewId <div class="pt">resId para o <tt>TextView</tt> existente dentro do <tt>contentView</tt>. Padrão é <tt>android.R.id.text1</tt>.</div> * @return this * @see Builder#contentView(int, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int) */ public Builder contentView(View contentView, @IdRes int textViewId) { this.contentView = contentView; this.textViewId = textViewId; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentViewId <div class="pt">layoutId que será inflado como o novo conteúdo para o tooltip.</div> * @param textViewId <div class="pt">resId para o <tt>TextView</tt> existente dentro do <tt>contentView</tt>. Padrão é <tt>android.R.id.text1</tt>.</div> * @return this * @see Builder#contentView(View, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int) */ public Builder contentView(@LayoutRes int contentViewId, @IdRes int textViewId) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.contentView = inflater.inflate(contentViewId, null, false); this.textViewId = textViewId; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentViewId <div class="pt">layoutId que será inflado como o novo conteúdo para o tooltip.</div> * @return this * @see Builder#contentView(View, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int, int) */ public Builder contentView(@LayoutRes int contentViewId) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.contentView = inflater.inflate(contentViewId, null, false); this.textViewId = 0; return this; } /** * <div class="pt">Define se o tooltip será fechado quando receber um clique dentro de sua área. Padrão é <tt>true</tt>.</div> * * @param dismissOnInsideTouch <div class="pt"><tt>true</tt> para fechar quando receber o click dentro, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnOutsideTouch(boolean) */ public Builder dismissOnInsideTouch(boolean dismissOnInsideTouch) { this.dismissOnInsideTouch = dismissOnInsideTouch; return this; } /** * <div class="pt">Define se o tooltip será fechado quando receber um clique fora de sua área. Padrão é <tt>true</tt>.</div> * * @param dismissOnOutsideTouch <div class="pt"><tt>true</tt> para fechar quando receber o click fora, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnInsideTouch(boolean) */ public Builder dismissOnOutsideTouch(boolean dismissOnOutsideTouch) { this.dismissOnOutsideTouch = dismissOnOutsideTouch; return this; } /** * <div class="pt">Define se a tela fiacrá bloqueada enquanto o tooltip estiver aberto. * Esse parâmetro deve ser combinado com <tt>Builder#dismissOnInsideTouch(boolean)</tt> e <tt>Builder#dismissOnOutsideTouch(boolean)</tt>. * Padrão é <tt>false</tt>.</div> * * @param modal <div class="pt"><tt>true</tt> para bloquear a tela, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnInsideTouch(boolean) * @see Builder#dismissOnOutsideTouch(boolean) */ public Builder modal(boolean modal) { this.modal = modal; return this; } /** * <div class="pt">Define o texto que sera exibido no <tt>TextView</tt> dentro do tooltip.</div> * * @param text <div class="pt">texto que sera exibido.</div> * @return this */ public Builder text(CharSequence text) { this.text = text; return this; } /** * <div class="pt">Define para qual <tt>View</tt> o tooltip deve apontar. Importante ter certeza que esta <tt>View</tt> já esteja pronta e exibida na tela.</div> * * @param anchorView <div class="pt"><tt>View</tt> para qual o tooltip deve apontar</div> * @return this */ public Builder anchorView(View anchorView) { this.anchorView = anchorView; return this; } /** * <div class="pt">Define a para qual lado o tooltip será posicionado em relação ao <tt>anchorView</tt>. * As opções existentes são <tt>Gravity.START</tt>, <tt>Gravity.END</tt>, <tt>Gravity.TOP</tt> e <tt>Gravity.BOTTOM</tt>. * O padrão é <tt>Gravity.BOTTOM</tt>.</div> * * @param gravity <div class="pt">lado para qual o tooltip será posicionado.</div> * @return this */ public Builder gravity(int gravity) { this.gravity = gravity; return this; } /** * <div class="pt">Define se o fundo da tela será escurecido ou transparente enquanto o tooltip estiver aberto. Padrão é <tt>true</tt>.</div> * * @param transparentOverlay <div class="pt"><tt>true</tt> para o fundo transparente, <tt>false</tt> para escurecido.</div> * @return this */ public Builder transparentOverlay(boolean transparentOverlay) { this.transparentOverlay = transparentOverlay; return this; } /** * <div class="pt">Define a largura máxima do Tooltip.</div> * * @param maxWidthRes <div class="pt">resId da largura máxima.</div> * @return <tt>this</tt> * @see Builder#maxWidth(float) */ public Builder maxWidth(@DimenRes int maxWidthRes) { this.maxWidth = context.getResources().getDimension(maxWidthRes); return this; } /** * <div class="pt">Define a largura máxima do Tooltip. Padrão é <tt>0</tt> (sem limite).</div> * * @param maxWidth <div class="pt">largura máxima em pixels.</div> * @return <tt>this</tt> * @see Builder#maxWidth(int) */ public Builder maxWidth(float maxWidth) { this.maxWidth = maxWidth; return this; } /** * <div class="pt">Define se o tooltip será animado enquanto estiver aberto. Disponível a partir do Android API 11. Padrão é <tt>false</tt>.</div> * * @param animated <div class="pt"><tt>true</tt> para tooltip animado, <tt>false</tt> caso contrário.</div> * @return this */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animated(boolean animated) { this.animated = animated; return this; } /** * <div class="pt">Define o tamanho do deslocamento durante a animação. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_animation_padding)</tt>.</div> * * @param animationPadding <div class="pt">tamanho do deslocamento em pixels.</div> * @return <tt>this</tt> * @see Builder#animationPadding(int) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationPadding(float animationPadding) { this.animationPadding = animationPadding; return this; } /** * <div class="pt">Define o tamanho do deslocamento durante a animação. Padrão é <tt>R.dimen.simpletooltip_animation_padding</tt>.</div> * * @param animationPaddingRes <div class="pt">resId do tamanho do deslocamento.</div> * @return <tt>this</tt> * @see Builder#animationPadding(float) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationPadding(@DimenRes int animationPaddingRes) { this.animationPadding = context.getResources().getDimension(animationPaddingRes); return this; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationDuration(long animationDuration) { this.animationDuration = animationDuration; return this; } /** * <div class="pt">Define o padding entre a borda do Tooltip e seu conteúdo. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_padding)</tt>.</div> * * @param padding <div class="pt">tamanho do padding em pixels.</div> * @return <tt>this</tt> * @see Builder#padding(int) */ public Builder padding(float padding) { this.padding = padding; return this; } /** * <div class="pt">Define o padding entre a borda do Tooltip e seu conteúdo. Padrão é <tt>R.dimen.simpletooltip_padding</tt>.</div> * * @param paddingRes <div class="pt">resId do tamanho do padding.</div> * @return <tt>this</tt> * @see Builder#padding(float) */ public Builder padding(@DimenRes int paddingRes) { this.padding = context.getResources().getDimension(paddingRes); return this; } /** * <div class="pt">Define a margem entre o Tooltip e o <tt>anchorView</tt>. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_margin)</tt>.</div> * * @param margin <div class="pt">tamanho da margem em pixels.</div> * @return <tt>this</tt> * @see Builder#margin(int) */ public Builder margin(float margin) { this.margin = margin; return this; } /** * <div class="pt">Define a margem entre o Tooltip e o <tt>anchorView</tt>. Padrão é <tt>R.dimen.simpletooltip_margin</tt>.</div> * * @param marginRes <div class="pt">resId do tamanho da margem.</div> * @return <tt>this</tt> * @see Builder#margin(float) */ public Builder margin(@DimenRes int marginRes) { this.margin = context.getResources().getDimension(marginRes); return this; } public Builder textColor(int textColor) { this.textColor = textColor; return this; } public Builder backgroundColor(@ColorInt int backgroundColor) { this.backgroundColor = backgroundColor; return this; } /** * <div class="pt">Indica se deve ser gerada a seta indicativa. Padrão é <tt>true</tt>.</div> * <div class="en">Indicates whether to be generated indicative arrow. Default is <tt>true</tt>.</div> * * @param showArrow <div class="pt"><tt>true</tt> para exibir a seta, <tt>false</tt> caso contrário.</div> * <div class="en"><tt>true</tt> to show arrow, <tt>false</tt> otherwise.</div> * @return this */ public Builder showArrow(boolean showArrow) { this.showArrow = showArrow; return this; } public Builder arrowDrawable(Drawable arrowDrawable) { this.arrowDrawable = arrowDrawable; return this; } public Builder arrowDrawable(@DrawableRes int drawableRes) { this.arrowDrawable = SimpleTooltipUtils.getDrawable(context, drawableRes); return this; } public Builder arrowColor(@ColorInt int arrowColor) { this.arrowColor = arrowColor; return this; } /** * <div class="pt">Altura da seta indicativa. Esse valor é automaticamente definido em Largura ou Altura conforme a <tt>Gravity</tt> configurada. * Este valor sobrescreve <tt>R.dimen.simpletooltip_arrow_height</tt></div> * <div class="en">Height of the arrow. This value is automatically set in the Width or Height as the <tt>Gravity</tt>.</div> * * @param arrowHeight <div class="pt">Altura em pixels.</div> * <div class="en">Height in pixels.</div> * @return this * @see Builder#arrowWidth(float) */ public Builder arrowHeight(float arrowHeight) { this.arrowHeight = arrowHeight; return this; } /** * <div class="pt">Largura da seta indicativa. Esse valor é automaticamente definido em Largura ou Altura conforme a <tt>Gravity</tt> configurada. * Este valor sobrescreve <tt>R.dimen.simpletooltip_arrow_width</tt></div> * <div class="en">Width of the arrow. This value is automatically set in the Width or Height as the <tt>Gravity</tt>.</div> * * @param arrowWidth <div class="pt">Largura em pixels.</div> * <div class="en">Width in pixels.</div> * @return this */ public Builder arrowWidth(float arrowWidth) { this.arrowWidth = arrowWidth; return this; } public Builder onDismissListener(OnDismissListener onDismissListener) { this.onDismissListener = onDismissListener; return this; } public Builder onShowListener(OnShowListener onShowListener) { this.onShowListener = onShowListener; return this; } } }
library/src/main/java/io/github/douglasjunior/androidSimpleTooltip/SimpleTooltip.java
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Douglas Nassif Roma Junior * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.douglasjunior.androidSimpleTooltip; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; /** * <p class='pt'>Um tooltip que pode ser utilizado para exibição de dicas.</p> * <p class='en'>A tooltip that can be used to display tips on the screen.</p> * * @author Created by douglas on 05/05/16. * @see android.widget.PopupWindow */ @SuppressWarnings("SameParameterValue") public class SimpleTooltip implements PopupWindow.OnDismissListener { // Default Resources private static final int mDefaultPopupWindowStyleRes = android.R.attr.popupWindowStyle; private static final int mDefaultTextAppearanceRes = R.style.simpletooltip_default; private static final int mDefaultBackgroundColorRes = R.color.simpletooltip_background; private static final int mDefaultTextColorRes = R.color.simpletooltip_text; private static final int mDefaultArrowColorRes = R.color.simpletooltip_arrow; private static final int mDefaultMarginRes = R.dimen.simpletooltip_margin; private static final int mDefaultPaddingRes = R.dimen.simpletooltip_padding; private static final int mDefaultAnimationPaddingRes = R.dimen.simpletooltip_animation_padding; private static final int mDefaultAnimationDurationRes = R.integer.simpletooltip_animation_duration; private static final int mDefaultArrowWidthRes = R.dimen.simpletooltip_arrow_width; private static final int mDefaultArrowHeightRes = R.dimen.simpletooltip_arrow_height; private final Context mContext; private OnDismissListener mOnDismissListener; private OnShowListener mOnShowListener; private PopupWindow mPopupWindow; private final int mGravity; private final boolean mDismissOnInsideTouch; private final boolean mDismissOnOutsideTouch; private final boolean mModal; private final View mContentView; private View mContentLayout; @IdRes private final int mTextViewId; private final CharSequence mText; private final View mAnchorView; private final boolean mTransparentOverlay; private final float mMaxWidth; private View mOverlay; private ViewGroup mRootView; private final boolean mShowArrow; private ImageView mArrowView; private final Drawable mArrowDrawable; private final boolean mAnimated; private AnimatorSet mAnimator; private final float mMargin; private final float mPadding; private final float mAnimationPadding; private final long mAnimationDuration; private final float mArrowWidth; private final float mArrowHeight; private boolean dismissed = false; private SimpleTooltip(Builder builder) { mContext = builder.context; mGravity = builder.gravity; mDismissOnInsideTouch = builder.dismissOnInsideTouch; mDismissOnOutsideTouch = builder.dismissOnOutsideTouch; mModal = builder.modal; mContentView = builder.contentView; mTextViewId = builder.textViewId; mText = builder.text; mAnchorView = builder.anchorView; mTransparentOverlay = builder.transparentOverlay; mMaxWidth = builder.maxWidth; mShowArrow = builder.showArrow; mArrowWidth = builder.arrowWidth; mArrowHeight = builder.arrowHeight; mArrowDrawable = builder.arrowDrawable; mAnimated = builder.animated; mMargin = builder.margin; mPadding = builder.padding; mAnimationPadding = builder.animationPadding; mAnimationDuration = builder.animationDuration; mOnDismissListener = builder.onDismissListener; mOnShowListener = builder.onShowListener; mRootView = (ViewGroup) mAnchorView.getRootView(); init(); } private void init() { configPopupWindow(); configContentView(); } private void configPopupWindow() { mPopupWindow = new PopupWindow(mContext, null, mDefaultPopupWindowStyleRes); mPopupWindow.setOnDismissListener(this); mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); mPopupWindow.setClippingEnabled(false); } public void show() { verifyDismissed(); mContentLayout.getViewTreeObserver().addOnGlobalLayoutListener(mLocationLayoutListener); mContentLayout.getViewTreeObserver().addOnGlobalLayoutListener(mAutoDismissLayoutListener); mRootView.post(new Runnable() { @Override public void run() { mPopupWindow.showAtLocation(mRootView, Gravity.NO_GRAVITY, mRootView.getWidth(), mRootView.getHeight()); } }); } private void verifyDismissed() { if (dismissed) { throw new IllegalArgumentException("Tooltip has ben dismissed."); } } private void createOverlay() { mOverlay = mTransparentOverlay ? new View(mContext) : new OverlayView(mContext, mAnchorView); mOverlay.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mOverlay.setOnTouchListener(mOverlayTouchListener); mRootView.addView(mOverlay); } private PointF calculePopupLocation() { PointF location = new PointF(); final RectF anchorRect = SimpleTooltipUtils.calculeRectInWindow(mAnchorView); final PointF anchorCenter = new PointF(anchorRect.centerX(), anchorRect.centerY()); switch (mGravity) { case Gravity.START: location.x = anchorRect.left - mPopupWindow.getContentView().getWidth() - mMargin; location.y = anchorCenter.y - mPopupWindow.getContentView().getHeight() / 2f; break; case Gravity.END: location.x = anchorRect.right + mMargin; location.y = anchorCenter.y - mPopupWindow.getContentView().getHeight() / 2f; break; case Gravity.TOP: location.x = anchorCenter.x - mPopupWindow.getContentView().getWidth() / 2f; location.y = anchorRect.top - mPopupWindow.getContentView().getHeight() - mMargin; break; case Gravity.BOTTOM: location.x = anchorCenter.x - mPopupWindow.getContentView().getWidth() / 2f; location.y = anchorRect.bottom + mMargin; break; default: throw new IllegalArgumentException("Gravity must have be START, END, TOP or BOTTOM."); } return location; } private void configContentView() { if (mContentView instanceof TextView) { TextView tv = (TextView) mContentView; tv.setText(mText); } else { TextView tv = (TextView) mContentView.findViewById(mTextViewId); if (tv != null) tv.setText(mText); } mContentView.setPadding((int) mPadding, (int) mPadding, (int) mPadding, (int) mPadding); LinearLayout linearLayout = new LinearLayout(mContext); linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(mGravity == Gravity.START || mGravity == Gravity.END ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); int layoutPadding = (int) (mAnimated ? mAnimationPadding : 0); linearLayout.setPadding(layoutPadding, layoutPadding, layoutPadding, layoutPadding); if (mShowArrow) { mArrowView = new ImageView(mContext); mArrowView.setImageDrawable(mArrowDrawable); LinearLayout.LayoutParams arrowLayoutParams; if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) { arrowLayoutParams = new LinearLayout.LayoutParams((int) mArrowWidth, (int) mArrowHeight, 0); } else { arrowLayoutParams = new LinearLayout.LayoutParams((int) mArrowHeight, (int) mArrowWidth, 0); } arrowLayoutParams.gravity = Gravity.CENTER; mArrowView.setLayoutParams(arrowLayoutParams); if (mGravity == Gravity.TOP || mGravity == Gravity.START) { linearLayout.addView(mContentView); linearLayout.addView(mArrowView); } else { linearLayout.addView(mArrowView); linearLayout.addView(mContentView); } } else { linearLayout.addView(mContentView); } LinearLayout.LayoutParams contentViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); contentViewParams.gravity = Gravity.CENTER; mContentView.setLayoutParams(contentViewParams); if (mDismissOnInsideTouch || mDismissOnOutsideTouch) mContentView.setOnTouchListener(mPopupWindowTouchListener); mContentLayout = linearLayout; mContentLayout.setVisibility(View.INVISIBLE); mPopupWindow.setContentView(mContentLayout); } public void dismiss() { if (dismissed) return; dismissed = true; if (mPopupWindow != null) { mPopupWindow.dismiss(); } } /** * <div class="pt">Indica se o tooltip está sendo exibido na tela.</div> * <div class=en">Indicate whether this tooltip is showing on screen.</div> * * @return <div class="pt"><tt>true</tt> se o tooltip estiver sendo exibido, <tt>false</tt> caso contrário</div> * <div class="en"><tt>true</tt> if the popup is showing, <tt>false</tt> otherwise</div> */ public boolean isShowing() { return mPopupWindow != null && mPopupWindow.isShowing(); } public <T extends View> T findViewById(int id) { //noinspection unchecked return (T) mContentLayout.findViewById(id); } @Override public void onDismiss() { dismissed = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (mAnimator != null) { mAnimator.removeAllListeners(); mAnimator.end(); mAnimator.cancel(); mAnimator = null; } } if (mRootView != null && mOverlay != null) { mRootView.removeView(mOverlay); } mRootView = null; mOverlay = null; if (mOnDismissListener != null) mOnDismissListener.onDismiss(this); mOnDismissListener = null; } private final View.OnTouchListener mPopupWindowTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) { if (mDismissOnInsideTouch) { dismiss(); return mModal; } return false; } if (event.getAction() == MotionEvent.ACTION_UP) { v.performClick(); } return mModal; } }; private final View.OnTouchListener mOverlayTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mDismissOnOutsideTouch) { dismiss(); } if (event.getAction() == MotionEvent.ACTION_UP) { v.performClick(); } return mModal; } }; private final ViewTreeObserver.OnGlobalLayoutListener mLocationLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (dismissed) { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); return; } if (mMaxWidth > 0 && mContentView.getWidth() > mMaxWidth) { SimpleTooltipUtils.setWidth(mContentView, mMaxWidth); mPopupWindow.update(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); return; } SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mArrowLayoutListener); PointF location = calculePopupLocation(); mPopupWindow.setClippingEnabled(true); mPopupWindow.update((int) location.x, (int) location.y, mPopupWindow.getWidth(), mPopupWindow.getHeight()); mPopupWindow.getContentView().requestLayout(); createOverlay(); } }; private final ViewTreeObserver.OnGlobalLayoutListener mArrowLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mAnimationLayoutListener); mPopupWindow.getContentView().getViewTreeObserver().addOnGlobalLayoutListener(mShowLayoutListener); if (mShowArrow) { RectF achorRect = SimpleTooltipUtils.calculeRectOnScreen(mAnchorView); RectF contentViewRect = SimpleTooltipUtils.calculeRectOnScreen(mContentLayout); float x, y; if (mGravity == Gravity.BOTTOM || mGravity == Gravity.TOP) { x = mContentLayout.getPaddingLeft() + SimpleTooltipUtils.pxFromDp(2); float centerX = (contentViewRect.width() / 2f) - (mArrowView.getWidth() / 2f); float newX = centerX - (contentViewRect.centerX() - achorRect.centerX()); if (newX > x) { if (newX + mArrowView.getWidth() + x > contentViewRect.width()) { x = contentViewRect.width() - mArrowView.getWidth() - x; } else { x = newX; } } y = mArrowView.getTop(); y = y + (mGravity == Gravity.TOP ? -1 : +1); } else { y = mContentLayout.getPaddingTop() + SimpleTooltipUtils.pxFromDp(2); float centerY = (contentViewRect.height() / 2f) - (mArrowView.getHeight() / 2f); float newY = centerY - (contentViewRect.centerY() - achorRect.centerY()); if (newY > y) { if (newY + mArrowView.getHeight() + y > contentViewRect.height()) { y = contentViewRect.height() - mArrowView.getHeight() - y; } else { y = newY; } } x = mArrowView.getLeft(); x = x + (mGravity == Gravity.START ? -1 : +1); } SimpleTooltipUtils.setX(mArrowView, (int) x); SimpleTooltipUtils.setY(mArrowView, (int) y); } mPopupWindow.getContentView().requestLayout(); } }; private final ViewTreeObserver.OnGlobalLayoutListener mShowLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; if (mOnShowListener != null) mOnShowListener.onShow(SimpleTooltip.this); mOnShowListener = null; mContentLayout.setVisibility(View.VISIBLE); } }; private final ViewTreeObserver.OnGlobalLayoutListener mAnimationLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); if (dismissed) return; if (mAnimated) { startAnimation(); } mPopupWindow.getContentView().requestLayout(); } }; @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void startAnimation() { final String property = mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM ? "translationY" : "translationX"; final ObjectAnimator anim1 = ObjectAnimator.ofFloat(mContentLayout, property, -mAnimationPadding, mAnimationPadding); anim1.setDuration(mAnimationDuration); anim1.setInterpolator(new AccelerateDecelerateInterpolator()); final ObjectAnimator anim2 = ObjectAnimator.ofFloat(mContentLayout, property, mAnimationPadding, -mAnimationPadding); anim2.setDuration(mAnimationDuration); anim2.setInterpolator(new AccelerateDecelerateInterpolator()); mAnimator = new AnimatorSet(); mAnimator.playSequentially(anim1, anim2); mAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (!dismissed && isShowing()) { animation.start(); } } }); mAnimator.start(); } /** * <div class="pt">Listener utilizado para chamar o <tt>SimpleTooltip#dismiss()</tt> quando a <tt>View</tt> root é encerrada sem que a tooltip seja fechada. * Pode ocorrer quando a tooltip é utilizada dentro de Dialogs.</div> */ private final ViewTreeObserver.OnGlobalLayoutListener mAutoDismissLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (dismissed) { SimpleTooltipUtils.removeOnGlobalLayoutListener(mPopupWindow.getContentView(), this); return; } if (!mRootView.isShown()) dismiss(); } }; public interface OnDismissListener { void onDismiss(SimpleTooltip tooltip); } public interface OnShowListener { void onShow(SimpleTooltip tooltip); } /** * <div class="pt">Classe responsável por facilitar a criação do objeto <tt>SimpleTooltip</tt>.</div> * <div class="en">Class responsible for making it easier to build the object <tt>SimpleTooltip</tt>.</div> * * @author Created by douglas on 05/05/16. */ @SuppressWarnings({"SameParameterValue", "unused"}) public static class Builder { private final Context context; private boolean dismissOnInsideTouch = true; private boolean dismissOnOutsideTouch = true; private boolean modal = false; private View contentView; @IdRes private int textViewId = android.R.id.text1; private CharSequence text = ""; private View anchorView; private int gravity = Gravity.BOTTOM; private boolean transparentOverlay = true; private float maxWidth; private boolean showArrow = true; private Drawable arrowDrawable; private boolean animated = false; private float margin = -1; private float padding = -1; private float animationPadding = -1; private OnDismissListener onDismissListener; private OnShowListener onShowListener; private long animationDuration; private int backgroundColor; private int textColor; private int arrowColor; private float arrowHeight; private float arrowWidth; public Builder(Context context) { this.context = context; } public SimpleTooltip build() throws IllegalArgumentException { validateArguments(); if (backgroundColor == 0) { backgroundColor = SimpleTooltipUtils.getColor(context, mDefaultBackgroundColorRes); } if (textColor == 0) { textColor = SimpleTooltipUtils.getColor(context, mDefaultTextColorRes); } if (contentView == null) { TextView tv = new TextView(context); SimpleTooltipUtils.setTextAppearance(tv, mDefaultTextAppearanceRes); tv.setBackgroundColor(backgroundColor); tv.setTextColor(textColor); contentView = tv; } if (arrowColor == 0) { arrowColor = SimpleTooltipUtils.getColor(context, mDefaultArrowColorRes); } if (arrowDrawable == null) { int arrowDirection = SimpleTooltipUtils.tooltipGravityToArrowDirection(gravity); arrowDrawable = new ArrowDrawable(arrowColor, arrowDirection); } if (margin < 0) { margin = context.getResources().getDimension(mDefaultMarginRes); } if (padding < 0) { padding = context.getResources().getDimension(mDefaultPaddingRes); } if (animationPadding < 0) { animationPadding = context.getResources().getDimension(mDefaultAnimationPaddingRes); } if (animationDuration == 0) { animationDuration = context.getResources().getInteger(mDefaultAnimationDurationRes); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { animated = false; } if (showArrow) { if (arrowWidth == 0) arrowWidth = context.getResources().getDimension(mDefaultArrowWidthRes); if (arrowHeight == 0) arrowHeight = context.getResources().getDimension(mDefaultArrowHeightRes); } return new SimpleTooltip(this); } private void validateArguments() throws IllegalArgumentException { if (context == null) { throw new IllegalArgumentException("Context not specified."); } if (anchorView == null) { throw new IllegalArgumentException("Anchor view not specified."); } } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param textView <div class="pt">novo conteúdo para o tooltip.</div> * @return this * @see Builder#contentView(int, int) * @see Builder#contentView(View, int) * @see Builder#contentView(int) */ public Builder contentView(TextView textView) { this.contentView = textView; this.textViewId = 0; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentView <div class="pt">novo conteúdo para o tooltip, pode ser um <tt>ViewGroup</tt> ou qualquer componente customizado.</div> * @param textViewId <div class="pt">resId para o <tt>TextView</tt> existente dentro do <tt>contentView</tt>. Padrão é <tt>android.R.id.text1</tt>.</div> * @return this * @see Builder#contentView(int, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int) */ public Builder contentView(View contentView, @IdRes int textViewId) { this.contentView = contentView; this.textViewId = textViewId; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentViewId <div class="pt">layoutId que será inflado como o novo conteúdo para o tooltip.</div> * @param textViewId <div class="pt">resId para o <tt>TextView</tt> existente dentro do <tt>contentView</tt>. Padrão é <tt>android.R.id.text1</tt>.</div> * @return this * @see Builder#contentView(View, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int) */ public Builder contentView(@LayoutRes int contentViewId, @IdRes int textViewId) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.contentView = inflater.inflate(contentViewId, null, false); this.textViewId = textViewId; return this; } /** * <div class="pt">Define um novo conteúdo customizado para o tooltip.</div> * * @param contentViewId <div class="pt">layoutId que será inflado como o novo conteúdo para o tooltip.</div> * @return this * @see Builder#contentView(View, int) * @see Builder#contentView(TextView) * @see Builder#contentView(int, int) */ public Builder contentView(@LayoutRes int contentViewId) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.contentView = inflater.inflate(contentViewId, null, false); this.textViewId = 0; return this; } /** * <div class="pt">Define se o tooltip será fechado quando receber um clique dentro de sua área. Padrão é <tt>true</tt>.</div> * * @param dismissOnInsideTouch <div class="pt"><tt>true</tt> para fechar quando receber o click dentro, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnOutsideTouch(boolean) */ public Builder dismissOnInsideTouch(boolean dismissOnInsideTouch) { this.dismissOnInsideTouch = dismissOnInsideTouch; return this; } /** * <div class="pt">Define se o tooltip será fechado quando receber um clique fora de sua área. Padrão é <tt>true</tt>.</div> * * @param dismissOnOutsideTouch <div class="pt"><tt>true</tt> para fechar quando receber o click fora, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnInsideTouch(boolean) */ public Builder dismissOnOutsideTouch(boolean dismissOnOutsideTouch) { this.dismissOnOutsideTouch = dismissOnOutsideTouch; return this; } /** * <div class="pt">Define se a tela fiacrá bloqueada enquanto o tooltip estiver aberto. * Esse parâmetro deve ser combinado com <tt>Builder#dismissOnInsideTouch(boolean)</tt> e <tt>Builder#dismissOnOutsideTouch(boolean)</tt>. * Padrão é <tt>false</tt>.</div> * * @param modal <div class="pt"><tt>true</tt> para bloquear a tela, <tt>false</tt> caso contrário.</div> * @return this * @see Builder#dismissOnInsideTouch(boolean) * @see Builder#dismissOnOutsideTouch(boolean) */ public Builder modal(boolean modal) { this.modal = modal; return this; } /** * <div class="pt">Define o texto que sera exibido no <tt>TextView</tt> dentro do tooltip.</div> * * @param text <div class="pt">texto que sera exibido.</div> * @return this */ public Builder text(CharSequence text) { this.text = text; return this; } /** * <div class="pt">Define para qual <tt>View</tt> o tooltip deve apontar. Importante ter certeza que esta <tt>View</tt> já esteja pronta e exibida na tela.</div> * * @param anchorView <div class="pt"><tt>View</tt> para qual o tooltip deve apontar</div> * @return this */ public Builder anchorView(View anchorView) { this.anchorView = anchorView; return this; } /** * <div class="pt">Define a para qual lado o tooltip será posicionado em relação ao <tt>anchorView</tt>. * As opções existentes são <tt>Gravity.START</tt>, <tt>Gravity.END</tt>, <tt>Gravity.TOP</tt> e <tt>Gravity.BOTTOM</tt>. * O padrão é <tt>Gravity.BOTTOM</tt>.</div> * * @param gravity <div class="pt">lado para qual o tooltip será posicionado.</div> * @return this */ public Builder gravity(int gravity) { this.gravity = gravity; return this; } /** * <div class="pt">Define se o fundo da tela será escurecido ou transparente enquanto o tooltip estiver aberto. Padrão é <tt>true</tt>.</div> * * @param transparentOverlay <div class="pt"><tt>true</tt> para o fundo transparente, <tt>false</tt> para escurecido.</div> * @return this */ public Builder transparentOverlay(boolean transparentOverlay) { this.transparentOverlay = transparentOverlay; return this; } /** * <div class="pt">Define a largura máxima do Tooltip.</div> * * @param maxWidthRes <div class="pt">resId da largura máxima.</div> * @return <tt>this</tt> * @see Builder#maxWidth(float) */ public Builder maxWidth(@DimenRes int maxWidthRes) { this.maxWidth = context.getResources().getDimension(maxWidthRes); return this; } /** * <div class="pt">Define a largura máxima do Tooltip. Padrão é <tt>0</tt> (sem limite).</div> * * @param maxWidth <div class="pt">largura máxima em pixels.</div> * @return <tt>this</tt> * @see Builder#maxWidth(int) */ public Builder maxWidth(float maxWidth) { this.maxWidth = maxWidth; return this; } /** * <div class="pt">Define se o tooltip será animado enquanto estiver aberto. Disponível a partir do Android API 11. Padrão é <tt>false</tt>.</div> * * @param animated <div class="pt"><tt>true</tt> para tooltip animado, <tt>false</tt> caso contrário.</div> * @return this */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animated(boolean animated) { this.animated = animated; return this; } /** * <div class="pt">Define o tamanho do deslocamento durante a animação. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_animation_padding)</tt>.</div> * * @param animationPadding <div class="pt">tamanho do deslocamento em pixels.</div> * @return <tt>this</tt> * @see Builder#animationPadding(int) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationPadding(float animationPadding) { this.animationPadding = animationPadding; return this; } /** * <div class="pt">Define o tamanho do deslocamento durante a animação. Padrão é <tt>R.dimen.simpletooltip_animation_padding</tt>.</div> * * @param animationPaddingRes <div class="pt">resId do tamanho do deslocamento.</div> * @return <tt>this</tt> * @see Builder#animationPadding(float) */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationPadding(@DimenRes int animationPaddingRes) { this.animationPadding = context.getResources().getDimension(animationPaddingRes); return this; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Builder animationDuration(long animationDuration) { this.animationDuration = animationDuration; return this; } /** * <div class="pt">Define o padding entre a borda do Tooltip e seu conteúdo. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_padding)</tt>.</div> * * @param padding <div class="pt">tamanho do padding em pixels.</div> * @return <tt>this</tt> * @see Builder#padding(int) */ public Builder padding(float padding) { this.padding = padding; return this; } /** * <div class="pt">Define o padding entre a borda do Tooltip e seu conteúdo. Padrão é <tt>R.dimen.simpletooltip_padding</tt>.</div> * * @param paddingRes <div class="pt">resId do tamanho do padding.</div> * @return <tt>this</tt> * @see Builder#padding(float) */ public Builder padding(@DimenRes int paddingRes) { this.padding = context.getResources().getDimension(paddingRes); return this; } /** * <div class="pt">Define a margem entre o Tooltip e o <tt>anchorView</tt>. Padrão é <tt>resources.getDimension(R.dimen.simpletooltip_margin)</tt>.</div> * * @param margin <div class="pt">tamanho da margem em pixels.</div> * @return <tt>this</tt> * @see Builder#margin(int) */ public Builder margin(float margin) { this.margin = margin; return this; } /** * <div class="pt">Define a margem entre o Tooltip e o <tt>anchorView</tt>. Padrão é <tt>R.dimen.simpletooltip_margin</tt>.</div> * * @param marginRes <div class="pt">resId do tamanho da margem.</div> * @return <tt>this</tt> * @see Builder#margin(float) */ public Builder margin(@DimenRes int marginRes) { this.margin = context.getResources().getDimension(marginRes); return this; } public Builder textColor(int textColor) { this.textColor = textColor; return this; } public Builder backgroundColor(@ColorInt int backgroundColor) { this.backgroundColor = backgroundColor; return this; } /** * <div class="pt">Indica se deve ser gerada a seta indicativa. Padrão é <tt>true</tt>.</div> * <div class="en">Indicates whether to be generated indicative arrow. Default is <tt>true</tt>.</div> * * @param showArrow <div class="pt"><tt>true</tt> para exibir a seta, <tt>false</tt> caso contrário.</div> * <div class="en"><tt>true</tt> to show arrow, <tt>false</tt> otherwise.</div> * @return this */ public Builder showArrow(boolean showArrow) { this.showArrow = showArrow; return this; } public Builder arrowDrawable(Drawable arrowDrawable) { this.arrowDrawable = arrowDrawable; return this; } public Builder arrowDrawable(@DrawableRes int drawableRes) { this.arrowDrawable = SimpleTooltipUtils.getDrawable(context, drawableRes); return this; } public Builder arrowColor(@ColorInt int arrowColor) { this.arrowColor = arrowColor; return this; } /** * <div class="pt">Altura da seta indicativa. Esse valor é automaticamente definido em Largura ou Altura conforme a <tt>Gravity</tt> configurada. * Este valor sobrescreve <tt>R.dimen.simpletooltip_arrow_height</tt></div> * <div class="en">Height of the arrow. This value is automatically set in the Width or Height as the <tt>Gravity</tt>.</div> * * @param arrowHeight <div class="pt">Altura em pixels.</div> * <div class="en">Height in pixels.</div> * @return this * @see Builder#arrowWidth(float) */ public Builder arrowHeight(float arrowHeight) { this.arrowHeight = arrowHeight; return this; } /** * <div class="pt">Largura da seta indicativa. Esse valor é automaticamente definido em Largura ou Altura conforme a <tt>Gravity</tt> configurada. * Este valor sobrescreve <tt>R.dimen.simpletooltip_arrow_width</tt></div> * <div class="en">Width of the arrow. This value is automatically set in the Width or Height as the <tt>Gravity</tt>.</div> * * @param arrowWidth <div class="pt">Largura em pixels.</div> * <div class="en">Width in pixels.</div> * @return this */ public Builder arrowWidth(float arrowWidth) { this.arrowWidth = arrowWidth; return this; } public Builder onDismissListener(OnDismissListener onDismissListener) { this.onDismissListener = onDismissListener; return this; } public Builder onShowListener(OnShowListener onShowListener) { this.onShowListener = onShowListener; return this; } } }
Removed all ViewTreeObserver.OnGlobalLayoutListener on dismiss to prevent NullPointerException #11
library/src/main/java/io/github/douglasjunior/androidSimpleTooltip/SimpleTooltip.java
Removed all ViewTreeObserver.OnGlobalLayoutListener on dismiss to prevent NullPointerException #11
Java
mit
48db601a1d998da12f9ad189d17368a85f211b25
0
kkrull/javaspec,kkrull/javaspec,kkrull/javaspec
package info.javaspec.runner.ng; import de.bechte.junit.runners.context.HierarchicalContextRunner; import info.javaspec.dsl.It; import info.javaspecproto.ContextClasses; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static info.javaspec.testutil.Matchers.matchesRegex; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; @RunWith(HierarchicalContextRunner.class) public class ClassSpecGatewayTest { private SpecGateway<ClassContext> subject; private ClassSpecGateway.LambdaSpecFactory specFactory = mock(ClassSpecGateway.LambdaSpecFactory.class); @Before public void setup() throws Exception { givenSpecFactoryMakes(mock(Spec.class, "DefaultSpec")); } public class countSpecs { @Test public void givenAContextClassWithNoSpecs_returns_0() throws Exception { shouldNotHaveSpecs(ContextClasses.Empty.class); } @Test public void givenAContextClassWith1OrMoreSpecs_returnsTheNumberOfSpecs() throws Exception { shouldHaveSpecs(ContextClasses.OneIt.class, 1); } } public class hasSpecs { @Test public void givenAContextClassWithNoSpecs_returnsFalse() throws Exception { shouldNotHaveSpecs(ContextClasses.Empty.class); } @Test public void givenAContextClassWith1OrMoreSpecs_returnsTrue() throws Exception { shouldHaveSpecs(ContextClasses.OneIt.class, 1); } } public class givenARootContextClass { @Test public void withNoFieldsOfTypeIt_hasNoSpecs() throws Exception { shouldNotHaveSpecs(ContextClasses.Empty.class); shouldNotReturnAnySpecs(ContextClasses.Empty.class); } @Test public void with1OrMoreOfInstanceFieldsOfTypeIt_hasASpecForEachOfThoseFields() throws Exception { shouldHaveSpecs(ContextClasses.OneIt.class, 1); } @Test public void withStaticFieldsOfTypeIt_doesNotCountThoseFieldsAsSpecs() throws Exception { shouldNotHaveSpecs(ContextClasses.StaticIt.class); shouldNotReturnAnySpecs(ContextClasses.StaticIt.class); } @Test public void withNestedClasses_countsSpecsInThoseClasses() throws Exception { shouldHaveSpecs(ContextClasses.NestedIt.class, 1); shouldHaveSpecs(ContextClasses.NestedThreeDeep.class, 1); } @Test public void withAStaticInnerClass_doesNotCountItFieldsInThoseClassesAsSpecs() throws Exception { shouldNotHaveSpecs(ContextClasses.NestedStaticClassIt.class); shouldNotReturnAnySpecs(ContextClasses.NestedStaticClassIt.class); } } public class rootContextId { @Test public void givenAClass_returnsTheFullClassName() throws Exception { subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); assertThat(subject.rootContextId(), matchesRegex("^.*[.]ContextClasses[$]OneIt$")); } } public class rootContext { private Context returned; @Before public void setup() throws Exception { subject = new ClassSpecGateway(ContextClasses.NestedBehavior.describes_some_conditions.class, specFactory); returned = subject.rootContext(); } @Test public void returnsAContextForTheGivenClass() throws Exception { assertThat(returned.id, matchesRegex("^.*[.]ContextClasses[$]NestedBehavior[$]describes_some_conditions$")); } //The root context class is just a container. It doesn't describe behavior, so its name doesn't get humanized. @Test public void usesTheSimpleNameForTheDisplayName() { assertThat(returned.displayName, equalTo("describes_some_conditions")); } } public class getSubcontexts { @Test public void givenAClassWithNoInnerClasses_returnsEmpty() { subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); List<ClassContext> returned = subject.getSubcontexts(subject.rootContext()); assertThat(returned, hasSize(0)); } @Test public void givenAClassWith1OrMoreInnerClasses_returnsAContextForEachClass() { subject = new ClassSpecGateway(ContextClasses.NestedThreeDeep.class, specFactory); shouldHaveSubcontexts(subject.rootContext(), "info.javaspecproto.ContextClasses$NestedThreeDeep$middle"); shouldHaveSubcontexts(onlySubcontext(subject.rootContext()), "info.javaspecproto.ContextClasses$NestedThreeDeep$middle$bottom"); } @Test public void givenAClassWithStaticHelperClasses_ignoresItFieldsInThatClass() { subject = new ClassSpecGateway(ContextClasses.NestedStaticClassIt.class, specFactory); shouldHaveSubcontexts(subject.rootContext()); } public class givenAContextClass { private Context returned; @Before public void setup() { subject = new ClassSpecGateway(ContextClasses.NestedBehavior.class, specFactory); List<ClassContext> subcontexts = subject.getSubcontexts(subject.rootContext()); returned = subcontexts.get(0); } @Test public void givenAClassNameInSnakeCase_replacesUnderscoresWithSpaces() { assertThat(returned.displayName, equalTo("describes some conditions")); } } private void shouldHaveSubcontexts(ClassContext context, String... ids) { List<String> actualIds = subject.getSubcontexts(context).stream().map(x -> x.id).collect(toList()); assertThat(actualIds, equalTo(Arrays.asList(ids))); } } public class getSpecs { @Test public void givenAClassWithInstanceItFields_returnsASpecForEachField() { subject = new ClassSpecGateway(ContextClasses.TwoIt.class, specFactory); assertThat(subject.getSpecs(subject.rootContext()), hasSize(2)); } @Test public void givenAnInnerClassWithInstanceItFields_returnsASpecForThoseFields() { subject = new ClassSpecGateway(ContextClasses.NestedContext.class, specFactory); assertThat(subject.getSpecs(onlySubcontext(subject.rootContext())), hasSize(1)); } public class givenAnInstanceItField { private Spec toReturn = mock(Spec.class, "Factory Made"); private List<Spec> returned; @Before public void setup() throws Exception { when(specFactory.makeSpec(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(toReturn); subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); returned = subject.getSpecs(subject.rootContext()); } @Test public void identifiesTheSpecByTheFullyQualifiedPathToThatField() { verify(specFactory).makeSpec(Mockito.eq("info.javaspecproto.ContextClasses.OneIt.only_test"), Mockito.any(), Mockito.any()); } @Test public void humanizesSnakeCasedFieldNamesByReplacingUnderscoresWithSpaces() { verify(specFactory).makeSpec(Mockito.anyString(), Mockito.eq("only test"), Mockito.any()); } @Test @Ignore public void createsTheSpecFromTheItField() {} @Test public void returnsASpecForThatField() { verify(specFactory).makeSpec(Mockito.anyString(), Mockito.any(), Mockito.any(It.class)); assertThat(returned, contains(sameInstance(toReturn))); } } } private void givenSpecFactoryMakes(Spec spec) { when(specFactory.makeSpec(Mockito.anyString(), Mockito.anyString(), Mockito.any(It.class))) .thenReturn(spec); } private ClassContext onlySubcontext(ClassContext parent) { List<ClassContext> children = subject.getSubcontexts(parent); if(children.size() != 1) { String msg = String.format("Expected context %s to have 1 child, but had %d", parent.id, children.size()); throw new RuntimeException(msg); } return children.get(0); } private void shouldHaveSpecs(Class<?> rootContextClass, long totalSpecs) { SpecGateway subject = new ClassSpecGateway(rootContextClass, specFactory); assertThat(subject.hasSpecs(), is(true)); assertThat(subject.countSpecs(), equalTo(totalSpecs)); } private void shouldNotHaveSpecs(Class<?> rootContextClass) { SpecGateway subject = new ClassSpecGateway(rootContextClass, specFactory); assertThat(subject.hasSpecs(), is(false)); assertThat(subject.countSpecs(), equalTo(0L)); } private void shouldNotReturnAnySpecs(Class<?> context) { subject = new ClassSpecGateway(context, specFactory); assertThat(subject.getSpecs(subject.rootContext()), hasSize(0)); } private void shouldHaveMadeSpecs(String... ids) { Stream.of(ids).forEach(id -> verify(specFactory, times(1)) .makeSpec( Mockito.eq(id), Mockito.anyString(), Mockito.any() )); } }
src/test/java/info/javaspec/runner/ng/ClassSpecGatewayTest.java
package info.javaspec.runner.ng; import de.bechte.junit.runners.context.HierarchicalContextRunner; import info.javaspec.dsl.It; import info.javaspecproto.ContextClasses; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static com.google.common.collect.Lists.newArrayList; import static info.javaspec.testutil.Matchers.matchesRegex; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; @RunWith(HierarchicalContextRunner.class) public class ClassSpecGatewayTest { private SpecGateway<ClassContext> subject; private ClassSpecGateway.LambdaSpecFactory specFactory = mock(ClassSpecGateway.LambdaSpecFactory.class); @Before public void setup() throws Exception { givenSpecFactoryMakes(mock(Spec.class, "DefaultSpec")); } public class countSpecs { @Test public void givenAContextClassWithNoSpecs_returns_0() throws Exception { shouldHaveSpecCount(ContextClasses.Empty.class, 0); } @Test public void givenAContextClassWith1OrMoreSpecs_returnsTheNumberOfSpecs() throws Exception { shouldHaveSpecCount(ContextClasses.OneIt.class, 1); } } public class hasSpecs { @Test public void givenAContextClassWithNoSpecs_returnsFalse() throws Exception { shouldNotHaveSpecs(ContextClasses.Empty.class); } @Test public void givenAContextClassWith1OrMoreSpecs_returnsTrue() throws Exception { shouldHaveSpecs(ContextClasses.OneIt.class); } } public class givenARootContextClass { @Test public void withNoFieldsOfTypeIt_hasNoSpecs() throws Exception { shouldNotHaveSpecs(ContextClasses.Empty.class); shouldHaveSpecCount(ContextClasses.Empty.class, 0); } @Test public void with1OrMoreOfInstanceFieldsOfTypeIt_hasASpecForEachOfThoseFields() throws Exception { shouldHaveSpecs(ContextClasses.OneIt.class); shouldHaveSpecCount(ContextClasses.OneIt.class, 1); } @Test public void withStaticFieldsOfTypeIt_doesNotCountThoseFieldsAsSpecs() throws Exception { shouldNotHaveSpecs(ContextClasses.StaticIt.class); shouldHaveSpecCount(ContextClasses.StaticIt.class, 0); } @Test public void withNestedClasses_countsSpecsInThoseClasses() throws Exception { shouldHaveSpecCount(ContextClasses.NestedIt.class, 1); shouldHaveSpecs(ContextClasses.NestedContext.class); shouldHaveSpecCount(ContextClasses.NestedThreeDeep.class, 1); shouldHaveSpecs(ContextClasses.NestedThreeDeep.class); } @Test public void withAStaticInnerClass_doesNotCountItFieldsInThoseClassesAsSpecs() throws Exception { shouldHaveSpecCount(ContextClasses.NestedStaticClassIt.class, 0); shouldNotHaveSpecs(ContextClasses.NestedStaticClassIt.class); } } public class rootContextId { @Test public void givenAClass_returnsTheFullClassName() throws Exception { subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); assertThat(subject.rootContextId(), matchesRegex("^.*[.]ContextClasses[$]OneIt$")); } } public class rootContext { private Context returned; @Before public void setup() throws Exception { subject = new ClassSpecGateway(ContextClasses.NestedBehavior.describes_some_conditions.class, specFactory); returned = subject.rootContext(); } @Test public void returnsAContextForTheGivenClass() throws Exception { assertThat(returned.id, matchesRegex("^.*[.]ContextClasses[$]NestedBehavior[$]describes_some_conditions$")); } //The root context class is just a container. It doesn't describe behavior, so its name doesn't get humanized. @Test public void usesTheSimpleNameForTheDisplayName() { assertThat(returned.displayName, equalTo("describes_some_conditions")); } } public class getSubcontexts { @Test public void givenAClassWithNoInnerClasses_returnsEmpty() { subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); List<ClassContext> returned = subject.getSubcontexts(subject.rootContext()); assertThat(returned, hasSize(0)); } @Test public void givenAClassWith1OrMoreInnerClasses_returnsAContextForEachClass() { subject = new ClassSpecGateway(ContextClasses.NestedThreeDeep.class, specFactory); shouldHaveSubcontexts(subject.rootContext(), "info.javaspecproto.ContextClasses$NestedThreeDeep$middle"); shouldHaveSubcontexts(onlySubcontext(subject.rootContext()), "info.javaspecproto.ContextClasses$NestedThreeDeep$middle$bottom"); } @Test public void givenAClassWithStaticHelperClasses_ignoresItFieldsInThatClass() { subject = new ClassSpecGateway(ContextClasses.NestedStaticClassIt.class, specFactory); shouldHaveSubcontexts(subject.rootContext()); } public class givenAContextClass { private Context returned; @Before public void setup() { subject = new ClassSpecGateway(ContextClasses.NestedBehavior.class, specFactory); List<ClassContext> subcontexts = subject.getSubcontexts(subject.rootContext()); returned = subcontexts.get(0); } @Test public void givenAClassNameInSnakeCase_replacesUnderscoresWithSpaces() { assertThat(returned.displayName, equalTo("describes some conditions")); } } private void shouldHaveSubcontexts(ClassContext context, String... ids) { List<String> actualIds = subject.getSubcontexts(context).stream().map(x -> x.id).collect(toList()); assertThat(actualIds, equalTo(Arrays.asList(ids))); } } public class getSpecs { @Test public void givenASpec_returnsThatSpec() { Spec factoryMade = mock(Spec.class, "FactoryMade"); givenSpecFactoryMakes("info.javaspecproto.ContextClasses.OneIt.only_test", factoryMade); subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); assertThat(subject.getSpecs(subject.rootContext()), equalTo(newArrayList(factoryMade))); } @Test public void givenAClassWithNoInstanceItFields_returnsEmpty() throws Exception { subject = new ClassSpecGateway(ContextClasses.Empty.class, specFactory); assertThat(subject.getSpecs(subject.rootContext()), hasSize(0)); } @Test public void givenAClassWithInstanceItFields_returnsASpecForEachField() { subject = new ClassSpecGateway(ContextClasses.TwoIt.class, specFactory); subject.getSpecs(subject.rootContext()); shouldHaveMadeSpecs("info.javaspecproto.ContextClasses.TwoIt.first_test", "info.javaspecproto.ContextClasses.TwoIt.second_test"); subject = new ClassSpecGateway(ContextClasses.NestedContext.class, specFactory); subject.getSpecs(onlySubcontext(subject.rootContext())); shouldHaveMadeSpecs("info.javaspecproto.ContextClasses.NestedContext.inner.asserts"); } @Test public void givenAClassWithStaticItFields_ignoresThoseFields() { subject = new ClassSpecGateway(ContextClasses.StaticIt.class, specFactory); shouldHaveSpecs(subject.rootContext()); } //TODO KDK: Refactor these tests to work with verifying calls to specFactory public class givenAnInstanceItField { private Spec toReturn = mock(Spec.class); private Spec returned; @Before public void setup() throws Exception { when(specFactory.makeSpec(Mockito.anyString(), Mockito.anyString(), Mockito.any())) .thenReturn(toReturn); subject = new ClassSpecGateway(ContextClasses.OneIt.class, specFactory); returned = subject.getSpecs(subject.rootContext()).get(0); } @Test public void identifiesTheSpecByTheFullyQualifiedPathToThatField() { verify(specFactory).makeSpec(Mockito.eq("info.javaspecproto.ContextClasses.OneIt.only_test"), Mockito.any(), Mockito.any()); } @Test //TODO KDK: Move to givenASpec? public void humanizesSnakeCasedFieldNamesByReplacingUnderscoresWithSpaces() { verify(specFactory).makeSpec(Mockito.anyString(), Mockito.eq("only test"), Mockito.any()); } @Test @Ignore public void returnsASpecForThatField() { verify(specFactory).makeSpec(Mockito.anyString(), Mockito.any(), Mockito.any(It.class)); assertThat(returned, sameInstance(toReturn)); } } private void shouldHaveSpecs(ClassContext context, String... ids) { List<String> actualIds = subject.getSpecs(context).stream().map(x -> x.id).collect(toList()); assertThat(actualIds, equalTo(Arrays.asList(ids))); } } private void givenSpecFactoryMakes(String id, Spec spec) { when(specFactory.makeSpec(Mockito.eq(id), Mockito.anyString(), Mockito.any(It.class))) .thenReturn(spec); } private void givenSpecFactoryMakes(Spec spec) { when(specFactory.makeSpec(Mockito.anyString(), Mockito.anyString(), Mockito.any(It.class))) .thenReturn(spec); } private ClassContext onlySubcontext(ClassContext parent) { List<ClassContext> children = subject.getSubcontexts(parent); if(children.size() != 1) { String msg = String.format("Expected context %s to have 1 child, but had %d", parent.id, children.size()); throw new RuntimeException(msg); } return children.get(0); } private void shouldHaveSpecs(Class<?> rootContextClass) { SpecGateway subject = new ClassSpecGateway(rootContextClass, specFactory); assertThat(subject.hasSpecs(), is(true)); } private void shouldNotHaveSpecs(Class<?> rootContextClass) { SpecGateway subject = new ClassSpecGateway(rootContextClass, specFactory); assertThat(subject.hasSpecs(), is(false)); } private void shouldHaveSpecCount(Class<?> contextClass, long numSpecs) { SpecGateway subject = new ClassSpecGateway(contextClass, specFactory); assertThat(subject.countSpecs(), equalTo(numSpecs)); } private void shouldHaveMadeSpecs(String... ids) { Stream.of(ids).forEach(id -> verify(specFactory, times(1)) .makeSpec( Mockito.eq(id), Mockito.anyString(), Mockito.any() )); } }
Simplified tests on getSpecs
src/test/java/info/javaspec/runner/ng/ClassSpecGatewayTest.java
Simplified tests on getSpecs
Java
mit
1ba8a2d9704f7b5c06ddc1a88c8d6ba49c8bace1
0
lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:21:00 PST by lamport // modified on Fri Sep 22 13:18:45 PDT 2000 by yuanyu package tlc2.value; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import tlc2.output.EC; import tlc2.tool.EvalException; import util.Assert; import util.WrongInvocationException; public class MethodValue extends OpValue implements Applicable { public Method md; /* Constructor */ public MethodValue(Method md) { this.md = md; } public final byte getKind() { return METHODVALUE; } public final int compareTo(Object obj) { Assert.fail("Attempted to compare operator " + this.toString() + " with value:\n" + obj == null ? "null" : ppr(obj.toString())); return 0; // make compiler happy } public final boolean equals(Object obj) { Assert.fail("Attempted to check equality of operator " + this.toString() + " with value:\n" + obj == null ? "null" : ppr(obj.toString())); return false; // make compiler happy } public final boolean member(Value elem) { Assert.fail("Attempted to check if the value:\n" + elem == null ? "null" : ppr(elem.toString()) + "\nis an element of operator " + this.toString()); return false; // make compiler happy } public final boolean isFinite() { Assert.fail("Attempted to check if the operator " + this.toString() + " is a finite set."); return false; // make compiler happy } public final Value apply(Value arg, int control) { throw new WrongInvocationException("It is a TLC bug: Should use the other apply method."); } public final Value apply(Value[] args, int control) { Value res = null; try { res = (Value)this.md.invoke(null, (Object[]) args); } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable targetException = ((InvocationTargetException)e).getTargetException(); throw new EvalException(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), targetException.getMessage()}); } else { Assert.fail(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), e.getMessage()}); } } return res; } public final Value select(Value arg) { throw new WrongInvocationException("It is a TLC bug: Attempted to call MethodValue.select()."); } public final Value takeExcept(ValueExcept ex) { Assert.fail("Attempted to appy EXCEPT construct to the operator " + this.toString() + "."); return null; // make compiler happy } public final Value takeExcept(ValueExcept[] exs) { Assert.fail("Attempted to apply EXCEPT construct to the operator " + this.toString() + "."); return null; // make compiler happy } public final Value getDomain() { Assert.fail("Attempted to compute the domain of the operator " + this.toString() + "."); return EmptySet; // make compiler happy } public final int size() { Assert.fail("Attempted to compute the number of elements in the operator " + this.toString() + "."); return 0; // make compiler happy } /* Should never normalize an operator. */ public final boolean isNormalized() { throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator."); } public final void normalize() { throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator."); } public final boolean isDefined() { return true; } public final Value deepCopy() { return this; } public final boolean assignable(Value val) { throw new WrongInvocationException("It is a TLC bug: Attempted to initialize an operator."); } /* String representation of the value. */ public final StringBuffer toString(StringBuffer sb, int offset) { return sb.append("<Java Method: " + this.md + ">"); } }
tlatools/src/tlc2/value/MethodValue.java
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:21:00 PST by lamport // modified on Fri Sep 22 13:18:45 PDT 2000 by yuanyu package tlc2.value; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import tlc2.output.EC; import tlc2.tool.EvalException; import util.Assert; import util.WrongInvocationException; public class MethodValue extends OpValue implements Applicable { public Method md; /* Constructor */ public MethodValue(Method md) { this.md = md; } public final byte getKind() { return METHODVALUE; } public final int compareTo(Object obj) { Assert.fail("Attempted to compare operator " + this.toString() + " with value:\n" + ppr(obj.toString())); return 0; // make compiler happy } public final boolean equals(Object obj) { Assert.fail("Attempted to check equality of operator " + this.toString() + " with value:\n" + ppr(obj.toString())); return false; // make compiler happy } public final boolean member(Value elem) { Assert.fail("Attempted to check if the value:\n" + ppr(elem.toString()) + "\nis an element of operator " + this.toString()); return false; // make compiler happy } public final boolean isFinite() { Assert.fail("Attempted to check if the operator " + this.toString() + " is a finite set."); return false; // make compiler happy } public final Value apply(Value arg, int control) { throw new WrongInvocationException("It is a TLC bug: Should use the other apply method."); } public final Value apply(Value[] args, int control) { Value res = null; try { res = (Value)this.md.invoke(null, (Object[]) args); } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable targetException = ((InvocationTargetException)e).getTargetException(); throw new EvalException(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), targetException.getMessage()}); } else { Assert.fail(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[]{this.md.toString(), e.getMessage()}); } } return res; } public final Value select(Value arg) { throw new WrongInvocationException("It is a TLC bug: Attempted to call MethodValue.select()."); } public final Value takeExcept(ValueExcept ex) { Assert.fail("Attempted to appy EXCEPT construct to the operator " + this.toString() + "."); return null; // make compiler happy } public final Value takeExcept(ValueExcept[] exs) { Assert.fail("Attempted to apply EXCEPT construct to the operator " + this.toString() + "."); return null; // make compiler happy } public final Value getDomain() { Assert.fail("Attempted to compute the domain of the operator " + this.toString() + "."); return EmptySet; // make compiler happy } public final int size() { Assert.fail("Attempted to compute the number of elements in the operator " + this.toString() + "."); return 0; // make compiler happy } /* Should never normalize an operator. */ public final boolean isNormalized() { throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator."); } public final void normalize() { throw new WrongInvocationException("It is a TLC bug: Attempted to normalize an operator."); } public final boolean isDefined() { return true; } public final Value deepCopy() { return this; } public final boolean assignable(Value val) { throw new WrongInvocationException("It is a TLC bug: Attempted to initialize an operator."); } /* String representation of the value. */ public final StringBuffer toString(StringBuffer sb, int offset) { return sb.append("<Java Method: " + this.md + ">"); } }
Check if parameter is null before using it
tlatools/src/tlc2/value/MethodValue.java
Check if parameter is null before using it
Java
mit
69a7eff1a2eca642cfbcb82b4c4f70c659d25930
0
YusukeIwaki/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android.Lily,YusukeIwaki/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android
package chat.rocket.android; import android.support.multidex.MultiDexApplication; import chat.rocket.android.model.ServerConfig; import chat.rocket.android.realm_helper.RealmStore; import com.facebook.stetho.Stetho; import com.instabug.library.Feature; import com.instabug.library.Instabug; import com.instabug.library.invocation.InstabugInvocationEvent; import com.uphyca.stetho_realm.RealmInspectorModulesProvider; import io.realm.Realm; import io.realm.RealmConfiguration; import java.util.List; import timber.log.Timber; /** * Customized Application-class for Rocket.Chat */ public class RocketChatApplication extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); Timber.plant(new Timber.DebugTree()); Realm.init(this); Realm.setDefaultConfiguration( new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build()); List<ServerConfig> configs = RealmStore.getDefault().executeTransactionForReadResults(realm -> realm.where(ServerConfig.class).isNotNull("session").findAll()); for (ServerConfig config : configs) { RealmStore.put(config.getServerConfigId()); } Stetho.initialize(Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build()) .build()); new Instabug.Builder(this, getString(R.string.instabug_api_key)) .setInvocationEvent(InstabugInvocationEvent.FLOATING_BUTTON) .setInAppMessagingState(Feature.State.DISABLED) //not available in Free plan... .build(); //TODO: add periodic trigger for RocketChatService.keepalive(this) here! } }
app/src/main/java/chat/rocket/android/RocketChatApplication.java
package chat.rocket.android; import android.support.multidex.MultiDexApplication; import chat.rocket.android.model.ServerConfig; import chat.rocket.android.realm_helper.RealmStore; import com.facebook.stetho.Stetho; import com.instabug.library.Instabug; import com.instabug.library.invocation.InstabugInvocationEvent; import com.uphyca.stetho_realm.RealmInspectorModulesProvider; import io.realm.Realm; import io.realm.RealmConfiguration; import java.util.List; import timber.log.Timber; /** * Customized Application-class for Rocket.Chat */ public class RocketChatApplication extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); Timber.plant(new Timber.DebugTree()); Realm.init(this); Realm.setDefaultConfiguration( new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build()); List<ServerConfig> configs = RealmStore.getDefault().executeTransactionForReadResults(realm -> realm.where(ServerConfig.class).isNotNull("session").findAll()); for (ServerConfig config : configs) { RealmStore.put(config.getServerConfigId()); } Stetho.initialize(Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build()) .build()); new Instabug.Builder(this, getString(R.string.instabug_api_key)) .setInvocationEvent(InstabugInvocationEvent.FLOATING_BUTTON) .build(); //TODO: add periodic trigger for RocketChatService.keepalive(this) here! } }
remove InAppMessaging feature from Instabug.
app/src/main/java/chat/rocket/android/RocketChatApplication.java
remove InAppMessaging feature from Instabug.
Java
mit
0bcc4d631e183722f569fb6297a584c4d99a51a5
0
prl-tokyo/MAPE-controller,prl-tokyo/MAPE-controller
src/test/java/jp/ac/nii/prl/mape/controller/configuration/DependencyGraphTest.java
package jp.ac.nii.prl.mape.controller.configuration; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Test; import jp.ac.nii.prl.mape.controller.model.AP; public class DependencyGraphTest { @Before public void setUp() throws Exception { } @Test public void testEmptyList() { DependencyGraph graph = new DependencyGraph(); Iterator<AP> iter = graph.getIterator(); assertFalse(iter.hasNext()); } @Test public void testOneElement() { DependencyGraph graph = new DependencyGraph(); AP ap = new AP(); ap.setId(1L); ap.setName("ap1"); ap.setPredecessors(new ArrayList<String>()); graph.insert(ap); Iterator<AP> iter = graph.getIterator(); assertTrue(iter.hasNext()); assertTrue(iter.next().equals(ap)); assertFalse(iter.hasNext()); } @Test public void testThreeElementsNoDependency() { DependencyGraph graph = new DependencyGraph(); AP ap1 = new AP(); ap1.setId(1L); ap1.setName("ap1"); ap1.setPredecessors(new ArrayList<String>()); graph.insert(ap1); AP ap2 = new AP(); ap2.setId(2L); ap2.setName("ap2"); ap2.setPredecessors(new ArrayList<String>()); graph.insert(ap2); AP ap3 = new AP(); ap3.setId(3L); ap3.setName("ap3"); ap3.setPredecessors(new ArrayList<String>()); graph.insert(ap3); Iterator<AP> iter = graph.getIterator(); iter.next(); iter.next(); iter.next(); assertFalse(iter.hasNext()); } @Test public void testElementsWithDependency() { DependencyGraph graph = new DependencyGraph(); AP ap1 = new AP(); ap1.setId(1L); ap1.setName("ap1"); ap1.setPredecessors(new ArrayList<String>()); graph.insert(ap1); AP ap2 = new AP(); ap2.setId(2L); ap2.setName("ap2"); List<String> predecessors = new ArrayList<String>(); predecessors.add("ap1"); ap2.setPredecessors(predecessors); graph.insert(ap2); Iterator<AP> iter = graph.getIterator(); assertEquals("ap1", iter.next().getName()); assertEquals("ap2", iter.next().getName()); assertFalse(iter.hasNext()); } @Test public void testElementsWithDependencyOtherInsertionOrder() { DependencyGraph graph = new DependencyGraph(); AP ap2 = new AP(); ap2.setId(2L); ap2.setName("ap2"); List<String> predecessors = new ArrayList<String>(); predecessors.add("ap1"); ap2.setPredecessors(predecessors); graph.insert(ap2); AP ap1 = new AP(); ap1.setId(1L); ap1.setName("ap1"); ap1.setPredecessors(new ArrayList<String>()); graph.insert(ap1); Iterator<AP> iter = graph.getIterator(); assertEquals("ap1", iter.next().getName()); assertEquals("ap2", iter.next().getName()); assertFalse(iter.hasNext()); } }
Remove tests for deleted class
src/test/java/jp/ac/nii/prl/mape/controller/configuration/DependencyGraphTest.java
Remove tests for deleted class
Java
epl-1.0
7951a69b29064470e1e6d7fb48e387c86064b658
0
DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base,DavidGutknecht/elexis-3-base
/******************************************************************************* * Copyright (c) 2014 MEDEVIT. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * T. Huster - initial API and implementation *******************************************************************************/ package at.medevit.elexis.inbox.ui.part; import java.util.List; import org.eclipse.core.commands.Command; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Menu; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.part.ViewPart; import org.slf4j.LoggerFactory; import at.medevit.elexis.inbox.model.IInboxElementService; import at.medevit.elexis.inbox.model.IInboxElementService.State; import at.medevit.elexis.inbox.model.IInboxUpdateListener; import at.medevit.elexis.inbox.model.InboxElement; import at.medevit.elexis.inbox.ui.InboxServiceComponent; import at.medevit.elexis.inbox.ui.command.AutoActivePatientHandler; import at.medevit.elexis.inbox.ui.part.action.InboxFilterAction; import at.medevit.elexis.inbox.ui.part.model.PatientInboxElements; import at.medevit.elexis.inbox.ui.part.provider.IInboxElementUiProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementContentProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementLabelProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementUiExtension; import at.medevit.elexis.inbox.ui.preferences.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.ui.events.ElexisUiEventListenerImpl; import ch.elexis.data.Mandant; import ch.elexis.data.Patient; public class InboxView extends ViewPart { private Text filterText; private CheckboxTreeViewer viewer; private boolean reloadPending; private InboxElementViewerFilter filter = new InboxElementViewerFilter(); private ElexisUiEventListenerImpl mandantChanged = new ElexisUiEventListenerImpl(Mandant.class, ElexisEvent.EVENT_MANDATOR_CHANGED) { @Override public void runInUi(ElexisEvent ev){ reload(); } }; private InboxElementContentProvider contentProvider; private boolean setAutoSelectPatient; @Override public void createPartControl(Composite parent){ Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Composite filterComposite = new Composite(composite, SWT.NONE); GridData data = new GridData(GridData.FILL_HORIZONTAL); filterComposite.setLayoutData(data); filterComposite.setLayout(new GridLayout(2, false)); filterText = new Text(filterComposite, SWT.SEARCH); filterText.setMessage("Filter"); data = new GridData(GridData.FILL_HORIZONTAL); filterText.setLayoutData(data); filterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e){ if (filterText.getText().length() > 1) { filter.setSearchText(filterText.getText()); viewer.refresh(); } else { filter.setSearchText(""); viewer.refresh(); } } }); ToolBarManager menuManager = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL | SWT.WRAP); menuManager.createControl(filterComposite); viewer = new CheckboxTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); viewer.getControl().setLayoutData(gd); ViewerFilter[] filters = new ViewerFilter[1]; filters[0] = filter; viewer.setFilters(filters); contentProvider = new InboxElementContentProvider(); viewer.setContentProvider(contentProvider); viewer.setLabelProvider(new InboxElementLabelProvider()); viewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event){ if (event.getElement() instanceof PatientInboxElements) { PatientInboxElements patientInbox = (PatientInboxElements) event.getElement(); for (InboxElement inboxElement : patientInbox.getElements()) { if (!filter.isActive() || filter.isSelect(inboxElement)) { State newState = toggleInboxElementState(inboxElement); if (newState == State.NEW) { viewer.setChecked(inboxElement, false); } else { viewer.setChecked(inboxElement, true); } contentProvider.refreshElement(inboxElement); } } contentProvider.refreshElement(patientInbox); } else if (event.getElement() instanceof InboxElement) { InboxElement inboxElement = (InboxElement) event.getElement(); if (!filter.isActive() || filter.isSelect(inboxElement)) { toggleInboxElementState(inboxElement); contentProvider.refreshElement(inboxElement); } } viewer.refresh(false); } }); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event){ StructuredSelection selection = (StructuredSelection) viewer.getSelection(); if (!selection.isEmpty()) { Object selectedObj = selection.getFirstElement(); if (selectedObj instanceof InboxElement) { InboxElementUiExtension extension = new InboxElementUiExtension(); extension.fireDoubleClicked((InboxElement) selectedObj); } } } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event){ ISelection selection = event.getSelection(); if (selection instanceof StructuredSelection && !selection.isEmpty()) { if (setAutoSelectPatient) { Object selectedElement = ((StructuredSelection) selection).getFirstElement(); if (selectedElement instanceof InboxElement) { ElexisEventDispatcher .fireSelectionEvent(((InboxElement) selectedElement).getPatient()); } else if (selectedElement instanceof PatientInboxElements) { ElexisEventDispatcher.fireSelectionEvent( ((PatientInboxElements) selectedElement).getPatient()); } } } } }); final Transfer[] dropTransferTypes = new Transfer[] { FileTransfer.getInstance() }; viewer.addDropSupport(DND.DROP_COPY, dropTransferTypes, new DropTargetAdapter() { @Override public void dragEnter(DropTargetEvent event){ event.detail = DND.DROP_COPY; } @Override public void drop(DropTargetEvent event){ if (dropTransferTypes[0].isSupportedType(event.currentDataType)) { String[] files = (String[]) event.data; Patient patient = null; if (event.item != null) { Object data = event.item.getData(); if (data instanceof InboxElement) { patient = ((InboxElement) data).getPatient(); } else if (data instanceof PatientInboxElements) { patient = ((PatientInboxElements) data).getPatient(); } } if (patient == null) { // fallback patient = ElexisEventDispatcher.getSelectedPatient(); } if (patient != null) { if (files != null) { for (String file : files) { try { InboxServiceComponent.getService().createInboxElement(patient, ElexisEventDispatcher.getSelectedMandator(), file, true); } catch (Exception e) { LoggerFactory.getLogger(InboxView.class).warn("drop error", e); } } } viewer.refresh(); } else { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Warnung", "Bitte wählen Sie zuerst einen Patienten aus."); } } } }); addFilterActions(menuManager); InboxServiceComponent.getService().addUpdateListener(new IInboxUpdateListener() { public void update(final InboxElement element){ if (viewer != null && !viewer.getControl().isDisposed()) { Display.getDefault().asyncExec(new Runnable() { public void run(){ contentProvider.refreshElement(element); viewer.refresh(); } }); } } }); reload(); MenuManager ctxtMenuManager = new MenuManager(); Menu menu = ctxtMenuManager.createContextMenu(viewer.getTree()); viewer.getTree().setMenu(menu); getSite().registerContextMenu(ctxtMenuManager, viewer); ElexisEventDispatcher.getInstance().addListeners(mandantChanged); getSite().setSelectionProvider(viewer); setAutoSelectPatientState(CoreHub.userCfg.get(Preferences.INBOX_PATIENT_AUTOSELECT, false)); } public void setAutoSelectPatientState(boolean value){ setAutoSelectPatient = value; ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); Command command = service.getCommand(AutoActivePatientHandler.CMD_ID); command.getState(AutoActivePatientHandler.STATE_ID).setValue(value); CoreHub.userCfg.set(Preferences.INBOX_PATIENT_AUTOSELECT, value); } private void addFilterActions(ToolBarManager menuManager){ InboxElementUiExtension extension = new InboxElementUiExtension(); List<IInboxElementUiProvider> providers = extension.getProviders(); for (IInboxElementUiProvider iInboxElementUiProvider : providers) { ViewerFilter extensionFilter = iInboxElementUiProvider.getFilter(); if (extensionFilter != null) { InboxFilterAction action = new InboxFilterAction(viewer, extensionFilter, iInboxElementUiProvider.getFilterImage()); menuManager.add(action); } } menuManager.update(true); } private State toggleInboxElementState(InboxElement inboxElement){ if (inboxElement.getState() == State.NEW) { inboxElement.setState(State.SEEN); return State.SEEN; } else if (inboxElement.getState() == State.SEEN) { inboxElement.setState(State.NEW); return State.NEW; } return State.NEW; } @Override public void setFocus(){ filterText.setFocus(); if (reloadPending) { reload(); } } private List<InboxElement> getOpenInboxElements(){ List<InboxElement> openElements = InboxServiceComponent.getService().getInboxElements( (Mandant) ElexisEventDispatcher.getSelected(Mandant.class), null, IInboxElementService.State.NEW); return openElements; } private class InboxElementViewerFilter extends ViewerFilter { protected String searchString; protected LabelProvider labelProvider = new InboxElementLabelProvider(); public void setSearchText(String s){ // Search must be a substring of the existing value this.searchString = s; } public boolean isActive(){ if (searchString == null || searchString.isEmpty()) { return false; } return true; } private boolean isSelect(Object leaf){ String label = labelProvider.getText(leaf); if (label != null && label.contains(searchString)) { return true; } return false; } @Override public boolean select(Viewer viewer, Object parentElement, Object element){ if (searchString == null || searchString.length() == 0) { return true; } StructuredViewer sviewer = (StructuredViewer) viewer; ITreeContentProvider provider = (ITreeContentProvider) sviewer.getContentProvider(); Object[] children = provider.getChildren(element); if (children != null && children.length > 0) { for (Object child : children) { if (select(viewer, element, child)) { return true; } } } return isSelect(element); } } public void reload(){ if (!viewer.getControl().isVisible()) { reloadPending = true; return; } viewer.setInput(getOpenInboxElements()); reloadPending = false; viewer.refresh(); } @Override public void dispose(){ ElexisEventDispatcher.getInstance().removeListeners(mandantChanged); super.dispose(); } public CheckboxTreeViewer getCheckboxTreeViewer(){ return viewer; } }
bundles/at.medevit.elexis.inbox.ui/src/at/medevit/elexis/inbox/ui/part/InboxView.java
/******************************************************************************* * Copyright (c) 2014 MEDEVIT. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * T. Huster - initial API and implementation *******************************************************************************/ package at.medevit.elexis.inbox.ui.part; import java.util.List; import org.eclipse.core.commands.Command; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Menu; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.part.ViewPart; import org.slf4j.LoggerFactory; import at.medevit.elexis.inbox.model.IInboxElementService; import at.medevit.elexis.inbox.model.IInboxElementService.State; import at.medevit.elexis.inbox.model.IInboxUpdateListener; import at.medevit.elexis.inbox.model.InboxElement; import at.medevit.elexis.inbox.ui.InboxServiceComponent; import at.medevit.elexis.inbox.ui.command.AutoActivePatientHandler; import at.medevit.elexis.inbox.ui.part.action.InboxFilterAction; import at.medevit.elexis.inbox.ui.part.model.PatientInboxElements; import at.medevit.elexis.inbox.ui.part.provider.IInboxElementUiProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementContentProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementLabelProvider; import at.medevit.elexis.inbox.ui.part.provider.InboxElementUiExtension; import at.medevit.elexis.inbox.ui.preferences.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.ui.events.ElexisUiEventListenerImpl; import ch.elexis.data.Mandant; import ch.elexis.data.Patient; public class InboxView extends ViewPart { private Text filterText; private CheckboxTreeViewer viewer; private boolean reloadPending; private InboxElementViewerFilter filter = new InboxElementViewerFilter(); private ElexisUiEventListenerImpl mandantChanged = new ElexisUiEventListenerImpl(Mandant.class, ElexisEvent.EVENT_MANDATOR_CHANGED) { @Override public void runInUi(ElexisEvent ev){ reload(); } }; private InboxElementContentProvider contentProvider; private boolean setAutoSelectPatient; @Override public void createPartControl(Composite parent){ Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Composite filterComposite = new Composite(composite, SWT.NONE); GridData data = new GridData(GridData.FILL_HORIZONTAL); filterComposite.setLayoutData(data); filterComposite.setLayout(new GridLayout(2, false)); filterText = new Text(filterComposite, SWT.SEARCH); filterText.setMessage("Filter"); data = new GridData(GridData.FILL_HORIZONTAL); filterText.setLayoutData(data); filterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e){ if (filterText.getText().length() > 1) { filter.setSearchText(filterText.getText()); viewer.refresh(); } else { filter.setSearchText(""); viewer.refresh(); } } }); ToolBarManager menuManager = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL | SWT.WRAP); menuManager.createControl(filterComposite); viewer = new CheckboxTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); viewer.getControl().setLayoutData(gd); ViewerFilter[] filters = new ViewerFilter[1]; filters[0] = filter; viewer.setFilters(filters); contentProvider = new InboxElementContentProvider(); viewer.setContentProvider(contentProvider); viewer.setLabelProvider(new InboxElementLabelProvider()); viewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent event){ if (event.getElement() instanceof PatientInboxElements) { PatientInboxElements patientInbox = (PatientInboxElements) event.getElement(); for (InboxElement inboxElement : patientInbox.getElements()) { if (!filter.isActive() || filter.isSelect(inboxElement)) { State newState = toggleInboxElementState(inboxElement); if (newState == State.NEW) { viewer.setChecked(inboxElement, false); } else { viewer.setChecked(inboxElement, true); } contentProvider.refreshElement(inboxElement); } } contentProvider.refreshElement(patientInbox); } else if (event.getElement() instanceof InboxElement) { InboxElement inboxElement = (InboxElement) event.getElement(); if (!filter.isActive() || filter.isSelect(inboxElement)) { toggleInboxElementState(inboxElement); contentProvider.refreshElement(inboxElement); } } viewer.refresh(false); } }); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event){ StructuredSelection selection = (StructuredSelection) viewer.getSelection(); if (!selection.isEmpty()) { Object selectedObj = selection.getFirstElement(); if (selectedObj instanceof InboxElement) { InboxElementUiExtension extension = new InboxElementUiExtension(); extension.fireDoubleClicked((InboxElement) selectedObj); } } } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event){ ISelection selection = event.getSelection(); if (selection instanceof StructuredSelection && !selection.isEmpty()) { if (setAutoSelectPatient) { Object selectedElement = ((StructuredSelection) selection).getFirstElement(); if (selectedElement instanceof InboxElement) { ElexisEventDispatcher .fireSelectionEvent(((InboxElement) selectedElement).getPatient()); } else if (selectedElement instanceof PatientInboxElements) { ElexisEventDispatcher.fireSelectionEvent( ((PatientInboxElements) selectedElement).getPatient()); } } } } }); final Transfer[] dropTransferTypes = new Transfer[] { FileTransfer.getInstance() }; viewer.addDropSupport(DND.DROP_COPY, dropTransferTypes, new DropTargetAdapter() { @Override public void dragEnter(DropTargetEvent event){ event.detail = DND.DROP_COPY; } @Override public void drop(DropTargetEvent event){ if (dropTransferTypes[0].isSupportedType(event.currentDataType)) { String[] files = (String[]) event.data; Patient patient = null; if (event.item != null) { Object data = event.item.getData(); if (data instanceof InboxElement) { patient = ((InboxElement) data).getPatient(); } else if (data instanceof PatientInboxElements) { patient = ((PatientInboxElements) data).getPatient(); } } if (patient == null) { // fallback patient = ElexisEventDispatcher.getSelectedPatient(); } if (patient != null) { if (files != null) { for (String file : files) { try { InboxServiceComponent.getService().createInboxElement(patient, ElexisEventDispatcher.getSelectedMandator(), file, true); } catch (Exception e) { LoggerFactory.getLogger(InboxView.class).warn("drop error", e); } } } viewer.refresh(); } else { MessageDialog.openWarning(Display.getCurrent().getActiveShell(), "Warnung", "Bitte wählen Sie zuerst einen Patienten aus."); } } } }); addFilterActions(menuManager); InboxServiceComponent.getService().addUpdateListener(new IInboxUpdateListener() { public void update(final InboxElement element){ Display.getDefault().asyncExec(new Runnable() { public void run(){ contentProvider.refreshElement(element); viewer.refresh(); } }); } }); reload(); MenuManager ctxtMenuManager = new MenuManager(); Menu menu = ctxtMenuManager.createContextMenu(viewer.getTree()); viewer.getTree().setMenu(menu); getSite().registerContextMenu(ctxtMenuManager, viewer); ElexisEventDispatcher.getInstance().addListeners(mandantChanged); getSite().setSelectionProvider(viewer); setAutoSelectPatientState(CoreHub.userCfg.get(Preferences.INBOX_PATIENT_AUTOSELECT, false)); } public void setAutoSelectPatientState(boolean value){ setAutoSelectPatient = value; ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); Command command = service.getCommand(AutoActivePatientHandler.CMD_ID); command.getState(AutoActivePatientHandler.STATE_ID).setValue(value); CoreHub.userCfg.set(Preferences.INBOX_PATIENT_AUTOSELECT, value); } private void addFilterActions(ToolBarManager menuManager){ InboxElementUiExtension extension = new InboxElementUiExtension(); List<IInboxElementUiProvider> providers = extension.getProviders(); for (IInboxElementUiProvider iInboxElementUiProvider : providers) { ViewerFilter extensionFilter = iInboxElementUiProvider.getFilter(); if (extensionFilter != null) { InboxFilterAction action = new InboxFilterAction(viewer, extensionFilter, iInboxElementUiProvider.getFilterImage()); menuManager.add(action); } } menuManager.update(true); } private State toggleInboxElementState(InboxElement inboxElement){ if (inboxElement.getState() == State.NEW) { inboxElement.setState(State.SEEN); return State.SEEN; } else if (inboxElement.getState() == State.SEEN) { inboxElement.setState(State.NEW); return State.NEW; } return State.NEW; } @Override public void setFocus(){ filterText.setFocus(); if (reloadPending) { reload(); } } private List<InboxElement> getOpenInboxElements(){ List<InboxElement> openElements = InboxServiceComponent.getService().getInboxElements( (Mandant) ElexisEventDispatcher.getSelected(Mandant.class), null, IInboxElementService.State.NEW); return openElements; } private class InboxElementViewerFilter extends ViewerFilter { protected String searchString; protected LabelProvider labelProvider = new InboxElementLabelProvider(); public void setSearchText(String s){ // Search must be a substring of the existing value this.searchString = s; } public boolean isActive(){ if (searchString == null || searchString.isEmpty()) { return false; } return true; } private boolean isSelect(Object leaf){ String label = labelProvider.getText(leaf); if (label != null && label.contains(searchString)) { return true; } return false; } @Override public boolean select(Viewer viewer, Object parentElement, Object element){ if (searchString == null || searchString.length() == 0) { return true; } StructuredViewer sviewer = (StructuredViewer) viewer; ITreeContentProvider provider = (ITreeContentProvider) sviewer.getContentProvider(); Object[] children = provider.getChildren(element); if (children != null && children.length > 0) { for (Object child : children) { if (select(viewer, element, child)) { return true; } } } return isSelect(element); } } public void reload(){ if (!viewer.getControl().isVisible()) { reloadPending = true; return; } viewer.setInput(getOpenInboxElements()); reloadPending = false; viewer.refresh(); } @Override public void dispose(){ ElexisEventDispatcher.getInstance().removeListeners(mandantChanged); super.dispose(); } public CheckboxTreeViewer getCheckboxTreeViewer(){ return viewer; } }
[14957] test if InboxView has valid viewer before update
bundles/at.medevit.elexis.inbox.ui/src/at/medevit/elexis/inbox/ui/part/InboxView.java
[14957] test if InboxView has valid viewer before update
Java
lgpl-2.1
e4148ff4bbd0fd7d921fc1e9bdf8c88087ea3bf5
0
jolie/jolie,jolie/jolie,jolie/jolie
/* * Copyright (C) 2006-2021 Fabrizio Montesi <famontesi@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package jolie.lang.parse; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import jolie.lang.Constants; import jolie.lang.Constants.EmbeddedServiceType; import jolie.lang.NativeType; import jolie.lang.parse.ast.AddAssignStatement; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationVariableInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.DivideAssignStatement; import jolie.lang.parse.ast.EmbedServiceNode; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ForEachArrayItemStatement; import jolie.lang.parse.ast.ForEachSubNodeStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.ImportStatement; import jolie.lang.parse.ast.ImportableSymbol.AccessModifier; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallFunctionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.InterfaceExtenderDefinition; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.MultiplyAssignStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationCollector; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PortInfo; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.ProvideUntilStatement; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.ServiceNode; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SubtractAssignStatement; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.VariablePathNode.Type; import jolie.lang.parse.ast.WhileStatement; import jolie.lang.parse.ast.courier.CourierChoiceStatement; import jolie.lang.parse.ast.courier.CourierDefinitionNode; import jolie.lang.parse.ast.courier.NotificationForwardStatement; import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement; import jolie.lang.parse.ast.expression.AndConditionNode; import jolie.lang.parse.ast.expression.ConstantBoolExpression; import jolie.lang.parse.ast.expression.ConstantDoubleExpression; import jolie.lang.parse.ast.expression.ConstantIntegerExpression; import jolie.lang.parse.ast.expression.ConstantLongExpression; import jolie.lang.parse.ast.expression.ConstantStringExpression; import jolie.lang.parse.ast.expression.FreshValueExpressionNode; import jolie.lang.parse.ast.expression.InlineTreeExpressionNode; import jolie.lang.parse.ast.expression.InstanceOfExpressionNode; import jolie.lang.parse.ast.expression.IsTypeExpressionNode; import jolie.lang.parse.ast.expression.NotExpressionNode; import jolie.lang.parse.ast.expression.OrConditionNode; import jolie.lang.parse.ast.expression.ProductExpressionNode; import jolie.lang.parse.ast.expression.SumExpressionNode; import jolie.lang.parse.ast.expression.VariableExpressionNode; import jolie.lang.parse.ast.expression.VoidExpressionNode; import jolie.lang.parse.ast.types.BasicTypeDefinition; import jolie.lang.parse.ast.types.TypeChoiceDefinition; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeDefinitionUndefined; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinement; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementDoubleRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementIntegerRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementLongRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringLength; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringList; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringRegex; import jolie.lang.parse.context.ParsingContext; import jolie.lang.parse.context.URIParsingContext; import jolie.lang.parse.util.ProgramBuilder; import jolie.util.Helpers; import jolie.util.Pair; import jolie.util.Range; import jolie.util.UriUtils; /** * Parser for a .ol file. * * @author Fabrizio Montesi * */ public class OLParser extends AbstractParser { private interface ParsingRunnable { void parse() throws IOException, ParserException; } private long faultIdCounter = 0; private final ProgramBuilder programBuilder; private final Map< String, Scanner.Token > constantsMap = new HashMap<>(); private boolean insideInstallFunction = false; private String[] includePaths; private boolean hasIncludeDirective = false; private final Map< String, InterfaceExtenderDefinition > interfaceExtenders = new HashMap<>(); private final Map< String, TypeDefinition > definedTypes; private final ClassLoader classLoader; private InterfaceExtenderDefinition currInterfaceExtender = null; private static enum RefinementPredicates { LENGTH, ENUM, RANGES, REGEX } private static final Map< String, OLParser.RefinementPredicates > BASIC_TYPE_REFINED_PREDICATES = new HashMap<>(); static { BASIC_TYPE_REFINED_PREDICATES.put( "length", RefinementPredicates.LENGTH ); // defines the minimum and the // maximum // length of a string BASIC_TYPE_REFINED_PREDICATES.put( "regex", RefinementPredicates.REGEX ); // defines the regex for a string BASIC_TYPE_REFINED_PREDICATES.put( "enum", RefinementPredicates.ENUM ); // defines a list of string that a // string // can be BASIC_TYPE_REFINED_PREDICATES.put( "ranges", RefinementPredicates.RANGES ); // it defines a list of intervals // where // an int | long | double can be } public OLParser( Scanner scanner, String[] includePaths, ClassLoader classLoader ) { super( scanner ); final ParsingContext context = new URIParsingContext( scanner.source(), 0 ); this.programBuilder = new ProgramBuilder( context ); this.includePaths = includePaths; this.classLoader = classLoader; this.definedTypes = createTypeDeclarationMap( context ); } public void putConstants( Map< String, Scanner.Token > constantsToPut ) { constantsMap.putAll( constantsToPut ); } public static Map< String, TypeDefinition > createTypeDeclarationMap( ParsingContext context ) { Map< String, TypeDefinition > definedTypes = new HashMap<>(); // Fill in defineTypes with all the supported native types (string, int, double, ...) for( NativeType type : NativeType.values() ) { definedTypes.put( type.id(), new TypeInlineDefinition( context, type.id(), BasicTypeDefinition.of( type ), Constants.RANGE_ONE_TO_ONE ) ); } definedTypes.put( TypeDefinitionUndefined.UNDEFINED_KEYWORD, TypeDefinitionUndefined.getInstance() ); return definedTypes; } public Program parse() throws IOException, ParserException { _parse(); if( initSequence != null ) { programBuilder.addChild( new DefinitionNode( getContext(), "init", initSequence ) ); } if( main != null ) { programBuilder.addChild( main ); } if( !programBuilder.isJolieModuleSystem() && main != null ) { programBuilder.transformProgramToModuleSystem(); } else if( hasIncludeDirective ) { // [backward-compatibility] for include directive, remove Deployment Instructions which was added // during include file parsing process programBuilder.removeModuleScopeDeploymentInstructions(); } return programBuilder.toProgram(); } private void parseLoop( ParsingRunnable... parseRunnables ) throws IOException, ParserException { nextToken(); if( token.is( Scanner.TokenType.HASH ) ) { // Shebang scripting scanner().readLine(); nextToken(); } Scanner.Token t; do { t = token; for( ParsingRunnable runnable : parseRunnables ) { parseInclude(); runnable.parse(); } } while( t != token ); // Loop until no procedures can eat the initial token if( t.isNot( Scanner.TokenType.EOF ) ) { throwException( "Invalid token encountered" ); } } private void _parse() throws IOException, ParserException { parseLoop( this::parseImport, this::parseConstants, this::parseExecution, this::parseCorrelationSets, this::parseTypes, this::parseInterface, this::parsePort, this::parseEmbedded, this::parseService, this::parseCode ); } private void parseTypes() throws IOException, ParserException { boolean keepRun = true; while( keepRun ) { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); if( token.isKeyword( "type" ) ) { AccessModifier accessModifier = AccessModifier.PUBLIC; if( accessModifierToken.isPresent() ) { accessModifier = accessModifierToken.get().is( Scanner.TokenType.PRIVATE ) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; accessModifierToken = Optional.empty(); } String typeName; TypeDefinition currentType; nextToken(); typeName = token.content(); eat( Scanner.TokenType.ID, "expected type name" ); if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else { prependToken( new Scanner.Token( Scanner.TokenType.ID, NativeType.VOID.id() ) ); nextToken(); } currentType = parseType( typeName, accessModifier ); if( forwardDocToken.isPresent() ) { parseBackwardAndSetDocumentation( currentType, forwardDocToken ); forwardDocToken = Optional.empty(); } else { parseBackwardAndSetDocumentation( currentType, Optional.empty() ); } typeName = currentType.name(); definedTypes.put( typeName, currentType ); programBuilder.addChild( currentType ); } else { keepRun = false; forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } } private TypeDefinition parseType( String typeName, AccessModifier accessModifier ) throws IOException, ParserException { TypeDefinition currentType; BasicTypeDefinition basicTypeDefinition = readBasicType(); if( basicTypeDefinition == null ) { // It's a user-defined type currentType = new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, token.content() ); nextToken(); } else { currentType = new TypeInlineDefinition( getContext(), typeName, basicTypeDefinition, Constants.RANGE_ONE_TO_ONE ); if( token.is( Scanner.TokenType.LCURLY ) ) { // We have sub-types to parse parseSubTypes( (TypeInlineDefinition) currentType ); } } if( token.is( Scanner.TokenType.PARALLEL ) ) { // It's a sum (union, choice) type nextToken(); final TypeDefinition secondType = parseType( typeName, accessModifier ); return new TypeChoiceDefinition( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, currentType, secondType ); } return currentType; } private void parseSubTypes( TypeInlineDefinition type ) throws IOException, ParserException { eat( Scanner.TokenType.LCURLY, "expected {" ); Optional< Scanner.Token > commentToken = Optional.empty(); boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = Optional.of( token ); nextToken(); } else if( token.is( Scanner.TokenType.QUESTION_MARK ) ) { type.setUntypedSubTypes( true ); nextToken(); } else { TypeDefinition currentSubType; while( !token.is( Scanner.TokenType.RCURLY ) ) { if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = Optional.of( token ); nextToken(); } else { if( token.is( Scanner.TokenType.DOT ) ) { if( hasMetNewline() ) { nextToken(); } else { throwException( "the dot prefix operator for type nodes is allowed only after a newline" ); } } // SubType id String id = token.content(); if( token.is( Scanner.TokenType.STRING ) ) { nextToken(); } else { eatIdentifier( "expected type node name" ); } Range cardinality = parseCardinality(); if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else { prependToken( new Scanner.Token( Scanner.TokenType.ID, NativeType.VOID.id() ) ); nextToken(); } currentSubType = parseSubType( id, cardinality ); parseBackwardAndSetDocumentation( currentSubType, commentToken ); commentToken = Optional.empty(); if( type.hasSubType( currentSubType.name() ) ) { throwException( "sub-type " + currentSubType.name() + " conflicts with another sub-type with the same name" ); } type.putSubType( currentSubType ); } } keepRun = false; // if ( haveComment ) { // addToken( commentToken ); // addToken( token ); // nextToken(); // } } } eat( Scanner.TokenType.RCURLY, "RCURLY expected" ); } private TypeDefinition parseSubType( String id, Range cardinality ) throws IOException, ParserException { String currentTokenContent = token.content(); TypeDefinition subType; // SubType id BasicTypeDefinition basicTypeDefinition = readBasicType(); if( basicTypeDefinition == null ) { // It's a user-defined type subType = new TypeDefinitionLink( getContext(), id, cardinality, currentTokenContent ); nextToken(); } else { subType = new TypeInlineDefinition( getContext(), id, basicTypeDefinition, cardinality ); Optional< Scanner.Token > commentToken = Optional.empty(); if( token.is( Scanner.TokenType.DOCUMENTATION_BACKWARD ) ) { commentToken = Optional.of( token ); nextToken(); } if( token.is( Scanner.TokenType.LCURLY ) ) { // Has ulterior sub-types parseSubTypes( (TypeInlineDefinition) subType ); } if( commentToken.isPresent() ) { // we return the backward comment token and the eaten one, to be parsed by // the super type addToken( commentToken.get() ); addToken( new Scanner.Token( Scanner.TokenType.NEWLINE ) ); addToken( token ); nextToken(); } } if( token.is( Scanner.TokenType.PARALLEL ) ) { nextToken(); TypeDefinition secondSubType = parseSubType( id, cardinality ); return new TypeChoiceDefinition( getContext(), id, cardinality, subType, secondSubType ); } return subType; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Integer > parseListOfInteger( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Integer > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.INT && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type integer, found " + token.content() ); } if( token.type() == Scanner.TokenType.INT ) { arrayList.add( Integer.valueOf( token.content() ) ); } else { arrayList.add( Integer.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< String > parseListOfString( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< String > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.STRING ) { throwException( "Expected a parameter of type string, found " + token.content() ); } arrayList.add( token.content().replaceAll( "\"", "" ) ); nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Double > parseListOfDouble( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Double > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.DOUBLE && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type string, found " + token.content() ); } if( token.type() == Scanner.TokenType.DOUBLE ) { arrayList.add( Double.valueOf( token.content() ) ); } else { arrayList.add( Double.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Long > parseListOfLong( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Long > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.LONG && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type string, found " + token.content() ); } if( token.type() == Scanner.TokenType.LONG ) { arrayList.add( Long.valueOf( token.content() ) ); } else { arrayList.add( Long.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } private BasicTypeDefinition readBasicType() throws IOException, ParserException { List< BasicTypeRefinement< ? > > basicTypeRefinementList = new ArrayList<>(); if( token.is( Scanner.TokenType.CAST_INT ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementIntegerRanges basicTypeRefinementIntegerRanges = new BasicTypeRefinementIntegerRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Integer > parametersInterval = parseListOfInteger( 2, 2, predicate ); basicTypeRefinementIntegerRanges .addInterval( new BasicTypeRefinementIntegerRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementIntegerRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.INT, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_DOUBLE ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementDoubleRanges basicTypeRefinementDoubleRanges = new BasicTypeRefinementDoubleRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Double > parametersInterval = parseListOfDouble( 2, 2, predicate ); basicTypeRefinementDoubleRanges .addInterval( new BasicTypeRefinementDoubleRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementDoubleRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.DOUBLE, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_STRING ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); eat( Scanner.TokenType.LPAREN, "( expected" ); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case LENGTH: ArrayList< Integer > parametersLength = parseListOfInteger( 2, 2, predicate ); BasicTypeRefinementStringLength basicTypeRefinementStringLength = new BasicTypeRefinementStringLength( parametersLength.get( 0 ), parametersLength.get( 1 ) ); basicTypeRefinementList.add( basicTypeRefinementStringLength ); break; case ENUM: ArrayList< String > parametersList = parseListOfString( 1, null, predicate ); BasicTypeRefinementStringList basicTypeRefinementStringList = new BasicTypeRefinementStringList( parametersList ); basicTypeRefinementList.add( basicTypeRefinementStringList ); break; case REGEX: assertToken( Scanner.TokenType.STRING, "Expected regex string for predicate " + predicate ); basicTypeRefinementList.add( new BasicTypeRefinementStringRegex( token.content() ) ); nextToken(); break; default: throwException( "Basic type refinement predicate " + predicate + " not supported for string" ); } } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.STRING, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_LONG ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementLongRanges basicTypeRefinementLongRanges = new BasicTypeRefinementLongRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Long > parametersInterval = parseListOfLong( 2, 2, predicate ); basicTypeRefinementLongRanges .addInterval( new BasicTypeRefinementLongRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementLongRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.LONG, basicTypeRefinementList ); } else { NativeType nativeType = NativeType.fromString( token.content() ); if( nativeType == null ) { return null; } nextToken(); return BasicTypeDefinition.of( nativeType ); } } private Range parseCardinality() throws IOException, ParserException { final int min; final int max; if( token.is( Scanner.TokenType.QUESTION_MARK ) ) { min = 0; max = 1; nextToken(); } else if( token.is( Scanner.TokenType.ASTERISK ) ) { min = 0; max = Integer.MAX_VALUE; nextToken(); } else if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); // eat [ // Minimum assertToken( Scanner.TokenType.INT, "expected int value" ); min = Integer.parseInt( token.content() ); if( min < 0 ) { throwException( "Minimum number of occurrences of a sub-type must be positive or zero" ); } nextToken(); eat( Scanner.TokenType.COMMA, "expected comma separator" ); // Maximum if( token.is( Scanner.TokenType.INT ) ) { max = Integer.parseInt( token.content() ); if( max < 1 ) { throwException( "Maximum number of occurrences of a sub-type must be positive" ); } } else if( token.is( Scanner.TokenType.ASTERISK ) ) { max = Integer.MAX_VALUE; } else { max = -1; throwException( "Maximum number of sub-type occurrences not valid: " + token.content() ); } nextToken(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { // Default (no cardinality specified) min = 1; max = 1; } return new Range( min, max ); } private EmbedServiceNode parseEmbeddedServiceNode() throws IOException, ParserException { nextToken(); String serviceName = token.content(); OutputPortInfo bindingPort = null; boolean hasNewKeyword = false; OLSyntaxNode passingParam = null; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); if( !token.is( Scanner.TokenType.RPAREN ) ) { passingParam = parseBasicExpression(); } eat( Scanner.TokenType.RPAREN, "expected )" ); } if( token.is( Scanner.TokenType.AS ) ) { nextToken(); hasNewKeyword = true; assertToken( Scanner.TokenType.ID, "expected output port name" ); bindingPort = new OutputPortInfo( getContext(), token.content() ); nextToken(); } else if( token.isKeyword( "in" ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected output port name" ); bindingPort = new OutputPortInfo( getContext(), token.content() ); nextToken(); } return new EmbedServiceNode( getContext(), serviceName, bindingPort, hasNewKeyword, passingParam ); } private void parseEmbedded() throws IOException, ParserException { if( token.isKeyword( "embedded" ) ) { String servicePath, portId; nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; Constants.EmbeddedServiceType type; while( keepRun ) { type = null; if( token.isKeyword( "Java" ) ) { type = Constants.EmbeddedServiceType.JAVA; } else if( token.isKeyword( "Jolie" ) ) { type = Constants.EmbeddedServiceType.JOLIE; } else if( token.isKeyword( "JavaScript" ) ) { type = Constants.EmbeddedServiceType.JAVASCRIPT; } if( type == null ) { keepRun = false; } else { nextToken(); eat( Scanner.TokenType.COLON, "expected : after embedded service type" ); checkConstant(); while( token.is( Scanner.TokenType.STRING ) ) { servicePath = token.content(); nextToken(); if( token.isKeyword( "in" ) ) { eatKeyword( "in", "expected in" ); assertToken( Scanner.TokenType.ID, "expected output port name" ); portId = token.content(); nextToken(); } else { portId = null; } programBuilder.addChild( new EmbeddedServiceNode( getContext(), type, servicePath, portId ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } } } eat( Scanner.TokenType.RCURLY, "expected }" ); } } private void parseCorrelationSets() throws IOException, ParserException { if( token.isKeyword( "cset" ) ) { for( CorrelationSetInfo csetInfo : _parseCorrelationSets() ) { programBuilder.addChild( csetInfo ); } } } private CorrelationSetInfo[] _parseCorrelationSets() throws IOException, ParserException { List< CorrelationSetInfo > result = new ArrayList<>(); while( token.isKeyword( "cset" ) ) { nextToken(); /* * assertToken( Scanner.TokenType.ID, "expected correlation set name" ); String csetName = * token.content(); nextToken(); */ eat( Scanner.TokenType.LCURLY, "expected {" ); List< CorrelationVariableInfo > variables = new LinkedList<>(); List< CorrelationAliasInfo > aliases; VariablePathNode correlationVariablePath; String typeName; while( token.is( Scanner.TokenType.ID ) ) { aliases = new LinkedList<>(); correlationVariablePath = parseVariablePath(); eat( Scanner.TokenType.COLON, "expected correlation variable alias list" ); assertToken( Scanner.TokenType.ID, "expected correlation variable alias" ); while( token.is( Scanner.TokenType.ID ) ) { typeName = token.content(); nextToken(); eat( Scanner.TokenType.DOT, "expected . after message type name in correlation alias" ); TypeDefinition aliasType = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); aliases.add( new CorrelationAliasInfo( aliasType, parseVariablePath() ) ); } variables.add( new CorrelationVariableInfo( correlationVariablePath, aliases ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } result.add( new CorrelationSetInfo( getContext(), variables ) ); eat( Scanner.TokenType.RCURLY, "expected }" ); } return result.toArray( new CorrelationSetInfo[ 0 ] ); } private void parseExecution() throws IOException, ParserException { if( token.is( Scanner.TokenType.EXECUTION ) ) { programBuilder.addChild( _parseExecutionInfo() ); } } private ExecutionInfo _parseExecutionInfo() throws IOException, ParserException { Constants.ExecutionMode mode = Constants.ExecutionMode.SEQUENTIAL; nextToken(); boolean inCurlyBrackets = false; if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else if( token.is( Scanner.TokenType.LCURLY ) ) { inCurlyBrackets = true; nextToken(); } else { throwException( "expected : or { after execution" ); } assertToken( Scanner.TokenType.ID, "expected execution modality" ); switch( token.content() ) { case "sequential": mode = Constants.ExecutionMode.SEQUENTIAL; break; case "concurrent": mode = Constants.ExecutionMode.CONCURRENT; break; case "single": mode = Constants.ExecutionMode.SINGLE; break; default: throwException( "Expected execution mode, found " + token.content() ); break; } nextToken(); if( inCurlyBrackets ) { eat( Scanner.TokenType.RCURLY, "} expected" ); } return new ExecutionInfo( getContext(), mode ); } private void parseConstants() throws IOException, ParserException { if( token.is( Scanner.TokenType.CONSTANTS ) ) { nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; while( token.is( Scanner.TokenType.ID ) && keepRun ) { String cId = token.content(); nextToken(); eat( Scanner.TokenType.ASSIGN, "expected =" ); if( token.isValidConstant() == false ) { throwException( "expected string, integer, double or identifier constant" ); } if( constantsMap.containsKey( cId ) == false ) { constantsMap.put( cId, token ); } nextToken(); if( token.isNot( Scanner.TokenType.COMMA ) ) { keepRun = false; } else { nextToken(); } } eat( Scanner.TokenType.RCURLY, "expected }" ); } } private URL guessIncludeFilepath( String urlStr, String filename, String path ) { try { if( urlStr.startsWith( "jap:" ) || urlStr.startsWith( "jar:" ) ) { // Try hard to resolve names, even in Windows if( filename.startsWith( "../" ) ) { String tmpPath = path; String tmpFilename = filename; if( !tmpPath.contains( "/" ) && tmpPath.contains( "\\" ) ) { // Windows only tmpPath = tmpPath.replace( "\\", "/" ); } while( tmpFilename.startsWith( "../" ) ) { tmpFilename = tmpFilename.substring( 2 ); if( tmpPath.endsWith( "/" ) ) { tmpPath = tmpPath.substring( 0, tmpPath.length() - 1 ); } tmpPath = tmpPath.substring( 0, tmpPath.lastIndexOf( "/" ) ); } String tmpUrl = build( tmpPath, tmpFilename ); try { return new URL( tmpUrl.substring( 0, 4 ) + tmpUrl.substring( 4 ) ); } catch( Exception exn ) { return null; } } else if( filename.startsWith( "./" ) ) { String tmpPath = path; String tmpFilename = filename; if( !tmpPath.contains( "/" ) && tmpPath.contains( "\\" ) ) { tmpPath = tmpPath.replace( "\\", "/" ); } tmpFilename = tmpFilename.substring( 1 ); if( tmpPath.endsWith( "/" ) ) { tmpPath = tmpPath.substring( 0, tmpPath.length() - 1 ); } String tmpUrl = build( tmpPath, tmpFilename ); return new URL( tmpUrl.substring( 0, 4 ) + tmpUrl.substring( 4 ) ); } else { /* * We need the embedded URL path, otherwise URI.normalize is going to do nothing. */ return new URL( urlStr.substring( 0, 4 ) + new URI( urlStr.substring( 4 ) ).normalize().toString() ); } } else { return new URL( new URI( urlStr ).normalize().toString() ); } } catch( MalformedURLException | URISyntaxException e ) { return null; } } private IncludeFile retrieveIncludeFile( final String context, final String target ) throws URISyntaxException { IncludeFile ret; String urlStr = UriUtils.normalizeJolieUri( UriUtils.normalizeWindowsPath( UriUtils.resolve( context, target ) ) ); ret = tryAccessIncludeFile( urlStr ); if( ret == null ) { final URL url = guessIncludeFilepath( urlStr, target, context ); if( url != null ) { ret = tryAccessIncludeFile( url.toString() ); } } return ret; } private final Map< String, URL > resourceCache = new HashMap<>(); private IncludeFile tryAccessIncludeFile( String origIncludeStr ) { final String includeStr = UriUtils.normalizeWindowsPath( origIncludeStr ); final Optional< IncludeFile > optIncludeFile = Helpers.firstNonNull( () -> { final URL url = resourceCache.get( includeStr ); if( url == null ) { return null; } try { return new IncludeFile( new BufferedInputStream( url.openStream() ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } }, () -> { try { Path path = Paths.get( includeStr ); return new IncludeFile( new BufferedInputStream( Files.newInputStream( path ) ), path.getParent().toString(), path.toUri() ); } catch( FileSystemNotFoundException | IOException | InvalidPathException e ) { return null; } }, () -> { try { final URL url = new URL( includeStr ); final InputStream is = url.openStream(); return new IncludeFile( new BufferedInputStream( is ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } }, () -> { final URL url = classLoader.getResource( includeStr ); if( url == null ) { return null; } try { return new IncludeFile( new BufferedInputStream( url.openStream() ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } } ); optIncludeFile.ifPresent( includeFile -> { try { resourceCache.putIfAbsent( includeStr, includeFile.uri.toURL() ); } catch( MalformedURLException e ) { e.printStackTrace(); } } ); return optIncludeFile.orElse( null ); } private void parseInclude() throws IOException, ParserException { String[] origIncludePaths; IncludeFile includeFile; while( token.is( Scanner.TokenType.INCLUDE ) ) { nextToken(); hasIncludeDirective = true; Scanner oldScanner = scanner(); assertToken( Scanner.TokenType.STRING, "expected filename to include" ); String includeStr = token.content(); includeFile = null; for( int i = 0; i < includePaths.length && includeFile == null; i++ ) { try { includeFile = retrieveIncludeFile( includePaths[ i ], includeStr ); } catch( URISyntaxException e ) { throw new ParserException( getContext(), e.getMessage() ); } } if( includeFile == null ) { includeFile = tryAccessIncludeFile( includeStr ); if( includeFile == null ) { throwException( "File not found: " + includeStr ); } } origIncludePaths = includePaths; // includes are explicitly parsed in ASCII to be independent of program's encoding setScanner( new Scanner( includeFile.getInputStream(), includeFile.getURI(), "US-ASCII", oldScanner.includeDocumentation() ) ); if( includeFile.getParentPath() == null ) { includePaths = Arrays.copyOf( origIncludePaths, origIncludePaths.length ); } else { includePaths = Arrays.copyOf( origIncludePaths, origIncludePaths.length + 1 ); includePaths[ origIncludePaths.length ] = includeFile.getParentPath(); } _parse(); includePaths = origIncludePaths; includeFile.getInputStream().close(); setScanner( oldScanner ); nextToken(); } } private boolean checkConstant() { if( token.is( Scanner.TokenType.ID ) ) { final Scanner.Token t; final Constants.Predefined p = Constants.Predefined.get( token.content() ); if( p != null ) { t = p.token(); } else { t = constantsMap.get( token.content() ); } if( t != null ) { token = t; return true; } } return false; } private void parsePort() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); final DocumentedNode node; final PortInfo p; if( token.isKeyword( "inputPort" ) || token.isKeyword( "outputPort" ) ) { if( accessModifierToken.isPresent() ) { throwException( "unexpected access modifier before inputPort/outputPort" ); } p = _parsePort(); programBuilder.addChild( p ); node = p; parseBackwardAndSetDocumentation( node, forwardDocToken ); } else { forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private PortInfo _parsePort() throws IOException, ParserException { PortInfo portInfo = null; if( token.isKeyword( "inputPort" ) ) { portInfo = parseInputPortInfo(); } else if( token.isKeyword( "outputPort" ) ) { portInfo = parseOutputPortInfo(); } return portInfo; } private Optional< Scanner.Token > parseAccessModifier() throws IOException, ParserException { Scanner.Token accessModToken = null; if( token.is( Scanner.TokenType.PRIVATE ) || token.is( Scanner.TokenType.PUBLIC ) ) { accessModToken = token; nextToken(); } return Optional.ofNullable( accessModToken ); } private Optional< Scanner.Token > parseForwardDocumentation() throws IOException { Scanner.Token docToken = null; while( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { docToken = token; nextToken(); } return Optional.ofNullable( docToken ); } private Optional< Scanner.Token > parseBackwardDocumentation() throws IOException { Scanner.Token docToken = null; while( token.is( Scanner.TokenType.DOCUMENTATION_BACKWARD ) ) { docToken = token; nextToken(); } return Optional.ofNullable( docToken ); } private void parseBackwardAndSetDocumentation( DocumentedNode node, Optional< Scanner.Token > forwardDocToken ) throws IOException { if( node != null ) { // <Java 8> // Optional< Scanner.Token > backwardDoc = parseBackwardDocumentation(); // if( backwardDoc.isPresent() ) { // node.setDocumentation( backwardDoc.get().content() ); // } else { // String forwardDoc = forwardDocToken // .orElse( new Scanner.Token( Scanner.TokenType.DOCUMENTATION_FORWARD, "" ) ).content(); // node.setDocumentation( forwardDoc ); // } // </Java 8> parseBackwardDocumentation().ifPresentOrElse( doc -> node.setDocumentation( doc.content() ), () -> node.setDocumentation( (forwardDocToken.orElse( new Scanner.Token( Scanner.TokenType.DOCUMENTATION_FORWARD, "" ) )) .content() ) ); } else { forwardDocToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private void parseInterface() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); if( token.isKeyword( "interface" ) ) { nextToken(); DocumentedNode docNode = null; AccessModifier accessModifier = (accessModifierToken.isPresent() && accessModifierToken.get().is( Scanner.TokenType.PRIVATE )) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; final InterfaceDefinition iface; if( token.isKeyword( "extender" ) ) { nextToken(); iface = _parseInterfaceExtender( accessModifier ); docNode = iface; } else { iface = _parseInterface( accessModifier ); docNode = iface; } if( docNode != null ) { parseBackwardAndSetDocumentation( docNode, forwardDocToken ); } programBuilder.addChild( iface ); } else { forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private OutputPortInfo createInternalServicePort( String name, InterfaceDefinition[] interfaceList ) throws ParserException { OutputPortInfo p = new OutputPortInfo( getContext(), name ); for( InterfaceDefinition interfaceDefinition : interfaceList ) { p.addInterface( interfaceDefinition ); } return p; } private InputPortInfo createInternalServiceInputPort( String serviceName, InterfaceDefinition[] interfaceList ) throws ParserException { InputPortInfo iport = new InputPortInfo( getContext(), serviceName + "InputPort", // input port name new ConstantStringExpression( getContext(), Constants.LOCAL_LOCATION_KEYWORD ), null, new InputPortInfo.AggregationItemInfo[] {}, Collections.< String, String >emptyMap() ); for( InterfaceDefinition i : interfaceList ) { iport.addInterface( i ); } return iport; } /** * Parses an internal service, i.e. service service_name {} */ private EmbeddedServiceNode createInternalService( ParsingContext ctx, String serviceName, InterfaceDefinition[] ifaces, SequenceStatement init, DefinitionNode main, ProgramBuilder parentProgramBuilder ) throws IOException, ParserException { // add output port to main program parentProgramBuilder.addChild( createInternalServicePort( serviceName, ifaces ) ); // create Program representing the internal service ProgramBuilder internalServiceProgramBuilder = new ProgramBuilder( ctx ); // copy children of parent to embedded service for( OLSyntaxNode child : parentProgramBuilder.children() ) { if( child instanceof OutputPortInfo || child instanceof TypeDefinition ) { internalServiceProgramBuilder.addChild( child ); } } // set execution to always concurrent internalServiceProgramBuilder.addChild( new ExecutionInfo( getContext(), Constants.ExecutionMode.CONCURRENT ) ); // add input port to internal service internalServiceProgramBuilder.addChild( createInternalServiceInputPort( serviceName, ifaces ) ); // add init if defined in internal service if( init != null ) { internalServiceProgramBuilder.addChild( new DefinitionNode( getContext(), "init", init ) ); } // add main defined in internal service internalServiceProgramBuilder.addChild( main ); // create internal embedded service node EmbeddedServiceNode internalServiceNode = new EmbeddedServiceNode( getContext(), Constants.EmbeddedServiceType.INTERNAL, serviceName, serviceName ); internalServiceProgramBuilder.transformProgramToModuleSystem(); // add internal service program to embedded service node internalServiceNode.setProgram( internalServiceProgramBuilder.toProgram() ); return internalServiceNode; } private InterfaceDefinition[] parseInternalServiceInterface() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected : after Interfaces" ); boolean keepRun = true; List< InterfaceDefinition > currInternalServiceIfaceList = new ArrayList<>(); while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); currInternalServiceIfaceList.add( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } return currInternalServiceIfaceList.toArray( new InterfaceDefinition[ 0 ] ); } private Pair< String, TypeDefinition > parseServiceParameter() throws IOException, ParserException { if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); if( token.is( Scanner.TokenType.RPAREN ) ) { // case ( ) nextToken(); return null; } else { // case ( path: type ) assertToken( Scanner.TokenType.ID, "expected parameter variable name" ); String paramPath = token.content(); nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String typeName = token.content(); TypeDefinition parameterType = parseType( typeName, AccessModifier.PRIVATE ); eat( Scanner.TokenType.RPAREN, "expected )" ); return new Pair<>( paramPath, parameterType ); } } else { return null; } } private ServiceNode createForeignServiceNode( ParsingContext ctx, String serviceName, Pair< String, TypeDefinition > parameter, AccessModifier accessModifier, ProgramBuilder serviceBlockProgramBuilder, EmbeddedServiceType technology, Map< String, String > implementationConfiguration ) { return ServiceNode.create( ctx, serviceName, accessModifier, serviceBlockProgramBuilder.toProgram(), parameter, technology, implementationConfiguration ); } private ServiceNode createJolieServiceNode( ParsingContext ctx, String serviceName, Pair< String, TypeDefinition > parameter, AccessModifier accessModifier, SequenceStatement init, DefinitionNode main, ProgramBuilder parentProgramBuilder, ProgramBuilder serviceBlockProgramBuilder ) { ProgramBuilder serviceNodeProgramBuilder = new ProgramBuilder( ctx ); // [backward-compatibility] inject top-level deployment instructions to the service node // so the include directive is still working in Module System, These deployment instructions of // parent's programBuilder are meant to remove at the end of parsing step. for( OLSyntaxNode child : parentProgramBuilder.children() ) { if( child instanceof OutputPortInfo || child instanceof InputPortInfo || child instanceof EmbeddedServiceNode ) { serviceNodeProgramBuilder.addChild( child ); } } // copy children of parent to embedded service for( OLSyntaxNode child : serviceBlockProgramBuilder.children() ) { serviceNodeProgramBuilder.addChild( child ); } // add init if defined in internal service if( init != null ) { serviceNodeProgramBuilder.addChild( new DefinitionNode( getContext(), "init", init ) ); } // add main defined in service if( main != null ) { serviceNodeProgramBuilder.addChild( main ); } ServiceNode node = ServiceNode.create( ctx, serviceName, accessModifier, serviceNodeProgramBuilder.toProgram(), parameter ); return node; } /** * Parses a service node, i.e. service service_name ( varpath : type ) {} */ private void parseService() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); // only proceed if a service declaration if( !token.isKeyword( "service" ) ) { forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); return; } nextToken(); Constants.EmbeddedServiceType tech = Constants.EmbeddedServiceType.SERVICENODE; Map< String, String > configMap = new HashMap<>(); assertToken( Scanner.TokenType.ID, "expected service name" ); ParsingContext ctx = getContext(); String serviceName = token.content(); nextToken(); Pair< String, TypeDefinition > parameter = parseServiceParameter(); eat( Scanner.TokenType.LCURLY, "{ expected" ); // jolie internal service's Interface InterfaceDefinition[] internalIfaces = null; DefinitionNode internalMain = null; SequenceStatement internalInit = null; ProgramBuilder serviceBlockProgramBuilder = new ProgramBuilder( getContext() ); boolean keepRun = true; while( keepRun ) { Optional< Scanner.Token > internalForwardDocToken = parseForwardDocumentation(); switch( token.content() ) { case "Interfaces": // internal service node syntax internalIfaces = parseInternalServiceInterface(); break; case "include": parseInclude(); break; case "cset": for( CorrelationSetInfo csetInfo : _parseCorrelationSets() ) { serviceBlockProgramBuilder.addChild( csetInfo ); } break; case "execution": serviceBlockProgramBuilder.addChild( _parseExecutionInfo() ); break; case "courier": serviceBlockProgramBuilder.addChild( parseCourierDefinition() ); break; case "init": if( internalInit == null ) { internalInit = new SequenceStatement( getContext() ); } internalInit.addChild( parseInit() ); break; case "main": if( internalMain != null ) { throwException( "you must specify only one main definition" ); } internalMain = parseMain(); break; case "inputPort": case "outputPort": PortInfo p = _parsePort(); parseBackwardAndSetDocumentation( ((DocumentedNode) p), internalForwardDocToken ); serviceBlockProgramBuilder.addChild( p ); break; case "define": serviceBlockProgramBuilder.addChild( parseDefinition() ); break; case "embed": EmbedServiceNode embedServiceNode = parseEmbeddedServiceNode(); if( embedServiceNode.isNewPort() ) { serviceBlockProgramBuilder .addChild( embedServiceNode.bindingPort() ); } serviceBlockProgramBuilder.addChild( embedServiceNode ); break; case "foreign": nextToken(); String technology = token.content(); if( technology.equals( "java" ) ) { tech = Constants.EmbeddedServiceType.SERVICENODE_JAVA; } nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); while( token.isNot( Scanner.TokenType.RCURLY ) ) { String key = token.content(); nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String value = ""; while( !hasMetNewline() ) { if( token.is( Scanner.TokenType.DOT ) ) { value += "."; } else { value += token.content(); } nextToken(); } configMap.put( key, value ); } eat( Scanner.TokenType.RCURLY, "expected }" ); default: assertToken( Scanner.TokenType.RCURLY, "invalid token found inside service " + serviceName ); keepRun = false; } } eat( Scanner.TokenType.RCURLY, "expected }" ); // it is a Jolie internal service if( internalIfaces != null && internalIfaces.length > 0 ) { if( internalMain == null ) { throwException( "You must specify a main for service " + serviceName ); } EmbeddedServiceNode node = createInternalService( ctx, serviceName, internalIfaces, internalInit, internalMain, programBuilder ); programBuilder.addChild( node ); } else { AccessModifier accessModifier = (accessModifierToken.isPresent() && accessModifierToken.get().is( Scanner.TokenType.PRIVATE )) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; ServiceNode serviceNode = null; switch( tech ) { case SERVICENODE: serviceNode = createJolieServiceNode( ctx, serviceName, parameter, accessModifier, internalInit, internalMain, programBuilder, serviceBlockProgramBuilder ); break; default: serviceNode = createForeignServiceNode( ctx, serviceName, parameter, accessModifier, serviceBlockProgramBuilder, tech, configMap ); } programBuilder.addChild( serviceNode ); } } private InputPortInfo parseInputPortInfo() throws IOException, ParserException { String inputPortName; OLSyntaxNode protocol = null; OLSyntaxNode location = null; List< InterfaceDefinition > interfaceList = new ArrayList<>(); nextToken(); assertToken( Scanner.TokenType.ID, "expected inputPort name" ); inputPortName = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "{ expected" ); InterfaceDefinition iface = new InterfaceDefinition( getContext(), "Internal interface for: " + inputPortName ); Map< String, String > redirectionMap = new HashMap<>(); List< InputPortInfo.AggregationItemInfo > aggregationList = new ArrayList<>(); boolean isLocationLocal = false; while( token.isNot( Scanner.TokenType.RCURLY ) ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( iface ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( iface ); } else if( token.isKeyword( "location" ) || token.isKeyword( "Location" ) ) { if( location != null ) { throwException( "Location already defined for service " + inputPortName ); } nextToken(); eat( Scanner.TokenType.COLON, "expected : after location" ); checkConstant(); if( token.content().startsWith( "local" ) ) { // check if the inputPort is listening to local protocol isLocationLocal = true; } location = parseBasicExpression(); } else if( token.isKeyword( "interfaces" ) || token.isKeyword( "Interfaces" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected : after interfaces" ); boolean keepRun = true; while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); interfaceList.add( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } } else if( token.isKeyword( "protocol" ) || token.isKeyword( "Protocol" ) ) { if( protocol != null ) { throwException( "Protocol already defined for inputPort " + inputPortName ); } nextToken(); eat( Scanner.TokenType.COLON, "expected : after protocol" ); checkConstant(); protocol = parseBasicExpression(); } else if( token.isKeyword( "redirects" ) || token.isKeyword( "Redirects" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String subLocationName; while( token.is( Scanner.TokenType.ID ) ) { subLocationName = token.content(); nextToken(); eat( Scanner.TokenType.ARROW, "expected =>" ); assertToken( Scanner.TokenType.ID, "expected outputPort identifier" ); redirectionMap.put( subLocationName, token.content() ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } } else if( token.isKeyword( "aggregates" ) || token.isKeyword( "Aggregates" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); parseAggregationList( aggregationList ); } else { throwException( "Unrecognized token in inputPort " + inputPortName ); } } eat( Scanner.TokenType.RCURLY, "} expected" ); if( location == null ) { throwException( "expected location URI for " + inputPortName ); } else if( (interfaceList.isEmpty() && iface.operationsMap().isEmpty()) && redirectionMap.isEmpty() && aggregationList.isEmpty() ) { throwException( "expected at least one operation, interface, aggregation or redirection for inputPort " + inputPortName ); } else if( protocol == null && !isLocationLocal ) { throwException( "expected protocol for inputPort " + inputPortName ); } InputPortInfo iport = new InputPortInfo( getContext(), inputPortName, location, protocol, aggregationList.toArray( new InputPortInfo.AggregationItemInfo[ aggregationList.size() ] ), redirectionMap ); for( InterfaceDefinition i : interfaceList ) { iport.addInterface( i ); } iface.copyTo( iport ); return iport; } private void parseAggregationList( List< InputPortInfo.AggregationItemInfo > aggregationList ) throws ParserException, IOException { List< String > outputPortNames; InterfaceExtenderDefinition extender; boolean mainKeepRun = true; while( mainKeepRun ) { extender = null; outputPortNames = new LinkedList<>(); if( token.is( Scanner.TokenType.LCURLY ) ) { nextToken(); boolean keepRun = true; while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected output port name" ); outputPortNames.add( token.content() ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else if( token.is( Scanner.TokenType.RCURLY ) ) { keepRun = false; nextToken(); } else { throwException( "unexpected token " + token.type() ); } } } else { assertToken( Scanner.TokenType.ID, "expected output port name" ); outputPortNames.add( token.content() ); nextToken(); } if( token.is( Scanner.TokenType.WITH ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected interface extender name" ); extender = interfaceExtenders.get( token.content() ); if( extender == null ) { throwException( "undefined interface extender: " + token.content() ); } nextToken(); } aggregationList.add( new InputPortInfo.AggregationItemInfo( outputPortNames.toArray( new String[ 0 ] ), extender ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { mainKeepRun = false; } } } private InterfaceDefinition _parseInterfaceExtender( AccessModifier accessModifier ) throws IOException, ParserException { String name; assertToken( Scanner.TokenType.ID, "expected interface extender name" ); name = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); InterfaceExtenderDefinition extender = currInterfaceExtender = new InterfaceExtenderDefinition( getContext(), name, accessModifier ); parseOperations( currInterfaceExtender ); interfaceExtenders.put( name, extender ); eat( Scanner.TokenType.RCURLY, "expected }" ); currInterfaceExtender = null; return extender; } private InterfaceDefinition _parseInterface( AccessModifier accessModifier ) throws IOException, ParserException { String name; InterfaceDefinition iface; assertToken( Scanner.TokenType.ID, "expected interface name" ); name = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); iface = new InterfaceDefinition( getContext(), name, accessModifier ); parseOperations( iface ); eat( Scanner.TokenType.RCURLY, "expected }" ); return iface; } private void parseOperations( OperationCollector oc ) throws IOException, ParserException { boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( oc ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( oc ); } else { keepRun = false; } } } private OutputPortInfo parseOutputPortInfo() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected output port identifier" ); OutputPortInfo p = new OutputPortInfo( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( p ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( p ); } else if( token.isKeyword( "interfaces" ) || token.isKeyword( "Interfaces" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected : after Interfaces" ); boolean r = true; while( r ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); p.addInterface( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { r = false; } } } else if( token.isKeyword( "location" ) || token.isKeyword( "Location" ) ) { if( p.location() != null ) { throwException( "Location already defined for output port " + p.id() ); } nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); checkConstant(); OLSyntaxNode expr = parseBasicExpression(); p.setLocation( expr ); } else if( token.isKeyword( "protocol" ) || token.isKeyword( "Protocol" ) ) { if( p.protocol() != null ) { throwException( "Protocol already defined for output port " + p.id() ); } nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); checkConstant(); OLSyntaxNode protocol = parseBasicExpression(); p.setProtocol( protocol ); } else { keepRun = false; } } eat( Scanner.TokenType.RCURLY, "expected }" ); return p; } private void parseOneWayOperations( OperationCollector oc ) throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); boolean keepRun = true; Scanner.Token commentToken = null; String opId; while( keepRun ) { checkConstant(); if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = token; nextToken(); } else if( token.is( Scanner.TokenType.ID ) || (currInterfaceExtender != null && token.is( Scanner.TokenType.ASTERISK )) ) { opId = token.content(); OneWayOperationDeclaration opDecl = new OneWayOperationDeclaration( getContext(), opId ); nextToken(); opDecl.setRequestType( TypeDefinitionUndefined.getInstance() ); if( token.is( Scanner.TokenType.LPAREN ) ) { // Type declaration nextToken(); // eat ( String typeName = token.content(); TypeDefinition type = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); opDecl.setRequestType( type ); nextToken(); // eat the type name eat( Scanner.TokenType.RPAREN, "expected )" ); } parseBackwardAndSetDocumentation( opDecl, Optional.ofNullable( commentToken ) ); commentToken = null; if( currInterfaceExtender != null && opId.equals( "*" ) ) { currInterfaceExtender.setDefaultOneWayOperation( opDecl ); } else { oc.addOperation( opDecl ); } if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } else { keepRun = false; } } } private void parseRequestResponseOperations( OperationCollector oc ) throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); boolean keepRun = true; Scanner.Token commentToken = null; String opId; while( keepRun ) { checkConstant(); if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = token; nextToken(); } else if( token.is( Scanner.TokenType.ID ) || (currInterfaceExtender != null && token.is( Scanner.TokenType.ASTERISK )) ) { opId = token.content(); nextToken(); String requestTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; String responseTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); // eat ( requestTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LPAREN, "expected (" ); responseTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); } Map< String, TypeDefinition > faultTypesMap = new HashMap<>(); if( token.is( Scanner.TokenType.THROWS ) ) { nextToken(); while( token.is( Scanner.TokenType.ID ) ) { String faultName = token.content(); String faultTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); // eat ( faultTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); } TypeDefinition faultType = new TypeDefinitionLink( getContext(), faultIdCounter++ + "#" + faultTypeName, Constants.RANGE_ONE_TO_ONE, faultTypeName ); if( definedTypes.containsKey( faultTypeName ) ) { faultType = definedTypes.get( faultTypeName ); } else { definedTypes.put( faultTypeName, faultType ); } faultTypesMap.put( faultName, faultType ); } } TypeDefinition requestType = definedTypes.getOrDefault( requestTypeName, new TypeDefinitionLink( getContext(), requestTypeName, Constants.RANGE_ONE_TO_ONE, requestTypeName ) ); TypeDefinition responseType = definedTypes.getOrDefault( responseTypeName, new TypeDefinitionLink( getContext(), responseTypeName, Constants.RANGE_ONE_TO_ONE, responseTypeName ) ); RequestResponseOperationDeclaration opRR = new RequestResponseOperationDeclaration( getContext(), opId, requestType, responseType, faultTypesMap ); parseBackwardAndSetDocumentation( opRR, Optional.ofNullable( commentToken ) ); commentToken = null; if( currInterfaceExtender != null && opId.equals( "*" ) ) { currInterfaceExtender.setDefaultRequestResponseOperation( opRR ); } else { oc.addOperation( opRR ); } if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } else { keepRun = false; } } } private SequenceStatement initSequence = null; private DefinitionNode main = null; private void parseCode() throws IOException, ParserException { boolean keepRun = true; do { if( token.is( Scanner.TokenType.DEFINE ) ) { programBuilder.addChild( parseDefinition() ); } else if( token.isKeyword( "courier" ) ) { programBuilder.addChild( parseCourierDefinition() ); } else if( token.isKeyword( "main" ) ) { if( main != null ) { throwException( "you must specify only one main definition" ); } main = parseMain(); } else if( token.is( Scanner.TokenType.INIT ) ) { if( initSequence == null ) { initSequence = new SequenceStatement( getContext() ); } initSequence.addChild( parseInit() ); } else { keepRun = false; } } while( keepRun ); } private DefinitionNode parseMain() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" ); DefinitionNode retVal = new DefinitionNode( getContext(), "main", parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" ); return retVal; } private OLSyntaxNode parseInit() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" ); OLSyntaxNode retVal = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" ); return retVal; } private DefinitionNode parseDefinition() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected definition identifier" ); String definitionId = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after definition declaration" ); DefinitionNode retVal = new DefinitionNode( getContext(), definitionId, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected } after definition declaration" ); return retVal; } private CourierDefinitionNode parseCourierDefinition() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected input port identifier" ); String inputPortName = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after courier definition" ); CourierDefinitionNode retVal = new CourierDefinitionNode( getContext(), inputPortName, parseCourierChoice() ); eat( Scanner.TokenType.RCURLY, "expected } after courier definition" ); return retVal; } public OLSyntaxNode parseProcess() throws IOException, ParserException { return parseParallelStatement(); } private ParallelStatement parseParallelStatement() throws IOException, ParserException { ParallelStatement stm = new ParallelStatement( getContext() ); stm.addChild( parseSequenceStatement() ); while( token.is( Scanner.TokenType.PARALLEL ) ) { nextToken(); stm.addChild( parseSequenceStatement() ); } return stm; } private SequenceStatement parseSequenceStatement() throws IOException, ParserException { SequenceStatement stm = new SequenceStatement( getContext() ); stm.addChild( parseBasicStatement() ); boolean run = true; while( run ) { if( token.is( Scanner.TokenType.SEQUENCE ) ) { nextToken(); stm.addChild( parseBasicStatement() ); } else if( hasMetNewline() ) { OLSyntaxNode basicStatement = parseBasicStatement( false ); if( basicStatement == null ) { run = false; } else { stm.addChild( basicStatement ); } } else { run = false; } } return stm; } private final List< List< Scanner.Token > > inVariablePaths = new ArrayList<>(); private OLSyntaxNode parseInVariablePathProcess( boolean withConstruct ) throws IOException, ParserException { OLSyntaxNode ret; LinkedList< Scanner.Token > tokens = new LinkedList<>(); try { if( withConstruct ) { eat( Scanner.TokenType.LPAREN, "expected (" ); while( token.isNot( Scanner.TokenType.LCURLY ) ) { tokens.add( token ); nextTokenNotEOF(); } // TODO transfer this whole buggy thing to the OOIT tokens.removeLast(); // nextToken(); } else { while( token.isNot( Scanner.TokenType.LCURLY ) ) { tokens.add( token ); nextTokenNotEOF(); } } } catch( EOFException eof ) { throwException( "with clause requires a { at the beginning of its body" ); } inVariablePaths.add( tokens ); eat( Scanner.TokenType.LCURLY, "expected {" ); ret = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); inVariablePaths.remove( inVariablePaths.size() - 1 ); return ret; } private OLSyntaxNode parseBasicStatement() throws IOException, ParserException { return parseBasicStatement( true ); } private OLSyntaxNode parseBasicStatement( boolean throwException ) throws IOException, ParserException { OLSyntaxNode retVal = null; switch( token.type() ) { case LSQUARE: retVal = parseNDChoiceStatement(); break; case PROVIDE: nextToken(); retVal = parseProvideUntilStatement(); break; case ID: if( checkConstant() ) { throwException( "cannot modify a constant in a statement" ); } String id = token.content(); nextToken(); if( token.is( Scanner.TokenType.LSQUARE ) || token.is( Scanner.TokenType.DOT ) || token.is( Scanner.TokenType.ASSIGN ) || token.is( Scanner.TokenType.ADD_ASSIGN ) || token.is( Scanner.TokenType.MINUS_ASSIGN ) || token.is( Scanner.TokenType.MULTIPLY_ASSIGN ) || token.is( Scanner.TokenType.DIVIDE_ASSIGN ) || token.is( Scanner.TokenType.POINTS_TO ) || token.is( Scanner.TokenType.DEEP_COPY_LEFT ) || token.is( Scanner.TokenType.DEEP_COPY_WITH_LINKS_LEFT ) || token.is( Scanner.TokenType.DECREMENT ) || token.is( Scanner.TokenType.INCREMENT ) ) { retVal = parseAssignOrDeepCopyOrPointerStatement( _parseVariablePath( id ) ); } else if( id.equals( "forward" ) && (token.is( Scanner.TokenType.ID ) || token.is( Scanner.TokenType.LPAREN )) ) { retVal = parseForwardStatement(); } else if( token.is( Scanner.TokenType.LPAREN ) ) { retVal = parseInputOperationStatement( id ); } else if( token.is( Scanner.TokenType.AT ) ) { nextToken(); retVal = parseOutputOperationStatement( id ); } else { retVal = new DefinitionCallStatement( getContext(), id ); } break; case WITH: nextToken(); retVal = parseInVariablePathProcess( true ); break; case INCREMENT: nextToken(); retVal = new PreIncrementStatement( getContext(), parseVariablePath() ); break; case DECREMENT: nextToken(); retVal = new PreDecrementStatement( getContext(), parseVariablePath() ); break; case UNDEF: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); retVal = new UndefStatement( getContext(), parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case SYNCHRONIZED: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected lock id" ); final String sid = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); retVal = new SynchronizedStatement( getContext(), sid, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case SPAWN: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); VariablePathNode indexVariablePath = parseVariablePath(); assertToken( Scanner.TokenType.ID, "expected over" ); if( token.isKeyword( "over" ) == false ) { throwException( "expected over" ); } nextToken(); OLSyntaxNode upperBoundExpression = parseBasicExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); VariablePathNode inVariablePath = null; if( token.isKeyword( "in" ) ) { nextToken(); inVariablePath = parseVariablePath(); } eat( Scanner.TokenType.LCURLY, "expected {" ); OLSyntaxNode process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); retVal = new SpawnStatement( getContext(), indexVariablePath, upperBoundExpression, inVariablePath, process ); break; case FOR: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); startBackup(); VariablePathNode leftPath; try { leftPath = parseVariablePath(); } catch( ParserException e ) { leftPath = null; } if( leftPath != null && token.isKeyword( "in" ) ) { // for( elem in path ) { ... } discardBackup(); nextToken(); VariablePathNode targetPath = parseVariablePath(); if( targetPath.path().get( targetPath.path().size() - 1 ).value() != null ) { throwException( "target in for ( elem -> array ) { ... } should be an array (cannot specify an index): " + targetPath.toPrettyString() ); } eat( Scanner.TokenType.RPAREN, "expected )" ); final OLSyntaxNode forEachBody = parseBasicStatement(); retVal = new ForEachArrayItemStatement( getContext(), leftPath, targetPath, forEachBody ); } else { // for( init, condition, post ) { ... } recoverBackup(); OLSyntaxNode init = parseProcess(); eat( Scanner.TokenType.COMMA, "expected ," ); OLSyntaxNode condition = parseExpression(); eat( Scanner.TokenType.COMMA, "expected ," ); OLSyntaxNode post = parseProcess(); eat( Scanner.TokenType.RPAREN, "expected )" ); OLSyntaxNode body = parseBasicStatement(); retVal = new ForStatement( getContext(), init, condition, post, body ); } break; case FOREACH: // foreach( k : path ) { ... } nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); final VariablePathNode keyPath = parseVariablePath(); eat( Scanner.TokenType.COLON, "expected :" ); final VariablePathNode targetPath = parseVariablePath(); eat( Scanner.TokenType.RPAREN, "expected )" ); final OLSyntaxNode forEachBody = parseBasicStatement(); retVal = new ForEachSubNodeStatement( getContext(), keyPath, targetPath, forEachBody ); break; case LINKIN: retVal = parseLinkInStatement(); break; case CURRENT_HANDLER: nextToken(); retVal = new CurrentHandlerStatement( getContext() ); break; case NULL_PROCESS: nextToken(); retVal = new NullProcessStatement( getContext() ); break; case EXIT: nextToken(); retVal = new ExitStatement( getContext() ); break; case WHILE: retVal = parseWhileStatement(); break; case LINKOUT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected link identifier" ); retVal = new LinkOutStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case LPAREN: nextToken(); retVal = parseProcess(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case LCURLY: nextToken(); retVal = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case SCOPE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected scope identifier" ); final String scopeId = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); retVal = new Scope( getContext(), scopeId, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case COMPENSATE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected scope identifier" ); retVal = new CompensateStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case THROW: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected fault identifier" ); String faultName = token.content(); nextToken(); if( token.is( Scanner.TokenType.RPAREN ) ) { retVal = new ThrowStatement( getContext(), faultName ); } else { eat( Scanner.TokenType.COMMA, "expected , or )" ); OLSyntaxNode expression = parseExpression(); /* * assertToken( Scanner.TokenType.ID, "expected variable path" ); String varId = token.content(); * nextToken(); VariablePathNode path = parseVariablePath( varId ); */ retVal = new ThrowStatement( getContext(), faultName, expression ); } eat( Scanner.TokenType.RPAREN, "expected )" ); break; case INSTALL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); Optional< InstallFunctionNode > optInstallNode = parseInstallFunction( false ); if( !optInstallNode.isPresent() ) { throwException( "expected install body" ); } retVal = new InstallStatement( getContext(), optInstallNode.get() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IF: IfStatement stm = new IfStatement( getContext() ); OLSyntaxNode cond; OLSyntaxNode node; nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); node = parseBasicStatement(); stm.addChild( new Pair<>( cond, node ) ); boolean keepRun = true; while( token.is( Scanner.TokenType.ELSE ) && keepRun ) { nextToken(); if( token.is( Scanner.TokenType.IF ) ) { // else if branch nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); node = parseBasicStatement(); stm.addChild( new Pair<>( cond, node ) ); } else { // else branch keepRun = false; stm.setElseProcess( parseBasicStatement() ); } } retVal = stm; break; case DOT: if( !inVariablePaths.isEmpty() ) { retVal = parseAssignOrDeepCopyOrPointerStatement( parsePrefixedVariablePath() ); } break; default: break; } if( throwException && retVal == null ) { throwException( "expected basic statement" ); } return retVal; } private OLSyntaxNode parseProvideUntilStatement() throws IOException, ParserException { ParsingContext context = getContext(); NDChoiceStatement provide = parseNDChoiceStatement(); if( !token.isKeyword( "until" ) ) { throwException( "expected until" ); } nextToken(); NDChoiceStatement until = parseNDChoiceStatement(); return new ProvideUntilStatement( context, provide, until ); } private OLSyntaxNode parseForwardStatement() throws IOException, ParserException { OLSyntaxNode retVal; String outputPortName = null; if( token.is( Scanner.TokenType.ID ) ) { outputPortName = token.content(); nextToken(); } VariablePathNode outputVariablePath = parseOperationVariablePathParameter(); if( token.is( Scanner.TokenType.LPAREN ) ) { // Solicit-Response VariablePathNode inputVariablePath = parseOperationVariablePathParameter(); retVal = new SolicitResponseForwardStatement( getContext(), outputPortName, outputVariablePath, inputVariablePath ); } else { // Notification retVal = new NotificationForwardStatement( getContext(), outputPortName, outputVariablePath ); } return retVal; } private Optional< InstallFunctionNode > parseInstallFunction( boolean hadNewLine ) throws IOException, ParserException { /* * Check that we're not consuming an input choice first. (This can happen for sequences separated by * spaces instead of ;.) */ if( token.is( Scanner.TokenType.ID ) ) { Scanner.Token idToken = token; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { // It's an input choice if( hadNewLine ) { addToken( new Scanner.Token( Scanner.TokenType.NEWLINE ) ); } addToken( new Scanner.Token( Scanner.TokenType.LSQUARE ) ); addToken( idToken ); addToken( token ); nextToken(); return Optional.empty(); } else { addToken( idToken ); addToken( token ); nextToken(); } } boolean backup = insideInstallFunction; insideInstallFunction = true; List< Pair< String, OLSyntaxNode > > vec = new LinkedList<>(); boolean keepRun = true; List< String > names = new ArrayList<>(); OLSyntaxNode handler; while( keepRun ) { do { if( token.is( Scanner.TokenType.THIS ) ) { names.add( null ); } else if( token.is( Scanner.TokenType.ID ) ) { names.add( token.content() ); } else { throwException( "expected fault identifier or this" ); } nextToken(); } while( token.isNot( Scanner.TokenType.ARROW ) ); nextToken(); // eat the arrow handler = parseProcess(); for( String name : names ) { vec.add( new Pair<>( name, handler ) ); } names.clear(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } insideInstallFunction = backup; return Optional.of( new InstallFunctionNode( vec.toArray( new Pair[ 0 ] ) ) ); } private OLSyntaxNode parseAssignOrDeepCopyOrPointerStatement( VariablePathNode path ) throws IOException, ParserException { OLSyntaxNode retVal = null; if( token.is( Scanner.TokenType.ASSIGN ) ) { nextToken(); retVal = new AssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.ADD_ASSIGN ) ) { nextToken(); retVal = new AddAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.MINUS_ASSIGN ) ) { nextToken(); retVal = new SubtractAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.MULTIPLY_ASSIGN ) ) { nextToken(); retVal = new MultiplyAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.DIVIDE_ASSIGN ) ) { nextToken(); retVal = new DivideAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.INCREMENT ) ) { nextToken(); retVal = new PostIncrementStatement( getContext(), path ); } else if( token.is( Scanner.TokenType.DECREMENT ) ) { nextToken(); retVal = new PostDecrementStatement( getContext(), path ); } else if( token.is( Scanner.TokenType.POINTS_TO ) ) { nextToken(); retVal = new PointerStatement( getContext(), path, parseVariablePath() ); } else if( token.is( Scanner.TokenType.DEEP_COPY_LEFT ) ) { ParsingContext context = getContext(); nextToken(); retVal = new DeepCopyStatement( context, path, parseExpression(), false ); } else if( token.is( Scanner.TokenType.DEEP_COPY_WITH_LINKS_LEFT ) ) { ParsingContext context = getContext(); nextToken(); retVal = new DeepCopyStatement( context, path, parseExpression(), true ); } else { throwException( "expected = or -> or << or -- or ++" ); } return retVal; } private VariablePathNode parseVariablePath() throws ParserException, IOException { if( token.is( Scanner.TokenType.DOT ) ) { return parsePrefixedVariablePath(); } assertIdentifier( "Expected variable path" ); String varId = token.content(); nextToken(); return _parseVariablePath( varId ); } private VariablePathNode _parseVariablePath( String varId ) throws IOException, ParserException { OLSyntaxNode expr; VariablePathNode path; switch( varId ) { case Constants.GLOBAL: path = new VariablePathNode( getContext(), Type.GLOBAL ); break; case Constants.CSETS: path = new VariablePathNode( getContext(), Type.CSET ); path.append( new Pair<>( new ConstantStringExpression( getContext(), varId ), new ConstantIntegerExpression( getContext(), 0 ) ) ); break; default: path = new VariablePathNode( getContext(), Type.NORMAL ); if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); expr = parseBasicExpression(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { expr = null; } path.append( new Pair<>( new ConstantStringExpression( getContext(), varId ), expr ) ); break; } OLSyntaxNode nodeExpr = null; while( token.is( Scanner.TokenType.DOT ) ) { nextToken(); if( token.isIdentifier() ) { nodeExpr = new ConstantStringExpression( getContext(), token.content() ); } else if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); nodeExpr = parseBasicExpression(); assertToken( Scanner.TokenType.RPAREN, "expected )" ); } else { throwException( "expected nested node identifier" ); } nextToken(); if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); expr = parseBasicExpression(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { expr = null; } path.append( new Pair<>( nodeExpr, expr ) ); } return path; } private VariablePathNode parsePrefixedVariablePath() throws IOException, ParserException { int i = inVariablePaths.size() - 1; List< Scanner.Token > tokens = new ArrayList<>(); try { tokens.addAll( inVariablePaths.get( i ) ); } catch( IndexOutOfBoundsException e ) { throwException( "Prefixed variable paths must be inside a with block" ); } while( tokens.get( 0 ).is( Scanner.TokenType.DOT ) ) { i--; tokens.addAll( 0, inVariablePaths.get( i ) ); } addTokens( tokens ); addTokens( Collections.singletonList( new Scanner.Token( Scanner.TokenType.DOT ) ) ); nextToken(); String varId = token.content(); nextToken(); return _parseVariablePath( varId ); } private CourierChoiceStatement parseCourierChoice() throws IOException, ParserException { CourierChoiceStatement stm = new CourierChoiceStatement( getContext() ); OLSyntaxNode body; InterfaceDefinition iface; String operationName; VariablePathNode inputVariablePath, outputVariablePath; while( token.is( Scanner.TokenType.LSQUARE ) ) { iface = null; operationName = null; inputVariablePath = null; outputVariablePath = null; nextToken(); if( token.isKeyword( "interface" ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected interface name" ); checkConstant(); iface = new InterfaceDefinition( getContext(), token.content() ); nextToken(); inputVariablePath = parseOperationVariablePathParameter(); if( inputVariablePath == null ) { throwException( "expected variable path" ); } if( token.is( Scanner.TokenType.LPAREN ) ) { // Request-Response outputVariablePath = parseOperationVariablePathParameter(); } } else if( token.is( Scanner.TokenType.ID ) ) { operationName = token.content(); nextToken(); inputVariablePath = parseOperationVariablePathParameter(); if( inputVariablePath == null ) { throwException( "expected variable path" ); } if( token.is( Scanner.TokenType.LPAREN ) ) { // Request-Response outputVariablePath = parseOperationVariablePathParameter(); } } else { throwException( "expected courier input guard (interface or operation name)" ); } eat( Scanner.TokenType.RSQUARE, "expected ]" ); eat( Scanner.TokenType.LCURLY, "expected {" ); body = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); if( iface == null ) { // It's an operation if( outputVariablePath == null ) { // One-Way stm.operationOneWayBranches().add( new CourierChoiceStatement.OperationOneWayBranch( operationName, inputVariablePath, body ) ); } else { // Request-Response stm.operationRequestResponseBranches() .add( new CourierChoiceStatement.OperationRequestResponseBranch( operationName, inputVariablePath, outputVariablePath, body ) ); } } else { // It's an interface if( outputVariablePath == null ) { // One-Way stm.interfaceOneWayBranches() .add( new CourierChoiceStatement.InterfaceOneWayBranch( iface, inputVariablePath, body ) ); } else { // Request-Response stm.interfaceRequestResponseBranches() .add( new CourierChoiceStatement.InterfaceRequestResponseBranch( iface, inputVariablePath, outputVariablePath, body ) ); } } } return stm; } private NDChoiceStatement parseNDChoiceStatement() throws IOException, ParserException { NDChoiceStatement stm = new NDChoiceStatement( getContext() ); OLSyntaxNode inputGuard = null; OLSyntaxNode process; while( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); // Eat [ /* * if ( token.is( Scanner.TokenType.LINKIN ) ) { inputGuard = parseLinkInStatement(); } else */if( token.is( Scanner.TokenType.ID ) ) { String id = token.content(); nextToken(); inputGuard = parseInputOperationStatement( id ); } else { throwException( "expected input guard" ); } eat( Scanner.TokenType.RSQUARE, "expected ]" ); if( token.is( Scanner.TokenType.LCURLY ) ) { eat( Scanner.TokenType.LCURLY, "expected {" ); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); } else { process = new NullProcessStatement( getContext() ); } stm.addChild( new Pair<>( inputGuard, process ) ); } return stm; } private LinkInStatement parseLinkInStatement() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected link identifier" ); LinkInStatement stm = new LinkInStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); return stm; } private OLSyntaxNode parseInputOperationStatement( String id ) throws IOException, ParserException { ParsingContext context = getContext(); VariablePathNode inputVarPath = parseOperationVariablePathParameter(); OLSyntaxNode stm; if( token.is( Scanner.TokenType.LPAREN ) ) { // Request Response operation OLSyntaxNode outputExpression = parseOperationExpressionParameter(); OLSyntaxNode process = new NullProcessStatement( getContext() ); if( token.is( Scanner.TokenType.LCURLY ) ) { // Request Response body nextToken(); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); } stm = new RequestResponseOperationStatement( context, id, inputVarPath, outputExpression, process ); } else { // One Way operation stm = new OneWayOperationStatement( context, id, inputVarPath ); } return stm; } /** * @return The VariablePath parameter of the statement. May be null. */ private VariablePathNode parseOperationVariablePathParameter() throws IOException, ParserException { VariablePathNode ret = null; eat( Scanner.TokenType.LPAREN, "expected (" ); if( token.is( Scanner.TokenType.ID ) ) { ret = parseVariablePath(); } else if( token.is( Scanner.TokenType.DOT ) ) { ret = parsePrefixedVariablePath(); } eat( Scanner.TokenType.RPAREN, "expected )" ); return ret; } private OLSyntaxNode parseOperationExpressionParameter() throws IOException, ParserException { OLSyntaxNode ret = null; eat( Scanner.TokenType.LPAREN, "expected (" ); if( token.isNot( Scanner.TokenType.RPAREN ) ) { ret = parseExpression(); } eat( Scanner.TokenType.RPAREN, "expected )" ); return ret; } private OLSyntaxNode parseOutputOperationStatement( String id ) throws IOException, ParserException { ParsingContext context = getContext(); String outputPortId = token.content(); nextToken(); OLSyntaxNode outputExpression = parseOperationExpressionParameter(); OLSyntaxNode stm; if( token.is( Scanner.TokenType.LPAREN ) ) { // Solicit Response operation VariablePathNode inputVarPath = parseOperationVariablePathParameter(); Optional< InstallFunctionNode > function = Optional.empty(); if( token.is( Scanner.TokenType.LSQUARE ) ) { boolean newLine = hasMetNewline(); eat( Scanner.TokenType.LSQUARE, "expected [" ); function = parseInstallFunction( newLine ); if( function.isPresent() ) { eat( Scanner.TokenType.RSQUARE, "expected ]" ); } } stm = new SolicitResponseOperationStatement( context, id, outputPortId, outputExpression, inputVarPath, function ); } else { // Notification operation stm = new NotificationOperationStatement( context, id, outputPortId, outputExpression ); } return stm; } private OLSyntaxNode parseWhileStatement() throws IOException, ParserException { ParsingContext context = getContext(); OLSyntaxNode cond, process; nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); return new WhileStatement( context, cond, process ); } private OLSyntaxNode parseExpression() throws IOException, ParserException { OrConditionNode orCond = new OrConditionNode( getContext() ); orCond.addChild( parseAndCondition() ); while( token.is( Scanner.TokenType.OR ) ) { nextToken(); orCond.addChild( parseAndCondition() ); } return orCond; } private OLSyntaxNode parseAndCondition() throws IOException, ParserException { AndConditionNode andCond = new AndConditionNode( getContext() ); andCond.addChild( parseBasicCondition() ); while( token.is( Scanner.TokenType.AND ) ) { nextToken(); andCond.addChild( parseBasicCondition() ); } return andCond; } private NativeType readNativeType() { if( token.is( Scanner.TokenType.CAST_INT ) ) { return NativeType.INT; } else if( token.is( Scanner.TokenType.CAST_DOUBLE ) ) { return NativeType.DOUBLE; } else if( token.is( Scanner.TokenType.CAST_STRING ) ) { return NativeType.STRING; } else if( token.is( Scanner.TokenType.CAST_LONG ) ) { return NativeType.LONG; } else if( token.is( Scanner.TokenType.CAST_BOOL ) ) { return NativeType.BOOL; } else { return NativeType.fromString( token.content() ); } } private OLSyntaxNode parseBasicCondition() throws IOException, ParserException { OLSyntaxNode ret; Scanner.TokenType opType; OLSyntaxNode expr1; expr1 = parseBasicExpression(); opType = token.type(); if( opType == Scanner.TokenType.EQUAL || opType == Scanner.TokenType.LANGLE || opType == Scanner.TokenType.RANGLE || opType == Scanner.TokenType.MAJOR_OR_EQUAL || opType == Scanner.TokenType.MINOR_OR_EQUAL || opType == Scanner.TokenType.NOT_EQUAL ) { OLSyntaxNode expr2; nextToken(); expr2 = parseBasicExpression(); ret = new CompareConditionNode( getContext(), expr1, expr2, opType ); } else if( opType == Scanner.TokenType.INSTANCE_OF ) { nextToken(); NativeType nativeType = readNativeType(); if( nativeType == null ) { // It's a user-defined type assertToken( Scanner.TokenType.ID, "expected type name after instanceof" ); } String typeName = token.content(); TypeDefinition type = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); ret = new InstanceOfExpressionNode( getContext(), expr1, type ); nextToken(); } else { ret = expr1; } if( ret == null ) { throwException( "expected condition" ); } return ret; } /* * todo: Check if negative integer handling is appropriate */ private OLSyntaxNode parseBasicExpression() throws IOException, ParserException { boolean keepRun = true; SumExpressionNode sum = new SumExpressionNode( getContext() ); sum.add( parseProductExpression() ); while( keepRun ) { if( token.is( Scanner.TokenType.PLUS ) ) { nextToken(); sum.add( parseProductExpression() ); } else if( token.is( Scanner.TokenType.MINUS ) ) { nextToken(); sum.subtract( parseProductExpression() ); } else if( token.is( Scanner.TokenType.INT ) ) { // e.g. i -1 int value = Integer.parseInt( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else if( token.is( Scanner.TokenType.LONG ) ) { // e.g. i -1L long value = Long.parseLong( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else if( token.is( Scanner.TokenType.DOUBLE ) ) { // e.g. i -1 double value = Double.parseDouble( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else { keepRun = false; } } return sum; } private OLSyntaxNode parseFactor() throws IOException, ParserException { OLSyntaxNode retVal = null; VariablePathNode path = null; checkConstant(); switch( token.type() ) { case ID: path = parseVariablePath(); VariablePathNode freshValuePath = new VariablePathNode( getContext(), Type.NORMAL ); freshValuePath.append( new Pair<>( new ConstantStringExpression( getContext(), "new" ), new ConstantIntegerExpression( getContext(), 0 ) ) ); if( path.isEquivalentTo( freshValuePath ) ) { retVal = new FreshValueExpressionNode( path.context() ); return retVal; } break; case DOT: path = parseVariablePath(); break; case CARET: if( insideInstallFunction ) { nextToken(); path = parseVariablePath(); retVal = new InstallFixedVariableExpressionNode( getContext(), path ); return retVal; } break; default: break; } if( path != null ) { switch( token.type() ) { case INCREMENT: nextToken(); retVal = new PostIncrementStatement( getContext(), path ); break; case DECREMENT: nextToken(); retVal = new PostDecrementStatement( getContext(), path ); break; case ASSIGN: nextToken(); retVal = new AssignStatement( getContext(), path, parseExpression() ); break; default: retVal = new VariableExpressionNode( getContext(), path ); break; } } else { switch( token.type() ) { case NOT: nextToken(); retVal = new NotExpressionNode( getContext(), parseFactor() ); break; case STRING: retVal = new ConstantStringExpression( getContext(), token.content() ); nextToken(); break; case INT: retVal = new ConstantIntegerExpression( getContext(), Integer.parseInt( token.content() ) ); nextToken(); break; case LONG: retVal = new ConstantLongExpression( getContext(), Long.parseLong( token.content() ) ); nextToken(); break; case TRUE: retVal = new ConstantBoolExpression( getContext(), true ); nextToken(); break; case FALSE: retVal = new ConstantBoolExpression( getContext(), false ); nextToken(); break; case DOUBLE: retVal = new ConstantDoubleExpression( getContext(), Double.parseDouble( token.content() ) ); nextToken(); break; case LPAREN: nextToken(); retVal = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case HASH: nextToken(); retVal = new ValueVectorSizeExpressionNode( getContext(), parseVariablePath() ); break; case INCREMENT: nextToken(); retVal = new PreIncrementStatement( getContext(), parseVariablePath() ); break; case DECREMENT: nextToken(); retVal = new PreDecrementStatement( getContext(), parseVariablePath() ); break; case IS_DEFINED: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.DEFINED, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_INT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.INT, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_DOUBLE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.DOUBLE, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_BOOL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.BOOL, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_LONG: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.LONG, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_STRING: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.STRING, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_INT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.INT, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_LONG: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.LONG, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_BOOL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.BOOL, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_DOUBLE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.DOUBLE, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_STRING: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.STRING, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; default: break; } } if( retVal == null ) { if( token.is( Scanner.TokenType.LCURLY ) ) { retVal = new VoidExpressionNode( getContext() ); } else { throwException( "expected expression" ); } } if( token.is( Scanner.TokenType.LCURLY ) ) { retVal = parseInlineTreeExpression( retVal ); } return retVal; } private OLSyntaxNode parseInlineTreeExpression( OLSyntaxNode rootExpression ) throws IOException, ParserException { eat( Scanner.TokenType.LCURLY, "expected {" ); VariablePathNode path; List< InlineTreeExpressionNode.Operation > operations = new ArrayList<>(); while( !token.is( Scanner.TokenType.RCURLY ) ) { maybeEat( Scanner.TokenType.DOT ); path = parseVariablePath(); InlineTreeExpressionNode.Operation operation = null; switch( token.type() ) { case DEEP_COPY_LEFT: nextToken(); operation = new InlineTreeExpressionNode.DeepCopyOperation( path, parseExpression() ); break; case ASSIGN: nextToken(); operation = new InlineTreeExpressionNode.AssignmentOperation( path, parseExpression() ); break; case POINTS_TO: nextToken(); operation = new InlineTreeExpressionNode.PointsToOperation( path, parseVariablePath() ); break; default: throwException( "expected =, <<, or ->" ); break; } operations.add( operation ); maybeEat( Scanner.TokenType.COMMA, Scanner.TokenType.SEQUENCE ); } eat( Scanner.TokenType.RCURLY, "expected }" ); return new InlineTreeExpressionNode( rootExpression.context(), rootExpression, operations.toArray( new InlineTreeExpressionNode.Operation[ 0 ] ) ); } private OLSyntaxNode parseProductExpression() throws IOException, ParserException { ProductExpressionNode product = new ProductExpressionNode( getContext() ); product.multiply( parseFactor() ); boolean keepRun = true; while( keepRun ) { switch( token.type() ) { case ASTERISK: nextToken(); product.multiply( parseFactor() ); break; case DIVIDE: nextToken(); product.divide( parseFactor() ); break; case PERCENT_SIGN: nextToken(); product.modulo( parseFactor() ); break; default: keepRun = false; break; } } return product; } private enum ExtendedIdentifierState { CAN_READ_ID, CANNOT_READ_ID, STOP } private String parseExtendedIdentifier( String errorMessage, Scanner.TokenType... extensions ) throws IOException, ParserException { List< String > importTargetComponents = new ArrayList<>(); ExtendedIdentifierState state = ExtendedIdentifierState.CAN_READ_ID; while( state != ExtendedIdentifierState.STOP ) { if( state == ExtendedIdentifierState.CAN_READ_ID && token.isIdentifier() ) { importTargetComponents.add( token.content() ); nextToken(); state = ExtendedIdentifierState.CANNOT_READ_ID; } else if( Arrays.stream( extensions ).anyMatch( extension -> token.is( extension ) ) ) { importTargetComponents.add( token.content() ); nextToken(); state = ExtendedIdentifierState.CAN_READ_ID; } else { state = ExtendedIdentifierState.STOP; } } String id = importTargetComponents.stream().collect( Collectors.joining() ); if( id.isEmpty() ) { throwException( errorMessage ); } return id; } private void parseImport() throws IOException, ParserException { if( token.is( Scanner.TokenType.FROM ) ) { ParsingContext context = getContext(); boolean isNamespaceImport = false; nextToken(); List< String > importTargets = new ArrayList<>(); boolean importTargetIDStarted = false; List< Pair< String, String > > pathNodes = null; boolean keepRun = true; do { if( token.is( Scanner.TokenType.IMPORT ) ) { keepRun = false; nextToken(); } else if( token.is( Scanner.TokenType.DOT ) ) { if( !importTargetIDStarted ) { importTargets.add( token.content() ); } nextToken(); } else { importTargets.add( parseExtendedIdentifier( "expected identifier for importing target after from", Scanner.TokenType.MINUS, Scanner.TokenType.AT ) ); importTargetIDStarted = true; // nextToken(); } } while( keepRun ); if( token.is( Scanner.TokenType.ASTERISK ) ) { isNamespaceImport = true; nextToken(); } else { assertIdentifier( "expected Identifier or * after import" ); pathNodes = new ArrayList<>(); keepRun = false; do { String targetName = token.content(); String localName = targetName; nextToken(); if( token.is( Scanner.TokenType.AS ) ) { nextToken(); assertIdentifier( "expected Identifier after as" ); localName = token.content(); nextToken(); } pathNodes.add( new Pair< String, String >( targetName, localName ) ); if( token.is( Scanner.TokenType.COMMA ) ) { keepRun = true; nextToken(); } else { keepRun = false; } } while( keepRun ); } ImportStatement stmt = null; if( isNamespaceImport ) { stmt = new ImportStatement( context, Collections.unmodifiableList( importTargets ) ); } else { stmt = new ImportStatement( context, Collections.unmodifiableList( importTargets ), Collections.unmodifiableList( pathNodes ) ); } programBuilder.addChild( stmt ); return; } } private static class IncludeFile { private final InputStream inputStream; private final String parentPath; private final URI uri; private IncludeFile( InputStream inputStream, String parentPath, URI uri ) { this.inputStream = inputStream; this.parentPath = parentPath; this.uri = uri; } private InputStream getInputStream() { return inputStream; } private String getParentPath() { return parentPath; } private URI getURI() { return uri; } } }
libjolie/src/main/java/jolie/lang/parse/OLParser.java
/* * Copyright (C) 2006-2021 Fabrizio Montesi <famontesi@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package jolie.lang.parse; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import jolie.lang.Constants; import jolie.lang.Constants.EmbeddedServiceType; import jolie.lang.NativeType; import jolie.lang.parse.ast.AddAssignStatement; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationVariableInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.DivideAssignStatement; import jolie.lang.parse.ast.EmbedServiceNode; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ForEachArrayItemStatement; import jolie.lang.parse.ast.ForEachSubNodeStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.ImportStatement; import jolie.lang.parse.ast.ImportableSymbol.AccessModifier; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallFunctionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.InterfaceExtenderDefinition; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.MultiplyAssignStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationCollector; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PortInfo; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.ProvideUntilStatement; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.ServiceNode; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SubtractAssignStatement; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.VariablePathNode.Type; import jolie.lang.parse.ast.WhileStatement; import jolie.lang.parse.ast.courier.CourierChoiceStatement; import jolie.lang.parse.ast.courier.CourierDefinitionNode; import jolie.lang.parse.ast.courier.NotificationForwardStatement; import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement; import jolie.lang.parse.ast.expression.AndConditionNode; import jolie.lang.parse.ast.expression.ConstantBoolExpression; import jolie.lang.parse.ast.expression.ConstantDoubleExpression; import jolie.lang.parse.ast.expression.ConstantIntegerExpression; import jolie.lang.parse.ast.expression.ConstantLongExpression; import jolie.lang.parse.ast.expression.ConstantStringExpression; import jolie.lang.parse.ast.expression.FreshValueExpressionNode; import jolie.lang.parse.ast.expression.InlineTreeExpressionNode; import jolie.lang.parse.ast.expression.InstanceOfExpressionNode; import jolie.lang.parse.ast.expression.IsTypeExpressionNode; import jolie.lang.parse.ast.expression.NotExpressionNode; import jolie.lang.parse.ast.expression.OrConditionNode; import jolie.lang.parse.ast.expression.ProductExpressionNode; import jolie.lang.parse.ast.expression.SumExpressionNode; import jolie.lang.parse.ast.expression.VariableExpressionNode; import jolie.lang.parse.ast.expression.VoidExpressionNode; import jolie.lang.parse.ast.types.BasicTypeDefinition; import jolie.lang.parse.ast.types.TypeChoiceDefinition; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeDefinitionUndefined; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinement; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementDoubleRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementIntegerRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementLongRanges; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringLength; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringList; import jolie.lang.parse.ast.types.refinements.BasicTypeRefinementStringRegex; import jolie.lang.parse.context.ParsingContext; import jolie.lang.parse.context.URIParsingContext; import jolie.lang.parse.util.ProgramBuilder; import jolie.util.Helpers; import jolie.util.Pair; import jolie.util.Range; import jolie.util.UriUtils; /** * Parser for a .ol file. * * @author Fabrizio Montesi * */ public class OLParser extends AbstractParser { private interface ParsingRunnable { void parse() throws IOException, ParserException; } private long faultIdCounter = 0; private final ProgramBuilder programBuilder; private final Map< String, Scanner.Token > constantsMap = new HashMap<>(); private boolean insideInstallFunction = false; private String[] includePaths; private boolean hasIncludeDirective = false; private final Map< String, InterfaceExtenderDefinition > interfaceExtenders = new HashMap<>(); private final Map< String, TypeDefinition > definedTypes; private final ClassLoader classLoader; private InterfaceExtenderDefinition currInterfaceExtender = null; private static enum RefinementPredicates { LENGTH, ENUM, RANGES, REGEX } private static final Map< String, OLParser.RefinementPredicates > BASIC_TYPE_REFINED_PREDICATES = new HashMap<>(); static { BASIC_TYPE_REFINED_PREDICATES.put( "length", RefinementPredicates.LENGTH ); // defines the minimum and the // maximum // length of a string BASIC_TYPE_REFINED_PREDICATES.put( "regex", RefinementPredicates.REGEX ); // defines the regex for a string BASIC_TYPE_REFINED_PREDICATES.put( "enum", RefinementPredicates.ENUM ); // defines a list of string that a // string // can be BASIC_TYPE_REFINED_PREDICATES.put( "ranges", RefinementPredicates.RANGES ); // it defines a list of intervals // where // an int | long | double can be } public OLParser( Scanner scanner, String[] includePaths, ClassLoader classLoader ) { super( scanner ); final ParsingContext context = new URIParsingContext( scanner.source(), 0 ); this.programBuilder = new ProgramBuilder( context ); this.includePaths = includePaths; this.classLoader = classLoader; this.definedTypes = createTypeDeclarationMap( context ); } public void putConstants( Map< String, Scanner.Token > constantsToPut ) { constantsMap.putAll( constantsToPut ); } public static Map< String, TypeDefinition > createTypeDeclarationMap( ParsingContext context ) { Map< String, TypeDefinition > definedTypes = new HashMap<>(); // Fill in defineTypes with all the supported native types (string, int, double, ...) for( NativeType type : NativeType.values() ) { definedTypes.put( type.id(), new TypeInlineDefinition( context, type.id(), BasicTypeDefinition.of( type ), Constants.RANGE_ONE_TO_ONE ) ); } definedTypes.put( TypeDefinitionUndefined.UNDEFINED_KEYWORD, TypeDefinitionUndefined.getInstance() ); return definedTypes; } public Program parse() throws IOException, ParserException { _parse(); if( initSequence != null ) { programBuilder.addChild( new DefinitionNode( getContext(), "init", initSequence ) ); } if( main != null ) { programBuilder.addChild( main ); } if( !programBuilder.isJolieModuleSystem() && main != null ) { programBuilder.transformProgramToModuleSystem(); } else if( hasIncludeDirective ) { // [backward-compatibility] for include directive, remove Deployment Instructions which was added // during include file parsing process programBuilder.removeModuleScopeDeploymentInstructions(); } return programBuilder.toProgram(); } private void parseLoop( ParsingRunnable... parseRunnables ) throws IOException, ParserException { nextToken(); if( token.is( Scanner.TokenType.HASH ) ) { // Shebang scripting scanner().readLine(); nextToken(); } Scanner.Token t; do { t = token; for( ParsingRunnable runnable : parseRunnables ) { parseInclude(); runnable.parse(); } } while( t != token ); // Loop until no procedures can eat the initial token if( t.isNot( Scanner.TokenType.EOF ) ) { throwException( "Invalid token encountered" ); } } private void _parse() throws IOException, ParserException { parseLoop( this::parseImport, this::parseConstants, this::parseExecution, this::parseCorrelationSets, this::parseTypes, this::parseInterface, this::parsePort, this::parseEmbedded, this::parseService, this::parseCode ); } private void parseTypes() throws IOException, ParserException { Scanner.Token commentToken = null; Scanner.Token accessModToken = null; boolean keepRun = true; boolean haveComment = false; boolean haveAccessModToken = false; while( keepRun ) { if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { haveComment = true; commentToken = token; nextToken(); } else if( token.is( Scanner.TokenType.PRIVATE ) || token.is( Scanner.TokenType.PUBLIC ) ) { haveAccessModToken = true; accessModToken = token; nextToken(); } else if( token.isKeyword( "type" ) ) { AccessModifier accessModifier = (accessModToken != null && accessModToken.is( Scanner.TokenType.PRIVATE )) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; String typeName; TypeDefinition currentType; nextToken(); typeName = token.content(); eat( Scanner.TokenType.ID, "expected type name" ); if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else { prependToken( new Scanner.Token( Scanner.TokenType.ID, NativeType.VOID.id() ) ); nextToken(); } currentType = parseType( typeName, accessModifier ); if( haveComment ) { haveComment = false; } parseBackwardAndSetDocumentation( currentType, Optional.ofNullable( commentToken ) ); commentToken = null; typeName = currentType.name(); definedTypes.put( typeName, currentType ); programBuilder.addChild( currentType ); } else { keepRun = false; if( haveComment ) { // we return the comment and the subsequent token since we did not use them addToken( commentToken ); addToken( token ); nextToken(); } if( haveAccessModToken ) { addToken( accessModToken ); addToken( token ); nextToken(); } } } } private TypeDefinition parseType( String typeName, AccessModifier accessModifier ) throws IOException, ParserException { TypeDefinition currentType; BasicTypeDefinition basicTypeDefinition = readBasicType(); if( basicTypeDefinition == null ) { // It's a user-defined type currentType = new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, token.content() ); nextToken(); } else { currentType = new TypeInlineDefinition( getContext(), typeName, basicTypeDefinition, Constants.RANGE_ONE_TO_ONE ); if( token.is( Scanner.TokenType.LCURLY ) ) { // We have sub-types to parse parseSubTypes( (TypeInlineDefinition) currentType ); } } if( token.is( Scanner.TokenType.PARALLEL ) ) { // It's a sum (union, choice) type nextToken(); final TypeDefinition secondType = parseType( typeName, accessModifier ); return new TypeChoiceDefinition( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, currentType, secondType ); } return currentType; } private void parseSubTypes( TypeInlineDefinition type ) throws IOException, ParserException { eat( Scanner.TokenType.LCURLY, "expected {" ); Optional< Scanner.Token > commentToken = Optional.empty(); boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = Optional.of( token ); nextToken(); } else if( token.is( Scanner.TokenType.QUESTION_MARK ) ) { type.setUntypedSubTypes( true ); nextToken(); } else { TypeDefinition currentSubType; while( !token.is( Scanner.TokenType.RCURLY ) ) { if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = Optional.of( token ); nextToken(); } else { if( token.is( Scanner.TokenType.DOT ) ) { if( hasMetNewline() ) { nextToken(); } else { throwException( "the dot prefix operator for type nodes is allowed only after a newline" ); } } // SubType id String id = token.content(); if( token.is( Scanner.TokenType.STRING ) ) { nextToken(); } else { eatIdentifier( "expected type node name" ); } Range cardinality = parseCardinality(); if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else { prependToken( new Scanner.Token( Scanner.TokenType.ID, NativeType.VOID.id() ) ); nextToken(); } currentSubType = parseSubType( id, cardinality ); parseBackwardAndSetDocumentation( currentSubType, commentToken ); commentToken = Optional.empty(); if( type.hasSubType( currentSubType.name() ) ) { throwException( "sub-type " + currentSubType.name() + " conflicts with another sub-type with the same name" ); } type.putSubType( currentSubType ); } } keepRun = false; // if ( haveComment ) { // addToken( commentToken ); // addToken( token ); // nextToken(); // } } } eat( Scanner.TokenType.RCURLY, "RCURLY expected" ); } private TypeDefinition parseSubType( String id, Range cardinality ) throws IOException, ParserException { String currentTokenContent = token.content(); TypeDefinition subType; // SubType id BasicTypeDefinition basicTypeDefinition = readBasicType(); if( basicTypeDefinition == null ) { // It's a user-defined type subType = new TypeDefinitionLink( getContext(), id, cardinality, currentTokenContent ); nextToken(); } else { subType = new TypeInlineDefinition( getContext(), id, basicTypeDefinition, cardinality ); Optional< Scanner.Token > commentToken = Optional.empty(); if( token.is( Scanner.TokenType.DOCUMENTATION_BACKWARD ) ) { commentToken = Optional.of( token ); nextToken(); } if( token.is( Scanner.TokenType.LCURLY ) ) { // Has ulterior sub-types parseSubTypes( (TypeInlineDefinition) subType ); } if( commentToken.isPresent() ) { // we return the backward comment token and the eaten one, to be parsed by // the super type addToken( commentToken.get() ); addToken( new Scanner.Token( Scanner.TokenType.NEWLINE ) ); addToken( token ); nextToken(); } } if( token.is( Scanner.TokenType.PARALLEL ) ) { nextToken(); TypeDefinition secondSubType = parseSubType( id, cardinality ); return new TypeChoiceDefinition( getContext(), id, cardinality, subType, secondSubType ); } return subType; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Integer > parseListOfInteger( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Integer > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.INT && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type integer, found " + token.content() ); } if( token.type() == Scanner.TokenType.INT ) { arrayList.add( Integer.valueOf( token.content() ) ); } else { arrayList.add( Integer.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< String > parseListOfString( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< String > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.STRING ) { throwException( "Expected a parameter of type string, found " + token.content() ); } arrayList.add( token.content().replaceAll( "\"", "" ) ); nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Double > parseListOfDouble( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Double > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.DOUBLE && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type string, found " + token.content() ); } if( token.type() == Scanner.TokenType.DOUBLE ) { arrayList.add( Double.valueOf( token.content() ) ); } else { arrayList.add( Double.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } /* * set maxNumberOfParameters = null to unbound the list */ private ArrayList< Long > parseListOfLong( Integer minNumberOfParameters, Integer maxNumberOfParameters, String predicate ) throws IOException, ParserException { ArrayList< Long > arrayList = new ArrayList<>(); eat( Scanner.TokenType.LSQUARE, "a list of parameters is expected" ); while( token.type() != Scanner.TokenType.RSQUARE ) { if( token.type() != Scanner.TokenType.LONG && token.type() != Scanner.TokenType.ASTERISK ) { throwException( "Expected a parameter of type string, found " + token.content() ); } if( token.type() == Scanner.TokenType.LONG ) { arrayList.add( Long.valueOf( token.content() ) ); } else { arrayList.add( Long.MAX_VALUE ); } nextToken(); if( token.type() == Scanner.TokenType.COMMA ) { nextToken(); } } eat( Scanner.TokenType.RSQUARE, "] expected" ); if( arrayList.size() < minNumberOfParameters ) { throwException( "Expected minimum number of parameters for predicate " + predicate + ", " + minNumberOfParameters ); } if( maxNumberOfParameters != null && arrayList.size() > maxNumberOfParameters ) { throwException( "Expected maximum number of parameters for predicate " + predicate + ", " + maxNumberOfParameters ); } return arrayList; } private BasicTypeDefinition readBasicType() throws IOException, ParserException { List< BasicTypeRefinement< ? > > basicTypeRefinementList = new ArrayList<>(); if( token.is( Scanner.TokenType.CAST_INT ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementIntegerRanges basicTypeRefinementIntegerRanges = new BasicTypeRefinementIntegerRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Integer > parametersInterval = parseListOfInteger( 2, 2, predicate ); basicTypeRefinementIntegerRanges .addInterval( new BasicTypeRefinementIntegerRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementIntegerRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.INT, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_DOUBLE ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementDoubleRanges basicTypeRefinementDoubleRanges = new BasicTypeRefinementDoubleRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Double > parametersInterval = parseListOfDouble( 2, 2, predicate ); basicTypeRefinementDoubleRanges .addInterval( new BasicTypeRefinementDoubleRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementDoubleRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.DOUBLE, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_STRING ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); eat( Scanner.TokenType.LPAREN, "( expected" ); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case LENGTH: ArrayList< Integer > parametersLength = parseListOfInteger( 2, 2, predicate ); BasicTypeRefinementStringLength basicTypeRefinementStringLength = new BasicTypeRefinementStringLength( parametersLength.get( 0 ), parametersLength.get( 1 ) ); basicTypeRefinementList.add( basicTypeRefinementStringLength ); break; case ENUM: ArrayList< String > parametersList = parseListOfString( 1, null, predicate ); BasicTypeRefinementStringList basicTypeRefinementStringList = new BasicTypeRefinementStringList( parametersList ); basicTypeRefinementList.add( basicTypeRefinementStringList ); break; case REGEX: assertToken( Scanner.TokenType.STRING, "Expected regex string for predicate " + predicate ); basicTypeRefinementList.add( new BasicTypeRefinementStringRegex( token.content() ) ); nextToken(); break; default: throwException( "Basic type refinement predicate " + predicate + " not supported for string" ); } } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.STRING, basicTypeRefinementList ); } else if( token.is( Scanner.TokenType.CAST_LONG ) ) { nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); while( token.type() != Scanner.TokenType.RPAREN ) { if( !token.type().equals( Scanner.TokenType.ID ) ) { throwException( "Basic type Refinement predicate expected" ); } String predicate = token.content(); nextToken(); if( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) != null ) { eat( Scanner.TokenType.LPAREN, "( expected" ); switch( BASIC_TYPE_REFINED_PREDICATES.get( predicate ) ) { case RANGES: BasicTypeRefinementLongRanges basicTypeRefinementLongRanges = new BasicTypeRefinementLongRanges(); while( token.type() != Scanner.TokenType.RPAREN ) { ArrayList< Long > parametersInterval = parseListOfLong( 2, 2, predicate ); basicTypeRefinementLongRanges .addInterval( new BasicTypeRefinementLongRanges.Interval( parametersInterval.get( 0 ), parametersInterval.get( 1 ) ) ); if( token.type() == Scanner.TokenType.COMMA ) { eat( Scanner.TokenType.COMMA, "" ); } else if( token.type() != Scanner.TokenType.RPAREN ) { throwException( ", expected" ); } } basicTypeRefinementList.add( basicTypeRefinementLongRanges ); break; default: throwException( "Basic type Refinement predicate " + predicate + " not supported for int" ); } eat( Scanner.TokenType.RPAREN, ") expected" ); } else { StringBuilder supportedList = new StringBuilder().append( " " ); BASIC_TYPE_REFINED_PREDICATES.keySet().stream() .forEach( s -> supportedList.append( s ).append( " " ) ); throwException( "Basic type Refinement predicate not supported. Supported list [" + supportedList + "], found " + predicate ); } } eat( Scanner.TokenType.RPAREN, ") expected" ); } return BasicTypeDefinition.of( NativeType.LONG, basicTypeRefinementList ); } else { NativeType nativeType = NativeType.fromString( token.content() ); if( nativeType == null ) { return null; } nextToken(); return BasicTypeDefinition.of( nativeType ); } } private Range parseCardinality() throws IOException, ParserException { final int min; final int max; if( token.is( Scanner.TokenType.QUESTION_MARK ) ) { min = 0; max = 1; nextToken(); } else if( token.is( Scanner.TokenType.ASTERISK ) ) { min = 0; max = Integer.MAX_VALUE; nextToken(); } else if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); // eat [ // Minimum assertToken( Scanner.TokenType.INT, "expected int value" ); min = Integer.parseInt( token.content() ); if( min < 0 ) { throwException( "Minimum number of occurrences of a sub-type must be positive or zero" ); } nextToken(); eat( Scanner.TokenType.COMMA, "expected comma separator" ); // Maximum if( token.is( Scanner.TokenType.INT ) ) { max = Integer.parseInt( token.content() ); if( max < 1 ) { throwException( "Maximum number of occurrences of a sub-type must be positive" ); } } else if( token.is( Scanner.TokenType.ASTERISK ) ) { max = Integer.MAX_VALUE; } else { max = -1; throwException( "Maximum number of sub-type occurrences not valid: " + token.content() ); } nextToken(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { // Default (no cardinality specified) min = 1; max = 1; } return new Range( min, max ); } private EmbedServiceNode parseEmbeddedServiceNode() throws IOException, ParserException { nextToken(); String serviceName = token.content(); OutputPortInfo bindingPort = null; boolean hasNewKeyword = false; OLSyntaxNode passingParam = null; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); if( !token.is( Scanner.TokenType.RPAREN ) ) { passingParam = parseBasicExpression(); } eat( Scanner.TokenType.RPAREN, "expected )" ); } if( token.is( Scanner.TokenType.AS ) ) { nextToken(); hasNewKeyword = true; assertToken( Scanner.TokenType.ID, "expected output port name" ); bindingPort = new OutputPortInfo( getContext(), token.content() ); nextToken(); } else if( token.isKeyword( "in" ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected output port name" ); bindingPort = new OutputPortInfo( getContext(), token.content() ); nextToken(); } return new EmbedServiceNode( getContext(), serviceName, bindingPort, hasNewKeyword, passingParam ); } private void parseEmbedded() throws IOException, ParserException { if( token.isKeyword( "embedded" ) ) { String servicePath, portId; nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; Constants.EmbeddedServiceType type; while( keepRun ) { type = null; if( token.isKeyword( "Java" ) ) { type = Constants.EmbeddedServiceType.JAVA; } else if( token.isKeyword( "Jolie" ) ) { type = Constants.EmbeddedServiceType.JOLIE; } else if( token.isKeyword( "JavaScript" ) ) { type = Constants.EmbeddedServiceType.JAVASCRIPT; } if( type == null ) { keepRun = false; } else { nextToken(); eat( Scanner.TokenType.COLON, "expected : after embedded service type" ); checkConstant(); while( token.is( Scanner.TokenType.STRING ) ) { servicePath = token.content(); nextToken(); if( token.isKeyword( "in" ) ) { eatKeyword( "in", "expected in" ); assertToken( Scanner.TokenType.ID, "expected output port name" ); portId = token.content(); nextToken(); } else { portId = null; } programBuilder.addChild( new EmbeddedServiceNode( getContext(), type, servicePath, portId ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } } } eat( Scanner.TokenType.RCURLY, "expected }" ); } } private void parseCorrelationSets() throws IOException, ParserException { if( token.isKeyword( "cset" ) ) { for( CorrelationSetInfo csetInfo : _parseCorrelationSets() ) { programBuilder.addChild( csetInfo ); } } } private CorrelationSetInfo[] _parseCorrelationSets() throws IOException, ParserException { List< CorrelationSetInfo > result = new ArrayList<>(); while( token.isKeyword( "cset" ) ) { nextToken(); /* * assertToken( Scanner.TokenType.ID, "expected correlation set name" ); String csetName = * token.content(); nextToken(); */ eat( Scanner.TokenType.LCURLY, "expected {" ); List< CorrelationVariableInfo > variables = new LinkedList<>(); List< CorrelationAliasInfo > aliases; VariablePathNode correlationVariablePath; String typeName; while( token.is( Scanner.TokenType.ID ) ) { aliases = new LinkedList<>(); correlationVariablePath = parseVariablePath(); eat( Scanner.TokenType.COLON, "expected correlation variable alias list" ); assertToken( Scanner.TokenType.ID, "expected correlation variable alias" ); while( token.is( Scanner.TokenType.ID ) ) { typeName = token.content(); nextToken(); eat( Scanner.TokenType.DOT, "expected . after message type name in correlation alias" ); TypeDefinition aliasType = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); aliases.add( new CorrelationAliasInfo( aliasType, parseVariablePath() ) ); } variables.add( new CorrelationVariableInfo( correlationVariablePath, aliases ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } result.add( new CorrelationSetInfo( getContext(), variables ) ); eat( Scanner.TokenType.RCURLY, "expected }" ); } return result.toArray( new CorrelationSetInfo[ 0 ] ); } private void parseExecution() throws IOException, ParserException { if( token.is( Scanner.TokenType.EXECUTION ) ) { programBuilder.addChild( _parseExecutionInfo() ); } } private ExecutionInfo _parseExecutionInfo() throws IOException, ParserException { Constants.ExecutionMode mode = Constants.ExecutionMode.SEQUENTIAL; nextToken(); boolean inCurlyBrackets = false; if( token.is( Scanner.TokenType.COLON ) ) { nextToken(); } else if( token.is( Scanner.TokenType.LCURLY ) ) { inCurlyBrackets = true; nextToken(); } else { throwException( "expected : or { after execution" ); } assertToken( Scanner.TokenType.ID, "expected execution modality" ); switch( token.content() ) { case "sequential": mode = Constants.ExecutionMode.SEQUENTIAL; break; case "concurrent": mode = Constants.ExecutionMode.CONCURRENT; break; case "single": mode = Constants.ExecutionMode.SINGLE; break; default: throwException( "Expected execution mode, found " + token.content() ); break; } nextToken(); if( inCurlyBrackets ) { eat( Scanner.TokenType.RCURLY, "} expected" ); } return new ExecutionInfo( getContext(), mode ); } private void parseConstants() throws IOException, ParserException { if( token.is( Scanner.TokenType.CONSTANTS ) ) { nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; while( token.is( Scanner.TokenType.ID ) && keepRun ) { String cId = token.content(); nextToken(); eat( Scanner.TokenType.ASSIGN, "expected =" ); if( token.isValidConstant() == false ) { throwException( "expected string, integer, double or identifier constant" ); } if( constantsMap.containsKey( cId ) == false ) { constantsMap.put( cId, token ); } nextToken(); if( token.isNot( Scanner.TokenType.COMMA ) ) { keepRun = false; } else { nextToken(); } } eat( Scanner.TokenType.RCURLY, "expected }" ); } } private URL guessIncludeFilepath( String urlStr, String filename, String path ) { try { if( urlStr.startsWith( "jap:" ) || urlStr.startsWith( "jar:" ) ) { // Try hard to resolve names, even in Windows if( filename.startsWith( "../" ) ) { String tmpPath = path; String tmpFilename = filename; if( !tmpPath.contains( "/" ) && tmpPath.contains( "\\" ) ) { // Windows only tmpPath = tmpPath.replace( "\\", "/" ); } while( tmpFilename.startsWith( "../" ) ) { tmpFilename = tmpFilename.substring( 2 ); if( tmpPath.endsWith( "/" ) ) { tmpPath = tmpPath.substring( 0, tmpPath.length() - 1 ); } tmpPath = tmpPath.substring( 0, tmpPath.lastIndexOf( "/" ) ); } String tmpUrl = build( tmpPath, tmpFilename ); try { return new URL( tmpUrl.substring( 0, 4 ) + tmpUrl.substring( 4 ) ); } catch( Exception exn ) { return null; } } else if( filename.startsWith( "./" ) ) { String tmpPath = path; String tmpFilename = filename; if( !tmpPath.contains( "/" ) && tmpPath.contains( "\\" ) ) { tmpPath = tmpPath.replace( "\\", "/" ); } tmpFilename = tmpFilename.substring( 1 ); if( tmpPath.endsWith( "/" ) ) { tmpPath = tmpPath.substring( 0, tmpPath.length() - 1 ); } String tmpUrl = build( tmpPath, tmpFilename ); return new URL( tmpUrl.substring( 0, 4 ) + tmpUrl.substring( 4 ) ); } else { /* * We need the embedded URL path, otherwise URI.normalize is going to do nothing. */ return new URL( urlStr.substring( 0, 4 ) + new URI( urlStr.substring( 4 ) ).normalize().toString() ); } } else { return new URL( new URI( urlStr ).normalize().toString() ); } } catch( MalformedURLException | URISyntaxException e ) { return null; } } private IncludeFile retrieveIncludeFile( final String context, final String target ) throws URISyntaxException { IncludeFile ret; String urlStr = UriUtils.normalizeJolieUri( UriUtils.normalizeWindowsPath( UriUtils.resolve( context, target ) ) ); ret = tryAccessIncludeFile( urlStr ); if( ret == null ) { final URL url = guessIncludeFilepath( urlStr, target, context ); if( url != null ) { ret = tryAccessIncludeFile( url.toString() ); } } return ret; } private final Map< String, URL > resourceCache = new HashMap<>(); private IncludeFile tryAccessIncludeFile( String origIncludeStr ) { final String includeStr = UriUtils.normalizeWindowsPath( origIncludeStr ); final Optional< IncludeFile > optIncludeFile = Helpers.firstNonNull( () -> { final URL url = resourceCache.get( includeStr ); if( url == null ) { return null; } try { return new IncludeFile( new BufferedInputStream( url.openStream() ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } }, () -> { try { Path path = Paths.get( includeStr ); return new IncludeFile( new BufferedInputStream( Files.newInputStream( path ) ), path.getParent().toString(), path.toUri() ); } catch( FileSystemNotFoundException | IOException | InvalidPathException e ) { return null; } }, () -> { try { final URL url = new URL( includeStr ); final InputStream is = url.openStream(); return new IncludeFile( new BufferedInputStream( is ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } }, () -> { final URL url = classLoader.getResource( includeStr ); if( url == null ) { return null; } try { return new IncludeFile( new BufferedInputStream( url.openStream() ), Helpers.parentFromURL( url ), url.toURI() ); } catch( IOException | URISyntaxException e ) { return null; } } ); optIncludeFile.ifPresent( includeFile -> { try { resourceCache.putIfAbsent( includeStr, includeFile.uri.toURL() ); } catch( MalformedURLException e ) { e.printStackTrace(); } } ); return optIncludeFile.orElse( null ); } private void parseInclude() throws IOException, ParserException { String[] origIncludePaths; IncludeFile includeFile; while( token.is( Scanner.TokenType.INCLUDE ) ) { nextToken(); hasIncludeDirective = true; Scanner oldScanner = scanner(); assertToken( Scanner.TokenType.STRING, "expected filename to include" ); String includeStr = token.content(); includeFile = null; for( int i = 0; i < includePaths.length && includeFile == null; i++ ) { try { includeFile = retrieveIncludeFile( includePaths[ i ], includeStr ); } catch( URISyntaxException e ) { throw new ParserException( getContext(), e.getMessage() ); } } if( includeFile == null ) { includeFile = tryAccessIncludeFile( includeStr ); if( includeFile == null ) { throwException( "File not found: " + includeStr ); } } origIncludePaths = includePaths; // includes are explicitly parsed in ASCII to be independent of program's encoding setScanner( new Scanner( includeFile.getInputStream(), includeFile.getURI(), "US-ASCII", oldScanner.includeDocumentation() ) ); if( includeFile.getParentPath() == null ) { includePaths = Arrays.copyOf( origIncludePaths, origIncludePaths.length ); } else { includePaths = Arrays.copyOf( origIncludePaths, origIncludePaths.length + 1 ); includePaths[ origIncludePaths.length ] = includeFile.getParentPath(); } _parse(); includePaths = origIncludePaths; includeFile.getInputStream().close(); setScanner( oldScanner ); nextToken(); } } private boolean checkConstant() { if( token.is( Scanner.TokenType.ID ) ) { final Scanner.Token t; final Constants.Predefined p = Constants.Predefined.get( token.content() ); if( p != null ) { t = p.token(); } else { t = constantsMap.get( token.content() ); } if( t != null ) { token = t; return true; } } return false; } private void parsePort() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); final DocumentedNode node; final PortInfo p; if( token.isKeyword( "inputPort" ) || token.isKeyword( "outputPort" ) ) { p = _parsePort(); programBuilder.addChild( p ); node = p; parseBackwardAndSetDocumentation( node, forwardDocToken ); } else { forwardDocToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private PortInfo _parsePort() throws IOException, ParserException { PortInfo portInfo = null; if( token.isKeyword( "inputPort" ) ) { portInfo = parseInputPortInfo(); } else if( token.isKeyword( "outputPort" ) ) { portInfo = parseOutputPortInfo(); } return portInfo; } private Optional< Scanner.Token > parseAccessModifier() throws IOException, ParserException { Scanner.Token accessModToken = null; if( token.is( Scanner.TokenType.PRIVATE ) || token.is( Scanner.TokenType.PUBLIC ) ) { accessModToken = token; nextToken(); } return Optional.ofNullable( accessModToken ); } private Optional< Scanner.Token > parseForwardDocumentation() throws IOException { Scanner.Token docToken = null; while( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { docToken = token; nextToken(); } return Optional.ofNullable( docToken ); } private Optional< Scanner.Token > parseBackwardDocumentation() throws IOException { Scanner.Token docToken = null; while( token.is( Scanner.TokenType.DOCUMENTATION_BACKWARD ) ) { docToken = token; nextToken(); } return Optional.ofNullable( docToken ); } private void parseBackwardAndSetDocumentation( DocumentedNode node, Optional< Scanner.Token > forwardDocToken ) throws IOException { if( node != null ) { // <Java 8> // Optional< Scanner.Token > backwardDoc = parseBackwardDocumentation(); // if( backwardDoc.isPresent() ) { // node.setDocumentation( backwardDoc.get().content() ); // } else { // String forwardDoc = forwardDocToken // .orElse( new Scanner.Token( Scanner.TokenType.DOCUMENTATION_FORWARD, "" ) ).content(); // node.setDocumentation( forwardDoc ); // } // </Java 8> parseBackwardDocumentation().ifPresentOrElse( doc -> node.setDocumentation( doc.content() ), () -> node.setDocumentation( (forwardDocToken.orElse( new Scanner.Token( Scanner.TokenType.DOCUMENTATION_FORWARD, "" ) )) .content() ) ); } else { forwardDocToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private void parseInterface() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); if( token.isKeyword( "interface" ) ) { nextToken(); DocumentedNode docNode = null; AccessModifier accessModifier = (accessModifierToken.isPresent() && accessModifierToken.get().is( Scanner.TokenType.PRIVATE )) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; final InterfaceDefinition iface; if( token.isKeyword( "extender" ) ) { nextToken(); iface = _parseInterfaceExtender( accessModifier ); docNode = iface; } else { iface = _parseInterface( accessModifier ); docNode = iface; } if( docNode != null ) { parseBackwardAndSetDocumentation( docNode, forwardDocToken ); } programBuilder.addChild( iface ); } else { forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); } } private OutputPortInfo createInternalServicePort( String name, InterfaceDefinition[] interfaceList ) throws ParserException { OutputPortInfo p = new OutputPortInfo( getContext(), name ); for( InterfaceDefinition interfaceDefinition : interfaceList ) { p.addInterface( interfaceDefinition ); } return p; } private InputPortInfo createInternalServiceInputPort( String serviceName, InterfaceDefinition[] interfaceList ) throws ParserException { InputPortInfo iport = new InputPortInfo( getContext(), serviceName + "InputPort", // input port name new ConstantStringExpression( getContext(), Constants.LOCAL_LOCATION_KEYWORD ), null, new InputPortInfo.AggregationItemInfo[] {}, Collections.< String, String >emptyMap() ); for( InterfaceDefinition i : interfaceList ) { iport.addInterface( i ); } return iport; } /** * Parses an internal service, i.e. service service_name {} */ private EmbeddedServiceNode createInternalService( ParsingContext ctx, String serviceName, InterfaceDefinition[] ifaces, SequenceStatement init, DefinitionNode main, ProgramBuilder parentProgramBuilder ) throws IOException, ParserException { // add output port to main program parentProgramBuilder.addChild( createInternalServicePort( serviceName, ifaces ) ); // create Program representing the internal service ProgramBuilder internalServiceProgramBuilder = new ProgramBuilder( ctx ); // copy children of parent to embedded service for( OLSyntaxNode child : parentProgramBuilder.children() ) { if( child instanceof OutputPortInfo || child instanceof TypeDefinition ) { internalServiceProgramBuilder.addChild( child ); } } // set execution to always concurrent internalServiceProgramBuilder.addChild( new ExecutionInfo( getContext(), Constants.ExecutionMode.CONCURRENT ) ); // add input port to internal service internalServiceProgramBuilder.addChild( createInternalServiceInputPort( serviceName, ifaces ) ); // add init if defined in internal service if( init != null ) { internalServiceProgramBuilder.addChild( new DefinitionNode( getContext(), "init", init ) ); } // add main defined in internal service internalServiceProgramBuilder.addChild( main ); // create internal embedded service node EmbeddedServiceNode internalServiceNode = new EmbeddedServiceNode( getContext(), Constants.EmbeddedServiceType.INTERNAL, serviceName, serviceName ); internalServiceProgramBuilder.transformProgramToModuleSystem(); // add internal service program to embedded service node internalServiceNode.setProgram( internalServiceProgramBuilder.toProgram() ); return internalServiceNode; } private InterfaceDefinition[] parseInternalServiceInterface() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected : after Interfaces" ); boolean keepRun = true; List< InterfaceDefinition > currInternalServiceIfaceList = new ArrayList<>(); while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); currInternalServiceIfaceList.add( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } return currInternalServiceIfaceList.toArray( new InterfaceDefinition[ 0 ] ); } private Pair< String, TypeDefinition > parseServiceParameter() throws IOException, ParserException { if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); if( token.is( Scanner.TokenType.RPAREN ) ) { // case ( ) nextToken(); return null; } else { // case ( path: type ) assertToken( Scanner.TokenType.ID, "expected parameter variable name" ); String paramPath = token.content(); nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String typeName = token.content(); TypeDefinition parameterType = parseType( typeName, AccessModifier.PRIVATE ); eat( Scanner.TokenType.RPAREN, "expected )" ); return new Pair<>( paramPath, parameterType ); } } else { return null; } } private ServiceNode createForeignServiceNode( ParsingContext ctx, String serviceName, Pair< String, TypeDefinition > parameter, AccessModifier accessModifier, ProgramBuilder serviceBlockProgramBuilder, EmbeddedServiceType technology, Map< String, String > implementationConfiguration ) { return ServiceNode.create( ctx, serviceName, accessModifier, serviceBlockProgramBuilder.toProgram(), parameter, technology, implementationConfiguration ); } private ServiceNode createJolieServiceNode( ParsingContext ctx, String serviceName, Pair< String, TypeDefinition > parameter, AccessModifier accessModifier, SequenceStatement init, DefinitionNode main, ProgramBuilder parentProgramBuilder, ProgramBuilder serviceBlockProgramBuilder ) { ProgramBuilder serviceNodeProgramBuilder = new ProgramBuilder( ctx ); // [backward-compatibility] inject top-level deployment instructions to the service node // so the include directive is still working in Module System, These deployment instructions of // parent's programBuilder are meant to remove at the end of parsing step. for( OLSyntaxNode child : parentProgramBuilder.children() ) { if( child instanceof OutputPortInfo || child instanceof InputPortInfo || child instanceof EmbeddedServiceNode ) { serviceNodeProgramBuilder.addChild( child ); } } // copy children of parent to embedded service for( OLSyntaxNode child : serviceBlockProgramBuilder.children() ) { serviceNodeProgramBuilder.addChild( child ); } // add init if defined in internal service if( init != null ) { serviceNodeProgramBuilder.addChild( new DefinitionNode( getContext(), "init", init ) ); } // add main defined in service if( main != null ) { serviceNodeProgramBuilder.addChild( main ); } ServiceNode node = ServiceNode.create( ctx, serviceName, accessModifier, serviceNodeProgramBuilder.toProgram(), parameter ); return node; } /** * Parses a service node, i.e. service service_name ( varpath : type ) {} */ private void parseService() throws IOException, ParserException { Optional< Scanner.Token > forwardDocToken = parseForwardDocumentation(); Optional< Scanner.Token > accessModifierToken = parseAccessModifier(); // only proceed if a service declaration if( !token.isKeyword( "service" ) ) { forwardDocToken.ifPresent( this::addToken ); accessModifierToken.ifPresent( this::addToken ); addToken( token ); nextToken(); return; } nextToken(); Constants.EmbeddedServiceType tech = Constants.EmbeddedServiceType.SERVICENODE; Map< String, String > configMap = new HashMap<>(); assertToken( Scanner.TokenType.ID, "expected service name" ); ParsingContext ctx = getContext(); String serviceName = token.content(); nextToken(); Pair< String, TypeDefinition > parameter = parseServiceParameter(); eat( Scanner.TokenType.LCURLY, "{ expected" ); // jolie internal service's Interface InterfaceDefinition[] internalIfaces = null; DefinitionNode internalMain = null; SequenceStatement internalInit = null; ProgramBuilder serviceBlockProgramBuilder = new ProgramBuilder( getContext() ); boolean keepRun = true; while( keepRun ) { forwardDocToken = parseForwardDocumentation(); switch( token.content() ) { case "Interfaces": // internal service node syntax internalIfaces = parseInternalServiceInterface(); break; case "include": parseInclude(); break; case "cset": for( CorrelationSetInfo csetInfo : _parseCorrelationSets() ) { serviceBlockProgramBuilder.addChild( csetInfo ); } break; case "execution": serviceBlockProgramBuilder.addChild( _parseExecutionInfo() ); break; case "courier": serviceBlockProgramBuilder.addChild( parseCourierDefinition() ); break; case "init": if( internalInit == null ) { internalInit = new SequenceStatement( getContext() ); } internalInit.addChild( parseInit() ); break; case "main": if( internalMain != null ) { throwException( "you must specify only one main definition" ); } internalMain = parseMain(); break; case "inputPort": case "outputPort": PortInfo p = _parsePort(); parseBackwardAndSetDocumentation( ((DocumentedNode) p), forwardDocToken ); serviceBlockProgramBuilder.addChild( p ); break; case "define": serviceBlockProgramBuilder.addChild( parseDefinition() ); break; case "embed": EmbedServiceNode embedServiceNode = parseEmbeddedServiceNode(); if( embedServiceNode.isNewPort() ) { serviceBlockProgramBuilder .addChild( embedServiceNode.bindingPort() ); } serviceBlockProgramBuilder.addChild( embedServiceNode ); break; case "foreign": nextToken(); String technology = token.content(); if( technology.equals( "java" ) ) { tech = Constants.EmbeddedServiceType.SERVICENODE_JAVA; } nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); while( token.isNot( Scanner.TokenType.RCURLY ) ) { String key = token.content(); nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String value = ""; while( !hasMetNewline() ) { if( token.is( Scanner.TokenType.DOT ) ) { value += "."; } else { value += token.content(); } nextToken(); } configMap.put( key, value ); } eat( Scanner.TokenType.RCURLY, "expected }" ); default: assertToken( Scanner.TokenType.RCURLY, "invalid token found inside service " + serviceName ); keepRun = false; } } eat( Scanner.TokenType.RCURLY, "expected }" ); // it is a Jolie internal service if( internalIfaces != null && internalIfaces.length > 0 ) { if( internalMain == null ) { throwException( "You must specify a main for service " + serviceName ); } EmbeddedServiceNode node = createInternalService( ctx, serviceName, internalIfaces, internalInit, internalMain, programBuilder ); programBuilder.addChild( node ); } else { AccessModifier accessModifier = (accessModifierToken.isPresent() && accessModifierToken.get().is( Scanner.TokenType.PRIVATE )) ? AccessModifier.PRIVATE : AccessModifier.PUBLIC; ServiceNode serviceNode = null; switch( tech ) { case SERVICENODE: serviceNode = createJolieServiceNode( ctx, serviceName, parameter, accessModifier, internalInit, internalMain, programBuilder, serviceBlockProgramBuilder ); break; default: serviceNode = createForeignServiceNode( ctx, serviceName, parameter, accessModifier, serviceBlockProgramBuilder, tech, configMap ); } programBuilder.addChild( serviceNode ); } } private InputPortInfo parseInputPortInfo() throws IOException, ParserException { String inputPortName; OLSyntaxNode protocol = null; OLSyntaxNode location = null; List< InterfaceDefinition > interfaceList = new ArrayList<>(); nextToken(); assertToken( Scanner.TokenType.ID, "expected inputPort name" ); inputPortName = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "{ expected" ); InterfaceDefinition iface = new InterfaceDefinition( getContext(), "Internal interface for: " + inputPortName ); Map< String, String > redirectionMap = new HashMap<>(); List< InputPortInfo.AggregationItemInfo > aggregationList = new ArrayList<>(); boolean isLocationLocal = false; while( token.isNot( Scanner.TokenType.RCURLY ) ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( iface ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( iface ); } else if( token.isKeyword( "location" ) || token.isKeyword( "Location" ) ) { if( location != null ) { throwException( "Location already defined for service " + inputPortName ); } nextToken(); eat( Scanner.TokenType.COLON, "expected : after location" ); checkConstant(); if( token.content().startsWith( "local" ) ) { // check if the inputPort is listening to local protocol isLocationLocal = true; } location = parseBasicExpression(); } else if( token.isKeyword( "interfaces" ) || token.isKeyword( "Interfaces" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected : after interfaces" ); boolean keepRun = true; while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); interfaceList.add( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } } else if( token.isKeyword( "protocol" ) || token.isKeyword( "Protocol" ) ) { if( protocol != null ) { throwException( "Protocol already defined for inputPort " + inputPortName ); } nextToken(); eat( Scanner.TokenType.COLON, "expected : after protocol" ); checkConstant(); protocol = parseBasicExpression(); } else if( token.isKeyword( "redirects" ) || token.isKeyword( "Redirects" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); String subLocationName; while( token.is( Scanner.TokenType.ID ) ) { subLocationName = token.content(); nextToken(); eat( Scanner.TokenType.ARROW, "expected =>" ); assertToken( Scanner.TokenType.ID, "expected outputPort identifier" ); redirectionMap.put( subLocationName, token.content() ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { break; } } } else if( token.isKeyword( "aggregates" ) || token.isKeyword( "Aggregates" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); parseAggregationList( aggregationList ); } else { throwException( "Unrecognized token in inputPort " + inputPortName ); } } eat( Scanner.TokenType.RCURLY, "} expected" ); if( location == null ) { throwException( "expected location URI for " + inputPortName ); } else if( (interfaceList.isEmpty() && iface.operationsMap().isEmpty()) && redirectionMap.isEmpty() && aggregationList.isEmpty() ) { throwException( "expected at least one operation, interface, aggregation or redirection for inputPort " + inputPortName ); } else if( protocol == null && !isLocationLocal ) { throwException( "expected protocol for inputPort " + inputPortName ); } InputPortInfo iport = new InputPortInfo( getContext(), inputPortName, location, protocol, aggregationList.toArray( new InputPortInfo.AggregationItemInfo[ aggregationList.size() ] ), redirectionMap ); for( InterfaceDefinition i : interfaceList ) { iport.addInterface( i ); } iface.copyTo( iport ); return iport; } private void parseAggregationList( List< InputPortInfo.AggregationItemInfo > aggregationList ) throws ParserException, IOException { List< String > outputPortNames; InterfaceExtenderDefinition extender; boolean mainKeepRun = true; while( mainKeepRun ) { extender = null; outputPortNames = new LinkedList<>(); if( token.is( Scanner.TokenType.LCURLY ) ) { nextToken(); boolean keepRun = true; while( keepRun ) { assertToken( Scanner.TokenType.ID, "expected output port name" ); outputPortNames.add( token.content() ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else if( token.is( Scanner.TokenType.RCURLY ) ) { keepRun = false; nextToken(); } else { throwException( "unexpected token " + token.type() ); } } } else { assertToken( Scanner.TokenType.ID, "expected output port name" ); outputPortNames.add( token.content() ); nextToken(); } if( token.is( Scanner.TokenType.WITH ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected interface extender name" ); extender = interfaceExtenders.get( token.content() ); if( extender == null ) { throwException( "undefined interface extender: " + token.content() ); } nextToken(); } aggregationList.add( new InputPortInfo.AggregationItemInfo( outputPortNames.toArray( new String[ 0 ] ), extender ) ); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { mainKeepRun = false; } } } private InterfaceDefinition _parseInterfaceExtender( AccessModifier accessModifier ) throws IOException, ParserException { String name; assertToken( Scanner.TokenType.ID, "expected interface extender name" ); name = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); InterfaceExtenderDefinition extender = currInterfaceExtender = new InterfaceExtenderDefinition( getContext(), name, accessModifier ); parseOperations( currInterfaceExtender ); interfaceExtenders.put( name, extender ); eat( Scanner.TokenType.RCURLY, "expected }" ); currInterfaceExtender = null; return extender; } private InterfaceDefinition _parseInterface( AccessModifier accessModifier ) throws IOException, ParserException { String name; InterfaceDefinition iface; assertToken( Scanner.TokenType.ID, "expected interface name" ); name = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); iface = new InterfaceDefinition( getContext(), name, accessModifier ); parseOperations( iface ); eat( Scanner.TokenType.RCURLY, "expected }" ); return iface; } private void parseOperations( OperationCollector oc ) throws IOException, ParserException { boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( oc ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( oc ); } else { keepRun = false; } } } private OutputPortInfo parseOutputPortInfo() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected output port identifier" ); OutputPortInfo p = new OutputPortInfo( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.LCURLY, "expected {" ); boolean keepRun = true; while( keepRun ) { if( token.is( Scanner.TokenType.OP_OW ) ) { parseOneWayOperations( p ); } else if( token.is( Scanner.TokenType.OP_RR ) ) { parseRequestResponseOperations( p ); } else if( token.isKeyword( "interfaces" ) || token.isKeyword( "Interfaces" ) ) { nextToken(); eat( Scanner.TokenType.COLON, "expected : after Interfaces" ); boolean r = true; while( r ) { assertToken( Scanner.TokenType.ID, "expected interface name" ); InterfaceDefinition i = new InterfaceDefinition( getContext(), token.content() ); p.addInterface( i ); nextToken(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { r = false; } } } else if( token.isKeyword( "location" ) || token.isKeyword( "Location" ) ) { if( p.location() != null ) { throwException( "Location already defined for output port " + p.id() ); } nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); checkConstant(); OLSyntaxNode expr = parseBasicExpression(); p.setLocation( expr ); } else if( token.isKeyword( "protocol" ) || token.isKeyword( "Protocol" ) ) { if( p.protocol() != null ) { throwException( "Protocol already defined for output port " + p.id() ); } nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); checkConstant(); OLSyntaxNode protocol = parseBasicExpression(); p.setProtocol( protocol ); } else { keepRun = false; } } eat( Scanner.TokenType.RCURLY, "expected }" ); return p; } private void parseOneWayOperations( OperationCollector oc ) throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); boolean keepRun = true; Scanner.Token commentToken = null; String opId; while( keepRun ) { checkConstant(); if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = token; nextToken(); } else if( token.is( Scanner.TokenType.ID ) || (currInterfaceExtender != null && token.is( Scanner.TokenType.ASTERISK )) ) { opId = token.content(); OneWayOperationDeclaration opDecl = new OneWayOperationDeclaration( getContext(), opId ); nextToken(); opDecl.setRequestType( TypeDefinitionUndefined.getInstance() ); if( token.is( Scanner.TokenType.LPAREN ) ) { // Type declaration nextToken(); // eat ( String typeName = token.content(); TypeDefinition type = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); opDecl.setRequestType( type ); nextToken(); // eat the type name eat( Scanner.TokenType.RPAREN, "expected )" ); } parseBackwardAndSetDocumentation( opDecl, Optional.ofNullable( commentToken ) ); commentToken = null; if( currInterfaceExtender != null && opId.equals( "*" ) ) { currInterfaceExtender.setDefaultOneWayOperation( opDecl ); } else { oc.addOperation( opDecl ); } if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } else { keepRun = false; } } } private void parseRequestResponseOperations( OperationCollector oc ) throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.COLON, "expected :" ); boolean keepRun = true; Scanner.Token commentToken = null; String opId; while( keepRun ) { checkConstant(); if( token.is( Scanner.TokenType.DOCUMENTATION_FORWARD ) ) { commentToken = token; nextToken(); } else if( token.is( Scanner.TokenType.ID ) || (currInterfaceExtender != null && token.is( Scanner.TokenType.ASTERISK )) ) { opId = token.content(); nextToken(); String requestTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; String responseTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); // eat ( requestTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LPAREN, "expected (" ); responseTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); } Map< String, TypeDefinition > faultTypesMap = new HashMap<>(); if( token.is( Scanner.TokenType.THROWS ) ) { nextToken(); while( token.is( Scanner.TokenType.ID ) ) { String faultName = token.content(); String faultTypeName = TypeDefinitionUndefined.UNDEFINED_KEYWORD; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); // eat ( faultTypeName = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); } TypeDefinition faultType = new TypeDefinitionLink( getContext(), faultIdCounter++ + "#" + faultTypeName, Constants.RANGE_ONE_TO_ONE, faultTypeName ); if( definedTypes.containsKey( faultTypeName ) ) { faultType = definedTypes.get( faultTypeName ); } else { definedTypes.put( faultTypeName, faultType ); } faultTypesMap.put( faultName, faultType ); } } TypeDefinition requestType = definedTypes.getOrDefault( requestTypeName, new TypeDefinitionLink( getContext(), requestTypeName, Constants.RANGE_ONE_TO_ONE, requestTypeName ) ); TypeDefinition responseType = definedTypes.getOrDefault( responseTypeName, new TypeDefinitionLink( getContext(), responseTypeName, Constants.RANGE_ONE_TO_ONE, responseTypeName ) ); RequestResponseOperationDeclaration opRR = new RequestResponseOperationDeclaration( getContext(), opId, requestType, responseType, faultTypesMap ); parseBackwardAndSetDocumentation( opRR, Optional.ofNullable( commentToken ) ); commentToken = null; if( currInterfaceExtender != null && opId.equals( "*" ) ) { currInterfaceExtender.setDefaultRequestResponseOperation( opRR ); } else { oc.addOperation( opRR ); } if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } else { keepRun = false; } } } private SequenceStatement initSequence = null; private DefinitionNode main = null; private void parseCode() throws IOException, ParserException { boolean keepRun = true; do { if( token.is( Scanner.TokenType.DEFINE ) ) { programBuilder.addChild( parseDefinition() ); } else if( token.isKeyword( "courier" ) ) { programBuilder.addChild( parseCourierDefinition() ); } else if( token.isKeyword( "main" ) ) { if( main != null ) { throwException( "you must specify only one main definition" ); } main = parseMain(); } else if( token.is( Scanner.TokenType.INIT ) ) { if( initSequence == null ) { initSequence = new SequenceStatement( getContext() ); } initSequence.addChild( parseInit() ); } else { keepRun = false; } } while( keepRun ); } private DefinitionNode parseMain() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" ); DefinitionNode retVal = new DefinitionNode( getContext(), "main", parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" ); return retVal; } private OLSyntaxNode parseInit() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" ); OLSyntaxNode retVal = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" ); return retVal; } private DefinitionNode parseDefinition() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected definition identifier" ); String definitionId = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after definition declaration" ); DefinitionNode retVal = new DefinitionNode( getContext(), definitionId, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected } after definition declaration" ); return retVal; } private CourierDefinitionNode parseCourierDefinition() throws IOException, ParserException { nextToken(); assertToken( Scanner.TokenType.ID, "expected input port identifier" ); String inputPortName = token.content(); nextToken(); eat( Scanner.TokenType.LCURLY, "expected { after courier definition" ); CourierDefinitionNode retVal = new CourierDefinitionNode( getContext(), inputPortName, parseCourierChoice() ); eat( Scanner.TokenType.RCURLY, "expected } after courier definition" ); return retVal; } public OLSyntaxNode parseProcess() throws IOException, ParserException { return parseParallelStatement(); } private ParallelStatement parseParallelStatement() throws IOException, ParserException { ParallelStatement stm = new ParallelStatement( getContext() ); stm.addChild( parseSequenceStatement() ); while( token.is( Scanner.TokenType.PARALLEL ) ) { nextToken(); stm.addChild( parseSequenceStatement() ); } return stm; } private SequenceStatement parseSequenceStatement() throws IOException, ParserException { SequenceStatement stm = new SequenceStatement( getContext() ); stm.addChild( parseBasicStatement() ); boolean run = true; while( run ) { if( token.is( Scanner.TokenType.SEQUENCE ) ) { nextToken(); stm.addChild( parseBasicStatement() ); } else if( hasMetNewline() ) { OLSyntaxNode basicStatement = parseBasicStatement( false ); if( basicStatement == null ) { run = false; } else { stm.addChild( basicStatement ); } } else { run = false; } } return stm; } private final List< List< Scanner.Token > > inVariablePaths = new ArrayList<>(); private OLSyntaxNode parseInVariablePathProcess( boolean withConstruct ) throws IOException, ParserException { OLSyntaxNode ret; LinkedList< Scanner.Token > tokens = new LinkedList<>(); try { if( withConstruct ) { eat( Scanner.TokenType.LPAREN, "expected (" ); while( token.isNot( Scanner.TokenType.LCURLY ) ) { tokens.add( token ); nextTokenNotEOF(); } // TODO transfer this whole buggy thing to the OOIT tokens.removeLast(); // nextToken(); } else { while( token.isNot( Scanner.TokenType.LCURLY ) ) { tokens.add( token ); nextTokenNotEOF(); } } } catch( EOFException eof ) { throwException( "with clause requires a { at the beginning of its body" ); } inVariablePaths.add( tokens ); eat( Scanner.TokenType.LCURLY, "expected {" ); ret = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); inVariablePaths.remove( inVariablePaths.size() - 1 ); return ret; } private OLSyntaxNode parseBasicStatement() throws IOException, ParserException { return parseBasicStatement( true ); } private OLSyntaxNode parseBasicStatement( boolean throwException ) throws IOException, ParserException { OLSyntaxNode retVal = null; switch( token.type() ) { case LSQUARE: retVal = parseNDChoiceStatement(); break; case PROVIDE: nextToken(); retVal = parseProvideUntilStatement(); break; case ID: if( checkConstant() ) { throwException( "cannot modify a constant in a statement" ); } String id = token.content(); nextToken(); if( token.is( Scanner.TokenType.LSQUARE ) || token.is( Scanner.TokenType.DOT ) || token.is( Scanner.TokenType.ASSIGN ) || token.is( Scanner.TokenType.ADD_ASSIGN ) || token.is( Scanner.TokenType.MINUS_ASSIGN ) || token.is( Scanner.TokenType.MULTIPLY_ASSIGN ) || token.is( Scanner.TokenType.DIVIDE_ASSIGN ) || token.is( Scanner.TokenType.POINTS_TO ) || token.is( Scanner.TokenType.DEEP_COPY_LEFT ) || token.is( Scanner.TokenType.DEEP_COPY_WITH_LINKS_LEFT ) || token.is( Scanner.TokenType.DECREMENT ) || token.is( Scanner.TokenType.INCREMENT ) ) { retVal = parseAssignOrDeepCopyOrPointerStatement( _parseVariablePath( id ) ); } else if( id.equals( "forward" ) && (token.is( Scanner.TokenType.ID ) || token.is( Scanner.TokenType.LPAREN )) ) { retVal = parseForwardStatement(); } else if( token.is( Scanner.TokenType.LPAREN ) ) { retVal = parseInputOperationStatement( id ); } else if( token.is( Scanner.TokenType.AT ) ) { nextToken(); retVal = parseOutputOperationStatement( id ); } else { retVal = new DefinitionCallStatement( getContext(), id ); } break; case WITH: nextToken(); retVal = parseInVariablePathProcess( true ); break; case INCREMENT: nextToken(); retVal = new PreIncrementStatement( getContext(), parseVariablePath() ); break; case DECREMENT: nextToken(); retVal = new PreDecrementStatement( getContext(), parseVariablePath() ); break; case UNDEF: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); retVal = new UndefStatement( getContext(), parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case SYNCHRONIZED: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected lock id" ); final String sid = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); retVal = new SynchronizedStatement( getContext(), sid, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case SPAWN: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); VariablePathNode indexVariablePath = parseVariablePath(); assertToken( Scanner.TokenType.ID, "expected over" ); if( token.isKeyword( "over" ) == false ) { throwException( "expected over" ); } nextToken(); OLSyntaxNode upperBoundExpression = parseBasicExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); VariablePathNode inVariablePath = null; if( token.isKeyword( "in" ) ) { nextToken(); inVariablePath = parseVariablePath(); } eat( Scanner.TokenType.LCURLY, "expected {" ); OLSyntaxNode process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); retVal = new SpawnStatement( getContext(), indexVariablePath, upperBoundExpression, inVariablePath, process ); break; case FOR: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); startBackup(); VariablePathNode leftPath; try { leftPath = parseVariablePath(); } catch( ParserException e ) { leftPath = null; } if( leftPath != null && token.isKeyword( "in" ) ) { // for( elem in path ) { ... } discardBackup(); nextToken(); VariablePathNode targetPath = parseVariablePath(); if( targetPath.path().get( targetPath.path().size() - 1 ).value() != null ) { throwException( "target in for ( elem -> array ) { ... } should be an array (cannot specify an index): " + targetPath.toPrettyString() ); } eat( Scanner.TokenType.RPAREN, "expected )" ); final OLSyntaxNode forEachBody = parseBasicStatement(); retVal = new ForEachArrayItemStatement( getContext(), leftPath, targetPath, forEachBody ); } else { // for( init, condition, post ) { ... } recoverBackup(); OLSyntaxNode init = parseProcess(); eat( Scanner.TokenType.COMMA, "expected ," ); OLSyntaxNode condition = parseExpression(); eat( Scanner.TokenType.COMMA, "expected ," ); OLSyntaxNode post = parseProcess(); eat( Scanner.TokenType.RPAREN, "expected )" ); OLSyntaxNode body = parseBasicStatement(); retVal = new ForStatement( getContext(), init, condition, post, body ); } break; case FOREACH: // foreach( k : path ) { ... } nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); final VariablePathNode keyPath = parseVariablePath(); eat( Scanner.TokenType.COLON, "expected :" ); final VariablePathNode targetPath = parseVariablePath(); eat( Scanner.TokenType.RPAREN, "expected )" ); final OLSyntaxNode forEachBody = parseBasicStatement(); retVal = new ForEachSubNodeStatement( getContext(), keyPath, targetPath, forEachBody ); break; case LINKIN: retVal = parseLinkInStatement(); break; case CURRENT_HANDLER: nextToken(); retVal = new CurrentHandlerStatement( getContext() ); break; case NULL_PROCESS: nextToken(); retVal = new NullProcessStatement( getContext() ); break; case EXIT: nextToken(); retVal = new ExitStatement( getContext() ); break; case WHILE: retVal = parseWhileStatement(); break; case LINKOUT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected link identifier" ); retVal = new LinkOutStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case LPAREN: nextToken(); retVal = parseProcess(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case LCURLY: nextToken(); retVal = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case SCOPE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected scope identifier" ); final String scopeId = token.content(); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); retVal = new Scope( getContext(), scopeId, parseProcess() ); eat( Scanner.TokenType.RCURLY, "expected }" ); break; case COMPENSATE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected scope identifier" ); retVal = new CompensateStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case THROW: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); checkConstant(); assertToken( Scanner.TokenType.ID, "expected fault identifier" ); String faultName = token.content(); nextToken(); if( token.is( Scanner.TokenType.RPAREN ) ) { retVal = new ThrowStatement( getContext(), faultName ); } else { eat( Scanner.TokenType.COMMA, "expected , or )" ); OLSyntaxNode expression = parseExpression(); /* * assertToken( Scanner.TokenType.ID, "expected variable path" ); String varId = token.content(); * nextToken(); VariablePathNode path = parseVariablePath( varId ); */ retVal = new ThrowStatement( getContext(), faultName, expression ); } eat( Scanner.TokenType.RPAREN, "expected )" ); break; case INSTALL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); Optional< InstallFunctionNode > optInstallNode = parseInstallFunction( false ); if( !optInstallNode.isPresent() ) { throwException( "expected install body" ); } retVal = new InstallStatement( getContext(), optInstallNode.get() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IF: IfStatement stm = new IfStatement( getContext() ); OLSyntaxNode cond; OLSyntaxNode node; nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); node = parseBasicStatement(); stm.addChild( new Pair<>( cond, node ) ); boolean keepRun = true; while( token.is( Scanner.TokenType.ELSE ) && keepRun ) { nextToken(); if( token.is( Scanner.TokenType.IF ) ) { // else if branch nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); node = parseBasicStatement(); stm.addChild( new Pair<>( cond, node ) ); } else { // else branch keepRun = false; stm.setElseProcess( parseBasicStatement() ); } } retVal = stm; break; case DOT: if( !inVariablePaths.isEmpty() ) { retVal = parseAssignOrDeepCopyOrPointerStatement( parsePrefixedVariablePath() ); } break; default: break; } if( throwException && retVal == null ) { throwException( "expected basic statement" ); } return retVal; } private OLSyntaxNode parseProvideUntilStatement() throws IOException, ParserException { ParsingContext context = getContext(); NDChoiceStatement provide = parseNDChoiceStatement(); if( !token.isKeyword( "until" ) ) { throwException( "expected until" ); } nextToken(); NDChoiceStatement until = parseNDChoiceStatement(); return new ProvideUntilStatement( context, provide, until ); } private OLSyntaxNode parseForwardStatement() throws IOException, ParserException { OLSyntaxNode retVal; String outputPortName = null; if( token.is( Scanner.TokenType.ID ) ) { outputPortName = token.content(); nextToken(); } VariablePathNode outputVariablePath = parseOperationVariablePathParameter(); if( token.is( Scanner.TokenType.LPAREN ) ) { // Solicit-Response VariablePathNode inputVariablePath = parseOperationVariablePathParameter(); retVal = new SolicitResponseForwardStatement( getContext(), outputPortName, outputVariablePath, inputVariablePath ); } else { // Notification retVal = new NotificationForwardStatement( getContext(), outputPortName, outputVariablePath ); } return retVal; } private Optional< InstallFunctionNode > parseInstallFunction( boolean hadNewLine ) throws IOException, ParserException { /* * Check that we're not consuming an input choice first. (This can happen for sequences separated by * spaces instead of ;.) */ if( token.is( Scanner.TokenType.ID ) ) { Scanner.Token idToken = token; nextToken(); if( token.is( Scanner.TokenType.LPAREN ) ) { // It's an input choice if( hadNewLine ) { addToken( new Scanner.Token( Scanner.TokenType.NEWLINE ) ); } addToken( new Scanner.Token( Scanner.TokenType.LSQUARE ) ); addToken( idToken ); addToken( token ); nextToken(); return Optional.empty(); } else { addToken( idToken ); addToken( token ); nextToken(); } } boolean backup = insideInstallFunction; insideInstallFunction = true; List< Pair< String, OLSyntaxNode > > vec = new LinkedList<>(); boolean keepRun = true; List< String > names = new ArrayList<>(); OLSyntaxNode handler; while( keepRun ) { do { if( token.is( Scanner.TokenType.THIS ) ) { names.add( null ); } else if( token.is( Scanner.TokenType.ID ) ) { names.add( token.content() ); } else { throwException( "expected fault identifier or this" ); } nextToken(); } while( token.isNot( Scanner.TokenType.ARROW ) ); nextToken(); // eat the arrow handler = parseProcess(); for( String name : names ) { vec.add( new Pair<>( name, handler ) ); } names.clear(); if( token.is( Scanner.TokenType.COMMA ) ) { nextToken(); } else { keepRun = false; } } insideInstallFunction = backup; return Optional.of( new InstallFunctionNode( vec.toArray( new Pair[ 0 ] ) ) ); } private OLSyntaxNode parseAssignOrDeepCopyOrPointerStatement( VariablePathNode path ) throws IOException, ParserException { OLSyntaxNode retVal = null; if( token.is( Scanner.TokenType.ASSIGN ) ) { nextToken(); retVal = new AssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.ADD_ASSIGN ) ) { nextToken(); retVal = new AddAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.MINUS_ASSIGN ) ) { nextToken(); retVal = new SubtractAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.MULTIPLY_ASSIGN ) ) { nextToken(); retVal = new MultiplyAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.DIVIDE_ASSIGN ) ) { nextToken(); retVal = new DivideAssignStatement( getContext(), path, parseExpression() ); } else if( token.is( Scanner.TokenType.INCREMENT ) ) { nextToken(); retVal = new PostIncrementStatement( getContext(), path ); } else if( token.is( Scanner.TokenType.DECREMENT ) ) { nextToken(); retVal = new PostDecrementStatement( getContext(), path ); } else if( token.is( Scanner.TokenType.POINTS_TO ) ) { nextToken(); retVal = new PointerStatement( getContext(), path, parseVariablePath() ); } else if( token.is( Scanner.TokenType.DEEP_COPY_LEFT ) ) { ParsingContext context = getContext(); nextToken(); retVal = new DeepCopyStatement( context, path, parseExpression(), false ); } else if( token.is( Scanner.TokenType.DEEP_COPY_WITH_LINKS_LEFT ) ) { ParsingContext context = getContext(); nextToken(); retVal = new DeepCopyStatement( context, path, parseExpression(), true ); } else { throwException( "expected = or -> or << or -- or ++" ); } return retVal; } private VariablePathNode parseVariablePath() throws ParserException, IOException { if( token.is( Scanner.TokenType.DOT ) ) { return parsePrefixedVariablePath(); } assertIdentifier( "Expected variable path" ); String varId = token.content(); nextToken(); return _parseVariablePath( varId ); } private VariablePathNode _parseVariablePath( String varId ) throws IOException, ParserException { OLSyntaxNode expr; VariablePathNode path; switch( varId ) { case Constants.GLOBAL: path = new VariablePathNode( getContext(), Type.GLOBAL ); break; case Constants.CSETS: path = new VariablePathNode( getContext(), Type.CSET ); path.append( new Pair<>( new ConstantStringExpression( getContext(), varId ), new ConstantIntegerExpression( getContext(), 0 ) ) ); break; default: path = new VariablePathNode( getContext(), Type.NORMAL ); if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); expr = parseBasicExpression(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { expr = null; } path.append( new Pair<>( new ConstantStringExpression( getContext(), varId ), expr ) ); break; } OLSyntaxNode nodeExpr = null; while( token.is( Scanner.TokenType.DOT ) ) { nextToken(); if( token.isIdentifier() ) { nodeExpr = new ConstantStringExpression( getContext(), token.content() ); } else if( token.is( Scanner.TokenType.LPAREN ) ) { nextToken(); nodeExpr = parseBasicExpression(); assertToken( Scanner.TokenType.RPAREN, "expected )" ); } else { throwException( "expected nested node identifier" ); } nextToken(); if( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); expr = parseBasicExpression(); eat( Scanner.TokenType.RSQUARE, "expected ]" ); } else { expr = null; } path.append( new Pair<>( nodeExpr, expr ) ); } return path; } private VariablePathNode parsePrefixedVariablePath() throws IOException, ParserException { int i = inVariablePaths.size() - 1; List< Scanner.Token > tokens = new ArrayList<>(); try { tokens.addAll( inVariablePaths.get( i ) ); } catch( IndexOutOfBoundsException e ) { throwException( "Prefixed variable paths must be inside a with block" ); } while( tokens.get( 0 ).is( Scanner.TokenType.DOT ) ) { i--; tokens.addAll( 0, inVariablePaths.get( i ) ); } addTokens( tokens ); addTokens( Collections.singletonList( new Scanner.Token( Scanner.TokenType.DOT ) ) ); nextToken(); String varId = token.content(); nextToken(); return _parseVariablePath( varId ); } private CourierChoiceStatement parseCourierChoice() throws IOException, ParserException { CourierChoiceStatement stm = new CourierChoiceStatement( getContext() ); OLSyntaxNode body; InterfaceDefinition iface; String operationName; VariablePathNode inputVariablePath, outputVariablePath; while( token.is( Scanner.TokenType.LSQUARE ) ) { iface = null; operationName = null; inputVariablePath = null; outputVariablePath = null; nextToken(); if( token.isKeyword( "interface" ) ) { nextToken(); assertToken( Scanner.TokenType.ID, "expected interface name" ); checkConstant(); iface = new InterfaceDefinition( getContext(), token.content() ); nextToken(); inputVariablePath = parseOperationVariablePathParameter(); if( inputVariablePath == null ) { throwException( "expected variable path" ); } if( token.is( Scanner.TokenType.LPAREN ) ) { // Request-Response outputVariablePath = parseOperationVariablePathParameter(); } } else if( token.is( Scanner.TokenType.ID ) ) { operationName = token.content(); nextToken(); inputVariablePath = parseOperationVariablePathParameter(); if( inputVariablePath == null ) { throwException( "expected variable path" ); } if( token.is( Scanner.TokenType.LPAREN ) ) { // Request-Response outputVariablePath = parseOperationVariablePathParameter(); } } else { throwException( "expected courier input guard (interface or operation name)" ); } eat( Scanner.TokenType.RSQUARE, "expected ]" ); eat( Scanner.TokenType.LCURLY, "expected {" ); body = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); if( iface == null ) { // It's an operation if( outputVariablePath == null ) { // One-Way stm.operationOneWayBranches().add( new CourierChoiceStatement.OperationOneWayBranch( operationName, inputVariablePath, body ) ); } else { // Request-Response stm.operationRequestResponseBranches() .add( new CourierChoiceStatement.OperationRequestResponseBranch( operationName, inputVariablePath, outputVariablePath, body ) ); } } else { // It's an interface if( outputVariablePath == null ) { // One-Way stm.interfaceOneWayBranches() .add( new CourierChoiceStatement.InterfaceOneWayBranch( iface, inputVariablePath, body ) ); } else { // Request-Response stm.interfaceRequestResponseBranches() .add( new CourierChoiceStatement.InterfaceRequestResponseBranch( iface, inputVariablePath, outputVariablePath, body ) ); } } } return stm; } private NDChoiceStatement parseNDChoiceStatement() throws IOException, ParserException { NDChoiceStatement stm = new NDChoiceStatement( getContext() ); OLSyntaxNode inputGuard = null; OLSyntaxNode process; while( token.is( Scanner.TokenType.LSQUARE ) ) { nextToken(); // Eat [ /* * if ( token.is( Scanner.TokenType.LINKIN ) ) { inputGuard = parseLinkInStatement(); } else */if( token.is( Scanner.TokenType.ID ) ) { String id = token.content(); nextToken(); inputGuard = parseInputOperationStatement( id ); } else { throwException( "expected input guard" ); } eat( Scanner.TokenType.RSQUARE, "expected ]" ); if( token.is( Scanner.TokenType.LCURLY ) ) { eat( Scanner.TokenType.LCURLY, "expected {" ); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); } else { process = new NullProcessStatement( getContext() ); } stm.addChild( new Pair<>( inputGuard, process ) ); } return stm; } private LinkInStatement parseLinkInStatement() throws IOException, ParserException { nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); assertToken( Scanner.TokenType.ID, "expected link identifier" ); LinkInStatement stm = new LinkInStatement( getContext(), token.content() ); nextToken(); eat( Scanner.TokenType.RPAREN, "expected )" ); return stm; } private OLSyntaxNode parseInputOperationStatement( String id ) throws IOException, ParserException { ParsingContext context = getContext(); VariablePathNode inputVarPath = parseOperationVariablePathParameter(); OLSyntaxNode stm; if( token.is( Scanner.TokenType.LPAREN ) ) { // Request Response operation OLSyntaxNode outputExpression = parseOperationExpressionParameter(); OLSyntaxNode process = new NullProcessStatement( getContext() ); if( token.is( Scanner.TokenType.LCURLY ) ) { // Request Response body nextToken(); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); } stm = new RequestResponseOperationStatement( context, id, inputVarPath, outputExpression, process ); } else { // One Way operation stm = new OneWayOperationStatement( context, id, inputVarPath ); } return stm; } /** * @return The VariablePath parameter of the statement. May be null. */ private VariablePathNode parseOperationVariablePathParameter() throws IOException, ParserException { VariablePathNode ret = null; eat( Scanner.TokenType.LPAREN, "expected (" ); if( token.is( Scanner.TokenType.ID ) ) { ret = parseVariablePath(); } else if( token.is( Scanner.TokenType.DOT ) ) { ret = parsePrefixedVariablePath(); } eat( Scanner.TokenType.RPAREN, "expected )" ); return ret; } private OLSyntaxNode parseOperationExpressionParameter() throws IOException, ParserException { OLSyntaxNode ret = null; eat( Scanner.TokenType.LPAREN, "expected (" ); if( token.isNot( Scanner.TokenType.RPAREN ) ) { ret = parseExpression(); } eat( Scanner.TokenType.RPAREN, "expected )" ); return ret; } private OLSyntaxNode parseOutputOperationStatement( String id ) throws IOException, ParserException { ParsingContext context = getContext(); String outputPortId = token.content(); nextToken(); OLSyntaxNode outputExpression = parseOperationExpressionParameter(); OLSyntaxNode stm; if( token.is( Scanner.TokenType.LPAREN ) ) { // Solicit Response operation VariablePathNode inputVarPath = parseOperationVariablePathParameter(); Optional< InstallFunctionNode > function = Optional.empty(); if( token.is( Scanner.TokenType.LSQUARE ) ) { boolean newLine = hasMetNewline(); eat( Scanner.TokenType.LSQUARE, "expected [" ); function = parseInstallFunction( newLine ); if( function.isPresent() ) { eat( Scanner.TokenType.RSQUARE, "expected ]" ); } } stm = new SolicitResponseOperationStatement( context, id, outputPortId, outputExpression, inputVarPath, function ); } else { // Notification operation stm = new NotificationOperationStatement( context, id, outputPortId, outputExpression ); } return stm; } private OLSyntaxNode parseWhileStatement() throws IOException, ParserException { ParsingContext context = getContext(); OLSyntaxNode cond, process; nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); cond = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); eat( Scanner.TokenType.LCURLY, "expected {" ); process = parseProcess(); eat( Scanner.TokenType.RCURLY, "expected }" ); return new WhileStatement( context, cond, process ); } private OLSyntaxNode parseExpression() throws IOException, ParserException { OrConditionNode orCond = new OrConditionNode( getContext() ); orCond.addChild( parseAndCondition() ); while( token.is( Scanner.TokenType.OR ) ) { nextToken(); orCond.addChild( parseAndCondition() ); } return orCond; } private OLSyntaxNode parseAndCondition() throws IOException, ParserException { AndConditionNode andCond = new AndConditionNode( getContext() ); andCond.addChild( parseBasicCondition() ); while( token.is( Scanner.TokenType.AND ) ) { nextToken(); andCond.addChild( parseBasicCondition() ); } return andCond; } private NativeType readNativeType() { if( token.is( Scanner.TokenType.CAST_INT ) ) { return NativeType.INT; } else if( token.is( Scanner.TokenType.CAST_DOUBLE ) ) { return NativeType.DOUBLE; } else if( token.is( Scanner.TokenType.CAST_STRING ) ) { return NativeType.STRING; } else if( token.is( Scanner.TokenType.CAST_LONG ) ) { return NativeType.LONG; } else if( token.is( Scanner.TokenType.CAST_BOOL ) ) { return NativeType.BOOL; } else { return NativeType.fromString( token.content() ); } } private OLSyntaxNode parseBasicCondition() throws IOException, ParserException { OLSyntaxNode ret; Scanner.TokenType opType; OLSyntaxNode expr1; expr1 = parseBasicExpression(); opType = token.type(); if( opType == Scanner.TokenType.EQUAL || opType == Scanner.TokenType.LANGLE || opType == Scanner.TokenType.RANGLE || opType == Scanner.TokenType.MAJOR_OR_EQUAL || opType == Scanner.TokenType.MINOR_OR_EQUAL || opType == Scanner.TokenType.NOT_EQUAL ) { OLSyntaxNode expr2; nextToken(); expr2 = parseBasicExpression(); ret = new CompareConditionNode( getContext(), expr1, expr2, opType ); } else if( opType == Scanner.TokenType.INSTANCE_OF ) { nextToken(); NativeType nativeType = readNativeType(); if( nativeType == null ) { // It's a user-defined type assertToken( Scanner.TokenType.ID, "expected type name after instanceof" ); } String typeName = token.content(); TypeDefinition type = definedTypes.getOrDefault( typeName, new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, typeName ) ); ret = new InstanceOfExpressionNode( getContext(), expr1, type ); nextToken(); } else { ret = expr1; } if( ret == null ) { throwException( "expected condition" ); } return ret; } /* * todo: Check if negative integer handling is appropriate */ private OLSyntaxNode parseBasicExpression() throws IOException, ParserException { boolean keepRun = true; SumExpressionNode sum = new SumExpressionNode( getContext() ); sum.add( parseProductExpression() ); while( keepRun ) { if( token.is( Scanner.TokenType.PLUS ) ) { nextToken(); sum.add( parseProductExpression() ); } else if( token.is( Scanner.TokenType.MINUS ) ) { nextToken(); sum.subtract( parseProductExpression() ); } else if( token.is( Scanner.TokenType.INT ) ) { // e.g. i -1 int value = Integer.parseInt( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else if( token.is( Scanner.TokenType.LONG ) ) { // e.g. i -1L long value = Long.parseLong( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else if( token.is( Scanner.TokenType.DOUBLE ) ) { // e.g. i -1 double value = Double.parseDouble( token.content() ); // We add it, because it's already negative. if( value < 0 ) { sum.add( parseProductExpression() ); } else { // e.g. i 1 throwException( "expected expression operator" ); } } else { keepRun = false; } } return sum; } private OLSyntaxNode parseFactor() throws IOException, ParserException { OLSyntaxNode retVal = null; VariablePathNode path = null; checkConstant(); switch( token.type() ) { case ID: path = parseVariablePath(); VariablePathNode freshValuePath = new VariablePathNode( getContext(), Type.NORMAL ); freshValuePath.append( new Pair<>( new ConstantStringExpression( getContext(), "new" ), new ConstantIntegerExpression( getContext(), 0 ) ) ); if( path.isEquivalentTo( freshValuePath ) ) { retVal = new FreshValueExpressionNode( path.context() ); return retVal; } break; case DOT: path = parseVariablePath(); break; case CARET: if( insideInstallFunction ) { nextToken(); path = parseVariablePath(); retVal = new InstallFixedVariableExpressionNode( getContext(), path ); return retVal; } break; default: break; } if( path != null ) { switch( token.type() ) { case INCREMENT: nextToken(); retVal = new PostIncrementStatement( getContext(), path ); break; case DECREMENT: nextToken(); retVal = new PostDecrementStatement( getContext(), path ); break; case ASSIGN: nextToken(); retVal = new AssignStatement( getContext(), path, parseExpression() ); break; default: retVal = new VariableExpressionNode( getContext(), path ); break; } } else { switch( token.type() ) { case NOT: nextToken(); retVal = new NotExpressionNode( getContext(), parseFactor() ); break; case STRING: retVal = new ConstantStringExpression( getContext(), token.content() ); nextToken(); break; case INT: retVal = new ConstantIntegerExpression( getContext(), Integer.parseInt( token.content() ) ); nextToken(); break; case LONG: retVal = new ConstantLongExpression( getContext(), Long.parseLong( token.content() ) ); nextToken(); break; case TRUE: retVal = new ConstantBoolExpression( getContext(), true ); nextToken(); break; case FALSE: retVal = new ConstantBoolExpression( getContext(), false ); nextToken(); break; case DOUBLE: retVal = new ConstantDoubleExpression( getContext(), Double.parseDouble( token.content() ) ); nextToken(); break; case LPAREN: nextToken(); retVal = parseExpression(); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case HASH: nextToken(); retVal = new ValueVectorSizeExpressionNode( getContext(), parseVariablePath() ); break; case INCREMENT: nextToken(); retVal = new PreIncrementStatement( getContext(), parseVariablePath() ); break; case DECREMENT: nextToken(); retVal = new PreDecrementStatement( getContext(), parseVariablePath() ); break; case IS_DEFINED: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.DEFINED, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_INT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.INT, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_DOUBLE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.DOUBLE, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_BOOL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.BOOL, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_LONG: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.LONG, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case IS_STRING: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new IsTypeExpressionNode( getContext(), IsTypeExpressionNode.CheckType.STRING, parseVariablePath() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_INT: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.INT, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_LONG: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.LONG, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_BOOL: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.BOOL, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_DOUBLE: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.DOUBLE, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; case CAST_STRING: nextToken(); eat( Scanner.TokenType.LPAREN, "expected (" ); retVal = new TypeCastExpressionNode( getContext(), NativeType.STRING, parseExpression() ); eat( Scanner.TokenType.RPAREN, "expected )" ); break; default: break; } } if( retVal == null ) { if( token.is( Scanner.TokenType.LCURLY ) ) { retVal = new VoidExpressionNode( getContext() ); } else { throwException( "expected expression" ); } } if( token.is( Scanner.TokenType.LCURLY ) ) { retVal = parseInlineTreeExpression( retVal ); } return retVal; } private OLSyntaxNode parseInlineTreeExpression( OLSyntaxNode rootExpression ) throws IOException, ParserException { eat( Scanner.TokenType.LCURLY, "expected {" ); VariablePathNode path; List< InlineTreeExpressionNode.Operation > operations = new ArrayList<>(); while( !token.is( Scanner.TokenType.RCURLY ) ) { maybeEat( Scanner.TokenType.DOT ); path = parseVariablePath(); InlineTreeExpressionNode.Operation operation = null; switch( token.type() ) { case DEEP_COPY_LEFT: nextToken(); operation = new InlineTreeExpressionNode.DeepCopyOperation( path, parseExpression() ); break; case ASSIGN: nextToken(); operation = new InlineTreeExpressionNode.AssignmentOperation( path, parseExpression() ); break; case POINTS_TO: nextToken(); operation = new InlineTreeExpressionNode.PointsToOperation( path, parseVariablePath() ); break; default: throwException( "expected =, <<, or ->" ); break; } operations.add( operation ); maybeEat( Scanner.TokenType.COMMA, Scanner.TokenType.SEQUENCE ); } eat( Scanner.TokenType.RCURLY, "expected }" ); return new InlineTreeExpressionNode( rootExpression.context(), rootExpression, operations.toArray( new InlineTreeExpressionNode.Operation[ 0 ] ) ); } private OLSyntaxNode parseProductExpression() throws IOException, ParserException { ProductExpressionNode product = new ProductExpressionNode( getContext() ); product.multiply( parseFactor() ); boolean keepRun = true; while( keepRun ) { switch( token.type() ) { case ASTERISK: nextToken(); product.multiply( parseFactor() ); break; case DIVIDE: nextToken(); product.divide( parseFactor() ); break; case PERCENT_SIGN: nextToken(); product.modulo( parseFactor() ); break; default: keepRun = false; break; } } return product; } private enum ExtendedIdentifierState { CAN_READ_ID, CANNOT_READ_ID, STOP } private String parseExtendedIdentifier( String errorMessage, Scanner.TokenType... extensions ) throws IOException, ParserException { List< String > importTargetComponents = new ArrayList<>(); ExtendedIdentifierState state = ExtendedIdentifierState.CAN_READ_ID; while( state != ExtendedIdentifierState.STOP ) { if( state == ExtendedIdentifierState.CAN_READ_ID && token.isIdentifier() ) { importTargetComponents.add( token.content() ); nextToken(); state = ExtendedIdentifierState.CANNOT_READ_ID; } else if( Arrays.stream( extensions ).anyMatch( extension -> token.is( extension ) ) ) { importTargetComponents.add( token.content() ); nextToken(); state = ExtendedIdentifierState.CAN_READ_ID; } else { state = ExtendedIdentifierState.STOP; } } String id = importTargetComponents.stream().collect( Collectors.joining() ); if( id.isEmpty() ) { throwException( errorMessage ); } return id; } private void parseImport() throws IOException, ParserException { if( token.is( Scanner.TokenType.FROM ) ) { ParsingContext context = getContext(); boolean isNamespaceImport = false; nextToken(); List< String > importTargets = new ArrayList<>(); boolean importTargetIDStarted = false; List< Pair< String, String > > pathNodes = null; boolean keepRun = true; do { if( token.is( Scanner.TokenType.IMPORT ) ) { keepRun = false; nextToken(); } else if( token.is( Scanner.TokenType.DOT ) ) { if( !importTargetIDStarted ) { importTargets.add( token.content() ); } nextToken(); } else { importTargets.add( parseExtendedIdentifier( "expected identifier for importing target after from", Scanner.TokenType.MINUS, Scanner.TokenType.AT ) ); importTargetIDStarted = true; // nextToken(); } } while( keepRun ); if( token.is( Scanner.TokenType.ASTERISK ) ) { isNamespaceImport = true; nextToken(); } else { assertIdentifier( "expected Identifier or * after import" ); pathNodes = new ArrayList<>(); keepRun = false; do { String targetName = token.content(); String localName = targetName; nextToken(); if( token.is( Scanner.TokenType.AS ) ) { nextToken(); assertIdentifier( "expected Identifier after as" ); localName = token.content(); nextToken(); } pathNodes.add( new Pair< String, String >( targetName, localName ) ); if( token.is( Scanner.TokenType.COMMA ) ) { keepRun = true; nextToken(); } else { keepRun = false; } } while( keepRun ); } ImportStatement stmt = null; if( isNamespaceImport ) { stmt = new ImportStatement( context, Collections.unmodifiableList( importTargets ) ); } else { stmt = new ImportStatement( context, Collections.unmodifiableList( importTargets ), Collections.unmodifiableList( pathNodes ) ); } programBuilder.addChild( stmt ); return; } } private static class IncludeFile { private final InputStream inputStream; private final String parentPath; private final URI uri; private IncludeFile( InputStream inputStream, String parentPath, URI uri ) { this.inputStream = inputStream; this.parentPath = parentPath; this.uri = uri; } private InputStream getInputStream() { return inputStream; } private String getParentPath() { return parentPath; } private URI getURI() { return uri; } } }
fix add/eat token when access modifier token is present
libjolie/src/main/java/jolie/lang/parse/OLParser.java
fix add/eat token when access modifier token is present
Java
lgpl-2.1
2b6537d02b33437f61d48d7dbeafcdc45965a152
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
package org.jetel.util; import java.util.Iterator; import java.util.NoSuchElementException; import org.jetel.util.string.StringUtils; /** * Class for resolving integer number from given mask.<br> * Mask can be in form: * <ul><li>*</li> * <li>number</li> * <li>minNumber-maxNumber</li> * <li>*-maxNumber</li> * <li>minNumber-*</li> * or as their combination separated by comma, eg. 1,3,5-7,9-* * * @author avackova (agata.vackova@javlinconsulting.cz) ; * (c) JavlinConsulting s.r.o. * www.javlinconsulting.cz * * @since Feb 23, 2007 * */ public class NumberIterator implements Iterator<Integer>{ private final static String ALL_NUMBERS_PATTERN = "*"; private String pattern; private String subPattern; private int index = 0; private int comaIndex; private int last; private int first; private IntervalIterator intervalIterator = null; private Integer next = null; private Integer tmp; /** * Constructor from given mask * * @param pattern */ public NumberIterator(String pattern, int first,int last){ this.first = first; this.last = last; this.pattern = pattern.trim(); if (pattern.equals(ALL_NUMBERS_PATTERN)) { subPattern = pattern; } next = first - 1; next = getNext(); } public NumberIterator(String pattern){ this(pattern, IntervalIterator.FIRST_ELEMENT, IntervalIterator.LAST_ELEMENT); } public void reset() { if (!subPattern.equals(ALL_NUMBERS_PATTERN)) { subPattern = null; } intervalIterator = null; index = 0; next = first - 1; next = getNext(); } private Integer getNext(){ if (pattern.equals("*")) { next++; return next <= last ? next : null; } //check if in current interval there is more numbers if (intervalIterator != null && intervalIterator.hasNext() ) { return intervalIterator.next(); } //get next part of pattern if (index == pattern.length()) {//end of mask return null; } comaIndex = pattern.indexOf(',', index); if (comaIndex == -1) { subPattern = pattern.substring(index).trim(); index = pattern.length(); }else{ subPattern = pattern.substring(index,comaIndex).trim(); index = comaIndex + 1; } if (StringUtils.isInteger(subPattern) == 0 || StringUtils.isInteger(subPattern) == 1) { intervalIterator = null; return Integer.parseInt(subPattern); }else { intervalIterator = new IntervalIterator(subPattern,first,last); if (intervalIterator.hasNext()) { return intervalIterator.next(); }else{ return getNext(); } } } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return next != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public Integer next() { tmp = next; if (next == null) { throw new NoSuchElementException(); } next = getNext(); return tmp; } public void remove() { throw new UnsupportedOperationException(); } /** * Class for resolving integer number from given mask. Mask has to be in form: * minNuber-maxNumber, when minNumber, maxNumber are integers or "*" * * * @author avackova (agata.vackova@javlinconsulting.cz) ; * (c) JavlinConsulting s.r.o. * www.javlinconsulting.cz * * @since Feb 23, 2007 * */ private class IntervalIterator implements Iterator<Integer>{ public final static int FIRST_ELEMENT = Integer.MIN_VALUE; public final static int LAST_ELEMENT = Integer.MAX_VALUE; private final static char DASH = '-'; private String firstPattern; private String lastPattern; private int next; private Integer last; /** * Constructor from given pattern * * @param pattern */ IntervalIterator(String pattern) { this(pattern,FIRST_ELEMENT,LAST_ELEMENT); } IntervalIterator(String pattern, int first, int last) { next = first; this.last = last; int dashIndex= pattern.trim().indexOf(DASH); if (dashIndex == -1) { throw new IllegalArgumentException("Not integer interval: " + pattern); }else if (dashIndex == 0) { dashIndex = pattern.indexOf(DASH, 1); if (dashIndex == -1) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } firstPattern = pattern.substring(0,dashIndex).trim(); lastPattern = pattern.substring(dashIndex + 1).trim(); if (!firstPattern.equals("*")) { try { next = Integer.parseInt(firstPattern); } catch (NumberFormatException e) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } if (!lastPattern.equals("*")){ try { this.last = Integer.parseInt(lastPattern); } catch (NumberFormatException e) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } } public boolean hasNext() { return (next <= last); } public Integer next() { return hasNext() ? next++ : null; } public void remove() { throw new UnsupportedOperationException(); } } }
cloveretl.engine/src/org/jetel/util/NumberIterator.java
package org.jetel.util; import java.util.Iterator; import java.util.NoSuchElementException; import org.jetel.util.string.StringUtils; /** * Class for resolving integer number from given mask.<br> * Mask can be in form: * <ul><li>*</li> * <li>number</li> * <li>minNumber-maxNumber</li> * <li>*-maxNumber</li> * <li>minNumber-*</li> * or as their combination separated by comma, eg. 1,3,5-7,9-* * * @author avackova (agata.vackova@javlinconsulting.cz) ; * (c) JavlinConsulting s.r.o. * www.javlinconsulting.cz * * @since Feb 23, 2007 * */ public class NumberIterator implements Iterator<Integer>{ private String pattern; private String subPattern; private int index = 0; private int comaIndex; private int last; private int first; private IntervalIterator intervalIterator = null; private Integer next = null; private Integer tmp; /** * Constructor from given mask * * @param pattern */ public NumberIterator(String pattern, int first,int last){ this.first = first; this.last = last; this.pattern = pattern.trim(); if (pattern.equals("*")) { subPattern = pattern; } next = first - 1; next = getNext(); } public NumberIterator(String pattern){ this(pattern, IntervalIterator.FIRST_ELEMENT, IntervalIterator.LAST_ELEMENT); } public void reset() { next = first - 1; next = getNext(); } private Integer getNext(){ if (pattern.equals("*")) { next++; return next <= last ? next : null; } //check if in current interval there is more numbers if (intervalIterator != null && intervalIterator.hasNext() ) { return intervalIterator.next(); } //get next part of pattern if (index == pattern.length()) {//end of mask return null; } comaIndex = pattern.indexOf(',', index); if (comaIndex == -1) { subPattern = pattern.substring(index).trim(); index = pattern.length(); }else{ subPattern = pattern.substring(index,comaIndex).trim(); index = comaIndex + 1; } if (StringUtils.isInteger(subPattern) == 0 || StringUtils.isInteger(subPattern) == 1) { intervalIterator = null; return Integer.parseInt(subPattern); }else { intervalIterator = new IntervalIterator(subPattern,first,last); if (intervalIterator.hasNext()) { return intervalIterator.next(); }else{ return getNext(); } } } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return next != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public Integer next() { tmp = next; if (next == null) { throw new NoSuchElementException(); } next = getNext(); return tmp; } public void remove() { throw new UnsupportedOperationException(); } /** * Class for resolving integer number from given mask. Mask has to be in form: * minNuber-maxNumber, when minNumber, maxNumber are integers or "*" * * * @author avackova (agata.vackova@javlinconsulting.cz) ; * (c) JavlinConsulting s.r.o. * www.javlinconsulting.cz * * @since Feb 23, 2007 * */ private class IntervalIterator implements Iterator<Integer>{ public final static int FIRST_ELEMENT = Integer.MIN_VALUE; public final static int LAST_ELEMENT = Integer.MAX_VALUE; private final static char DASH = '-'; private String firstPattern; private String lastPattern; private int next; private Integer last; /** * Constructor from given pattern * * @param pattern */ IntervalIterator(String pattern) { this(pattern,FIRST_ELEMENT,LAST_ELEMENT); } IntervalIterator(String pattern, int first, int last) { next = first; this.last = last; int dashIndex= pattern.trim().indexOf(DASH); if (dashIndex == -1) { throw new IllegalArgumentException("Not integer interval: " + pattern); }else if (dashIndex == 0) { dashIndex = pattern.indexOf(DASH, 1); if (dashIndex == -1) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } firstPattern = pattern.substring(0,dashIndex).trim(); lastPattern = pattern.substring(dashIndex + 1).trim(); if (!firstPattern.equals("*")) { try { next = Integer.parseInt(firstPattern); } catch (NumberFormatException e) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } if (!lastPattern.equals("*")){ try { this.last = Integer.parseInt(lastPattern); } catch (NumberFormatException e) { throw new IllegalArgumentException("Not integer interval: " + pattern); } } } public boolean hasNext() { return (next <= last); } public Integer next() { return hasNext() ? next++ : null; } public void remove() { throw new UnsupportedOperationException(); } } }
FIX:NumberIterator - fixed reset() method git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@3927 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/util/NumberIterator.java
FIX:NumberIterator - fixed reset() method
Java
apache-2.0
bc18a45776e200084881578a9c5ac247fe785117
0
filestack/filestack-java,filestack/filestack-java
package com.filestack.util; import com.google.gson.JsonObject; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface FsCloudService { String URL = "https://cloud.filestackapi.com/"; @POST("prefetch") Call<JsonObject> prefetch(@Body JsonObject body); @POST("folder/list") Call<JsonObject> list(@Body JsonObject body); // Cloudrouter requires the trailing slash @POST("store/") Call<JsonObject> store(@Body JsonObject body); @POST("/auth/logout") Call<ResponseBody> logout(@Body JsonObject body); }
src/main/java/com/filestack/util/FsCloudService.java
package com.filestack.util; import com.google.gson.JsonObject; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface FsCloudService { String URL = "https://cloud.filestackapi.com/"; @POST("prefetch") Call<JsonObject> prefetch(@Body JsonObject body); @POST("folder/list") Call<JsonObject> list(@Body JsonObject body); // Cloudrouter requires the trailing slash @POST("store/") Call<JsonObject> store(@Body JsonObject body); }
Add cloud logout endpoint
src/main/java/com/filestack/util/FsCloudService.java
Add cloud logout endpoint
Java
apache-2.0
8790d0a9aa49d960bf487be7f49e1f6472f18c7a
0
openmandragora/xeneo-db-impl
package org.xeneo.db; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.xeneo.core.plugin.PluginConfiguration; import org.xeneo.core.plugin.PluginProperty; import org.xeneo.core.plugin.PluginPropertyType; import org.xeneo.core.plugin.PluginRepository; import org.xeneo.core.plugin.PluginType; /** * * @author Stefan Huber */ public class JdbcPluginRepository implements PluginRepository { private static Logger logger = LoggerFactory.getLogger(JdbcPluginRepository.class); private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertPluginInstance; public void setJdbcTemplate(JdbcTemplate jt) { this.jdbcTemplate = jt; // create plugin instance insert insertPluginInstance = new SimpleJdbcInsert(jdbcTemplate); insertPluginInstance.withTableName("PluginInstance"); insertPluginInstance.usingGeneratedKeyColumns("PluginInstanceID"); } // Plugin Table private static final String PLUGIN_EXISTS = "select count(*) from Plugin where PluginURI = ?"; private static final String PLUGIN_UPDATE = "update Plugin set PluginType=?, Title=?, Description=?, Classname=?, Active=1 where PluginURI = ?"; private static final String PLUGIN_ADD = "insert into Plugin (PluginURI,PluginType,Title,Description,Classname,Active) values (?,?,?,?,?,1)"; private static final String PLUGIN_DEACTIVATE = "update Plugin set Active=0 where PluginURI = ?"; // Plugin Property Table private static final String PLUGIN_PROPERTIES_ADD = "insert into PluginProperty (PluginURI,Name,Type) values %s"; private static final String PLUGIN_PROPERTIES_DELETE = "delete from pluginproperty where PluginURI = ?"; // CRAZY PLUGIN LISTING QUERY private static final String PLUGIN_LIST = "select p.PluginURI, p.PluginType, p.Title, p.Description, p.Classname, pp.Name, pp.Type, pi.PluginInstanceID, pip.Value from Plugin p inner join PluginProperty pp on p.pluginURI = pp.pluginURI left join PluginInstance pi on p.pluginURI = pi.pluginURI left join PluginInstanceProperty pip on (pip.Name = pp.Name and pip.PluginInstanceID = pi.PluginInstanceID) where pi.OwnerURI = ? and p.active = 1 "; // Plugin Instance Table private static final String PLUGIN_INSTANCE_EXISTS = "select count(*) from PluginInstance where PluginURI = ? and OwnerURI = ?"; private static final String PLUGIN_INSTANCE_ADD = "insert into PluginInstance (PluginURI,OwnerURI,Active) values (?,?,1)"; private static final String PLUGIN_INSTANCE_UPDATE = "update PluginInstance set PluginURI=?,OwnerURI=?"; // Plugin Instance Property Table private static final String PLUGIN_INSTANCE_PROPERTY_ADD = "insert into PluginInstanceProperty (PluginInstanceID,Name,Value) values %s"; private static final String PLUGIN_INSTANCE_PROPERTY_DELETE = "delete from PluginInstanceProperty where PluginInstanceID = ?"; public void init() { logger.info("PluginManager initialized."); } public void addPlugin(PluginConfiguration configuration) { logger.info("Try to add plugin with URI: " + configuration.getPluginURI() + " and name: " + configuration.getTitle()); boolean preDelete = false; if (jdbcTemplate.queryForInt(PLUGIN_EXISTS, configuration.getPluginURI()) > 0) { logger.info("update Plugin: " + configuration.getTitle()); jdbcTemplate.update(PLUGIN_UPDATE, configuration.getPluginType().typeURI(), configuration.getTitle(), configuration.getDescription(), configuration.getPluginClass(), configuration.getPluginURI()); preDelete = true; } else { logger.info("add Plugin: " + configuration.getTitle()); jdbcTemplate.update(PLUGIN_ADD, configuration.getPluginURI(), configuration.getPluginType(), configuration.getTitle(), configuration.getDescription(), configuration.getPluginClass()); } addPluginProperties(configuration.getPluginURI(),configuration.getProperties(),preDelete); } public void addPluginProperties(String pluginURI, PluginProperty[] props, boolean preDelete) { if (preDelete) { jdbcTemplate.update(PLUGIN_PROPERTIES_DELETE, pluginURI); } String values = ""; for (PluginProperty p : props) { values += ",('" + pluginURI + "','" + p.getName() + "','" + p.getType().name() + "')"; } // substring 1 to strip the first "," String query = String.format(PLUGIN_PROPERTIES_ADD, values.substring(1)); logger.info("INSERT INTO PLUGIN PROPERTIES QUERY: " + query); jdbcTemplate.update(query); } public void deactivatePlugin(String pluginURI) { logger.info("Try to deactivate Plugin with URI: " + pluginURI); jdbcTemplate.update(PLUGIN_DEACTIVATE, pluginURI); } public void configurePlugin(PluginConfiguration pc) { if (pc.getId()<0) { Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("PluginURI", pc.getPluginURI()); parameters.put("OwnerURI", pc.getOwnerURI()); parameters.put("Active", true); Number n = insertPluginInstance.executeAndReturnKey(parameters); addPluginInstanceProperties(n.intValue(), pc.getProperties(), false); } else { // no update of teh Plugin Instance Table is done, because only PluginURI and OwnerURI, which remain the same throughout the lifetime of an instance addPluginInstanceProperties(pc.getId(), pc.getProperties(), true); } } public void addPluginInstanceProperties(int pluginInstanceId, PluginProperty[] props, boolean preDelete) { if (preDelete) { jdbcTemplate.update(PLUGIN_INSTANCE_PROPERTY_DELETE, pluginInstanceId); } String values = ""; for (PluginProperty p : props) { values += ",('" + pluginInstanceId + "','" + p.getName() + "','" + p.getValue() + "')"; } String query = String.format(PLUGIN_INSTANCE_PROPERTY_ADD, values.substring(1)); logger.info("INSERT INTO PLUGIN PROPERTIES QUERY: " + query); jdbcTemplate.update(query); } public List<PluginConfiguration> listAvailablePlugins(String userURI, PluginType[] pts) { SqlRowSet set = jdbcTemplate.queryForRowSet(PLUGIN_LIST, userURI); Map<String,PluginConfiguration> output = new HashMap<String,PluginConfiguration>(); while (set.next()) { String pluginURI = set.getString("p.PluginURI"); String pluginType = set.getString("p.PluginType"); String className = set.getString("p.Classname"); String title = set.getString("p.Title"); String desc = set.getString("p.Description"); String paramName = set.getString("pp.Name"); String paramType = set.getString("pp.Type"); String paramValue = set.getString("pip.Value"); int pluginInstanceId = set.getInt("pi.PluginInstanceID"); if (!output.containsKey(pluginURI)) { PluginConfiguration pc = new PluginConfiguration(); pc.setPluginURI(pluginURI); pc.setPluginType(PluginType.valueOf(pluginType)); pc.setOwnerURI(userURI); pc.setTitle(title); pc.setDescription(desc); if (pluginInstanceId > 0) pc.setId(pluginInstanceId); // TODO: maybe find a better key for the map output.put(pluginURI, pc); } PluginProperty pp = new PluginProperty(); pp.setName(paramName); pp.setType(PluginPropertyType.valueOf(paramType)); if (paramValue != null && !paramValue.isEmpty()) pp.setValue(paramValue); PluginConfiguration pc = output.get(pluginURI); pc.addProperty(pp); } return new ArrayList<PluginConfiguration>(output.values()); } }
src/main/java/org/xeneo/db/JdbcPluginRepository.java
package org.xeneo.db; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.xeneo.core.plugin.PluginConfiguration; import org.xeneo.core.plugin.PluginProperty; import org.xeneo.core.plugin.PluginPropertyType; import org.xeneo.core.plugin.PluginRepository; import org.xeneo.core.plugin.PluginType; /** * * @author Stefan Huber */ public class JdbcPluginRepository implements PluginRepository { private static Logger logger = LoggerFactory.getLogger(JdbcPluginRepository.class); private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertPluginInstance; public void setJdbcTemplate(JdbcTemplate jt) { this.jdbcTemplate = jt; // create plugin instance insert insertPluginInstance = new SimpleJdbcInsert(jdbcTemplate); insertPluginInstance.withTableName("PluginInstance"); insertPluginInstance.usingGeneratedKeyColumns("PluginInstanceID"); } // Plugin Table private static final String PLUGIN_EXISTS = "select count(*) from Plugin where PluginURI = ?"; private static final String PLUGIN_UPDATE = "update Plugin set PluginType=?, Title=?, Description=?, Classname=?, Active=1 where PluginURI = ?"; private static final String PLUGIN_ADD = "insert into Plugin (PluginURI,PluginType,Title,Description,Classname,Active) values (?,?,?,?,?,1)"; private static final String PLUGIN_DEACTIVATE = "update Plugin set Active=0 where PluginURI = ?"; // Plugin Property Table private static final String PLUGIN_PROPERTIES_ADD = "insert into PluginProperty (PluginURI,Name,Type) values %s"; private static final String PLUGIN_PROPERTIES_DELETE = "delete from pluginproperty where PluginURI = ?"; // CRAZY PLUGIN LISTING QUERY private static final String PLUGIN_LIST = "select p.PluginURI, p.PluginType, p.Title, p.Description, p.Classname, pp.Name, pp.Type, pi.PluginInstanceID, pip.Value from Plugin p inner join PluginProperty pp on p.pluginURI = pp.pluginURI left join PluginInstance pi on p.pluginURI = pi.pluginURI left join PluginInstanceProperty pip on (pip.Name = pp.Name and pip.PluginInstanceID = pi.PluginInstanceID) where pi.OwnerURI = ? and p.active = 1 "; // Plugin Instance Table private static final String PLUGIN_INSTANCE_EXISTS = "select count(*) from PluginInstance where PluginURI = ? and OwnerURI = ?"; private static final String PLUGIN_INSTANCE_ADD = "insert into PluginInstance (PluginURI,OwnerURI,Active) values (?,?,1)"; private static final String PLUGIN_INSTANCE_UPDATE = "update PluginInstance set PluginURI=?,OwnerURI=?"; // Plugin Instance Property Table private static final String PLUGIN_INSTANCE_PROPERTY_ADD = "insert into PluginInstanceProperty (PluginInstanceID,Name,Value) values %s"; private static final String PLUGIN_INSTANCE_PROPERTY_DELETE = "delete from PluginInstanceProperty where PluginInstanceID = ?"; public void init() { logger.info("PluginManager initialized."); } public void addPlugin(PluginConfiguration configuration) { logger.info("Try to add plugin with URI: " + configuration.getPluginURI() + " and name: " + configuration.getTitle()); boolean preDelete = false; if (jdbcTemplate.queryForInt(PLUGIN_EXISTS, configuration.getPluginURI()) > 0) { logger.info("update Plugin: " + configuration.getTitle()); jdbcTemplate.update(PLUGIN_UPDATE, configuration.getPluginType().typeURI(), configuration.getTitle(), configuration.getDescription(), configuration.getPluginClass(), configuration.getPluginURI()); preDelete = true; } else { logger.info("add Plugin: " + configuration.getTitle()); jdbcTemplate.update(PLUGIN_ADD, configuration.getPluginURI(), configuration.getPluginType(), configuration.getTitle(), configuration.getDescription(), configuration.getPluginClass()); } addPluginProperties(configuration.getPluginURI(),configuration.getProperties(),preDelete); } public void addPluginProperties(String pluginURI, PluginProperty[] props, boolean preDelete) { if (preDelete) { jdbcTemplate.update(PLUGIN_PROPERTIES_DELETE, pluginURI); } String values = ""; for (PluginProperty p : props) { values += ",('" + pluginURI + "','" + p.getName() + "','" + p.getType().name() + "')"; } // substring 1 to strip the first "," String query = String.format(PLUGIN_PROPERTIES_ADD, values.substring(1)); logger.info("INSERT INTO PLUGIN PROPERTIES QUERY: " + query); jdbcTemplate.update(query); } public void deactivatePlugin(String pluginURI) { logger.info("Try to deactivate Plugin with URI: " + pluginURI); jdbcTemplate.update(PLUGIN_DEACTIVATE, pluginURI); } public void configurePlugin(PluginConfiguration pc) { if (pc.getId()<0) { Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("PluginURI", pc.getPluginURI()); parameters.put("OwnerURI", pc.getOwnerURI()); parameters.put("Active", true); Number n = insertPluginInstance.executeAndReturnKey(parameters); addPluginInstanceProperties(n.intValue(), pc.getProperties(), false); } else { // no update of teh Plugin Instance Table is done, because only PluginURI and OwnerURI, which remain the same throughout the lifetime of an instance addPluginInstanceProperties(pc.getId(), pc.getProperties(), true); } } public void addPluginInstanceProperties(int pluginInstanceId, PluginProperty[] props, boolean preDelete) { if (preDelete) { jdbcTemplate.update(PLUGIN_INSTANCE_PROPERTY_DELETE, pluginInstanceId); } String values = ""; for (PluginProperty p : props) { values += ",('" + pluginInstanceId + "','" + p.getName() + "','" + p.getValue() + "')"; } String query = String.format(PLUGIN_INSTANCE_PROPERTY_ADD, values.substring(1)); logger.info("INSERT INTO PLUGIN PROPERTIES QUERY: " + query); jdbcTemplate.update(query); } public List<PluginConfiguration> listAvailablePlugins(String userURI, PluginType[] pts) { SqlRowSet set = jdbcTemplate.queryForRowSet(PLUGIN_LIST, userURI); Map<String,PluginConfiguration> output = new HashMap<String,PluginConfiguration>(); while (set.next()) { String pluginURI = set.getString("p.PluginURI"); String pluginType = set.getString("p.PluginType"); String className = set.getString("p.Classname"); String title = set.getString("p.Title"); String desc = set.getString("p.Description"); String paramName = set.getString("pp.Name"); String paramType = set.getString("pp.Type"); String paramValue = set.getString("pip.Value"); int pluginInstanceId = set.getInt("pi.PluginInstanceID"); if (!output.containsKey(pluginURI)) { PluginConfiguration pc = new PluginConfiguration(); pc.setPluginURI(pluginURI); pc.setPluginType(PluginType.valueOf(pluginType)); pc.setOwnerURI(userURI); pc.setTitle(title); pc.setDescription(desc); if (pluginInstanceId > 0) pc.setId(pluginInstanceId); // TODO: maybe find a better key for the map output.put(pluginURI, pc); } PluginProperty pp = new PluginProperty(); pp.setName(paramName); pp.setType(PluginPropertyType.valueOf(paramType)); if (paramValue != null && !paramValue.isEmpty()) pp.setValue(paramValue); PluginConfiguration pc = output.get(pluginURI); pc.addProperty(pp); } return new ArrayList<PluginConfiguration>(output.values()); } }
modified Plugin Sql
src/main/java/org/xeneo/db/JdbcPluginRepository.java
modified Plugin Sql
Java
apache-2.0
b22e9ef930838d3adc5a6f19adf8ba18a43f74a2
0
qingsong-xu/butterknife,ze-pequeno/butterknife,qingsong-xu/butterknife,JakeWharton/butterknife,ChristianBecker/butterknife,ze-pequeno/butterknife,JakeWharton/butterknife,ze-pequeno/butterknife,ChristianBecker/butterknife,ChristianBecker/butterknife,JakeWharton/butterknife,hzsweers/butterknife,hzsweers/butterknife,JakeWharton/butterknife,hzsweers/butterknife,ChristianBecker/butterknife,ze-pequeno/butterknife,qingsong-xu/butterknife
package butterknife.compiler; import butterknife.BindArray; import butterknife.BindBitmap; import butterknife.BindBool; import butterknife.BindColor; import butterknife.BindDimen; import butterknife.BindDrawable; import butterknife.BindInt; import butterknife.BindString; import butterknife.BindView; import butterknife.BindViews; import butterknife.OnCheckedChanged; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnFocusChange; import butterknife.OnItemClick; import butterknife.OnItemLongClick; import butterknife.OnItemSelected; import butterknife.OnLongClick; import butterknife.OnPageChange; import butterknife.OnTextChanged; import butterknife.OnTouch; import butterknife.Optional; import butterknife.internal.ListenerClass; import butterknife.internal.ListenerMethod; import com.google.auto.common.SuperficialValidation; import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.sun.source.tree.ClassTree; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeScanner; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; 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.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.ElementKind.INTERFACE; import static javax.lang.model.element.ElementKind.METHOD; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; @AutoService(Processor.class) public final class ButterKnifeProcessor extends AbstractProcessor { static final Id NO_ID = new Id(-1); static final String VIEW_TYPE = "android.view.View"; private static final String COLOR_STATE_LIST_TYPE = "android.content.res.ColorStateList"; private static final String BITMAP_TYPE = "android.graphics.Bitmap"; private static final String DRAWABLE_TYPE = "android.graphics.drawable.Drawable"; private static final String TYPED_ARRAY_TYPE = "android.content.res.TypedArray"; private static final String NULLABLE_ANNOTATION_NAME = "Nullable"; private static final String STRING_TYPE = "java.lang.String"; private static final String LIST_TYPE = List.class.getCanonicalName(); private static final String R = "R"; private static final List<Class<? extends Annotation>> LISTENERS = Arrays.asList(// OnCheckedChanged.class, // OnClick.class, // OnEditorAction.class, // OnFocusChange.class, // OnItemClick.class, // OnItemLongClick.class, // OnItemSelected.class, // OnLongClick.class, // OnPageChange.class, // OnTextChanged.class, // OnTouch.class // ); private static final List<String> SUPPORTED_TYPES = Arrays.asList( "array", "attr", "bool", "color", "dimen", "drawable", "id", "integer", "string" ); private Elements elementUtils; private Types typeUtils; private Filer filer; private Trees trees; private final Map<Integer, Id> symbols = new LinkedHashMap<>(); @Override public synchronized void init(ProcessingEnvironment env) { super.init(env); elementUtils = env.getElementUtils(); typeUtils = env.getTypeUtils(); filer = env.getFiler(); trees = Trees.instance(processingEnv); } @Override public Set<String> getSupportedAnnotationTypes() { Set<String> types = new LinkedHashSet<>(); for (Class<? extends Annotation> annotation : getSupportedAnnotations()) { types.add(annotation.getCanonicalName()); } return types; } private Set<Class<? extends Annotation>> getSupportedAnnotations() { Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>(); annotations.add(BindArray.class); annotations.add(BindBitmap.class); annotations.add(BindBool.class); annotations.add(BindColor.class); annotations.add(BindDimen.class); annotations.add(BindDrawable.class); annotations.add(BindInt.class); annotations.add(BindString.class); annotations.add(BindView.class); annotations.add(BindViews.class); annotations.addAll(LISTENERS); return annotations; } @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env); for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); BindingClass bindingClass = entry.getValue(); for (JavaFile javaFile : bindingClass.brewJava()) { try { javaFile.writeTo(filer); } catch (IOException e) { error(typeElement, "Unable to write view binder for type %s: %s", typeElement, e.getMessage()); } } } return true; } private Map<TypeElement, BindingClass> findAndParseTargets(RoundEnvironment env) { Map<TypeElement, BindingClass> targetClassMap = new LinkedHashMap<>(); Set<TypeElement> erasedTargetNames = new LinkedHashSet<>(); scanForRClasses(env); // Process each @BindArray element. for (Element element : env.getElementsAnnotatedWith(BindArray.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceArray(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindArray.class, e); } } // Process each @BindBitmap element. for (Element element : env.getElementsAnnotatedWith(BindBitmap.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceBitmap(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindBitmap.class, e); } } // Process each @BindBool element. for (Element element : env.getElementsAnnotatedWith(BindBool.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceBool(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindBool.class, e); } } // Process each @BindColor element. for (Element element : env.getElementsAnnotatedWith(BindColor.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceColor(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindColor.class, e); } } // Process each @BindDimen element. for (Element element : env.getElementsAnnotatedWith(BindDimen.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceDimen(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindDimen.class, e); } } // Process each @BindDrawable element. for (Element element : env.getElementsAnnotatedWith(BindDrawable.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceDrawable(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindDrawable.class, e); } } // Process each @BindInt element. for (Element element : env.getElementsAnnotatedWith(BindInt.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceInt(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindInt.class, e); } } // Process each @BindString element. for (Element element : env.getElementsAnnotatedWith(BindString.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceString(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindString.class, e); } } // Process each @BindView element. for (Element element : env.getElementsAnnotatedWith(BindView.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseBindView(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindView.class, e); } } // Process each @BindViews element. for (Element element : env.getElementsAnnotatedWith(BindViews.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseBindViews(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindViews.class, e); } } // Process each annotation that corresponds to a listener. for (Class<? extends Annotation> listener : LISTENERS) { findAndParseListener(env, listener, targetClassMap, erasedTargetNames); } // Try to find a parent binder for each. for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) { TypeElement parentType = findParentType(entry.getKey(), erasedTargetNames); if (parentType != null) { BindingClass bindingClass = entry.getValue(); BindingClass parentBindingClass = targetClassMap.get(parentType); bindingClass.setParent(parentBindingClass); } } return targetClassMap; } private void logParsingError(Element element, Class<? extends Annotation> annotation, Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to parse @%s binding.\n\n%s", annotation.getSimpleName(), stackTrace); } private boolean isInaccessibleViaGeneratedCode(Class<? extends Annotation> annotationClass, String targetThing, Element element) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify method modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { error(element, "@%s %s must not be private or static. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error(enclosingElement, "@%s %s may only be contained in classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing class visibility is not private. if (enclosingElement.getModifiers().contains(PRIVATE)) { error(enclosingElement, "@%s %s may not be contained in private classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } return hasError; } private boolean isBindingInWrongPackage(Class<? extends Annotation> annotationClass, Element element) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); String qualifiedName = enclosingElement.getQualifiedName().toString(); if (qualifiedName.startsWith("android.")) { error(element, "@%s-annotated class incorrectly in Android framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } if (qualifiedName.startsWith("java.")) { error(element, "@%s-annotated class incorrectly in Java framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } return false; } private void parseBindView(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Start by verifying common generated code restrictions. boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element) || isBindingInWrongPackage(BindView.class, element); // Verify that the target type extends from View. TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) elementType; elementType = typeVariable.getUpperBound(); } if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) { error(element, "@%s fields must extend from View or be an interface. (%s.%s)", BindView.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } // Assemble information on the field. int id = element.getAnnotation(BindView.class).value(); BindingClass bindingClass = targetClassMap.get(enclosingElement); if (bindingClass != null) { ViewBindings viewBindings = bindingClass.getViewBinding(getId(id)); if (viewBindings != null && viewBindings.getFieldBinding() != null) { FieldViewBinding existingBinding = viewBindings.getFieldBinding(); error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)", BindView.class.getSimpleName(), id, existingBinding.getName(), enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } else { bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); } String name = element.getSimpleName().toString(); TypeName type = TypeName.get(elementType); boolean required = isFieldRequired(element); FieldViewBinding binding = new FieldViewBinding(name, type, required); bindingClass.addField(getId(id), binding); // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement); } private void parseBindViews(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Start by verifying common generated code restrictions. boolean hasError = isInaccessibleViaGeneratedCode(BindViews.class, "fields", element) || isBindingInWrongPackage(BindViews.class, element); // Verify that the type is a List or an array. TypeMirror elementType = element.asType(); String erasedType = doubleErasure(elementType); TypeMirror viewType = null; FieldCollectionViewBinding.Kind kind = null; if (elementType.getKind() == TypeKind.ARRAY) { ArrayType arrayType = (ArrayType) elementType; viewType = arrayType.getComponentType(); kind = FieldCollectionViewBinding.Kind.ARRAY; } else if (LIST_TYPE.equals(erasedType)) { DeclaredType declaredType = (DeclaredType) elementType; List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (typeArguments.size() != 1) { error(element, "@%s List must have a generic component. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } else { viewType = typeArguments.get(0); } kind = FieldCollectionViewBinding.Kind.LIST; } else { error(element, "@%s must be a List or array. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (viewType != null && viewType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) viewType; viewType = typeVariable.getUpperBound(); } // Verify that the target type extends from View. if (viewType != null && !isSubtypeOfType(viewType, VIEW_TYPE) && !isInterface(viewType)) { error(element, "@%s List or array type must extend from View or be an interface. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Assemble information on the field. String name = element.getSimpleName().toString(); int[] ids = element.getAnnotation(BindViews.class).value(); if (ids.length == 0) { error(element, "@%s must specify at least one ID. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } Integer duplicateId = findDuplicate(ids); if (duplicateId != null) { error(element, "@%s annotation contains duplicate ID %d. (%s.%s)", BindViews.class.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } assert viewType != null; // Always false as hasError would have been true. TypeName type = TypeName.get(viewType); boolean required = isFieldRequired(element); List<Id> idVars = new ArrayList<>(); for (int id : ids) { idVars.add(getId(id)); } BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldCollectionViewBinding binding = new FieldCollectionViewBinding(name, type, kind, required); bindingClass.addFieldCollection(idVars, binding); erasedTargetNames.add(enclosingElement); } private void parseResourceBool(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is bool. if (element.asType().getKind() != TypeKind.BOOLEAN) { error(element, "@%s field type must be 'boolean'. (%s.%s)", BindBool.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindBool.class, "fields", element); hasError |= isBindingInWrongPackage(BindBool.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindBool.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getBoolean", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceColor(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int or ColorStateList. boolean isColorStateList = false; TypeMirror elementType = element.asType(); if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) { isColorStateList = true; } else if (elementType.getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)", BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element); hasError |= isBindingInWrongPackage(BindColor.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindColor.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, isColorStateList ? "getColorStateList" : "getColor", true); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceDimen(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int or ColorStateList. boolean isInt = false; TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.INT) { isInt = true; } else if (elementType.getKind() != TypeKind.FLOAT) { error(element, "@%s field type must be 'int' or 'float'. (%s.%s)", BindDimen.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindDimen.class, "fields", element); hasError |= isBindingInWrongPackage(BindDimen.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindDimen.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, isInt ? "getDimensionPixelSize" : "getDimension", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceBitmap(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is Bitmap. if (!BITMAP_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'Bitmap'. (%s.%s)", BindBitmap.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindBitmap.class, "fields", element); hasError |= isBindingInWrongPackage(BindBitmap.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindBitmap.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldBitmapBinding binding = new FieldBitmapBinding(getId(id), name); bindingClass.addBitmap(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceDrawable(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is Drawable. if (!DRAWABLE_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'Drawable'. (%s.%s)", BindDrawable.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindDrawable.class, "fields", element); hasError |= isBindingInWrongPackage(BindDrawable.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindDrawable.class).value(); int tint = element.getAnnotation(BindDrawable.class).tint(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldDrawableBinding binding = new FieldDrawableBinding(getId(id), name, getId(tint)); bindingClass.addDrawable(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceInt(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int. if (element.asType().getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int'. (%s.%s)", BindInt.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindInt.class, "fields", element); hasError |= isBindingInWrongPackage(BindInt.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindInt.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getInteger", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceString(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is String. if (!STRING_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'String'. (%s.%s)", BindString.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindString.class, "fields", element); hasError |= isBindingInWrongPackage(BindString.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindString.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getString", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceArray(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is supported. String methodName = getArrayResourceMethodName(element); if (methodName == null) { error(element, "@%s field type must be one of: String[], int[], CharSequence[], %s. (%s.%s)", BindArray.class.getSimpleName(), TYPED_ARRAY_TYPE, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindArray.class, "fields", element); hasError |= isBindingInWrongPackage(BindArray.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindArray.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, methodName, false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } /** * Returns a method name from the {@link android.content.res.Resources} class for array resource * binding, null if the element type is not supported. */ private static String getArrayResourceMethodName(Element element) { TypeMirror typeMirror = element.asType(); if (TYPED_ARRAY_TYPE.equals(typeMirror.toString())) { return "obtainTypedArray"; } if (TypeKind.ARRAY.equals(typeMirror.getKind())) { ArrayType arrayType = (ArrayType) typeMirror; String componentType = arrayType.getComponentType().toString(); if (STRING_TYPE.equals(componentType)) { return "getStringArray"; } else if ("int".equals(componentType)) { return "getIntArray"; } else if ("java.lang.CharSequence".equals(componentType)) { return "getTextArray"; } } return null; } /** Returns the first duplicate element inside an array, null if there are no duplicates. */ private static Integer findDuplicate(int[] array) { Set<Integer> seenElements = new LinkedHashSet<>(); for (int element : array) { if (!seenElements.add(element)) { return element; } } return null; } /** Uses both {@link Types#erasure} and string manipulation to strip any generic types. */ private String doubleErasure(TypeMirror elementType) { String name = typeUtils.erasure(elementType).toString(); int typeParamStart = name.indexOf('<'); if (typeParamStart != -1) { name = name.substring(0, typeParamStart); } return name; } private void findAndParseListener(RoundEnvironment env, Class<? extends Annotation> annotationClass, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { for (Element element : env.getElementsAnnotatedWith(annotationClass)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseListenerAnnotation(annotationClass, element, targetClassMap, erasedTargetNames); } catch (Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to generate view binder for @%s.\n\n%s", annotationClass.getSimpleName(), stackTrace.toString()); } } } private void parseListenerAnnotation(Class<? extends Annotation> annotationClass, Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) throws Exception { // This should be guarded by the annotation's @Target but it's worth a check for safe casting. if (!(element instanceof ExecutableElement) || element.getKind() != METHOD) { throw new IllegalStateException( String.format("@%s annotation must be on a method.", annotationClass.getSimpleName())); } ExecutableElement executableElement = (ExecutableElement) element; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Assemble information on the method. Annotation annotation = element.getAnnotation(annotationClass); Method annotationValue = annotationClass.getDeclaredMethod("value"); if (annotationValue.getReturnType() != int[].class) { throw new IllegalStateException( String.format("@%s annotation value() type not int[].", annotationClass)); } int[] ids = (int[]) annotationValue.invoke(annotation); String name = executableElement.getSimpleName().toString(); boolean required = isListenerRequired(executableElement); // Verify that the method and its containing class are accessible via generated code. boolean hasError = isInaccessibleViaGeneratedCode(annotationClass, "methods", element); hasError |= isBindingInWrongPackage(annotationClass, element); Integer duplicateId = findDuplicate(ids); if (duplicateId != null) { error(element, "@%s annotation for method contains duplicate ID %d. (%s.%s)", annotationClass.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } ListenerClass listener = annotationClass.getAnnotation(ListenerClass.class); if (listener == null) { throw new IllegalStateException( String.format("No @%s defined on @%s.", ListenerClass.class.getSimpleName(), annotationClass.getSimpleName())); } for (int id : ids) { if (id == NO_ID.value) { if (ids.length == 1) { if (!required) { error(element, "ID-free binding must not be annotated with @Optional. (%s.%s)", enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify target type is valid for a binding without an id. String targetType = listener.targetType(); if (!isSubtypeOfType(enclosingElement.asType(), targetType) && !isInterface(enclosingElement.asType())) { error(element, "@%s annotation without an ID may only be used with an object of type " + "\"%s\" or an interface. (%s.%s)", annotationClass.getSimpleName(), targetType, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } } else { error(element, "@%s annotation contains invalid ID %d. (%s.%s)", annotationClass.getSimpleName(), id, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } } } ListenerMethod method; ListenerMethod[] methods = listener.method(); if (methods.length > 1) { throw new IllegalStateException(String.format("Multiple listener methods specified on @%s.", annotationClass.getSimpleName())); } else if (methods.length == 1) { if (listener.callbacks() != ListenerClass.NONE.class) { throw new IllegalStateException( String.format("Both method() and callback() defined on @%s.", annotationClass.getSimpleName())); } method = methods[0]; } else { Method annotationCallback = annotationClass.getDeclaredMethod("callback"); Enum<?> callback = (Enum<?>) annotationCallback.invoke(annotation); Field callbackField = callback.getDeclaringClass().getField(callback.name()); method = callbackField.getAnnotation(ListenerMethod.class); if (method == null) { throw new IllegalStateException( String.format("No @%s defined on @%s's %s.%s.", ListenerMethod.class.getSimpleName(), annotationClass.getSimpleName(), callback.getDeclaringClass().getSimpleName(), callback.name())); } } // Verify that the method has equal to or less than the number of parameters as the listener. List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > method.parameters().length) { error(element, "@%s methods can have at most %s parameter(s). (%s.%s)", annotationClass.getSimpleName(), method.parameters().length, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify method return type matches the listener. TypeMirror returnType = executableElement.getReturnType(); if (returnType instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) returnType; returnType = typeVariable.getUpperBound(); } if (!returnType.toString().equals(method.returnType())) { error(element, "@%s methods must have a '%s' return type. (%s.%s)", annotationClass.getSimpleName(), method.returnType(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } Parameter[] parameters = Parameter.NONE; if (!methodParameters.isEmpty()) { parameters = new Parameter[methodParameters.size()]; BitSet methodParameterUsed = new BitSet(methodParameters.size()); String[] parameterTypes = method.parameters(); for (int i = 0; i < methodParameters.size(); i++) { VariableElement methodParameter = methodParameters.get(i); TypeMirror methodParameterType = methodParameter.asType(); if (methodParameterType instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) methodParameterType; methodParameterType = typeVariable.getUpperBound(); } for (int j = 0; j < parameterTypes.length; j++) { if (methodParameterUsed.get(j)) { continue; } if (isSubtypeOfType(methodParameterType, parameterTypes[j]) || isInterface(methodParameterType)) { parameters[i] = new Parameter(j, TypeName.get(methodParameterType)); methodParameterUsed.set(j); break; } } if (parameters[i] == null) { StringBuilder builder = new StringBuilder(); builder.append("Unable to match @") .append(annotationClass.getSimpleName()) .append(" method arguments. (") .append(enclosingElement.getQualifiedName()) .append('.') .append(element.getSimpleName()) .append(')'); for (int j = 0; j < parameters.length; j++) { Parameter parameter = parameters[j]; builder.append("\n\n Parameter #") .append(j + 1) .append(": ") .append(methodParameters.get(j).asType().toString()) .append("\n "); if (parameter == null) { builder.append("did not match any listener parameters"); } else { builder.append("matched listener parameter #") .append(parameter.getListenerPosition() + 1) .append(": ") .append(parameter.getType()); } } builder.append("\n\nMethods may have up to ") .append(method.parameters().length) .append(" parameter(s):\n"); for (String parameterType : method.parameters()) { builder.append("\n ").append(parameterType); } builder.append( "\n\nThese may be listed in any order but will be searched for from top to bottom."); error(executableElement, builder.toString()); return; } } } MethodViewBinding binding = new MethodViewBinding(name, Arrays.asList(parameters), required); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); for (int id : ids) { if (!bindingClass.addMethod(getId(id), listener, method, binding)) { error(element, "Multiple listener methods with return value specified for ID %d. (%s.%s)", id, enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement); } private boolean isInterface(TypeMirror typeMirror) { return typeMirror instanceof DeclaredType && ((DeclaredType) typeMirror).asElement().getKind() == INTERFACE; } private boolean isSubtypeOfType(TypeMirror typeMirror, String otherType) { if (otherType.equals(typeMirror.toString())) { return true; } if (typeMirror.getKind() != TypeKind.DECLARED) { return false; } DeclaredType declaredType = (DeclaredType) typeMirror; List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (typeArguments.size() > 0) { StringBuilder typeString = new StringBuilder(declaredType.asElement().toString()); typeString.append('<'); for (int i = 0; i < typeArguments.size(); i++) { if (i > 0) { typeString.append(','); } typeString.append('?'); } typeString.append('>'); if (typeString.toString().equals(otherType)) { return true; } } Element element = declaredType.asElement(); if (!(element instanceof TypeElement)) { return false; } TypeElement typeElement = (TypeElement) element; TypeMirror superType = typeElement.getSuperclass(); if (isSubtypeOfType(superType, otherType)) { return true; } for (TypeMirror interfaceType : typeElement.getInterfaces()) { if (isSubtypeOfType(interfaceType, otherType)) { return true; } } return false; } private BindingClass getOrCreateTargetClass(Map<TypeElement, BindingClass> targetClassMap, TypeElement enclosingElement) { BindingClass bindingClass = targetClassMap.get(enclosingElement); if (bindingClass == null) { TypeName targetType = TypeName.get(enclosingElement.asType()); if (targetType instanceof ParameterizedTypeName) { targetType = ((ParameterizedTypeName) targetType).rawType; } String packageName = getPackageName(enclosingElement); String className = getClassName(enclosingElement, packageName); ClassName binderClassName = ClassName.get(packageName, className + "_ViewBinder"); ClassName unbinderClassName = ClassName.get(packageName, className + "_ViewBinding"); boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL); bindingClass = new BindingClass(targetType, binderClassName, unbinderClassName, isFinal); targetClassMap.put(enclosingElement, bindingClass); } return bindingClass; } private static String getClassName(TypeElement type, String packageName) { int packageLen = packageName.length() + 1; return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); } /** Finds the parent binder type in the supplied set, if any. */ private TypeElement findParentType(TypeElement typeElement, Set<TypeElement> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } typeElement = (TypeElement) ((DeclaredType) type).asElement(); if (parents.contains(typeElement)) { return typeElement; } } } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } private void error(Element element, String message, Object... args) { if (args.length > 0) { message = String.format(message, args); } processingEnv.getMessager().printMessage(ERROR, message, element); } private String getPackageName(TypeElement type) { return elementUtils.getPackageOf(type).getQualifiedName().toString(); } private static boolean hasAnnotationWithName(Element element, String simpleName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString(); if (simpleName.equals(annotationName)) { return true; } } return false; } private static boolean isFieldRequired(Element element) { return !hasAnnotationWithName(element, NULLABLE_ANNOTATION_NAME); } private static boolean isListenerRequired(ExecutableElement element) { return element.getAnnotation(Optional.class) == null; } private static AnnotationMirror getMirror(Element element, Class<? extends Annotation> annotation) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (annotationMirror.getAnnotationType().toString().equals(annotation.getCanonicalName())) { return annotationMirror; } } return null; } private Id getId(int id) { if (symbols.get(id) == null) { symbols.put(id, new Id(id)); } return symbols.get(id); } private void scanForRClasses(RoundEnvironment env) { RClassScanner scanner = new RClassScanner(); for (Class<? extends Annotation> annotation : getSupportedAnnotations()) { for (Element element : env.getElementsAnnotatedWith(annotation)) { JCTree tree = (JCTree) trees.getTree(element, getMirror(element, annotation)); if (tree != null) { // tree can be null if the references are compiled types and not source tree.accept(scanner); } } } for (String rClass : scanner.getRClasses()) { parseRClass(rClass); } } private void parseRClass(String rClass) { Element element; try { element = elementUtils.getTypeElement(rClass); } catch (MirroredTypeException mte) { element = typeUtils.asElement(mte.getTypeMirror()); } JCTree tree = (JCTree) trees.getTree(element); if (tree != null) { // tree can be null if the references are compiled types and not source IdScanner idScanner = new IdScanner(symbols, elementUtils.getPackageOf(element).getQualifiedName().toString()); tree.accept(idScanner); } else { parseCompiledR((TypeElement) element); } } private void parseCompiledR(TypeElement rClass) { for (Element element : rClass.getEnclosedElements()) { String innerClassName = element.getSimpleName().toString(); if (SUPPORTED_TYPES.contains(innerClassName)) { for (Element enclosedElement : element.getEnclosedElements()) { if (enclosedElement instanceof VariableElement) { VariableElement variableElement = (VariableElement) enclosedElement; Object value = variableElement.getConstantValue(); if (value instanceof Integer) { int id = (Integer) value; ClassName rClassName = ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R", innerClassName); String resourceName = variableElement.getSimpleName().toString(); symbols.put(id, new Id(id, rClassName, resourceName)); } } } } } } private static class RClassScanner extends TreeScanner { private final Set<String> rClasses = new LinkedHashSet<>(); @Override public void visitSelect(JCTree.JCFieldAccess jcFieldAccess) { Symbol symbol = jcFieldAccess.sym; if (symbol != null && symbol.getEnclosingElement() != null && symbol.getEnclosingElement().getEnclosingElement() != null && symbol.getEnclosingElement().getEnclosingElement().enclClass() != null) { rClasses.add(symbol.getEnclosingElement().getEnclosingElement().enclClass().className()); } } Set<String> getRClasses() { return rClasses; } } private static class IdScanner extends TreeScanner { private final Map<Integer, Id> ids; private final String packageName; IdScanner(Map<Integer, Id> ids, String packageName) { this.ids = ids; this.packageName = packageName; } @Override public void visitClassDef(JCTree.JCClassDecl jcClassDecl) { for (JCTree tree : jcClassDecl.defs) { if (tree instanceof ClassTree) { ClassTree classTree = (ClassTree) tree; String className = classTree.getSimpleName().toString(); if (SUPPORTED_TYPES.contains(className)) { ClassName rClassName = ClassName.get(packageName, "R", className); VarScanner scanner = new VarScanner(ids, rClassName); ((JCTree) classTree).accept(scanner); } } } } } private static class VarScanner extends TreeScanner { private final Map<Integer, Id> ids; private final ClassName className; private VarScanner(Map<Integer, Id> ids, ClassName className) { this.ids = ids; this.className = className; } @Override public void visitVarDef(JCTree.JCVariableDecl jcVariableDecl) { if ("int".equals(jcVariableDecl.getType().toString())) { int id = Integer.valueOf(jcVariableDecl.getInitializer().toString()); String resourceName = jcVariableDecl.getName().toString(); ids.put(id, new Id(id, className, resourceName)); } } } }
butterknife-compiler/src/main/java/butterknife/compiler/ButterKnifeProcessor.java
package butterknife.compiler; import butterknife.BindArray; import butterknife.BindBitmap; import butterknife.BindBool; import butterknife.BindColor; import butterknife.BindDimen; import butterknife.BindDrawable; import butterknife.BindInt; import butterknife.BindString; import butterknife.BindView; import butterknife.BindViews; import butterknife.OnCheckedChanged; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnFocusChange; import butterknife.OnItemClick; import butterknife.OnItemLongClick; import butterknife.OnItemSelected; import butterknife.OnLongClick; import butterknife.OnPageChange; import butterknife.OnTextChanged; import butterknife.OnTouch; import butterknife.Optional; import butterknife.internal.ListenerClass; import butterknife.internal.ListenerMethod; import com.google.auto.common.SuperficialValidation; import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.sun.source.tree.ClassTree; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeScanner; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; 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.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.ElementKind.INTERFACE; import static javax.lang.model.element.ElementKind.METHOD; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; import static javax.tools.Diagnostic.Kind.ERROR; @AutoService(Processor.class) public final class ButterKnifeProcessor extends AbstractProcessor { static final Id NO_ID = new Id(-1); static final String VIEW_TYPE = "android.view.View"; private static final String COLOR_STATE_LIST_TYPE = "android.content.res.ColorStateList"; private static final String BITMAP_TYPE = "android.graphics.Bitmap"; private static final String DRAWABLE_TYPE = "android.graphics.drawable.Drawable"; private static final String TYPED_ARRAY_TYPE = "android.content.res.TypedArray"; private static final String NULLABLE_ANNOTATION_NAME = "Nullable"; private static final String STRING_TYPE = "java.lang.String"; private static final String LIST_TYPE = List.class.getCanonicalName(); private static final String R = "R"; private static final List<Class<? extends Annotation>> LISTENERS = Arrays.asList(// OnCheckedChanged.class, // OnClick.class, // OnEditorAction.class, // OnFocusChange.class, // OnItemClick.class, // OnItemLongClick.class, // OnItemSelected.class, // OnLongClick.class, // OnPageChange.class, // OnTextChanged.class, // OnTouch.class // ); private static final List<String> SUPPORTED_TYPES = Arrays.asList( "array", "attr", "bool", "color", "dimen", "drawable", "id", "integer", "string" ); private Elements elementUtils; private Types typeUtils; private Filer filer; private Trees trees; private final Map<Integer, Id> symbols = new LinkedHashMap<>(); @Override public synchronized void init(ProcessingEnvironment env) { super.init(env); elementUtils = env.getElementUtils(); typeUtils = env.getTypeUtils(); filer = env.getFiler(); trees = Trees.instance(processingEnv); } @Override public Set<String> getSupportedAnnotationTypes() { Set<String> types = new LinkedHashSet<>(); for (Class<? extends Annotation> annotation : getSupportedAnnotations()) { types.add(annotation.getCanonicalName()); } return types; } private Set<Class<? extends Annotation>> getSupportedAnnotations() { Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>(); annotations.add(BindArray.class); annotations.add(BindBitmap.class); annotations.add(BindBool.class); annotations.add(BindColor.class); annotations.add(BindDimen.class); annotations.add(BindDrawable.class); annotations.add(BindInt.class); annotations.add(BindString.class); annotations.add(BindView.class); annotations.add(BindViews.class); annotations.addAll(LISTENERS); return annotations; } @Override public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) { Map<TypeElement, BindingClass> targetClassMap = findAndParseTargets(env); for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); BindingClass bindingClass = entry.getValue(); for (JavaFile javaFile : bindingClass.brewJava()) { try { javaFile.writeTo(filer); } catch (IOException e) { error(typeElement, "Unable to write view binder for type %s: %s", typeElement, e.getMessage()); } } } return true; } private Map<TypeElement, BindingClass> findAndParseTargets(RoundEnvironment env) { Map<TypeElement, BindingClass> targetClassMap = new LinkedHashMap<>(); Set<TypeElement> erasedTargetNames = new LinkedHashSet<>(); scanForRClasses(env); // Process each @BindArray element. for (Element element : env.getElementsAnnotatedWith(BindArray.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceArray(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindArray.class, e); } } // Process each @BindBitmap element. for (Element element : env.getElementsAnnotatedWith(BindBitmap.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceBitmap(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindBitmap.class, e); } } // Process each @BindBool element. for (Element element : env.getElementsAnnotatedWith(BindBool.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceBool(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindBool.class, e); } } // Process each @BindColor element. for (Element element : env.getElementsAnnotatedWith(BindColor.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceColor(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindColor.class, e); } } // Process each @BindDimen element. for (Element element : env.getElementsAnnotatedWith(BindDimen.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceDimen(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindDimen.class, e); } } // Process each @BindDrawable element. for (Element element : env.getElementsAnnotatedWith(BindDrawable.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceDrawable(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindDrawable.class, e); } } // Process each @BindInt element. for (Element element : env.getElementsAnnotatedWith(BindInt.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceInt(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindInt.class, e); } } // Process each @BindString element. for (Element element : env.getElementsAnnotatedWith(BindString.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseResourceString(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindString.class, e); } } // Process each @BindView element. for (Element element : env.getElementsAnnotatedWith(BindView.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseBindView(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindView.class, e); } } // Process each @BindViews element. for (Element element : env.getElementsAnnotatedWith(BindViews.class)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseBindViews(element, targetClassMap, erasedTargetNames); } catch (Exception e) { logParsingError(element, BindViews.class, e); } } // Process each annotation that corresponds to a listener. for (Class<? extends Annotation> listener : LISTENERS) { findAndParseListener(env, listener, targetClassMap, erasedTargetNames); } // Try to find a parent binder for each. for (Map.Entry<TypeElement, BindingClass> entry : targetClassMap.entrySet()) { TypeElement parentType = findParentType(entry.getKey(), erasedTargetNames); if (parentType != null) { BindingClass bindingClass = entry.getValue(); BindingClass parentBindingClass = targetClassMap.get(parentType); bindingClass.setParent(parentBindingClass); } } return targetClassMap; } private void logParsingError(Element element, Class<? extends Annotation> annotation, Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to parse @%s binding.\n\n%s", annotation.getSimpleName(), stackTrace); } private boolean isInaccessibleViaGeneratedCode(Class<? extends Annotation> annotationClass, String targetThing, Element element) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify method modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { error(element, "@%s %s must not be private or static. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error(enclosingElement, "@%s %s may only be contained in classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing class visibility is not private. if (enclosingElement.getModifiers().contains(PRIVATE)) { error(enclosingElement, "@%s %s may not be contained in private classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } return hasError; } private boolean isBindingInWrongPackage(Class<? extends Annotation> annotationClass, Element element) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); String qualifiedName = enclosingElement.getQualifiedName().toString(); if (qualifiedName.startsWith("android.")) { error(element, "@%s-annotated class incorrectly in Android framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } if (qualifiedName.startsWith("java.")) { error(element, "@%s-annotated class incorrectly in Java framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } return false; } private void parseBindView(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Start by verifying common generated code restrictions. boolean hasError = isInaccessibleViaGeneratedCode(BindView.class, "fields", element) || isBindingInWrongPackage(BindView.class, element); // Verify that the target type extends from View. TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) elementType; elementType = typeVariable.getUpperBound(); } if (!isSubtypeOfType(elementType, VIEW_TYPE) && !isInterface(elementType)) { error(element, "@%s fields must extend from View or be an interface. (%s.%s)", BindView.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } // Assemble information on the field. int id = element.getAnnotation(BindView.class).value(); BindingClass bindingClass = targetClassMap.get(enclosingElement); if (bindingClass != null) { ViewBindings viewBindings = bindingClass.getViewBinding(getId(id)); if (viewBindings != null && viewBindings.getFieldBinding() != null) { FieldViewBinding existingBinding = viewBindings.getFieldBinding(); error(element, "Attempt to use @%s for an already bound ID %d on '%s'. (%s.%s)", BindView.class.getSimpleName(), id, existingBinding.getName(), enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } else { bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); } String name = element.getSimpleName().toString(); TypeName type = TypeName.get(elementType); boolean required = isFieldRequired(element); FieldViewBinding binding = new FieldViewBinding(name, type, required); bindingClass.addField(getId(id), binding); // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement); } private void parseBindViews(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Start by verifying common generated code restrictions. boolean hasError = isInaccessibleViaGeneratedCode(BindViews.class, "fields", element) || isBindingInWrongPackage(BindViews.class, element); // Verify that the type is a List or an array. TypeMirror elementType = element.asType(); String erasedType = doubleErasure(elementType); TypeMirror viewType = null; FieldCollectionViewBinding.Kind kind = null; if (elementType.getKind() == TypeKind.ARRAY) { ArrayType arrayType = (ArrayType) elementType; viewType = arrayType.getComponentType(); kind = FieldCollectionViewBinding.Kind.ARRAY; } else if (LIST_TYPE.equals(erasedType)) { DeclaredType declaredType = (DeclaredType) elementType; List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (typeArguments.size() != 1) { error(element, "@%s List must have a generic component. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } else { viewType = typeArguments.get(0); } kind = FieldCollectionViewBinding.Kind.LIST; } else { error(element, "@%s must be a List or array. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (viewType != null && viewType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) viewType; viewType = typeVariable.getUpperBound(); } // Verify that the target type extends from View. if (viewType != null && !isSubtypeOfType(viewType, VIEW_TYPE) && !isInterface(viewType)) { error(element, "@%s List or array type must extend from View or be an interface. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Assemble information on the field. String name = element.getSimpleName().toString(); int[] ids = element.getAnnotation(BindViews.class).value(); if (ids.length == 0) { error(element, "@%s must specify at least one ID. (%s.%s)", BindViews.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } Integer duplicateId = findDuplicate(ids); if (duplicateId != null) { error(element, "@%s annotation contains duplicate ID %d. (%s.%s)", BindViews.class.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } assert viewType != null; // Always false as hasError would have been true. TypeName type = TypeName.get(viewType); boolean required = isFieldRequired(element); List<Id> idVars = new ArrayList<>(); for (int id : ids) { idVars.add(getId(id)); } BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldCollectionViewBinding binding = new FieldCollectionViewBinding(name, type, kind, required); bindingClass.addFieldCollection(idVars, binding); erasedTargetNames.add(enclosingElement); } private void parseResourceBool(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is bool. if (element.asType().getKind() != TypeKind.BOOLEAN) { error(element, "@%s field type must be 'boolean'. (%s.%s)", BindBool.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindBool.class, "fields", element); hasError |= isBindingInWrongPackage(BindBool.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindBool.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getBoolean", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceColor(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int or ColorStateList. boolean isColorStateList = false; TypeMirror elementType = element.asType(); if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) { isColorStateList = true; } else if (elementType.getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)", BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element); hasError |= isBindingInWrongPackage(BindColor.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindColor.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, isColorStateList ? "getColorStateList" : "getColor", true); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceDimen(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int or ColorStateList. boolean isInt = false; TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.INT) { isInt = true; } else if (elementType.getKind() != TypeKind.FLOAT) { error(element, "@%s field type must be 'int' or 'float'. (%s.%s)", BindDimen.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindDimen.class, "fields", element); hasError |= isBindingInWrongPackage(BindDimen.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindDimen.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, isInt ? "getDimensionPixelSize" : "getDimension", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceBitmap(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is Bitmap. if (!BITMAP_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'Bitmap'. (%s.%s)", BindBitmap.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindBitmap.class, "fields", element); hasError |= isBindingInWrongPackage(BindBitmap.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindBitmap.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldBitmapBinding binding = new FieldBitmapBinding(getId(id), name); bindingClass.addBitmap(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceDrawable(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is Drawable. if (!DRAWABLE_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'Drawable'. (%s.%s)", BindDrawable.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindDrawable.class, "fields", element); hasError |= isBindingInWrongPackage(BindDrawable.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindDrawable.class).value(); int tint = element.getAnnotation(BindDrawable.class).tint(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldDrawableBinding binding = new FieldDrawableBinding(getId(id), name, getId(tint)); bindingClass.addDrawable(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceInt(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int. if (element.asType().getKind() != TypeKind.INT) { error(element, "@%s field type must be 'int'. (%s.%s)", BindInt.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindInt.class, "fields", element); hasError |= isBindingInWrongPackage(BindInt.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindInt.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getInteger", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceString(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is String. if (!STRING_TYPE.equals(element.asType().toString())) { error(element, "@%s field type must be 'String'. (%s.%s)", BindString.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindString.class, "fields", element); hasError |= isBindingInWrongPackage(BindString.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindString.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, "getString", false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } private void parseResourceArray(Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is supported. String methodName = getArrayResourceMethodName(element); if (methodName == null) { error(element, "@%s field type must be one of: String[], int[], CharSequence[], %s. (%s.%s)", BindArray.class.getSimpleName(), TYPED_ARRAY_TYPE, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindArray.class, "fields", element); hasError |= isBindingInWrongPackage(BindArray.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindArray.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(getId(id), name, methodName, false); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement); } /** * Returns a method name from the {@link android.content.res.Resources} class for array resource * binding, null if the element type is not supported. */ private static String getArrayResourceMethodName(Element element) { TypeMirror typeMirror = element.asType(); if (TYPED_ARRAY_TYPE.equals(typeMirror.toString())) { return "obtainTypedArray"; } if (TypeKind.ARRAY.equals(typeMirror.getKind())) { ArrayType arrayType = (ArrayType) typeMirror; String componentType = arrayType.getComponentType().toString(); if (STRING_TYPE.equals(componentType)) { return "getStringArray"; } else if ("int".equals(componentType)) { return "getIntArray"; } else if ("java.lang.CharSequence".equals(componentType)) { return "getTextArray"; } } return null; } /** Returns the first duplicate element inside an array, null if there are no duplicates. */ private static Integer findDuplicate(int[] array) { Set<Integer> seenElements = new LinkedHashSet<>(); for (int element : array) { if (!seenElements.add(element)) { return element; } } return null; } /** Uses both {@link Types#erasure} and string manipulation to strip any generic types. */ private String doubleErasure(TypeMirror elementType) { String name = typeUtils.erasure(elementType).toString(); int typeParamStart = name.indexOf('<'); if (typeParamStart != -1) { name = name.substring(0, typeParamStart); } return name; } private void findAndParseListener(RoundEnvironment env, Class<? extends Annotation> annotationClass, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) { for (Element element : env.getElementsAnnotatedWith(annotationClass)) { if (!SuperficialValidation.validateElement(element)) continue; try { parseListenerAnnotation(annotationClass, element, targetClassMap, erasedTargetNames); } catch (Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to generate view binder for @%s.\n\n%s", annotationClass.getSimpleName(), stackTrace.toString()); } } } private void parseListenerAnnotation(Class<? extends Annotation> annotationClass, Element element, Map<TypeElement, BindingClass> targetClassMap, Set<TypeElement> erasedTargetNames) throws Exception { // This should be guarded by the annotation's @Target but it's worth a check for safe casting. if (!(element instanceof ExecutableElement) || element.getKind() != METHOD) { throw new IllegalStateException( String.format("@%s annotation must be on a method.", annotationClass.getSimpleName())); } ExecutableElement executableElement = (ExecutableElement) element; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Assemble information on the method. Annotation annotation = element.getAnnotation(annotationClass); Method annotationValue = annotationClass.getDeclaredMethod("value"); if (annotationValue.getReturnType() != int[].class) { throw new IllegalStateException( String.format("@%s annotation value() type not int[].", annotationClass)); } int[] ids = (int[]) annotationValue.invoke(annotation); String name = executableElement.getSimpleName().toString(); boolean required = isListenerRequired(executableElement); // Verify that the method and its containing class are accessible via generated code. boolean hasError = isInaccessibleViaGeneratedCode(annotationClass, "methods", element); hasError |= isBindingInWrongPackage(annotationClass, element); Integer duplicateId = findDuplicate(ids); if (duplicateId != null) { error(element, "@%s annotation for method contains duplicate ID %d. (%s.%s)", annotationClass.getSimpleName(), duplicateId, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } ListenerClass listener = annotationClass.getAnnotation(ListenerClass.class); if (listener == null) { throw new IllegalStateException( String.format("No @%s defined on @%s.", ListenerClass.class.getSimpleName(), annotationClass.getSimpleName())); } for (int id : ids) { if (id == NO_ID.value) { if (ids.length == 1) { if (!required) { error(element, "ID-free binding must not be annotated with @Optional. (%s.%s)", enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify target type is valid for a binding without an id. String targetType = listener.targetType(); if (!isSubtypeOfType(enclosingElement.asType(), targetType) && !isInterface(enclosingElement.asType())) { error(element, "@%s annotation without an ID may only be used with an object of type " + "\"%s\" or an interface. (%s.%s)", annotationClass.getSimpleName(), targetType, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } } else { error(element, "@%s annotation contains invalid ID %d. (%s.%s)", annotationClass.getSimpleName(), id, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } } } ListenerMethod method; ListenerMethod[] methods = listener.method(); if (methods.length > 1) { throw new IllegalStateException(String.format("Multiple listener methods specified on @%s.", annotationClass.getSimpleName())); } else if (methods.length == 1) { if (listener.callbacks() != ListenerClass.NONE.class) { throw new IllegalStateException( String.format("Both method() and callback() defined on @%s.", annotationClass.getSimpleName())); } method = methods[0]; } else { Method annotationCallback = annotationClass.getDeclaredMethod("callback"); Enum<?> callback = (Enum<?>) annotationCallback.invoke(annotation); Field callbackField = callback.getDeclaringClass().getField(callback.name()); method = callbackField.getAnnotation(ListenerMethod.class); if (method == null) { throw new IllegalStateException( String.format("No @%s defined on @%s's %s.%s.", ListenerMethod.class.getSimpleName(), annotationClass.getSimpleName(), callback.getDeclaringClass().getSimpleName(), callback.name())); } } // Verify that the method has equal to or less than the number of parameters as the listener. List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > method.parameters().length) { error(element, "@%s methods can have at most %s parameter(s). (%s.%s)", annotationClass.getSimpleName(), method.parameters().length, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify method return type matches the listener. TypeMirror returnType = executableElement.getReturnType(); if (returnType instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) returnType; returnType = typeVariable.getUpperBound(); } if (!returnType.toString().equals(method.returnType())) { error(element, "@%s methods must have a '%s' return type. (%s.%s)", annotationClass.getSimpleName(), method.returnType(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } if (hasError) { return; } Parameter[] parameters = Parameter.NONE; if (!methodParameters.isEmpty()) { parameters = new Parameter[methodParameters.size()]; BitSet methodParameterUsed = new BitSet(methodParameters.size()); String[] parameterTypes = method.parameters(); for (int i = 0; i < methodParameters.size(); i++) { VariableElement methodParameter = methodParameters.get(i); TypeMirror methodParameterType = methodParameter.asType(); if (methodParameterType instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) methodParameterType; methodParameterType = typeVariable.getUpperBound(); } for (int j = 0; j < parameterTypes.length; j++) { if (methodParameterUsed.get(j)) { continue; } if (isSubtypeOfType(methodParameterType, parameterTypes[j]) || isInterface(methodParameterType)) { parameters[i] = new Parameter(j, TypeName.get(methodParameterType)); methodParameterUsed.set(j); break; } } if (parameters[i] == null) { StringBuilder builder = new StringBuilder(); builder.append("Unable to match @") .append(annotationClass.getSimpleName()) .append(" method arguments. (") .append(enclosingElement.getQualifiedName()) .append('.') .append(element.getSimpleName()) .append(')'); for (int j = 0; j < parameters.length; j++) { Parameter parameter = parameters[j]; builder.append("\n\n Parameter #") .append(j + 1) .append(": ") .append(methodParameters.get(j).asType().toString()) .append("\n "); if (parameter == null) { builder.append("did not match any listener parameters"); } else { builder.append("matched listener parameter #") .append(parameter.getListenerPosition() + 1) .append(": ") .append(parameter.getType()); } } builder.append("\n\nMethods may have up to ") .append(method.parameters().length) .append(" parameter(s):\n"); for (String parameterType : method.parameters()) { builder.append("\n ").append(parameterType); } builder.append( "\n\nThese may be listed in any order but will be searched for from top to bottom."); error(executableElement, builder.toString()); return; } } } MethodViewBinding binding = new MethodViewBinding(name, Arrays.asList(parameters), required); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); for (int id : ids) { if (!bindingClass.addMethod(getId(id), listener, method, binding)) { error(element, "Multiple listener methods with return value specified for ID %d. (%s.%s)", id, enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement); } private boolean isInterface(TypeMirror typeMirror) { return typeMirror instanceof DeclaredType && ((DeclaredType) typeMirror).asElement().getKind() == INTERFACE; } private boolean isSubtypeOfType(TypeMirror typeMirror, String otherType) { if (otherType.equals(typeMirror.toString())) { return true; } if (typeMirror.getKind() != TypeKind.DECLARED) { return false; } DeclaredType declaredType = (DeclaredType) typeMirror; List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (typeArguments.size() > 0) { StringBuilder typeString = new StringBuilder(declaredType.asElement().toString()); typeString.append('<'); for (int i = 0; i < typeArguments.size(); i++) { if (i > 0) { typeString.append(','); } typeString.append('?'); } typeString.append('>'); if (typeString.toString().equals(otherType)) { return true; } } Element element = declaredType.asElement(); if (!(element instanceof TypeElement)) { return false; } TypeElement typeElement = (TypeElement) element; TypeMirror superType = typeElement.getSuperclass(); if (isSubtypeOfType(superType, otherType)) { return true; } for (TypeMirror interfaceType : typeElement.getInterfaces()) { if (isSubtypeOfType(interfaceType, otherType)) { return true; } } return false; } private BindingClass getOrCreateTargetClass(Map<TypeElement, BindingClass> targetClassMap, TypeElement enclosingElement) { BindingClass bindingClass = targetClassMap.get(enclosingElement); if (bindingClass == null) { TypeName targetType = TypeName.get(enclosingElement.asType()); if (targetType instanceof ParameterizedTypeName) { targetType = ((ParameterizedTypeName) targetType).rawType; } String packageName = getPackageName(enclosingElement); String className = getClassName(enclosingElement, packageName); ClassName binderClassName = ClassName.get(packageName, className + "_ViewBinder"); ClassName unbinderClassName = ClassName.get(packageName, className + "_ViewBinding"); boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL); bindingClass = new BindingClass(targetType, binderClassName, unbinderClassName, isFinal); targetClassMap.put(enclosingElement, bindingClass); } return bindingClass; } private static String getClassName(TypeElement type, String packageName) { int packageLen = packageName.length() + 1; return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); } /** Finds the parent binder type in the supplied set, if any. */ private TypeElement findParentType(TypeElement typeElement, Set<TypeElement> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } typeElement = (TypeElement) ((DeclaredType) type).asElement(); if (parents.contains(typeElement)) { return typeElement; } } } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } private void error(Element element, String message, Object... args) { if (args.length > 0) { message = String.format(message, args); } processingEnv.getMessager().printMessage(ERROR, message, element); } private String getPackageName(TypeElement type) { return elementUtils.getPackageOf(type).getQualifiedName().toString(); } private static boolean hasAnnotationWithName(Element element, String simpleName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString(); if (simpleName.equals(annotationName)) { return true; } } return false; } private static boolean isFieldRequired(Element element) { return !hasAnnotationWithName(element, NULLABLE_ANNOTATION_NAME); } private static boolean isListenerRequired(ExecutableElement element) { return element.getAnnotation(Optional.class) == null; } private static AnnotationMirror getMirror(Element element, Class<? extends Annotation> annotation) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (annotationMirror.getAnnotationType().toString().equals(annotation.getCanonicalName())) { return annotationMirror; } } return null; } private Id getId(int id) { if (symbols.get(id) == null) { symbols.put(id, new Id(id)); } return symbols.get(id); } private void scanForRClasses(RoundEnvironment env) { RClassScanner scanner = new RClassScanner(); for (Class<? extends Annotation> annotation : getSupportedAnnotations()) { for (Element element : env.getElementsAnnotatedWith(annotation)) { JCTree tree = (JCTree) trees.getTree(element, getMirror(element, annotation)); tree.accept(scanner); } } for (String rClass : scanner.getRClasses()) { parseRClass(rClass); } } private void parseRClass(String rClass) { Element element; try { element = elementUtils.getTypeElement(rClass); } catch (MirroredTypeException mte) { element = typeUtils.asElement(mte.getTypeMirror()); } JCTree tree = (JCTree) trees.getTree(element); if (tree != null) { // tree can be null if the references are compiled types and not source IdScanner idScanner = new IdScanner(symbols, elementUtils.getPackageOf(element).getQualifiedName().toString()); tree.accept(idScanner); } else { parseCompiledR((TypeElement) element); } } private void parseCompiledR(TypeElement rClass) { for (Element element : rClass.getEnclosedElements()) { String innerClassName = element.getSimpleName().toString(); if (SUPPORTED_TYPES.contains(innerClassName)) { for (Element enclosedElement : element.getEnclosedElements()) { if (enclosedElement instanceof VariableElement) { VariableElement variableElement = (VariableElement) enclosedElement; Object value = variableElement.getConstantValue(); if (value instanceof Integer) { int id = (Integer) value; ClassName rClassName = ClassName.get(elementUtils.getPackageOf(variableElement).toString(), "R", innerClassName); String resourceName = variableElement.getSimpleName().toString(); symbols.put(id, new Id(id, rClassName, resourceName)); } } } } } } private static class RClassScanner extends TreeScanner { private final Set<String> rClasses = new LinkedHashSet<>(); @Override public void visitSelect(JCTree.JCFieldAccess jcFieldAccess) { Symbol symbol = jcFieldAccess.sym; if (symbol != null && symbol.getEnclosingElement() != null && symbol.getEnclosingElement().getEnclosingElement() != null && symbol.getEnclosingElement().getEnclosingElement().enclClass() != null) { rClasses.add(symbol.getEnclosingElement().getEnclosingElement().enclClass().className()); } } Set<String> getRClasses() { return rClasses; } } private static class IdScanner extends TreeScanner { private final Map<Integer, Id> ids; private final String packageName; IdScanner(Map<Integer, Id> ids, String packageName) { this.ids = ids; this.packageName = packageName; } @Override public void visitClassDef(JCTree.JCClassDecl jcClassDecl) { for (JCTree tree : jcClassDecl.defs) { if (tree instanceof ClassTree) { ClassTree classTree = (ClassTree) tree; String className = classTree.getSimpleName().toString(); if (SUPPORTED_TYPES.contains(className)) { ClassName rClassName = ClassName.get(packageName, "R", className); VarScanner scanner = new VarScanner(ids, rClassName); ((JCTree) classTree).accept(scanner); } } } } } private static class VarScanner extends TreeScanner { private final Map<Integer, Id> ids; private final ClassName className; private VarScanner(Map<Integer, Id> ids, ClassName className) { this.ids = ids; this.className = className; } @Override public void visitVarDef(JCTree.JCVariableDecl jcVariableDecl) { if ("int".equals(jcVariableDecl.getType().toString())) { int id = Integer.valueOf(jcVariableDecl.getInitializer().toString()); String resourceName = jcVariableDecl.getName().toString(); ids.put(id, new Id(id, className, resourceName)); } } } }
Guard for null tree when scanning for R Classes
butterknife-compiler/src/main/java/butterknife/compiler/ButterKnifeProcessor.java
Guard for null tree when scanning for R Classes
Java
apache-2.0
121d489ae454be371ef12c5b47b31ad0272b86b7
0
FasterXML/jackson-databind,FasterXML/jackson-databind
package com.fasterxml.jackson.databind.deser.std; import java.io.IOException; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.BeanDeserializer; import com.fasterxml.jackson.databind.deser.SettableBeanProperty; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Deserializer that builds on basic {@link BeanDeserializer} but * override some aspects like instance construction. */ public class ThrowableDeserializer extends BeanDeserializer { private static final long serialVersionUID = 1L; protected final static String PROP_NAME_MESSAGE = "message"; /* /************************************************************ /* Construction /************************************************************ */ public ThrowableDeserializer(BeanDeserializer baseDeserializer) { super(baseDeserializer); // need to disable this, since we do post-processing _vanillaProcessing = false; } /** * Alternative constructor used when creating "unwrapping" deserializers */ protected ThrowableDeserializer(BeanDeserializer src, NameTransformer unwrapper) { super(src, unwrapper); } @Override public JsonDeserializer<Object> unwrappingDeserializer(NameTransformer unwrapper) { if (getClass() != ThrowableDeserializer.class) { return this; } /* main thing really is to just enforce ignoring of unknown * properties; since there may be multiple unwrapped values * and properties for all may be interleaved... */ return new ThrowableDeserializer(this, unwrapper); } /* /************************************************************ /* Overridden methods /************************************************************ */ @Override public Object deserializeFromObject(JsonParser p, DeserializationContext ctxt) throws IOException { // 30-Sep-2010, tatu: Need to allow use of @JsonCreator, so: if (_propertyBasedCreator != null) { // proper @JsonCreator return _deserializeUsingPropertyBased(p, ctxt); } if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(p, ctxt)); } if (_beanType.isAbstract()) { // for good measure, check this too return ctxt.handleMissingInstantiator(handledType(), getValueInstantiator(), p, "abstract type (need to add/enable type information?)"); } boolean hasStringCreator = _valueInstantiator.canCreateFromString(); boolean hasDefaultCtor = _valueInstantiator.canCreateUsingDefault(); // and finally, verify we do have single-String arg constructor (if no @JsonCreator) if (!hasStringCreator && !hasDefaultCtor) { return ctxt.handleMissingInstantiator(handledType(), getValueInstantiator(), p, "Throwable needs a default constructor, a single-String-arg constructor; or explicit @JsonCreator"); } Object throwable = null; Object[] pending = null; int pendingIx = 0; for (; p.getCurrentToken() != JsonToken.END_OBJECT; p.nextToken()) { String propName = p.getCurrentName(); SettableBeanProperty prop = _beanProperties.find(propName); p.nextToken(); // to point to field value if (prop != null) { // normal case if (throwable != null) { prop.deserializeAndSet(p, ctxt, throwable); continue; } // nope; need to defer if (pending == null) { int len = _beanProperties.size(); pending = new Object[len + len]; } pending[pendingIx++] = prop; pending[pendingIx++] = prop.deserialize(p, ctxt); continue; } // Maybe it's "message"? final boolean isMessage = PROP_NAME_MESSAGE.equals(propName); if (isMessage) { if (hasStringCreator) { throwable = _valueInstantiator.createFromString(ctxt, p.getValueAsString()); // any pending values? if (pending != null) { for (int i = 0, len = pendingIx; i < len; i += 2) { prop = (SettableBeanProperty)pending[i]; prop.set(throwable, pending[i+1]); } pending = null; } continue; } } // Things marked as ignorable should not be passed to any setter if ((_ignorableProps != null) && _ignorableProps.contains(propName)) { p.skipChildren(); continue; } if (_anySetter != null) { _anySetter.deserializeAndSet(p, ctxt, throwable, propName); continue; } // 23-Jan-2018, tatu: One concern would be `message`, but without any-setter or single-String-ctor // (or explicit constructor). We could just ignore it but for now, let it fail // Unknown: let's call handler method handleUnknownProperty(p, ctxt, throwable, propName); } // Sanity check: did we find "message"? if (throwable == null) { /* 15-Oct-2010, tatu: Can't assume missing message is an error, since it may be * suppressed during serialization, as per [JACKSON-388]. * * Should probably allow use of default constructor, too... */ //throw new JsonMappingException("No 'message' property found: could not deserialize "+_beanType); if (hasStringCreator) { throwable = _valueInstantiator.createFromString(ctxt, null); } else { throwable = _valueInstantiator.createUsingDefault(ctxt); } // any pending values? if (pending != null) { for (int i = 0, len = pendingIx; i < len; i += 2) { SettableBeanProperty prop = (SettableBeanProperty)pending[i]; prop.set(throwable, pending[i+1]); } } } return throwable; } }
src/main/java/com/fasterxml/jackson/databind/deser/std/ThrowableDeserializer.java
package com.fasterxml.jackson.databind.deser.std; import java.io.IOException; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.BeanDeserializer; import com.fasterxml.jackson.databind.deser.SettableBeanProperty; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Deserializer that builds on basic {@link BeanDeserializer} but * override some aspects like instance construction. */ public class ThrowableDeserializer extends BeanDeserializer { private static final long serialVersionUID = 1L; protected final static String PROP_NAME_MESSAGE = "message"; /* /************************************************************ /* Construction /************************************************************ */ public ThrowableDeserializer(BeanDeserializer baseDeserializer) { super(baseDeserializer); // need to disable this, since we do post-processing _vanillaProcessing = false; } /** * Alternative constructor used when creating "unwrapping" deserializers */ protected ThrowableDeserializer(BeanDeserializer src, NameTransformer unwrapper) { super(src, unwrapper); } @Override public JsonDeserializer<Object> unwrappingDeserializer(NameTransformer unwrapper) { if (getClass() != ThrowableDeserializer.class) { return this; } /* main thing really is to just enforce ignoring of unknown * properties; since there may be multiple unwrapped values * and properties for all may be interleaved... */ return new ThrowableDeserializer(this, unwrapper); } /* /************************************************************ /* Overridden methods /************************************************************ */ @Override public Object deserializeFromObject(JsonParser p, DeserializationContext ctxt) throws IOException { // 30-Sep-2010, tatu: Need to allow use of @JsonCreator, so: if (_propertyBasedCreator != null) { // proper @JsonCreator return _deserializeUsingPropertyBased(p, ctxt); } if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(ctxt, _delegateDeserializer.deserialize(p, ctxt)); } if (_beanType.isAbstract()) { // for good measure, check this too return ctxt.handleMissingInstantiator(handledType(), getValueInstantiator(), p, "abstract type (need to add/enable type information?)"); } boolean hasStringCreator = _valueInstantiator.canCreateFromString(); boolean hasDefaultCtor = _valueInstantiator.canCreateUsingDefault(); // and finally, verify we do have single-String arg constructor (if no @JsonCreator) if (!hasStringCreator && !hasDefaultCtor) { return ctxt.handleMissingInstantiator(handledType(), getValueInstantiator(), p, "Throwable needs a default contructor, a single-String-arg constructor; or explicit @JsonCreator"); } Object throwable = null; Object[] pending = null; int pendingIx = 0; for (; p.getCurrentToken() != JsonToken.END_OBJECT; p.nextToken()) { String propName = p.getCurrentName(); SettableBeanProperty prop = _beanProperties.find(propName); p.nextToken(); // to point to field value if (prop != null) { // normal case if (throwable != null) { prop.deserializeAndSet(p, ctxt, throwable); continue; } // nope; need to defer if (pending == null) { int len = _beanProperties.size(); pending = new Object[len + len]; } pending[pendingIx++] = prop; pending[pendingIx++] = prop.deserialize(p, ctxt); continue; } // Maybe it's "message"? final boolean isMessage = PROP_NAME_MESSAGE.equals(propName); if (isMessage) { if (hasStringCreator) { throwable = _valueInstantiator.createFromString(ctxt, p.getValueAsString()); // any pending values? if (pending != null) { for (int i = 0, len = pendingIx; i < len; i += 2) { prop = (SettableBeanProperty)pending[i]; prop.set(throwable, pending[i+1]); } pending = null; } continue; } } // Things marked as ignorable should not be passed to any setter if ((_ignorableProps != null) && _ignorableProps.contains(propName)) { p.skipChildren(); continue; } if (_anySetter != null) { _anySetter.deserializeAndSet(p, ctxt, throwable, propName); continue; } // 23-Jan-2018, tatu: One concern would be `message`, but without any-setter or single-String-ctor // (or explicit constructor). We could just ignore it but for now, let it fail // Unknown: let's call handler method handleUnknownProperty(p, ctxt, throwable, propName); } // Sanity check: did we find "message"? if (throwable == null) { /* 15-Oct-2010, tatu: Can't assume missing message is an error, since it may be * suppressed during serialization, as per [JACKSON-388]. * * Should probably allow use of default constructor, too... */ //throw new JsonMappingException("No 'message' property found: could not deserialize "+_beanType); if (hasStringCreator) { throwable = _valueInstantiator.createFromString(ctxt, null); } else { throwable = _valueInstantiator.createUsingDefault(ctxt); } // any pending values? if (pending != null) { for (int i = 0, len = pendingIx; i < len; i += 2) { SettableBeanProperty prop = (SettableBeanProperty)pending[i]; prop.set(throwable, pending[i+1]); } } } return throwable; } }
Update ThrowableDeserializer.java (#2355)
src/main/java/com/fasterxml/jackson/databind/deser/std/ThrowableDeserializer.java
Update ThrowableDeserializer.java (#2355)
Java
apache-2.0
f3743a810c8d278891b049322fb40a81d814822f
0
muxiangqiu/bdf3
package com.bstek.bdf3.export.utils; import java.io.File; import java.text.SimpleDateFormat; import org.apache.commons.lang.StringUtils; import com.bstek.dorado.core.Configure; public class ExportUtils { public static String getFileStorePath() { String fileLocation = Configure.getString("bdf3.export.location"); if (StringUtils.isNotEmpty(fileLocation)) { return fileLocation.endsWith(File.separator) ? fileLocation : fileLocation + File.separator; } else { fileLocation = System.getProperty("java.io.tmpdir"); if (!fileLocation.endsWith(File.separator)) { fileLocation += File.separator; } File file = new File(fileLocation + "bdf3-export-temp"); if (!file.exists()) { file.mkdirs(); } return fileLocation + "bdf3-export-temp"+ File.separator; } } public static File getFile(String id, String name) { if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(name)) { String fullName = id + "_" + name; return new File(ExportUtils.getFileStorePath(), fullName); } return null; } public static SimpleDateFormat getSimpleDateFormat() { String format = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf; } }
bdf3-parent/bdf3-export/src/main/java/com/bstek/bdf3/export/utils/ExportUtils.java
package com.bstek.bdf3.export.utils; import java.io.File; import java.text.SimpleDateFormat; import org.apache.commons.lang.StringUtils; import com.bstek.dorado.core.Configure; public class ExportUtils { public static String getFileStorePath() { String fileLocation = Configure.getString("bdf2.export.location"); if (StringUtils.isNotEmpty(fileLocation)) { return fileLocation.endsWith(File.separator) ? fileLocation : fileLocation + File.separator; } else { fileLocation = System.getProperty("java.io.tmpdir"); if (!fileLocation.endsWith(File.separator)) { fileLocation += File.separator; } return fileLocation + "bdf2-export-temp"+ File.separator; } } public static File getFile(String id, String name) { if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(name)) { String fullName = id + "_" + name; return new File(ExportUtils.getFileStorePath(), fullName); } return null; } public static SimpleDateFormat getSimpleDateFormat() { String format = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf; } }
修复在linus系统下,导出报找不到文件错误
bdf3-parent/bdf3-export/src/main/java/com/bstek/bdf3/export/utils/ExportUtils.java
修复在linus系统下,导出报找不到文件错误
Java
apache-2.0
83a091ef21c8186be29909c77456198b988cb00a
0
hobinyoon/apache-cassandra-3.0.5-src,hobinyoon/apache-cassandra-3.0.5-src,hobinyoon/apache-cassandra-3.0.5-src
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.io.IOException; import java.lang.InterruptedException; import java.net.InetSocketAddress; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.stream.Collectors; import com.datastax.driver.core.*; import com.datastax.driver.core.exceptions.*; import com.datastax.driver.core.policies.*; import com.google.common.base.Joiner; class Cass { // What Cassandra Ec2Snitch returns private static String _localDc = null; private static List<String> _remoteDCs = null; private static List<String> _allDCs = null; // Partial replication private static String _ks_pr = null; // Attribute popularity keyspace. A table per attribute. private static String _ks_attr_pop = null; // Object location keyspace. private static String _ks_obj_loc = null; private static String _ks_exe_barrier = null; private static String _ks_exp_meta = null; // For comparison private static String _ks_regular = null; public static void Init() throws Exception { try (Cons.MT _ = new Cons.MT("Cass Init ...")) { _WaitUntilYouSeeAllDCs(); String ks_prefix = "acorn"; _ks_pr = ks_prefix + "_pr"; _ks_attr_pop = ks_prefix + "_attr_pop"; _ks_obj_loc = ks_prefix + "_obj_loc"; _ks_exe_barrier = ks_prefix + "_exe_barrier"; _ks_exp_meta = ks_prefix + "_exp_meta"; _ks_regular = ks_prefix + "_regular"; } } private static void _WaitUntilYouSeeAllDCs() throws Exception { try (Cons.MT _ = new Cons.MT("Wait until you see all DCs ...")) { ResultSet rs = _GetSession().execute("select data_center from system.local;"); // Note that calling rs.all() for the second time returns an empty List<>. List<Row> rows = rs.all(); if (rows.size() != 1) throw new RuntimeException(String.format("Unexpcted: %d", rows.size())); _localDc = rows.get(0).getString("data_center"); Cons.P("Local DC: %s", _localDc); Cons.Pnnl("Remote DCs:"); long bt = System.currentTimeMillis(); boolean first = true; while (true) { rs = _GetSession().execute("select data_center from system.peers;"); rows = rs.all(); if (rows.size() == DC.remoteDCs.size()) break; if (first) { System.out.print(" "); first = false; } System.out.print("."); System.out.flush(); if (System.currentTimeMillis() - bt > 2000) { System.out.printf("\n"); throw new RuntimeException("Time out :("); } Thread.sleep(100); } _remoteDCs = new ArrayList<String>(); for (Row r: rows) _remoteDCs.add(r.getString("data_center")); for (String rDc: _remoteDCs) System.out.printf(" %s", rDc); System.out.printf("\n"); _allDCs = new ArrayList<String>(); _allDCs.add(_localDc); for (String rDc: _remoteDCs) _allDCs.add(rDc); // Prepare remote sessions for later. It takes about 800 ms. Can be // threaded to save time, if needed. try (Cons.MT _1 = new Cons.MT("Prepareing remote sessions ...")) { for (String rDc: _remoteDCs) _GetSession(rDc); } } } public static String LocalDC() { return _localDc; } public static boolean SchemaExist() throws Exception { // Check if the created table, that is created last, exists String q = String.format("select * from %s.t0 limit 1", _ks_regular); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { _GetSession().execute(s); return true; } catch (com.datastax.driver.core.exceptions.InvalidQueryException e) { if (e.toString().matches("(.*)Keyspace (.*) does not exist")) { return false; } else if (e.toString().contains("unconfigured table")) { return false; } Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } public static void CreateSchema() throws Exception { // You want to make sure that each test is starting from a clean sheet. // - But it takes too much time like 20 secs. Reuse the schema and make // object IDs unique across runs, using the datetime of the run. // - Drop the keyspaces when the schema changes. (It is re-created.) // https://docs.datastax.com/en/cql/3.1/cql/cql_reference/create_keyspace_r.html try (Cons.MT _ = new Cons.MT("Creating schema ...")) { String q = null; // It takes about exactly the same time with ALL and LOCAL_ONE. I wonder // it's always ALL implicitly for keyspace and table creation queries. //ConsistencyLevel cl = ConsistencyLevel.ALL; ConsistencyLevel cl = ConsistencyLevel.LOCAL_ONE; try { // Prepare datacenter query string StringBuilder q_dcs = new StringBuilder(); for (String r: _allDCs) q_dcs.append(String.format(", '%s' : 1", r)); // Object keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_pr, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); // It shouldn't already exist. The keyspace name is supposed to be // unique for each run. No need to catch AlreadyExistsException. // A minimal schema to prove the concept. q = String.format("CREATE TABLE %s.t0" + " (video_id text" // YouTube video id. Primary key + ", uid bigint" // Attribute user. The uploader of the video. + ", topics set<text>" // Attribute topics + ", extra_data blob" // Extra data to make the record size configurable + ", PRIMARY KEY (video_id)" // Primary key is mandatory + ");", _ks_pr); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Attribute popularity keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_attr_pop, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); // These are periodically updated (broadcasted). Cassandra doesn't like "-". for (String dc: _allDCs) { q = String.format("CREATE TABLE %s.%s_user (user_id text, PRIMARY KEY (user_id));" , _ks_attr_pop, dc.replace("-", "_")); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.%s_topic (topic text, PRIMARY KEY (topic));" , _ks_attr_pop, dc.replace("-", "_")); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } } // Object location keyspace. { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_obj_loc, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.obj_loc (obj_id text, locations set<text>, PRIMARY KEY (obj_id));" , _ks_obj_loc); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Execution barrier keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_exe_barrier, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0 (barrier_id text, PRIMARY KEY (barrier_id));" , _ks_exe_barrier); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Experiment metadata keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_exp_meta, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0 (key text, value text, PRIMARY KEY (key));" , _ks_exp_meta); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // A regular keyspace for comparison. Useful for a full replication // experiment. { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_regular, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0" + " (video_id text" // YouTube video id. Primary key + ", uid bigint" // Attribute user. The uploader of the video. + ", topics set<text>" // Attribute topics + ", extra_data blob" // Extra data to make the record size configurable + ", PRIMARY KEY (video_id)" // Primary key is mandatory + ");", _ks_regular); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception %s. query=[%s]", e, q); throw e; } } } public static void WaitForSchemaCreation() throws Exception { try (Cons.MT _ = new Cons.MT("Waiting for the schema creation ...")) { // Select data from the last created table with a CL LOCAL_ONE until // there is no exception. String q = String.format("select * from %s.t0 limit 1", _ks_regular); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Checking:"); boolean first = true; // Count the # of NoHostAvailableException(s) int nhaeCnt = 0; while (true) { try { _GetSession().execute(s); break; } catch (com.datastax.driver.core.exceptions.InvalidQueryException e) { char error_code = '-'; // Keyspace acorn_test_160510_011454_obj_loc does not exist. if (e.toString().matches("(.*)Keyspace (.*) does not exist")) { error_code = 'k'; } // unconfigured table else if (e.toString().contains("unconfigured table")) { error_code = 'u'; } if (error_code == '-') { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } if (first) { System.out.printf(" "); first = false; } System.out.printf("%c", error_code); System.out.flush(); Thread.sleep(100); } catch (com.datastax.driver.core.exceptions.DriverException e) { // This repeats. Not very often though. // // Datastax java driver message: WARN com.datastax.driver.core.RequestHandler - /54.177.190.122:9042 replied with server error (java.lang.IllegalArgumentException: Unknown CF 7dff11a0-1c6d-11e6-ad95-19553343aa25), defuncting connection. // // com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /54.177.190.122:9042 (com.datastax.driver.core.exceptions.ServerError: An unexpected error occurred server side on /54.177.190.122:9042: java.lang.IllegalArgumentException: Unknown CF 7dff11a0-1c6d-11e6-ad95-19553343aa25)) // // I might have to reconnect, instead of just retrying. Let's see how // it goes next time. boolean ok = false; if (e instanceof NoHostAvailableException) { nhaeCnt ++; if (nhaeCnt < 10) { ok = true; System.out.printf("h"); System.out.flush(); Thread.sleep(100); } } if (ok == false) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } } System.out.printf(" exists\n"); ExecutionBarrier(); } } // TODO: configurable private static int youTubeExtraDataSize = 4000; private static PreparedStatement _ps0 = null; private static Object _ps0_sync = new Object(); public static void WriteYoutubeRegular(YoutubeData.Req r) throws Exception { byte[] b = new byte[youTubeExtraDataSize]; Random rand = ThreadLocalRandom.current(); rand.nextBytes(b); ByteBuffer extraData = ByteBuffer.wrap(b); // Make once and reuse synchronized (_ps0_sync) { if (_ps0 == null) { _ps0 = _GetSession().prepare( String.format("INSERT INTO %s.t0 (video_id, uid, topics, extra_data) VALUES (?,?,?,?)", _ks_regular)); } } BoundStatement bs = new BoundStatement(_ps0); _GetSession().execute(bs.bind(r.vid, r.videoUploader, new TreeSet<String>(r.topics), extraData)); } public static void ReadYoutubeRegular(YoutubeData.Req r) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra // server. Doesn't matter for non acorn.*_pr keyspaces. String q = String.format("SELECT * from %s.t0 WHERE video_id='%s'", _ks_regular, r.vid); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { // TODO: report to ProgMon System.out.printf("@"); System.out.flush(); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public void InsertRecordPartial(String obj_id, String user, Set<String> topics) throws Exception { String q = null; try { q = String.format( "INSERT INTO %s.t0 (obj_id, user, topics) VALUES ('%s', '%s', {%s});" , _ks_pr, obj_id, user , String.join(", ", topics.stream().map(t -> String.format("'%s'", t)).collect(Collectors.toList()))); _GetSession().execute(q); } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public void SelectRecordLocalUntilSucceed(String obj_id) throws Exception { try (Cons.MT _ = new Cons.MT("Select record %s ", obj_id)) { // Select data from the last created table with a CL local_ONE until // succeed. String q = String.format("select obj_id from %s.t0 where obj_id='%s'" , _ks_pr, obj_id); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Checking: "); while (true) { try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { System.out.printf("."); System.out.flush(); Thread.sleep(10); } else if (rows.size() == 1) { System.out.printf(" found one\n"); break; } else { throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } } } static public List<Row> SelectRecordLocal(String objId) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra server String q = String.format("select * from %s.t0 where obj_id='%s'" , _ks_pr, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); return rows; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public List<Row> SelectRecordRemote(String dc, String objId) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra server String q = String.format("select * from %s.t0 where obj_id='%s'" , _ks_pr, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession(dc).execute(s); List<Row> rows = rs.all(); return rows; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static private class ClusterSession { Cluster c; // Session instances are thread-safe and usually a single instance is enough per application. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html Session s; ClusterSession(Cluster c, Session s) { this.c = c; this.s = s; } } static private Map<String, ClusterSession> _mapDcSession = new TreeMap<String, ClusterSession>(); static private Session _GetSession(String dc) throws Exception { //Cons.P(dc); ClusterSession cs = _GetDcCassSessionStartsWith(dc); if (cs == null) { // The default LoadBalancingPolicy is DCAwareRoundRobinPolicy, which // round-robins over the nodes of the local data center, which is exactly // what you want in this project. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.html Cluster c = new Cluster.Builder() .addContactPoints(_GetDcPubIp(dc)) // It says, // [main] INFO com.datastax.driver.core.Cluster - New Cassandra host /54.177.212.255:9042 added // [main] INFO com.datastax.driver.core.Cluster - New Cassandra host /127.0.0.1:9042 added // , which made me wonder if this connect to a remote region as well. // The public IP is on a different region. // // Specifying a white list doesn't seem to make any difference. //.withLoadBalancingPolicy( // new WhiteListPolicy(new DCAwareRoundRobinPolicy.Builder().build() // , Collections.singletonList(new InetSocketAddress("127.0.0.1", 9042)) // )) // // It might not mean which nodes this client connects to. .build(); // Session instances are thread-safe and usually a single instance is enough per application. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html Session s = c.connect(); //Metadata metadata = c.getMetadata(); //Cons.P("Connected to cluster '%s'.", metadata.getClusterName()); _mapDcSession.put(dc, new ClusterSession(c, s)); return s; } else { return cs.s; } } static private ClusterSession _GetDcCassSessionStartsWith(String dc) { for (Map.Entry<String, ClusterSession> e : _mapDcSession.entrySet()) { String k = e.getKey(); ClusterSession v = e.getValue(); if (k.startsWith(dc)) return v; } return null; } static private String _availabilityZone = null; static private Session _GetSession() throws Exception { if (_localDc != null) return _GetSession(_localDc); if (_availabilityZone == null) { Runtime r = Runtime.getRuntime(); Process p = r.exec("curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone"); p.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = b.readLine()) != null) { _availabilityZone = line; } b.close(); } // Trim the last [a-z] return _GetSession(_availabilityZone.substring(0, _availabilityZone.length() - 1)); } static private Map<String, String> _mapDcPubIp = new TreeMap<String, String>(); static private String _GetDcPubIp(String dc) throws Exception { String ip = _GetDcPubIpStartsWith(dc); if (ip == null) { File fn_jar = new File(AcornYoutube.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); // /mnt/local-ssd0/work/apache-cassandra-3.0.5-src/acorn/test/AcornYoutube/target/AcornYoutube-0.1.jar String fn = String.format("%s/.run/dc-ip-map", fn_jar.getParentFile().getParentFile()); Cons.P(fn); try (BufferedReader br = new BufferedReader(new FileReader(fn))) { String line; while ((line = br.readLine()) != null) { // us-east-1 54.160.118.182 String[] t = line.split("\\s+"); if (t.length !=2) throw new RuntimeException(String.format("Unexpcted format [%s]", line)); _mapDcPubIp.put(t[0], t[1]); } } ip = _GetDcPubIpStartsWith(dc); if (ip == null) throw new RuntimeException(String.format("No pub ip found for dc %s", dc)); } return ip; } static private String _GetDcPubIpStartsWith(String dc) { for (Map.Entry<String, String> e : _mapDcPubIp.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (k.startsWith(dc)) return v; } return null; } static public String GetObjLoc(String objId) throws Exception { String q = String.format("select obj_id, locations from %s.obj_loc where obj_id='%s'" , _ks_obj_loc, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { return null; } else if (rows.size() == 1) { Row r = rows.get(0); Set<String> locs = r.getSet(1, String.class); int locSize = locs.size(); if (locSize == 0) throw new RuntimeException(String.format("Unexpected: no location for object %s", objId)); int rand = (ThreadLocalRandom.current()).nextInt(locSize); int i = 0; for (String l: locs) { if (i == rand) return l; i ++; } } else { throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } return null; } static private int _barrier_id = 0; // Wait until everyone gets here static public long ExecutionBarrier() throws Exception { String q = null; long lapTime = 0; try { Cons.Pnnl("Execution barrier"); long bt = System.currentTimeMillis(); // Write us-(local_dc)-(exp_id)-(barrier_id) with CL One. CL doesn't matter it // will propagate eventually. q = String.format("Insert into %s.t0 (barrier_id) values ('%s-%s-%d');" , _ks_exe_barrier, LocalDC(), Conf.ExpID(), _barrier_id); Statement s = new SimpleStatement(q); _GetSession().execute(s); // Keep reading us-(remote_dc)-(exp_id)-(barrier_id) with CL LOCAL_ONE until // it sees the message from the other side. This doesn't need to be // parallelized. for (String peer_dc: _remoteDCs) { q = String.format("select barrier_id from %s.t0 where barrier_id='%s-%s-%d';" , _ks_exe_barrier, peer_dc, Conf.ExpID(), _barrier_id); s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); int sleepCnt = 0; while (true) { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { if (sleepCnt % 10 == 9) { if (sleepCnt == 9) System.out.printf(" "); System.out.printf("."); System.out.flush(); } Thread.sleep(10); sleepCnt ++; } else if (rows.size() == 1) { lapTime = System.currentTimeMillis() - bt; break; } else throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); lapTime = System.currentTimeMillis() - bt; if (lapTime > 10000) { System.out.printf("\n"); throw new RuntimeException("Execution barrier wait timed out :("); } } } _barrier_id ++; System.out.printf(" took %d ms\n", System.currentTimeMillis() - bt); } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } return lapTime; } static public void WriteStartTime(long startTime) throws Exception { String k = String.format("starttime-%s", Conf.ExpID()); String v = Long.toString(startTime); PreparedStatement ps = _GetSession().prepare( String.format("insert into %s.t0 (key, value) values (?,?)", _ks_exp_meta)); BoundStatement bs = new BoundStatement(ps); _GetSession().execute(bs.bind(k, v)); } static public long ReadStartTimeUntilSucceed() throws Exception { String k = String.format("starttime-%s", Conf.ExpID()); String q = String.format("select * from %s.t0 where key='%s'" , _ks_exp_meta, k); try { Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Getting start time:"); long bt = System.currentTimeMillis(); int cntSleep = 0; while (true) { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { if (cntSleep % 10 == 9) { if (cntSleep == 9) System.out.print(" "); System.out.print("."); System.out.flush(); } Thread.sleep(10); cntSleep ++; } else if (rows.size() == 1) { Row r = rows.get(0); String v = r.getString("value"); //Cons.P("v=%s", v); System.out.printf(" took %d ms\n", System.currentTimeMillis() - bt); return Long.parseLong(v); } else { throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); } if (System.currentTimeMillis() - bt > 2000) { System.out.printf("\n"); throw new RuntimeException("Time out :("); } } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } // TODO: clean up //static public void InsertRandomToRegular(String obj_id, int recSize) throws Exception { // try { // // http://ac31004.blogspot.com/2014/03/saving-image-in-cassandra-blob-field.html // // http://stackoverflow.com/questions/5683206/how-to-create-an-array-of-20-random-bytes // byte[] b = new byte[recSize]; // _rand.nextBytes(b); // ByteBuffer bb = ByteBuffer.wrap(b); // PreparedStatement ps = _GetSession().prepare( // String.format("insert into %s.t0 (c0, c1) values (?,?)", _ks_regular)); // BoundStatement bs = new BoundStatement(ps); // _GetSession().execute(bs.bind(obj_id, bb)); // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s]", e); // throw e; // } //} //static public List<Row> SelectFromRegular(ConsistencyLevel cl, String obj_id) throws Exception { // String q = String.format("select * from %s.t0 where c0='%s'" // , _ks_regular, obj_id); // try { // Statement s = new SimpleStatement(q).setConsistencyLevel(cl); // ResultSet rs = _GetSession().execute(s); // List<Row> rows = rs.all(); // if (rows.size() != 1) // throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); // return rows; // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s] query=[%s]", e, q); // throw e; // } //} //static public long SelectCountFromRegular(ConsistencyLevel cl, String objId0, String objId1) throws Exception { // String q = String.format("select count(*) from %s.t0 where c0 in ('%s', '%s')" // , _ks_regular, objId0, objId1); // try { // Statement s = new SimpleStatement(q).setConsistencyLevel(cl); // ResultSet rs = _GetSession().execute(s); // List<Row> rows = rs.all(); // if (rows.size() != 1) // throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); // Row r = rows.get(0); // return r.getLong(0); // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s] query=[%s]", e, q); // throw e; // } //} }
acorn/clients/youtube/src/main/java/Cass.java
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.io.IOException; import java.lang.InterruptedException; import java.net.InetSocketAddress; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.stream.Collectors; import com.datastax.driver.core.*; import com.datastax.driver.core.exceptions.*; import com.datastax.driver.core.policies.*; import com.google.common.base.Joiner; class Cass { // What Cassandra Ec2Snitch returns private static String _localDc = null; private static List<String> _remoteDCs = null; private static List<String> _allDCs = null; // Partial replication private static String _ks_pr = null; // Attribute popularity keyspace. A table per attribute. private static String _ks_attr_pop = null; // Object location keyspace. private static String _ks_obj_loc = null; private static String _ks_exe_barrier = null; private static String _ks_exp_meta = null; // For comparison private static String _ks_regular = null; public static void Init() throws Exception { try (Cons.MT _ = new Cons.MT("Cass Init ...")) { _WaitUntilYouSeeAllDCs(); String ks_prefix = "acorn"; _ks_pr = ks_prefix + "_pr"; _ks_attr_pop = ks_prefix + "_attr_pop"; _ks_obj_loc = ks_prefix + "_obj_loc"; _ks_exe_barrier = ks_prefix + "_exe_barrier"; _ks_exp_meta = ks_prefix + "_exp_meta"; _ks_regular = ks_prefix + "_regular"; } } private static void _WaitUntilYouSeeAllDCs() throws Exception { try (Cons.MT _ = new Cons.MT("Wait until you see all DCs ...")) { ResultSet rs = _GetSession().execute("select data_center from system.local;"); // Note that calling rs.all() for the second time returns an empty List<>. List<Row> rows = rs.all(); if (rows.size() != 1) throw new RuntimeException(String.format("Unexpcted: %d", rows.size())); _localDc = rows.get(0).getString("data_center"); Cons.P("Local DC: %s", _localDc); Cons.Pnnl("Remote DCs:"); long bt = System.currentTimeMillis(); boolean first = true; while (true) { rs = _GetSession().execute("select data_center from system.peers;"); rows = rs.all(); if (rows.size() == DC.remoteDCs.size()) break; if (first) { System.out.print(" "); first = false; } System.out.print("."); System.out.flush(); if (System.currentTimeMillis() - bt > 2000) { System.out.printf("\n"); throw new RuntimeException("Time out :("); } Thread.sleep(100); } _remoteDCs = new ArrayList<String>(); for (Row r: rows) _remoteDCs.add(r.getString("data_center")); for (String rDc: _remoteDCs) System.out.printf(" %s", rDc); System.out.printf("\n"); _allDCs = new ArrayList<String>(); _allDCs.add(_localDc); for (String rDc: _remoteDCs) _allDCs.add(rDc); // Prepare remote sessions for later. It takes about 800 ms. Can be // threaded to save time, if needed. try (Cons.MT _1 = new Cons.MT("Prepareing remote sessions ...")) { for (String rDc: _remoteDCs) _GetSession(rDc); } } } public static String LocalDC() { return _localDc; } public static boolean SchemaExist() throws Exception { // Check if the created table, that is created last, exists String q = String.format("select * from %s.t0 limit 1", _ks_regular); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { _GetSession().execute(s); return true; } catch (com.datastax.driver.core.exceptions.InvalidQueryException e) { if (e.toString().matches("(.*)Keyspace (.*) does not exist")) { return false; } else if (e.toString().contains("unconfigured table")) { return false; } Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } public static void CreateSchema() throws Exception { // You want to make sure that each test is starting from a clean sheet. // - But it takes too much time like 20 secs. Reuse the schema and make // object IDs unique across runs, using the datetime of the run. // - Drop the keyspaces when the schema changes. (It is re-created.) // https://docs.datastax.com/en/cql/3.1/cql/cql_reference/create_keyspace_r.html try (Cons.MT _ = new Cons.MT("Creating schema ...")) { String q = null; // It takes about exactly the same time with ALL and LOCAL_ONE. I wonder // it's always ALL implicitly for keyspace and table creation queries. //ConsistencyLevel cl = ConsistencyLevel.ALL; ConsistencyLevel cl = ConsistencyLevel.LOCAL_ONE; try { // Prepare datacenter query string StringBuilder q_dcs = new StringBuilder(); for (String r: _allDCs) q_dcs.append(String.format(", '%s' : 1", r)); // Object keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_pr, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); // It shouldn't already exist. The keyspace name is supposed to be // unique for each run. No need to catch AlreadyExistsException. // A minimal schema to prove the concept. q = String.format("CREATE TABLE %s.t0" + " (video_id text" // YouTube video id. Primary key + ", uid bigint" // Attribute user. The uploader of the video. + ", topics set<text>" // Attribute topics + ", extra_data blob" // Extra data to make the record size configurable + ", PRIMARY KEY (video_id)" // Primary key is mandatory + ");", _ks_pr); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Attribute popularity keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_attr_pop, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); // These are periodically updated (broadcasted). Cassandra doesn't like "-". for (String dc: _allDCs) { q = String.format("CREATE TABLE %s.%s_user (user_id text, PRIMARY KEY (user_id));" , _ks_attr_pop, dc.replace("-", "_")); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.%s_topic (topic text, PRIMARY KEY (topic));" , _ks_attr_pop, dc.replace("-", "_")); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } } // Object location keyspace. { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_obj_loc, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.obj_loc (obj_id text, locations set<text>, PRIMARY KEY (obj_id));" , _ks_obj_loc); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Execution barrier keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_exe_barrier, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0 (barrier_id text, PRIMARY KEY (barrier_id));" , _ks_exe_barrier); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // Experiment metadata keyspace { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_exp_meta, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0 (key text, value text, PRIMARY KEY (key));" , _ks_exp_meta); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } // A regular keyspace for comparison. Useful for a full replication // experiment. { q = String.format("CREATE KEYSPACE %s WITH replication = {" + " 'class' : 'NetworkTopologyStrategy'%s};" , _ks_regular, q_dcs); Statement s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); q = String.format("CREATE TABLE %s.t0" + " (video_id text" // YouTube video id. Primary key + ", uid bigint" // Attribute user. The uploader of the video. + ", topics set<text>" // Attribute topics + ", extra_data blob" // Extra data to make the record size configurable + ", PRIMARY KEY (video_id)" // Primary key is mandatory + ");", _ks_regular); s = new SimpleStatement(q).setConsistencyLevel(cl); _GetSession().execute(s); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception %s. query=[%s]", e, q); throw e; } } } public static void WaitForSchemaCreation() throws Exception { try (Cons.MT _ = new Cons.MT("Waiting for the schema creation ...")) { // Select data from the last created table with a CL LOCAL_ONE until // there is no exception. String q = String.format("select * from %s.t0 limit 1", _ks_regular); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Checking:"); boolean first = true; // Count the # of NoHostAvailableException(s) int nhaeCnt = 0; while (true) { try { _GetSession().execute(s); break; } catch (com.datastax.driver.core.exceptions.InvalidQueryException e) { char error_code = '-'; // Keyspace acorn_test_160510_011454_obj_loc does not exist. if (e.toString().matches("(.*)Keyspace (.*) does not exist")) { error_code = 'k'; } // unconfigured table else if (e.toString().contains("unconfigured table")) { error_code = 'u'; } if (error_code == '-') { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } if (first) { System.out.printf(" "); first = false; } System.out.printf("%c", error_code); System.out.flush(); Thread.sleep(100); } catch (com.datastax.driver.core.exceptions.DriverException e) { // This repeats. Not very often though. // // Datastax java driver message: WARN com.datastax.driver.core.RequestHandler - /54.177.190.122:9042 replied with server error (java.lang.IllegalArgumentException: Unknown CF 7dff11a0-1c6d-11e6-ad95-19553343aa25), defuncting connection. // // com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /54.177.190.122:9042 (com.datastax.driver.core.exceptions.ServerError: An unexpected error occurred server side on /54.177.190.122:9042: java.lang.IllegalArgumentException: Unknown CF 7dff11a0-1c6d-11e6-ad95-19553343aa25)) boolean ok = false; if (e instanceof NoHostAvailableException) { nhaeCnt ++; if (nhaeCnt < 10) { ok = true; System.out.printf("h"); System.out.flush(); Thread.sleep(100); } } if (ok == false) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } } System.out.printf(" exists\n"); ExecutionBarrier(); } } // TODO: configurable private static int youTubeExtraDataSize = 4000; private static PreparedStatement _ps0 = null; private static Object _ps0_sync = new Object(); public static void WriteYoutubeRegular(YoutubeData.Req r) throws Exception { byte[] b = new byte[youTubeExtraDataSize]; Random rand = ThreadLocalRandom.current(); rand.nextBytes(b); ByteBuffer extraData = ByteBuffer.wrap(b); // Make once and reuse synchronized (_ps0_sync) { if (_ps0 == null) { _ps0 = _GetSession().prepare( String.format("INSERT INTO %s.t0 (video_id, uid, topics, extra_data) VALUES (?,?,?,?)", _ks_regular)); } } BoundStatement bs = new BoundStatement(_ps0); _GetSession().execute(bs.bind(r.vid, r.videoUploader, new TreeSet<String>(r.topics), extraData)); } public static void ReadYoutubeRegular(YoutubeData.Req r) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra // server. Doesn't matter for non acorn.*_pr keyspaces. String q = String.format("SELECT * from %s.t0 WHERE video_id='%s'", _ks_regular, r.vid); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { // TODO: report to ProgMon System.out.printf("@"); System.out.flush(); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public void InsertRecordPartial(String obj_id, String user, Set<String> topics) throws Exception { String q = null; try { q = String.format( "INSERT INTO %s.t0 (obj_id, user, topics) VALUES ('%s', '%s', {%s});" , _ks_pr, obj_id, user , String.join(", ", topics.stream().map(t -> String.format("'%s'", t)).collect(Collectors.toList()))); _GetSession().execute(q); } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public void SelectRecordLocalUntilSucceed(String obj_id) throws Exception { try (Cons.MT _ = new Cons.MT("Select record %s ", obj_id)) { // Select data from the last created table with a CL local_ONE until // succeed. String q = String.format("select obj_id from %s.t0 where obj_id='%s'" , _ks_pr, obj_id); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Checking: "); while (true) { try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { System.out.printf("."); System.out.flush(); Thread.sleep(10); } else if (rows.size() == 1) { System.out.printf(" found one\n"); break; } else { throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } } } static public List<Row> SelectRecordLocal(String objId) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra server String q = String.format("select * from %s.t0 where obj_id='%s'" , _ks_pr, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); return rows; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static public List<Row> SelectRecordRemote(String dc, String objId) throws Exception { // Note: Must do select * to have all attributes processed inside Cassandra server String q = String.format("select * from %s.t0 where obj_id='%s'" , _ks_pr, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession(dc).execute(s); List<Row> rows = rs.all(); return rows; } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } static private class ClusterSession { Cluster c; // Session instances are thread-safe and usually a single instance is enough per application. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html Session s; ClusterSession(Cluster c, Session s) { this.c = c; this.s = s; } } static private Map<String, ClusterSession> _mapDcSession = new TreeMap<String, ClusterSession>(); static private Session _GetSession(String dc) throws Exception { //Cons.P(dc); ClusterSession cs = _GetDcCassSessionStartsWith(dc); if (cs == null) { // The default LoadBalancingPolicy is DCAwareRoundRobinPolicy, which // round-robins over the nodes of the local data center, which is exactly // what you want in this project. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.html Cluster c = new Cluster.Builder() .addContactPoints(_GetDcPubIp(dc)) // It says, // [main] INFO com.datastax.driver.core.Cluster - New Cassandra host /54.177.212.255:9042 added // [main] INFO com.datastax.driver.core.Cluster - New Cassandra host /127.0.0.1:9042 added // , which made me wonder if this connect to a remote region as well. // The public IP is on a different region. // // Specifying a white list doesn't seem to make any difference. //.withLoadBalancingPolicy( // new WhiteListPolicy(new DCAwareRoundRobinPolicy.Builder().build() // , Collections.singletonList(new InetSocketAddress("127.0.0.1", 9042)) // )) // // It might not mean which nodes this client connects to. .build(); // Session instances are thread-safe and usually a single instance is enough per application. // http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html Session s = c.connect(); //Metadata metadata = c.getMetadata(); //Cons.P("Connected to cluster '%s'.", metadata.getClusterName()); _mapDcSession.put(dc, new ClusterSession(c, s)); return s; } else { return cs.s; } } static private ClusterSession _GetDcCassSessionStartsWith(String dc) { for (Map.Entry<String, ClusterSession> e : _mapDcSession.entrySet()) { String k = e.getKey(); ClusterSession v = e.getValue(); if (k.startsWith(dc)) return v; } return null; } static private String _availabilityZone = null; static private Session _GetSession() throws Exception { if (_localDc != null) return _GetSession(_localDc); if (_availabilityZone == null) { Runtime r = Runtime.getRuntime(); Process p = r.exec("curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone"); p.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = b.readLine()) != null) { _availabilityZone = line; } b.close(); } // Trim the last [a-z] return _GetSession(_availabilityZone.substring(0, _availabilityZone.length() - 1)); } static private Map<String, String> _mapDcPubIp = new TreeMap<String, String>(); static private String _GetDcPubIp(String dc) throws Exception { String ip = _GetDcPubIpStartsWith(dc); if (ip == null) { File fn_jar = new File(AcornYoutube.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); // /mnt/local-ssd0/work/apache-cassandra-3.0.5-src/acorn/test/AcornYoutube/target/AcornYoutube-0.1.jar String fn = String.format("%s/.run/dc-ip-map", fn_jar.getParentFile().getParentFile()); Cons.P(fn); try (BufferedReader br = new BufferedReader(new FileReader(fn))) { String line; while ((line = br.readLine()) != null) { // us-east-1 54.160.118.182 String[] t = line.split("\\s+"); if (t.length !=2) throw new RuntimeException(String.format("Unexpcted format [%s]", line)); _mapDcPubIp.put(t[0], t[1]); } } ip = _GetDcPubIpStartsWith(dc); if (ip == null) throw new RuntimeException(String.format("No pub ip found for dc %s", dc)); } return ip; } static private String _GetDcPubIpStartsWith(String dc) { for (Map.Entry<String, String> e : _mapDcPubIp.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (k.startsWith(dc)) return v; } return null; } static public String GetObjLoc(String objId) throws Exception { String q = String.format("select obj_id, locations from %s.obj_loc where obj_id='%s'" , _ks_obj_loc, objId); Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); try { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { return null; } else if (rows.size() == 1) { Row r = rows.get(0); Set<String> locs = r.getSet(1, String.class); int locSize = locs.size(); if (locSize == 0) throw new RuntimeException(String.format("Unexpected: no location for object %s", objId)); int rand = (ThreadLocalRandom.current()).nextInt(locSize); int i = 0; for (String l: locs) { if (i == rand) return l; i ++; } } else { throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } return null; } static private int _barrier_id = 0; // Wait until everyone gets here static public long ExecutionBarrier() throws Exception { String q = null; long lapTime = 0; try { Cons.Pnnl("Execution barrier"); long bt = System.currentTimeMillis(); // Write us-(local_dc)-(exp_id)-(barrier_id) with CL One. CL doesn't matter it // will propagate eventually. q = String.format("Insert into %s.t0 (barrier_id) values ('%s-%s-%d');" , _ks_exe_barrier, LocalDC(), Conf.ExpID(), _barrier_id); Statement s = new SimpleStatement(q); _GetSession().execute(s); // Keep reading us-(remote_dc)-(exp_id)-(barrier_id) with CL LOCAL_ONE until // it sees the message from the other side. This doesn't need to be // parallelized. for (String peer_dc: _remoteDCs) { q = String.format("select barrier_id from %s.t0 where barrier_id='%s-%s-%d';" , _ks_exe_barrier, peer_dc, Conf.ExpID(), _barrier_id); s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); int sleepCnt = 0; while (true) { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { if (sleepCnt % 10 == 9) { if (sleepCnt == 9) System.out.printf(" "); System.out.printf("."); System.out.flush(); } Thread.sleep(10); sleepCnt ++; } else if (rows.size() == 1) { lapTime = System.currentTimeMillis() - bt; break; } else throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); lapTime = System.currentTimeMillis() - bt; if (lapTime > 10000) { System.out.printf("\n"); throw new RuntimeException("Execution barrier wait timed out :("); } } } _barrier_id ++; System.out.printf(" took %d ms\n", System.currentTimeMillis() - bt); } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } return lapTime; } static public void WriteStartTime(long startTime) throws Exception { String k = String.format("starttime-%s", Conf.ExpID()); String v = Long.toString(startTime); PreparedStatement ps = _GetSession().prepare( String.format("insert into %s.t0 (key, value) values (?,?)", _ks_exp_meta)); BoundStatement bs = new BoundStatement(ps); _GetSession().execute(bs.bind(k, v)); } static public long ReadStartTimeUntilSucceed() throws Exception { String k = String.format("starttime-%s", Conf.ExpID()); String q = String.format("select * from %s.t0 where key='%s'" , _ks_exp_meta, k); try { Statement s = new SimpleStatement(q).setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); Cons.Pnnl("Getting start time:"); long bt = System.currentTimeMillis(); int cntSleep = 0; while (true) { ResultSet rs = _GetSession().execute(s); List<Row> rows = rs.all(); if (rows.size() == 0) { if (cntSleep % 10 == 9) { if (cntSleep == 9) System.out.print(" "); System.out.print("."); System.out.flush(); } Thread.sleep(10); cntSleep ++; } else if (rows.size() == 1) { Row r = rows.get(0); String v = r.getString("value"); //Cons.P("v=%s", v); System.out.printf(" took %d ms\n", System.currentTimeMillis() - bt); return Long.parseLong(v); } else { throw new RuntimeException(String.format("Unexpected: rows.size()=%d", rows.size())); } if (System.currentTimeMillis() - bt > 2000) { System.out.printf("\n"); throw new RuntimeException("Time out :("); } } } catch (com.datastax.driver.core.exceptions.DriverException e) { Cons.P("Exception=[%s] query=[%s]", e, q); throw e; } } // TODO: clean up //static public void InsertRandomToRegular(String obj_id, int recSize) throws Exception { // try { // // http://ac31004.blogspot.com/2014/03/saving-image-in-cassandra-blob-field.html // // http://stackoverflow.com/questions/5683206/how-to-create-an-array-of-20-random-bytes // byte[] b = new byte[recSize]; // _rand.nextBytes(b); // ByteBuffer bb = ByteBuffer.wrap(b); // PreparedStatement ps = _GetSession().prepare( // String.format("insert into %s.t0 (c0, c1) values (?,?)", _ks_regular)); // BoundStatement bs = new BoundStatement(ps); // _GetSession().execute(bs.bind(obj_id, bb)); // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s]", e); // throw e; // } //} //static public List<Row> SelectFromRegular(ConsistencyLevel cl, String obj_id) throws Exception { // String q = String.format("select * from %s.t0 where c0='%s'" // , _ks_regular, obj_id); // try { // Statement s = new SimpleStatement(q).setConsistencyLevel(cl); // ResultSet rs = _GetSession().execute(s); // List<Row> rows = rs.all(); // if (rows.size() != 1) // throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); // return rows; // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s] query=[%s]", e, q); // throw e; // } //} //static public long SelectCountFromRegular(ConsistencyLevel cl, String objId0, String objId1) throws Exception { // String q = String.format("select count(*) from %s.t0 where c0 in ('%s', '%s')" // , _ks_regular, objId0, objId1); // try { // Statement s = new SimpleStatement(q).setConsistencyLevel(cl); // ResultSet rs = _GetSession().execute(s); // List<Row> rows = rs.all(); // if (rows.size() != 1) // throw new RuntimeException(String.format("Unexpcted: rows.size()=%d", rows.size())); // Row r = rows.get(0); // return r.getLong(0); // } catch (com.datastax.driver.core.exceptions.DriverException e) { // Cons.P("Exception=[%s] query=[%s]", e, q); // throw e; // } //} }
update
acorn/clients/youtube/src/main/java/Cass.java
update
Java
apache-2.0
ef68e5076bd970afb92a9d890f3f3c122be4e765
0
joserabal/sakai,OpenCollabZA/sakai,ouit0408/sakai,frasese/sakai,bzhouduke123/sakai,bzhouduke123/sakai,bzhouduke123/sakai,clhedrick/sakai,joserabal/sakai,frasese/sakai,OpenCollabZA/sakai,willkara/sakai,ouit0408/sakai,Fudan-University/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,frasese/sakai,pushyamig/sakai,kwedoff1/sakai,bzhouduke123/sakai,clhedrick/sakai,lorenamgUMU/sakai,kwedoff1/sakai,lorenamgUMU/sakai,ouit0408/sakai,pushyamig/sakai,joserabal/sakai,rodriguezdevera/sakai,willkara/sakai,zqian/sakai,conder/sakai,ktakacs/sakai,colczr/sakai,joserabal/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,conder/sakai,frasese/sakai,willkara/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,conder/sakai,pushyamig/sakai,clhedrick/sakai,Fudan-University/sakai,lorenamgUMU/sakai,pushyamig/sakai,ktakacs/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,ouit0408/sakai,conder/sakai,liubo404/sakai,kwedoff1/sakai,kwedoff1/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,clhedrick/sakai,ktakacs/sakai,lorenamgUMU/sakai,conder/sakai,rodriguezdevera/sakai,zqian/sakai,willkara/sakai,conder/sakai,clhedrick/sakai,willkara/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,joserabal/sakai,liubo404/sakai,joserabal/sakai,willkara/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,ktakacs/sakai,Fudan-University/sakai,clhedrick/sakai,colczr/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,colczr/sakai,joserabal/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,ktakacs/sakai,rodriguezdevera/sakai,ouit0408/sakai,Fudan-University/sakai,ouit0408/sakai,lorenamgUMU/sakai,zqian/sakai,pushyamig/sakai,frasese/sakai,colczr/sakai,willkara/sakai,willkara/sakai,rodriguezdevera/sakai,frasese/sakai,conder/sakai,Fudan-University/sakai,kwedoff1/sakai,colczr/sakai,buckett/sakai-gitflow,liubo404/sakai,joserabal/sakai,liubo404/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,ktakacs/sakai,rodriguezdevera/sakai,ktakacs/sakai,Fudan-University/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,colczr/sakai,kwedoff1/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,pushyamig/sakai,rodriguezdevera/sakai,clhedrick/sakai,ouit0408/sakai,pushyamig/sakai,frasese/sakai,conder/sakai,ouit0408/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,kwedoff1/sakai,liubo404/sakai,zqian/sakai,liubo404/sakai,zqian/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,zqian/sakai,frasese/sakai,buckett/sakai-gitflow,liubo404/sakai,colczr/sakai,colczr/sakai,rodriguezdevera/sakai,bzhouduke123/sakai
package org.sakaiproject.util; import java.io.File; /** * A utility for generating (and cleaning up) {@link Component}s. Please * note that the tear-down is highly aggressive: it deletes the entire * root components directory that it generates. * * * @author dmccallum * */ public class ComponentBuilder { private File componentsRootDir; private Compiler compiler; public ComponentBuilder() { compiler = new Compiler(); } /** * Verifies that this builder has a reasonable chance at performing * its work, i.e. can at least attempt to compile generated source code. * * @return */ public boolean isUseable() { return compiler.isUseable(); } public Component buildComponent() { return buildComponent(nextComponentId()); } public Component buildComponent(String id, String... jars) { if ( !(isUseable()) ) { throw new IllegalStateException("ComponentBuilder not currently useable, probably because the JDK compiler is unavailable."); } initComponentsRootDir(); Component component = new Component(id, componentsRootDir.getAbsolutePath(), compiler, jars); component.generate(); return component; } protected String nextComponentId() { return Long.toString((long)(Math.random() * 2821109907456L), 36); } protected void initComponentsRootDir() { if ( componentsRootDir != null && componentsRootDir.exists() ) { return; } doInitComponentsRootDir(); } protected void doInitComponentsRootDir() { File tmpDir = new File(System.getProperty("java.io.tmpdir")); if ( !(tmpDir.exists()) || !(tmpDir.isDirectory()) || !(tmpDir.canWrite()) ) { throw new IllegalStateException("Unable to create components root dir in [" + tmpDir + "]"); } File newRoot = null; for ( int i = 0; i < 1000; i++ ) { newRoot = new File(tmpDir.getAbsolutePath() + File.separator + "components" + (i == 0 ? "" : "-" + i)); if ( newRoot.mkdir() ) { componentsRootDir = newRoot; break; } } if ( componentsRootDir == null ) { throw new IllegalStateException("Unable to create new components root dir below " + tmpDir); } } public File getComponentsRootDir() { return componentsRootDir; } public void tearDown() { if ( componentsRootDir == null || !(componentsRootDir.exists()) ) { return; } deleteDir(componentsRootDir); } protected void deleteDir(File dir) { if (!(dir.exists())) { return; } if(dir.isDirectory()) { File[] files = dir.listFiles(); for ( File file : files ) { deleteDir(file); } dir.delete(); } else { dir.delete(); } } }
kernel/component-manager/src/test/java/org/sakaiproject/util/ComponentBuilder.java
package org.sakaiproject.util; import java.io.File; /** * A utility for generating (and cleaning up) {@link Component}s. Please * note that the tear-down is highly aggressive: it deletes the entire * root components directory that it generates. * * * @author dmccallum * */ public class ComponentBuilder { private File componentsRootDir; private Compiler compiler; public ComponentBuilder() { compiler = new Compiler(); } /** * Verifies that this builder has a reasonable chance at performing * its work, i.e. can at least attempt to compile generated source code. * * @return */ public boolean isUseable() { return compiler.isUseable(); } public Component buildComponent() { return buildComponent(nextComponentId()); } public Component buildComponent(String id, String... jars) { if ( !(isUseable()) ) { throw new IllegalStateException("ComponentBuilder not currently useable, probably because the JDK compiler is unavailable."); } initComponentsRootDir(); Component component = new Component(id, componentsRootDir.getAbsolutePath(), compiler, jars); component.generate(); return component; } protected String nextComponentId() { return Long.toString((long)(Math.random() * 2821109907456L), 36); } protected void initComponentsRootDir() { if ( componentsRootDir != null && componentsRootDir.exists() ) { return; } doInitComponentsRootDir(); } protected void doInitComponentsRootDir() { File tmpDir = new File(System.getProperty("java.io.tmpdir")); if ( !(tmpDir.exists()) || !(tmpDir.isDirectory()) || !(tmpDir.canWrite()) ) { throw new IllegalStateException("Unable to create components root dir in [" + tmpDir + "]"); } File newRoot = null; for ( int i = 0; i < 1000; i++ ) { newRoot = new File(tmpDir.getAbsolutePath() + File.separator + "components" + (i == 0 ? "" : "-" + i)); if ( newRoot.mkdir() ) { componentsRootDir = newRoot; break; } } if ( componentsRootDir == null ) { throw new IllegalStateException("Unable to create new components root dir below " + tmpDir); } } public File getComponentsRootDir() { return componentsRootDir; } public void tearDown() { if ( componentsRootDir == null || !(componentsRootDir.exists()) ) { return; } deleteDir(componentsRootDir); } protected void deleteDir(File dir) { if (!(dir.exists())) { return; } if(dir.isDirectory()) { File[] files = dir.listFiles(); for ( File file : files ) { deleteDir(file); } dir.delete(); } else { dir.delete(); } } @Override protected void finalize() { tearDown(); } }
KNL-1396 The finalize() call would break tests. The test would finish and then the directory would get deleted, then the next test would start up and it would use the same directory location (recreating it). Then the finalize() method on the first test would be called and this would remove the directory which was now being used by the second test. The other option would have been to have had all the tests use a different directory, but removing the finalize() is a sensible thing todo as it could cause confusion in the future. In my tests even when a test failed I was still seeing the directory get cleaned up, it's only if the caller doesn't call tearDown() that the directory would remain.
kernel/component-manager/src/test/java/org/sakaiproject/util/ComponentBuilder.java
KNL-1396 The finalize() call would break tests.
Java
apache-2.0
8c620d4d018756ea962a715de276a3f98fabbd78
0
shiguang1120/AndEngine,ericlaro/AndEngineLibrary,parthipanramesh/AndEngine,Munazza/AndEngine,yaye729125/gles,viacheslavokolitiy/AndEngine,godghdai/AndEngine,Munazza/AndEngine,borrom/AndEngine,nicolasgramlich/AndEngine,luoxiaoshenghustedu/AndEngine,Munazza/AndEngine,yudhir/AndEngine,pongo710/AndEngine,borrom/AndEngine,jduberville/AndEngine,zhidew/AndEngine,parthipanramesh/AndEngine,jduberville/AndEngine,yudhir/AndEngine,zcwk/AndEngine,godghdai/AndEngine,msdgwzhy6/AndEngine,msdgwzhy6/AndEngine,godghdai/AndEngine,pongo710/AndEngine,viacheslavokolitiy/AndEngine,borrom/AndEngine,shiguang1120/AndEngine,godghdai/AndEngine,nicolasgramlich/AndEngine,parthipanramesh/AndEngine,zhidew/AndEngine,Munazza/AndEngine,parthipanramesh/AndEngine,zhidew/AndEngine,shiguang1120/AndEngine,zcwk/AndEngine,duchien85/AndEngine,yudhir/AndEngine,yudhir/AndEngine,ericlaro/AndEngineLibrary,luoxiaoshenghustedu/AndEngine,borrom/AndEngine,shiguang1120/AndEngine,chautn/AndEngine,pongo710/AndEngine,jduberville/AndEngine,nicolasgramlich/AndEngine,zhidew/AndEngine,luoxiaoshenghustedu/AndEngine,chautn/AndEngine,zcwk/AndEngine,chautn/AndEngine,viacheslavokolitiy/AndEngine,ericlaro/AndEngineLibrary,yaye729125/gles,msdgwzhy6/AndEngine,yaye729125/gles,duchien85/AndEngine,nicolasgramlich/AndEngine,msdgwzhy6/AndEngine,jduberville/AndEngine,viacheslavokolitiy/AndEngine,ericlaro/AndEngineLibrary,pongo710/AndEngine,luoxiaoshenghustedu/AndEngine,chautn/AndEngine,yaye729125/gles,zcwk/AndEngine
package org.anddev.andengine.engine.camera; /** * @author Nicolas Gramlich * @since 15:55:54 - 27.07.2010 */ public class BoundCamera extends Camera { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mBoundMinX; private float mBoundMaxX; private float mBoundMinY; private float mBoundMaxY; private boolean mBoundsEnabled; // =========================================================== // Constructors // =========================================================== public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { super(pX, pY, pWidth, pHeight); this.setBounds(pBoundMinX, pBoundMaxX, pBoundMinY, pBoundMaxY); } // =========================================================== // Getter & Setter // =========================================================== public void setBoundsEnabled(final boolean pBoundsEnabled) { this.mBoundsEnabled = pBoundsEnabled; } public void setBounds(final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { this.mBoundMinX = pBoundMinX; this.mBoundMaxX = pBoundMaxX; this.mBoundMinY = pBoundMinY; this.mBoundMaxY = pBoundMaxY; } @Override public void setCenter(final float pCenterX, final float pCenterY) { super.setCenter(pCenterX, pCenterY); if(this.mBoundsEnabled) { final float newCenterX = this.getCenterX(); final float newCenterY = this.getCenterY(); final float minXBoundExceededAmount = this.mBoundMinX - this.getMinX(); final boolean minXBoundExceeded = minXBoundExceededAmount > 0; final float maxXBoundExceededAmount = this.getMaxX() - this.mBoundMaxX; final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0; final float minYBoundExceededAmount = this.mBoundMinY - this.getMinY(); final boolean minYBoundExceeded = minYBoundExceededAmount > 0; final float maxYBoundExceededAmount = this.getMaxY() - this.mBoundMaxY; final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0; if(minXBoundExceeded || maxXBoundExceeded || minYBoundExceeded || maxYBoundExceeded) { final float boundedCenterX; final float boundedCenterY; if(minXBoundExceeded) { if(maxXBoundExceeded) { /* Both X exceeded. */ boundedCenterX = newCenterX - maxXBoundExceededAmount + minXBoundExceededAmount; } else { /* Only min X exceeded. */ boundedCenterX = newCenterX + minXBoundExceededAmount; } } else { if(maxXBoundExceeded) { /* Only max X exceeded. */ boundedCenterX = newCenterX - maxXBoundExceededAmount; } else { /* Nothing exceeded. */ boundedCenterX = newCenterX; } } if(minYBoundExceeded) { if(maxYBoundExceeded) { /* Both Y exceeded. */ boundedCenterY = newCenterY - maxYBoundExceededAmount + minYBoundExceededAmount; } else { /* Only min Y exceeded. */ boundedCenterY = newCenterY + minYBoundExceededAmount; } } else { if(maxYBoundExceeded) { /* Only max Y exceeded. */ boundedCenterY = newCenterY - maxYBoundExceededAmount; } else { /* Nothing exceeded. */ boundedCenterY = newCenterY; } } super.setCenter(boundedCenterX, boundedCenterY); } } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
src/org/anddev/andengine/engine/camera/BoundCamera.java
package org.anddev.andengine.engine.camera; /** * @author Nicolas Gramlich * @since 15:55:54 - 27.07.2010 */ public class BoundCamera extends Camera { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float mBoundMinX; private final float mBoundMaxX; private final float mBoundMinY; private final float mBoundMaxY; private boolean mBoundsEnabled; // =========================================================== // Constructors // =========================================================== public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) { super(pX, pY, pWidth, pHeight); this.mBoundMinX = pBoundMinX; this.mBoundMaxX = pBoundMaxX; this.mBoundMinY = pBoundMinY; this.mBoundMaxY = pBoundMaxY; } // =========================================================== // Getter & Setter // =========================================================== public void setBoundsEnabled(final boolean pBoundsEnabled) { this.mBoundsEnabled = pBoundsEnabled; } @Override public void setCenter(final float pCenterX, final float pCenterY) { super.setCenter(pCenterX, pCenterY); if(this.mBoundsEnabled) { final float newCenterX = this.getCenterX(); final float newCenterY = this.getCenterY(); final float minXBoundExceededAmount = this.mBoundMinX - this.getMinX(); final boolean minXBoundExceeded = minXBoundExceededAmount > 0; final float maxXBoundExceededAmount = this.getMaxX() - this.mBoundMaxX; final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0; final float minYBoundExceededAmount = this.mBoundMinY - this.getMinY(); final boolean minYBoundExceeded = minYBoundExceededAmount > 0; final float maxYBoundExceededAmount = this.getMaxY() - this.mBoundMaxY; final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0; if(minXBoundExceeded || maxXBoundExceeded || minYBoundExceeded || maxYBoundExceeded) { final float boundedCenterX; final float boundedCenterY; if(minXBoundExceeded) { if(maxXBoundExceeded) { /* Both X exceeded. */ boundedCenterX = newCenterX - maxXBoundExceededAmount + minXBoundExceededAmount; } else { /* Only min X exceeded. */ boundedCenterX = newCenterX + minXBoundExceededAmount; } } else { if(maxXBoundExceeded) { /* Only max X exceeded. */ boundedCenterX = newCenterX - maxXBoundExceededAmount; } else { /* Nothing exceeded. */ boundedCenterX = newCenterX; } } if(minYBoundExceeded) { if(maxYBoundExceeded) { /* Both Y exceeded. */ boundedCenterY = newCenterY - maxYBoundExceededAmount + minYBoundExceededAmount; } else { /* Only min Y exceeded. */ boundedCenterY = newCenterY + minYBoundExceededAmount; } } else { if(maxYBoundExceeded) { /* Only max Y exceeded. */ boundedCenterY = newCenterY - maxYBoundExceededAmount; } else { /* Nothing exceeded. */ boundedCenterY = newCenterY; } } super.setCenter(boundedCenterX, boundedCenterY); } } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
BoundCamera: bounds can now be changed.
src/org/anddev/andengine/engine/camera/BoundCamera.java
BoundCamera: bounds can now be changed.
Java
apache-2.0
a6348953b61000580f08f9168024657de640982d
0
rimolive/rhiot,lasombra/rhiot,rhiot/rhiot,jasonchaffee/camel-labs,finiteloopme/rhiot,rimolive/rhiot,rimolive/rhiot,krissman/rhiot,finiteloopme/rhiot,krissman/rhiot,lasombra/rhiot,rhiot/rhiot,krissman/rhiot,jasonchaffee/camel-labs,rimolive/rhiot,rimolive/rhiot,rhiot/rhiot,krissman/rhiot,rimolive/rhiot,lasombra/rhiot,rhiot/rhiot,krissman/rhiot,lasombra/rhiot,jasonchaffee/camel-labs,rimolive/rhiot,rhiot/rhiot,krissman/rhiot,finiteloopme/rhiot,krissman/rhiot,finiteloopme/rhiot,rhiot/rhiot,rhiot/rhiot
/** * Licensed to the Camel Labs under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.camellabs.iot.gateway; import org.apache.activemq.broker.BrokerService; import org.apache.camel.ConsumerTemplate; import org.apache.camel.EndpointInject; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.github.camellabs.iot.gateway.CamelIotGatewayConstants.HEARTBEAT_ENDPOINT; import static java.lang.System.setProperty; import static org.springframework.util.SocketUtils.findAvailableTcpPort; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = CamelIotGatewayTest.class) @IntegrationTest("camellabs.iot.gateway.heartbeat.mqtt=true") public class CamelIotGatewayTest extends Assert { static int mqttPort = findAvailableTcpPort(); @EndpointInject(uri = "mock:test") MockEndpoint mockEndpoint; @Autowired ConsumerTemplate consumerTemplate; @Bean RouteBuilderCallback mockRouteBuilderCallback() { return routeBuilder -> routeBuilder.interceptFrom(HEARTBEAT_ENDPOINT).to("mock:test"); } // TODO https://github.com/camel-labs/camel-labs/issues/66 (Camel Spring Boot should start embedded MQTT router for tests) @Bean(initMethod = "start", destroyMethod = "stop") BrokerService broker() throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(false); broker.addConnector("mqtt://localhost:" + mqttPort); return broker; } @BeforeClass public static void beforeClass() { setProperty("camellabs.iot.gateway.heartbeat.mqtt.broker.url", "tcp://localhost:" + mqttPort); } // Tests @Test public void shouldInterceptHeartbeatEndpoint() throws InterruptedException { mockEndpoint.setMinimumExpectedMessageCount(1); mockEndpoint.assertIsSatisfied(); } @Test public void shouldReceiveHeartbeatMqttMessage() { String heartbeat = consumerTemplate.receiveBody("paho:heartbeat?brokerUrl={{camellabs.iot.gateway.heartbeat.mqtt.broker.url}}", String.class); assertNotNull(heartbeat); } }
iot/gateway/src/test/java/com/github/camellabs/iot/gateway/CamelIotGatewayTest.java
/** * Licensed to the Camel Labs under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.camellabs.iot.gateway; import org.apache.activemq.broker.BrokerService; import org.apache.camel.ConsumerTemplate; import org.apache.camel.EndpointInject; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.github.camellabs.iot.gateway.CamelIotGatewayConstants.HEARTBEAT_ENDPOINT; import static java.lang.System.setProperty; import static org.springframework.util.SocketUtils.findAvailableTcpPort; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = CamelIotGatewayTest.class) @IntegrationTest("camellabs.iot.gateway.heartbeat.mqtt=true") public class CamelIotGatewayTest extends Assert { static int mqttPort = findAvailableTcpPort(); @EndpointInject(uri = "mock:test") MockEndpoint mockEndpoint; @Autowired ConsumerTemplate consumerTemplate; @Bean RouteBuilderCallback mockRouteBuilderCallback() { return routeBuilder -> routeBuilder.interceptFrom(HEARTBEAT_ENDPOINT).to("mock:test"); } // TODO https://github.com/camel-labs/camel-labs/issues/66 (Camel Spring Boot should start embedded MQTT router for tests) @Bean(initMethod = "start", destroyMethod = "stop") BrokerService broker() throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(false); broker.addConnector("mqtt://localhost:" + mqttPort); return broker; } @BeforeClass public static void beforeClass() { setProperty("camellabs.iot.gateway.heartbeat.mqtt.broker.url", "tcp://localhost:" + mqttPort); } @Test public void shouldInterceptHeartbeatEndpoint() throws InterruptedException { mockEndpoint.setExpectedCount(1); mockEndpoint.assertIsSatisfied(); } @Test public void shouldReceiveHeartbeatMqttMessage() { String heartbeat = consumerTemplate.receiveBody("paho:heartbeat?brokerUrl={{camellabs.iot.gateway.heartbeat.mqtt.broker.url}}", String.class); assertNotNull(heartbeat); } }
Fixed gateway tests concurrency.
iot/gateway/src/test/java/com/github/camellabs/iot/gateway/CamelIotGatewayTest.java
Fixed gateway tests concurrency.
Java
apache-2.0
f468e449a6e0752d52ee2d3e439c732db588012d
0
serandel/hollywood,serandel/hollywood
package org.granchi.hollywood; import org.junit.Ignore; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) @Ignore public class CrewTest { @Mock private Model model; // @Mock // private Actor.Factory actorFactory; @Mock private Actor actor, actor2; @Mock private Action action, action2, action3; // @Test // @SuppressWarnings("unchecked") // public void testPropagatesModels() { // Subject<Model, Model> models = BehaviorSubject.create(); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // when(actor.getActions()).thenReturn(Observable.empty()); // when(actor2.getActions()).thenReturn(Observable.empty()); // // TestSubscriber<Model<ActorMetadata>> testSubscriber = new TestSubscriber<>(); // TestSubscriber<Model<ActorMetadata>> testSubscriber2 = new TestSubscriber<>(); // // doAnswer(invocation -> { // invocation.getArgumentAt(0, Observable.class).subscribe(testSubscriber); // return null; // }).when(actor).subscribeTo(models); // // doAnswer(invocation -> { // invocation.getArgumentAt(0, Observable.class).subscribe(testSubscriber2); // return null; // }).when(actor2).subscribeTo(models); // // MinimumCrew cast = new MinimumCrew(models); // cast.ensureCrew(metadatas); // models.onNext(model); // // verify(actor).subscribeTo(models); // verify(actor2).subscribeTo(models); // // testSubscriber.assertValue(model); // testSubscriber2.assertValue(model); // } // // @Test // public void testMergesActions() { // Set<ActorMetadata> metadatas = new HashSet<>(Arrays.asList(metadata, metadata2)); // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action, action3)); // when(actor2.getActions()).thenReturn(Observable.just(action2)); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // cast.ensureCrew(metadatas); // // // I don't have to be sure of the order // testSubscriber.assertValueCount(3); // } // // @Test // public void testMergesActionsEvenIfCreatedLater() { // Set<ActorMetadata> metadatas = new HashSet<>(Collections.singletonList(metadata)); // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action, action3)); // when(actor2.getActions()).thenReturn(Observable.just(action2)); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // cast.ensureCrew(metadatas); // // metadatas.add(metadata2); // // cast.ensureCrew(metadatas); // // // Now I know the order, because actor2 was created later // testSubscriber.assertValues(action, action3, action2); // } // // @Test // public void testDontGetActionsFromRemovedActors() { // Set<ActorMetadata> metadatas = new HashSet<>(Arrays.asList(metadata, metadata2)); // // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // PublishSubject<Action> actions2 = PublishSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action)); // when(actor2.getActions()).thenReturn(actions2); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // // Two actors // cast.ensureCrew(metadatas); // // Action from 2 // actions2.onNext(action2); // // // Remove actor2 // metadatas.remove(metadata2); // cast.ensureCrew(metadatas); // // // Another action // actions2.onNext(action3); // // // No action3 // testSubscriber.assertValues(action, action2); // } // // private class MinimumCrew extends Crew<ActorMetadata> { // final Map<ActorMetadata, Actor<ActorMetadata>> actors = new HashMap<>(); // // protected MinimumCrew(Observable<Model<ActorMetadata>> models) { // super(models); // } // // @Override // protected Actor<ActorMetadata> buildActorFrom(ActorMetadata metadata) { // Actor<ActorMetadata> actor = actorFactory.create(metadata); // actors.put(metadata, actor); // return actor; // } // // @Override // protected boolean containsActorFrom(ActorMetadata metadata) { // return actors.containsKey(metadata); // } // // @Override // protected Collection<Actor<ActorMetadata>> getActors() { // return actors.values(); // } // // @Override // protected boolean isActorFrom(Actor<ActorMetadata> actor, ActorMetadata metadata) { // return actors.containsKey(metadata) && (actors.get(metadata) == actor); // } // // @Override // protected void remove(Actor<ActorMetadata> actor) { // Iterator<Map.Entry<ActorMetadata, Actor<ActorMetadata>>> // it = // actors.entrySet().iterator(); // // while (it.hasNext()) { // if (it.next().getValue() == actor) { // it.remove(); // break; // } // } // } // } }
core/src/test/java/org/granchi/hollywood/CrewTest.java
package org.granchi.hollywood; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class CrewTest { @Mock private Model model; // @Mock // private Actor.Factory actorFactory; @Mock private Actor actor, actor2; @Mock private Action action, action2, action3; // @Test // @SuppressWarnings("unchecked") // public void testPropagatesModels() { // Subject<Model, Model> models = BehaviorSubject.create(); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // when(actor.getActions()).thenReturn(Observable.empty()); // when(actor2.getActions()).thenReturn(Observable.empty()); // // TestSubscriber<Model<ActorMetadata>> testSubscriber = new TestSubscriber<>(); // TestSubscriber<Model<ActorMetadata>> testSubscriber2 = new TestSubscriber<>(); // // doAnswer(invocation -> { // invocation.getArgumentAt(0, Observable.class).subscribe(testSubscriber); // return null; // }).when(actor).subscribeTo(models); // // doAnswer(invocation -> { // invocation.getArgumentAt(0, Observable.class).subscribe(testSubscriber2); // return null; // }).when(actor2).subscribeTo(models); // // MinimumCrew cast = new MinimumCrew(models); // cast.ensureCrew(metadatas); // models.onNext(model); // // verify(actor).subscribeTo(models); // verify(actor2).subscribeTo(models); // // testSubscriber.assertValue(model); // testSubscriber2.assertValue(model); // } // // @Test // public void testMergesActions() { // Set<ActorMetadata> metadatas = new HashSet<>(Arrays.asList(metadata, metadata2)); // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action, action3)); // when(actor2.getActions()).thenReturn(Observable.just(action2)); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // cast.ensureCrew(metadatas); // // // I don't have to be sure of the order // testSubscriber.assertValueCount(3); // } // // @Test // public void testMergesActionsEvenIfCreatedLater() { // Set<ActorMetadata> metadatas = new HashSet<>(Collections.singletonList(metadata)); // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action, action3)); // when(actor2.getActions()).thenReturn(Observable.just(action2)); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // cast.ensureCrew(metadatas); // // metadatas.add(metadata2); // // cast.ensureCrew(metadatas); // // // Now I know the order, because actor2 was created later // testSubscriber.assertValues(action, action3, action2); // } // // @Test // public void testDontGetActionsFromRemovedActors() { // Set<ActorMetadata> metadatas = new HashSet<>(Arrays.asList(metadata, metadata2)); // // Subject<Model<ActorMetadata>, Model<ActorMetadata>> models = BehaviorSubject.create(); // // PublishSubject<Action> actions2 = PublishSubject.create(); // // when(actor.getActions()).thenReturn(Observable.just(action)); // when(actor2.getActions()).thenReturn(actions2); // // when(actorFactory.create(metadata)).thenReturn(actor); // when(actorFactory.create(metadata2)).thenReturn(actor2); // // TestSubscriber<Action> testSubscriber = new TestSubscriber<>(); // // MinimumCrew cast = new MinimumCrew(models); // cast.getActions().subscribe(testSubscriber); // // // Two actors // cast.ensureCrew(metadatas); // // Action from 2 // actions2.onNext(action2); // // // Remove actor2 // metadatas.remove(metadata2); // cast.ensureCrew(metadatas); // // // Another action // actions2.onNext(action3); // // // No action3 // testSubscriber.assertValues(action, action2); // } // // private class MinimumCrew extends Crew<ActorMetadata> { // final Map<ActorMetadata, Actor<ActorMetadata>> actors = new HashMap<>(); // // protected MinimumCrew(Observable<Model<ActorMetadata>> models) { // super(models); // } // // @Override // protected Actor<ActorMetadata> buildActorFrom(ActorMetadata metadata) { // Actor<ActorMetadata> actor = actorFactory.create(metadata); // actors.put(metadata, actor); // return actor; // } // // @Override // protected boolean containsActorFrom(ActorMetadata metadata) { // return actors.containsKey(metadata); // } // // @Override // protected Collection<Actor<ActorMetadata>> getActors() { // return actors.values(); // } // // @Override // protected boolean isActorFrom(Actor<ActorMetadata> actor, ActorMetadata metadata) { // return actors.containsKey(metadata) && (actors.get(metadata) == actor); // } // // @Override // protected void remove(Actor<ActorMetadata> actor) { // Iterator<Map.Entry<ActorMetadata, Actor<ActorMetadata>>> // it = // actors.entrySet().iterator(); // // while (it.hasNext()) { // if (it.next().getValue() == actor) { // it.remove(); // break; // } // } // } // } }
Ignore unused test for now
core/src/test/java/org/granchi/hollywood/CrewTest.java
Ignore unused test for now
Java
apache-2.0
7b4e74a95f71405c346eef733a4d50a1bcab0ec2
0
ringdna/jitsi,procandi/jitsi,jibaro/jitsi,pplatek/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,damencho/jitsi,iant-gmbh/jitsi,martin7890/jitsi,Metaswitch/jitsi,jitsi/jitsi,damencho/jitsi,jitsi/jitsi,gpolitis/jitsi,dkcreinoso/jitsi,level7systems/jitsi,459below/jitsi,level7systems/jitsi,jibaro/jitsi,iant-gmbh/jitsi,martin7890/jitsi,marclaporte/jitsi,level7systems/jitsi,bebo/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,dkcreinoso/jitsi,gpolitis/jitsi,jibaro/jitsi,cobratbq/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,marclaporte/jitsi,marclaporte/jitsi,tuijldert/jitsi,ringdna/jitsi,mckayclarey/jitsi,procandi/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,jibaro/jitsi,Metaswitch/jitsi,bhatvv/jitsi,459below/jitsi,dkcreinoso/jitsi,damencho/jitsi,bebo/jitsi,dkcreinoso/jitsi,459below/jitsi,jitsi/jitsi,ibauersachs/jitsi,mckayclarey/jitsi,damencho/jitsi,martin7890/jitsi,bhatvv/jitsi,ibauersachs/jitsi,marclaporte/jitsi,tuijldert/jitsi,HelioGuilherme66/jitsi,bebo/jitsi,jitsi/jitsi,martin7890/jitsi,cobratbq/jitsi,tuijldert/jitsi,ringdna/jitsi,bhatvv/jitsi,bebo/jitsi,damencho/jitsi,mckayclarey/jitsi,459below/jitsi,Metaswitch/jitsi,cobratbq/jitsi,ringdna/jitsi,procandi/jitsi,459below/jitsi,marclaporte/jitsi,ibauersachs/jitsi,level7systems/jitsi,pplatek/jitsi,level7systems/jitsi,bebo/jitsi,laborautonomo/jitsi,tuijldert/jitsi,mckayclarey/jitsi,procandi/jitsi,mckayclarey/jitsi,bhatvv/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,pplatek/jitsi,procandi/jitsi,ringdna/jitsi,iant-gmbh/jitsi,martin7890/jitsi,jitsi/jitsi,cobratbq/jitsi,gpolitis/jitsi,jibaro/jitsi,gpolitis/jitsi,tuijldert/jitsi,cobratbq/jitsi,laborautonomo/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.irc; import java.util.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * An IRC implementation of the ProtocolProviderService. * * @author Loic Kempf * @author Stephane Remy */ public class ProtocolProviderServiceIrcImpl implements ProtocolProviderService { private static final Logger logger = Logger.getLogger(ProtocolProviderServiceIrcImpl.class); /** * The irc server. */ private IrcStack ircStack; /** * The id of the account that this protocol provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private Object initializationLock = new Object(); /** * The hashtable with the operation sets that we support locally. */ private Hashtable supportedOperationSets = new Hashtable(); /** * A list of listeners interested in changes in our registration state. */ private Vector registrationStateListeners = new Vector(); /** * Indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * The icon corresponding to the irc protocol. */ private ProtocolIconIrcImpl ircIcon = new ProtocolIconIrcImpl(); /** * The default constructor for the IRC protocol provider. */ public ProtocolProviderServiceIrcImpl() { logger.trace("Creating a irc provider."); } /** * Keeps our current registration state. */ private RegistrationState currentRegistrationState = RegistrationState.UNREGISTERED; /** * Initializes the service implementation, and puts it in a sate where it * could operate with other services. It is strongly recommended that * properties in this Map be mapped to property names as specified by * <tt>AccountProperties</tt>. * * @param userID the user id of the IRC account we're currently * initializing * @param accountID the identifier of the account that this protocol * provider represents. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String userID, AccountID accountID) { synchronized(initializationLock) { this.accountID = accountID; //Initialize the multi user chat support OperationSetMultiUserChatIrcImpl multiUserChat = new OperationSetMultiUserChatIrcImpl(this); supportedOperationSets.put( OperationSetMultiUserChat.class.getName(), multiUserChat); this.ircStack = new IrcStack( this, getAccountID().getUserID(), getAccountID().getUserID(), "SIP Communicator 1.0", ""); isInitialized = true; } } /** * Registers the specified listener with this provider so that it would * receive notifications on changes of its state or other properties such * as its local address and display name. * * @param listener the listener to register. */ public void addRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationStateListeners) { if (!registrationStateListeners.contains(listener)) registrationStateListeners.add(listener); } } /** * Removes the specified registration listener so that it won't receive * further notifications when our registration state changes. * * @param listener the listener to remove. */ public void removeRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationStateListeners) { registrationStateListeners.remove(listener); } } /** * Creates a <tt>RegistrationStateChangeEvent</tt> corresponding to the * specified old and new states and notifies all currently registered * listeners. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in. * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the RegistrationStateChangeEvent class, indicating the reason for * this state transition. * @param reason a String further explaining the reason code or null if * no such explanation is necessary. */ protected void fireRegistrationStateChanged(RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { RegistrationStateChangeEvent event = new RegistrationStateChangeEvent( this, oldState, newState, reasonCode, reason); logger.debug("Dispatching " + event + " to " + registrationStateListeners.size()+ " listeners."); Iterator listeners = null; synchronized (registrationStateListeners) { listeners = new ArrayList(registrationStateListeners).iterator(); } while (listeners.hasNext()) { RegistrationStateChangeListener listener = (RegistrationStateChangeListener) listeners.next(); listener.registrationStateChanged(event); } logger.trace("Done."); } /** * Returns the AccountID that uniquely identifies the account represented * by this instance of the ProtocolProviderService. * * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the operation set corresponding to the specified class or null * if this operation set is not supported by the provider implementation. * * @param opsetClass the <tt>Class</tt> of the operation set that we're * looking for. * @return returns an OperationSet of the specified <tt>Class</tt> if * the underlying implementation supports it or null otherwise. */ public OperationSet getOperationSet(Class opsetClass) { return (OperationSet) getSupportedOperationSets() .get(opsetClass.getName()); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). * * @return a String containing the short name of the protocol this * service is implementing (most often that would be a name in * ProtocolNames). */ public String getProtocolName() { return ProtocolNames.IRC; } /** * Returns the state of the registration of this protocol provider with * the corresponding registration service. * * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { return currentRegistrationState; } /** * Returns an array containing all operation sets supported by the * current implementation. * * @return a java.util.Map containing instance of all supported * operation sets mapped against their class names (e.g. * OperationSetPresence.class.getName()) . */ public Map getSupportedOperationSets() { //Copy the map so that the caller is not able to modify it. return (Map) supportedOperationSets.clone(); } /** * Indicates whether or not this provider is registered * * @return true if the provider is currently registered and false * otherwise. */ public boolean isRegistered() { return currentRegistrationState .equals(RegistrationState.REGISTERED); } /** * Starts the registration process. * * @param authority the security authority that will be used for * resolving any security challenges that may be returned during the * registration or at any moment while wer're registered. * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { Map accountProperties = getAccountID().getAccountProperties(); String serverAddress = (String) accountProperties .get(ProtocolProviderFactory.SERVER_ADDRESS); String serverPort = (String) accountProperties .get(ProtocolProviderFactory.SERVER_PORT); if(serverPort == null || serverPort.equals("")) { serverPort = "6667"; } //Verify whether a password has already been stored for this account String serverPassword = IrcActivator. getProtocolProviderFactory().loadPassword(getAccountID()); boolean autoNickChange = true; boolean passwordRequired = true; if(accountProperties .get(ProtocolProviderFactory.AUTO_CHANGE_USER_NAME) != null) { autoNickChange = new Boolean((String)accountProperties .get(ProtocolProviderFactory.AUTO_CHANGE_USER_NAME)) .booleanValue(); } if(accountProperties .get(ProtocolProviderFactory.PASSWORD_REQUIRED) != null) { passwordRequired = new Boolean((String)accountProperties .get(ProtocolProviderFactory.PASSWORD_REQUIRED)) .booleanValue(); } //if we don't - retrieve it from the user through the security authority if (serverPassword == null && passwordRequired) { //create a default credentials object UserCredentials credentials = new UserCredentials(); credentials.setUserName(getAccountID().getUserID()); //request a password from the user credentials = authority.obtainCredentials(ProtocolNames.IRC, credentials); //extract the password the user passed us. char[] pass = credentials.getPassword(); // the user didn't provide us a password (canceled the operation) if (pass == null) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } serverPassword = new String(pass); //if the user indicated that the password should be saved, we'll ask //the proto provider factory to store it for us. if (credentials.isPasswordPersistent()) { IrcActivator.getProtocolProviderFactory() .storePassword(getAccountID(), serverPassword); } } this.ircStack.connect( serverAddress, Integer.parseInt(serverPort), serverPassword, autoNickChange); } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for * shutdown/garbage collection. */ public void shutdown() { if(!isInitialized) { return; } logger.trace("Killing the Irc Protocol Provider."); if(isRegistered()) { try { //do the un-registration synchronized(this.initializationLock) { unregister(); this.ircStack.dispose(); ircStack = null; } } catch (OperationFailedException ex) { //we're shutting down so we need to silence the exception here logger.error( "Failed to properly unregister before shutting down. " + getAccountID() , ex); } } isInitialized = false; } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { RegistrationState oldState = currentRegistrationState; currentRegistrationState = RegistrationState.UNREGISTERED; if (ircStack.isConnected()) ircStack.disconnect(); fireRegistrationStateChanged( oldState , currentRegistrationState , RegistrationStateChangeEvent.REASON_USER_REQUEST , null); } /** * Returns the icon for this protocol. * * @return the icon for this protocol */ public ProtocolIcon getProtocolIcon() { return ircIcon; } /** * Returns the IRC stack implementation. * * @return the IRC stack implementation. */ public IrcStack getIrcStack() { return ircStack; } /** * Returns the current registration state of this protocol provider. * * @return the current registration state of this protocol provider */ protected RegistrationState getCurrentRegistrationState() { return currentRegistrationState; } /** * Sets the current registration state of this protocol provider. * * @param regState the new registration state to set */ protected void setCurrentRegistrationState( RegistrationState regState) { this.currentRegistrationState = regState; } }
src/net/java/sip/communicator/impl/protocol/irc/ProtocolProviderServiceIrcImpl.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.irc; import java.util.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * An IRC implementation of the ProtocolProviderService. * * @author Loic Kempf * @author Stephane Remy */ public class ProtocolProviderServiceIrcImpl implements ProtocolProviderService { private static final Logger logger = Logger.getLogger(ProtocolProviderServiceIrcImpl.class); /** * The irc server. */ private IrcStack ircStack; /** * The id of the account that this protocol provider represents. */ private AccountID accountID = null; /** * We use this to lock access to initialization. */ private Object initializationLock = new Object(); /** * The hashtable with the operation sets that we support locally. */ private Hashtable supportedOperationSets = new Hashtable(); /** * A list of listeners interested in changes in our registration state. */ private Vector registrationStateListeners = new Vector(); /** * Indicates whether or not the provider is initialized and ready for use. */ private boolean isInitialized = false; /** * The icon corresponding to the irc protocol. */ private ProtocolIconIrcImpl ircIcon = new ProtocolIconIrcImpl(); /** * The default constructor for the IRC protocol provider. */ public ProtocolProviderServiceIrcImpl() { logger.trace("Creating a irc provider."); } /** * Keeps our current registration state. */ private RegistrationState currentRegistrationState = RegistrationState.UNREGISTERED; /** * Initializes the service implementation, and puts it in a sate where it * could operate with other services. It is strongly recommended that * properties in this Map be mapped to property names as specified by * <tt>AccountProperties</tt>. * * @param userID the user id of the IRC account we're currently * initializing * @param accountID the identifier of the account that this protocol * provider represents. * * @see net.java.sip.communicator.service.protocol.AccountID */ protected void initialize(String userID, AccountID accountID) { synchronized(initializationLock) { this.accountID = accountID; //Initialize the multi user chat support OperationSetMultiUserChatIrcImpl multiUserChat = new OperationSetMultiUserChatIrcImpl(this); supportedOperationSets.put( OperationSetMultiUserChat.class.getName(), multiUserChat); this.ircStack = new IrcStack( this, getAccountID().getUserID(), getAccountID().getUserID(), "SIP Communicator 1.0", ""); isInitialized = true; } } /** * Registers the specified listener with this provider so that it would * receive notifications on changes of its state or other properties such * as its local address and display name. * * @param listener the listener to register. */ public void addRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationStateListeners) { if (!registrationStateListeners.contains(listener)) registrationStateListeners.add(listener); } } /** * Removes the specified registration listener so that it won't receive * further notifications when our registration state changes. * * @param listener the listener to remove. */ public void removeRegistrationStateChangeListener( RegistrationStateChangeListener listener) { synchronized(registrationStateListeners) { registrationStateListeners.remove(listener); } } /** * Creates a <tt>RegistrationStateChangeEvent</tt> corresponding to the * specified old and new states and notifies all currently registered * listeners. * * @param oldState the state that the provider had before the change * occurred * @param newState the state that the provider is currently in. * @param reasonCode a value corresponding to one of the REASON_XXX fields * of the RegistrationStateChangeEvent class, indicating the reason for * this state transition. * @param reason a String further explaining the reason code or null if * no such explanation is necessary. */ protected void fireRegistrationStateChanged(RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { RegistrationStateChangeEvent event = new RegistrationStateChangeEvent( this, oldState, newState, reasonCode, reason); logger.debug("Dispatching " + event + " to " + registrationStateListeners.size()+ " listeners."); Iterator listeners = null; synchronized (registrationStateListeners) { listeners = new ArrayList(registrationStateListeners).iterator(); } while (listeners.hasNext()) { RegistrationStateChangeListener listener = (RegistrationStateChangeListener) listeners.next(); listener.registrationStateChanged(event); } logger.trace("Done."); } /** * Returns the AccountID that uniquely identifies the account represented * by this instance of the ProtocolProviderService. * * @return the id of the account represented by this provider. */ public AccountID getAccountID() { return accountID; } /** * Returns the operation set corresponding to the specified class or null * if this operation set is not supported by the provider implementation. * * @param opsetClass the <tt>Class</tt> of the operation set that we're * looking for. * @return returns an OperationSet of the specified <tt>Class</tt> if * the underlying implementation supports it or null otherwise. */ public OperationSet getOperationSet(Class opsetClass) { return (OperationSet) getSupportedOperationSets() .get(opsetClass.getName()); } /** * Returns the short name of the protocol that the implementation of this * provider is based upon (like SIP, Jabber, ICQ/AIM, or others for * example). * * @return a String containing the short name of the protocol this * service is implementing (most often that would be a name in * ProtocolNames). */ public String getProtocolName() { return ProtocolNames.IRC; } /** * Returns the state of the registration of this protocol provider with * the corresponding registration service. * * @return ProviderRegistrationState */ public RegistrationState getRegistrationState() { return currentRegistrationState; } /** * Returns an array containing all operation sets supported by the * current implementation. * * @return a java.util.Map containing instance of all supported * operation sets mapped against their class names (e.g. * OperationSetPresence.class.getName()) . */ public Map getSupportedOperationSets() { //Copy the map so that the caller is not able to modify it. return (Map) supportedOperationSets.clone(); } /** * Indicates whether or not this provider is registered * * @return true if the provider is currently registered and false * otherwise. */ public boolean isRegistered() { return currentRegistrationState .equals(RegistrationState.REGISTERED); } /** * Starts the registration process. * * @param authority the security authority that will be used for * resolving any security challenges that may be returned during the * registration or at any moment while wer're registered. * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void register(SecurityAuthority authority) throws OperationFailedException { Map accountProperties = getAccountID().getAccountProperties(); String serverAddress = (String) accountProperties .get(ProtocolProviderFactory.SERVER_ADDRESS); String serverPort = (String) accountProperties .get(ProtocolProviderFactory.SERVER_PORT); if(serverPort == null || serverPort.equals("")) { serverPort = "6667"; } //Verify whether a password has already been stored for this account String serverPassword = IrcActivator. getProtocolProviderFactory().loadPassword(getAccountID()); boolean autoNickChange = true; boolean passwordRequired = true; if(accountProperties .get(ProtocolProviderFactory.AUTO_CHANGE_USER_NAME) != null) { autoNickChange = new Boolean((String)accountProperties .get(ProtocolProviderFactory.AUTO_CHANGE_USER_NAME)) .booleanValue(); } if(accountProperties .get(ProtocolProviderFactory.PASSWORD_REQUIRED) != null) { passwordRequired = new Boolean((String)accountProperties .get(ProtocolProviderFactory.PASSWORD_REQUIRED)) .booleanValue(); } //if we don't - retrieve it from the user through the security authority if (serverPassword == null && passwordRequired) { //create a default credentials object UserCredentials credentials = new UserCredentials(); credentials.setUserName(getAccountID().getUserID()); //request a password from the user credentials = authority.obtainCredentials(ProtocolNames.IRC, credentials); //extract the password the user passed us. char[] pass = credentials.getPassword(); // the user didn't provide us a password (canceled the operation) if (pass == null) { fireRegistrationStateChanged( getRegistrationState(), RegistrationState.UNREGISTERED, RegistrationStateChangeEvent.REASON_USER_REQUEST, ""); return; } serverPassword = new String(pass); //if the user indicated that the password should be saved, we'll ask //the proto provider factory to store it for us. if (credentials.isPasswordPersistent()) { IrcActivator.getProtocolProviderFactory() .storePassword(getAccountID(), serverPassword); } } this.ircStack.connect( serverAddress, Integer.parseInt(serverPort), serverPassword, autoNickChange); } /** * Makes the service implementation close all open sockets and release * any resources that it might have taken and prepare for * shutdown/garbage collection. */ public void shutdown() { if(!isInitialized) { return; } logger.trace("Killing the Irc Protocol Provider."); if(isRegistered()) { try { //do the un-registration synchronized(this.initializationLock) { unregister(); this.ircStack.dispose(); ircStack = null; } } catch (OperationFailedException ex) { //we're shutting down so we need to silence the exception here logger.error( "Failed to properly unregister before shutting down. " + getAccountID() , ex); } } isInitialized = false; } /** * Ends the registration of this protocol provider with the current * registration service. * * @throws OperationFailedException with the corresponding code it the * registration fails for some reason (e.g. a networking error or an * implementation problem). */ public void unregister() throws OperationFailedException { RegistrationState oldState = currentRegistrationState; currentRegistrationState = RegistrationState.UNREGISTERED; if (ircStack.isConnected()) ircStack.disconnect(); fireRegistrationStateChanged( oldState , currentRegistrationState , RegistrationStateChangeEvent.REASON_USER_REQUEST , null); } /** * Returns the icon for this protocol. * * @return the icon for this protocol */ public ProtocolIcon getProtocolIcon() { return ircIcon; } /** * Returns the IRC stack implementation. * * @return the IRC stack implementation. */ public IrcStack getIrcStack() { return ircStack; } /** * Returns the current registration state of this protocol provider. * * @return the current registration state of this protocol provider */ protected RegistrationState getCurrentRegistrationState() { return currentRegistrationState; } /** * Sets the current registration state of this protocol provider. * * @param currentRegistrationState the new registration state to set */ protected void setCurrentRegistrationState( RegistrationState regState) { this.currentRegistrationState = regState; } }
fix cruisecontrol reported javadoc warning
src/net/java/sip/communicator/impl/protocol/irc/ProtocolProviderServiceIrcImpl.java
fix cruisecontrol reported javadoc warning
Java
apache-2.0
abfbb3e58a44ec7e65430ce6aa040c711e529a28
0
jbossas/jboss-threads
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.threads; import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadLocalRandom; import org.wildfly.common.Assert; /** * A simple load-balancing executor. If no delegate executors are defined, then tasks are rejected. Executors are * chosen in a random fashion. */ public class BalancingExecutor implements Executor { private static final Executor[] NO_EXECUTORS = new Executor[0]; private volatile Executor[] executors = NO_EXECUTORS; private static final AtomicArray<BalancingExecutor, Executor> executorsUpdater = AtomicArray.create(newUpdater(BalancingExecutor.class, Executor[].class, "executors"), NO_EXECUTORS); /** * Construct a new instance. */ public BalancingExecutor() { } /** * Construct a new instance. * * @param executors the initial list of executors to delegate to */ public BalancingExecutor(Executor... executors) { if (executors != null && executors.length > 0) { final Executor[] clone = executors.clone(); for (int i = 0; i < clone.length; i++) { Assert.checkNotNullArrayParam("executors", i, clone[i]); } executorsUpdater.set(this, clone); } else { executorsUpdater.clear(this); } } /** * Execute a task. * * @param command the task to execute * @throws RejectedExecutionException if no executors are available to run the task */ public void execute(final Runnable command) throws RejectedExecutionException { final Executor[] executors = this.executors; final int len = executors.length; if (len == 0) { throw new RejectedExecutionException("No executors available to run task"); } executors[ThreadLocalRandom.current().nextInt(len)].execute(command); } /** * Clear out all delegate executors at once. Tasks will be rejected until another delegate executor is added. */ public void clear() { executorsUpdater.clear(this); } /** * Add a delegate executor. * * @param executor the executor to add */ public void addExecutor(final Executor executor) { Assert.checkNotNullParam("executor", executor); synchronized (this) { executorsUpdater.add(this, executor); } } /** * Remove a delegate executor. * * @param executor the executor to remove */ public void removeExecutor(final Executor executor) { if (executor == null) { return; } synchronized (this) { executorsUpdater.remove(this, executor, true); } } }
src/main/java/org/jboss/threads/BalancingExecutor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.threads; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater; /** * A simple load-balancing executor. If no delegate executors are defined, then tasks are rejected. Executors are * chosen in a round-robin fashion. */ public class BalancingExecutor implements Executor { private static final Executor[] NO_EXECUTORS = new Executor[0]; private volatile Executor[] executors = null; private final AtomicInteger seq = new AtomicInteger(); private final Lock writeLock = new ReentrantLock(); private static final AtomicArray<BalancingExecutor, Executor> executorsUpdater = AtomicArray.create(newUpdater(BalancingExecutor.class, Executor[].class, "executors"), NO_EXECUTORS); /** * Construct a new instance. */ public BalancingExecutor() { executorsUpdater.clear(this); } /** * Construct a new instance. * * @param executors the initial list of executors to delegate to */ public BalancingExecutor(Executor... executors) { if (executors != null && executors.length > 0) { final Executor[] clone = executors.clone(); for (int i = 0; i < clone.length; i++) { if (clone[i] == null) { throw new NullPointerException("executor at index " + i + " is null"); } } executorsUpdater.set(this, clone); } else { executorsUpdater.clear(this); } } /** * Execute a task. * * @param command the task to execute * @throws RejectedExecutionException if no executors are available to run the task */ public void execute(final Runnable command) throws RejectedExecutionException { final Executor[] executors = this.executors; final int len = executors.length; if (len == 0) { throw new RejectedExecutionException("No executors available to run task"); } executors[seq.getAndIncrement() % len].execute(command); } /** * Clear out all delegate executors at once. Tasks will be rejected until another delegate executor is added. */ public void clear() { executorsUpdater.clear(this); } /** * Add a delegate executor. * * @param executor the executor to add */ public void addExecutor(final Executor executor) { if (executor == null) { throw new NullPointerException("executor is null"); } final Lock lock = writeLock; lock.lock(); try { executorsUpdater.add(this, executor); } finally { lock.unlock(); } } /** * Remove a delegate executor. * * @param executor the executor to remove */ public void removeExecutor(final Executor executor) { if (executor == null) { return; } final Lock lock = writeLock; lock.lock(); try { executorsUpdater.remove(this, executor, true); } finally { lock.unlock(); } } }
[JBTHR-43] Simplify and update BalancingExecutor
src/main/java/org/jboss/threads/BalancingExecutor.java
[JBTHR-43] Simplify and update BalancingExecutor
Java
apache-2.0
31dac77e031bf1c0ba2c237afe26f89e43a23453
0
gianpaj/mongo-java-driver,kevinsawicki/mongo-java-driver,PSCGroup/mongo-java-driver,wanggc/mongo-java-driver,kevinsawicki/mongo-java-driver,jyemin/mongo-java-driver,davydotcom/mongo-java-driver,rozza/mongo-java-driver,jsonking/mongo-java-driver,wanggc/mongo-java-driver,kay-kim/mongo-java-driver,kevinsawicki/mongo-java-driver,rozza/mongo-java-driver,eltimn/mongo-java-driver,eltimn/mongo-java-driver,eltimn/mongo-java-driver,davydotcom/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver
// MongoException.java /** * Copyright (C) 2008 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb; public class MongoException extends RuntimeException { public MongoException( String msg ){ super( msg ); } public MongoException( String msg , Throwable t ){ super( msg , _massage( t ) ); } static Throwable _massage( Throwable t ){ if ( t instanceof Network ) return ((Network)t)._ioe; return t; } public static class Network extends MongoException { Network( String msg , java.io.IOException ioe ){ super( msg , ioe ); _ioe = ioe; } Network( java.io.IOException ioe ){ super( ioe.toString() , ioe ); _ioe = ioe; } final java.io.IOException _ioe; } public static class DuplicateKey extends MongoException { DuplicateKey( String msg ){ super( msg ); } } }
src/main/com/mongodb/MongoException.java
// MongoException.java /** * Copyright (C) 2008 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb; public class MongoException extends RuntimeException { public MongoException( String msg ){ super( msg ); } public MongoException( String msg , Throwable t ){ super( msg , _massage( t ) ); } static Throwable _massage( Throwable t ){ if ( t instanceof Network ) return ((Network)t)._ioe; return t; } static class Network extends MongoException { Network( String msg , java.io.IOException ioe ){ super( msg , ioe ); _ioe = ioe; } Network( java.io.IOException ioe ){ super( ioe.toString() , ioe ); _ioe = ioe; } final java.io.IOException _ioe; } static class DuplicateKey extends MongoException { DuplicateKey( String msg ){ super( msg ); } } }
made some innert classes public
src/main/com/mongodb/MongoException.java
made some innert classes public
Java
apache-2.0
72223c27b998e7a579cc41986f3315e3f493f521
0
anchela/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.backup; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.jackrabbit.oak.plugins.segment.Journal; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeBuilder; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeState; import org.apache.jackrabbit.oak.plugins.segment.file.FileStore; import org.apache.jackrabbit.oak.spi.state.ApplyDiff; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileStoreBackup { private static final Logger log = LoggerFactory .getLogger(FileStoreBackup.class); private static final long DEFAULT_LIFETIME = TimeUnit.HOURS.toMillis(1); static int MAX_FILE_SIZE = 256; public static void backup(NodeStore store, File destination) throws IOException { long s = System.currentTimeMillis(); // 1. create a new checkpoint with the current state String checkpoint = store.checkpoint(DEFAULT_LIFETIME); NodeState current = store.retrieve(checkpoint); if (current == null) { // unable to retrieve the checkpoint; use root state instead current = store.getRoot(); } // 2. init filestore FileStore backup = new FileStore(destination, MAX_FILE_SIZE, false); try { Journal journal = backup.getJournal("root"); SegmentNodeState state = new SegmentNodeState( backup.getWriter().getDummySegment(), journal.getHead()); SegmentNodeBuilder builder = state.builder(); String beforeCheckpoint = state.getString("checkpoint"); if (beforeCheckpoint == null) { // 3.1 no stored checkpoint, so do the initial full backup builder.setChildNode("root", current); } else { // 3.2 try to retrieve the previously backed up checkpoint NodeState before = store.retrieve(beforeCheckpoint); if (before == null) { // the previous checkpoint is no longer available, // so use the backed up state as the basis of the // incremental backup diff before = state.getChildNode("root"); } current.compareAgainstBaseState( before, new ApplyDiff(builder.child("root"))); } builder.setProperty("checkpoint", checkpoint); // 4. commit the backup journal.setHead( state.getRecordId(), builder.getNodeState().getRecordId()); } finally { backup.close(); } log.debug("Backup finished in {} ms.", System.currentTimeMillis() - s); } }
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/backup/FileStoreBackup.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.plugins.backup; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.jackrabbit.oak.plugins.segment.Journal; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeBuilder; import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeState; import org.apache.jackrabbit.oak.plugins.segment.file.FileStore; import org.apache.jackrabbit.oak.spi.state.ApplyDiff; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileStoreBackup { private static final Logger log = LoggerFactory .getLogger(FileStoreBackup.class); private static final long DEFAULT_LIFETIME = TimeUnit.HOURS.toMillis(1); static int MAX_FILE_SIZE = 256; public static void backup(NodeStore store, File destination) throws IOException { long s = System.currentTimeMillis(); // 1. create a new checkpoint with the current state String checkpoint = store.checkpoint(DEFAULT_LIFETIME); NodeState current = store.retrieve(checkpoint); if (current == null) { // unable to retrieve the checkpoint; use root state instead current = store.getRoot(); } // 2. init filestore FileStore backup = new FileStore(destination, MAX_FILE_SIZE, false); try { Journal journal = backup.getJournal("root"); SegmentNodeState state = new SegmentNodeState( backup.getWriter().getDummySegment(), journal.getHead()); SegmentNodeBuilder builder = state.builder(); String beforeCheckpoint = state.getString("checkpoint"); if (beforeCheckpoint == null) { // 3.1 no stored checkpoint, so do the initial full backup builder.setChildNode("root", current); } else { // 3.2 try to retrieve the previously backed up checkpoint NodeState before = store.retrieve(beforeCheckpoint); if (before == null) { // the previous checkpoint is no longer available, // so use the backed up state as the basis of the // incremental backup diff before = state.getChildNode("root"); } current.compareAgainstBaseState( before, new ApplyDiff(builder.child("root"))); } builder.setProperty("checkpoint", checkpoint); // 4. commit the backup journal.setHead( state.getRecordId(), builder.getNodeState().getRecordId()); } finally { backup.close(); } log.debug("Backup done in {} ms.", System.currentTimeMillis() - s); } }
OAK-1464 FileStoreBackup NPE in retrieving old state - re-wording debug logs git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1571251 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/backup/FileStoreBackup.java
OAK-1464 FileStoreBackup NPE in retrieving old state - re-wording debug logs
Java
apache-2.0
ed75736bb217c51319c89ea6a25c2e3a78cec512
0
ScottMansfield/exo
/** * Copyright 2015 Scott Mansfield * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.widowcrawler.exo.model; import org.joda.time.DateTime; import java.net.URL; /** * @author Scott Mansfield * * url * loc - URI (required) * lastmod - Date/Time * changefreq - ChangeFreq * priority - Double * isMobile - has mobile content */ public class SitemapURL { private URL location; private DateTime lastModified; private ChangeFreq changeFrequency; private Double priority; private Boolean isMobileContent; public static class Builder { private SitemapURL building; public Builder() { this.building = new SitemapURL(); } public Builder withLocation(URL location) { building.location = location; return this; } public Builder withLastModified(DateTime lastModified) { building.lastModified = lastModified; return this; } public Builder withChangeFrequency(ChangeFreq changeFrequency) { building.changeFrequency = changeFrequency; return this; } public Builder withPriority(Double priority) { building.priority = priority; return this; } public Builder withIsMobileContent(Boolean isMobileContent) { building.isMobileContent = isMobileContent; return this; } public SitemapURL build() { return building; } } private SitemapURL() { } @Override public int hashCode() { int hash = 1; if (location != null) { hash *= 31 * location.hashCode(); } if (lastModified != null) { hash *= 23 * lastModified.hashCode(); } if (changeFrequency != null) { hash *= 67 * changeFrequency.hashCode(); } if (priority != null) { hash *= 47 * priority.hashCode(); } if (isMobileContent != null) { hash *= 13 * isMobileContent.hashCode(); } return hash; } @Override public boolean equals(Object obj) { if (!(obj instanceof SitemapURL)) { return false; } SitemapURL other = (SitemapURL) obj; if ((this.location != null && !this.location.equals(other.getLocation())) || this.location == null && other.getLocation() != null) { return false; } if ((this.lastModified != null && !this.lastModified.equals(other.getLastModified())) || this.lastModified == null && other.getLastModified() != null) { return false; } if ((this.changeFrequency != null && !this.changeFrequency.equals(other.getChangeFrequency())) || (this.changeFrequency == null && other.getChangeFrequency() != null)) { return false; } if ((this.priority != null && !this.priority.equals(other.getPriority())) || (this.priority == null && other.getPriority() != null)) { return false; } if ((this.isMobileContent != null && !this.isMobileContent.equals(other.isMobileContent())) || (this.isMobileContent == null && other.isMobileContent() != null)) { return false; } return true; } @Override public String toString() { return "Location: " + this.location + "\nLastModified: " + this.lastModified + "\nChangeFrequency: " + this.changeFrequency + "\nPriority: " + this.priority + "\nIsMobileContent: " + this.isMobileContent; } public URL getLocation() { return location; } public DateTime getLastModified() { return lastModified; } public ChangeFreq getChangeFrequency() { return changeFrequency; } public Double getPriority() { return priority; } public Boolean isMobileContent() { return isMobileContent; } }
src/main/java/com/widowcrawler/exo/model/SitemapURL.java
/** * Copyright 2015 Scott Mansfield * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.widowcrawler.exo.model; import org.joda.time.DateTime; import java.net.URL; /** * @author Scott Mansfield * * url * loc - URI (required) * lastmod - Date/Time * changefreq - ChangeFreq * priority - Double */ public class SitemapURL { private URL location; private DateTime lastModified; private ChangeFreq changeFrequency; private Double priority; private Boolean isMobileContent; public static class Builder { private SitemapURL building; public Builder() { this.building = new SitemapURL(); } public Builder withLocation(URL location) { building.location = location; return this; } public Builder withLastModified(DateTime lastModified) { building.lastModified = lastModified; return this; } public Builder withChangeFrequency(ChangeFreq changeFrequency) { building.changeFrequency = changeFrequency; return this; } public Builder withPriority(Double priority) { building.priority = priority; return this; } public Builder withIsMobileContent(Boolean isMobileContent) { building.isMobileContent = isMobileContent; return this; } public SitemapURL build() { return building; } } private SitemapURL() { } public URL getLocation() { return location; } public DateTime getLastModified() { return lastModified; } public ChangeFreq getChangeFrequency() { return changeFrequency; } public Double getPriority() { return priority; } public Boolean isMobileContent() { return isMobileContent; } }
Adding equals(), hashCode(), and toString() implementations on SitemapURL
src/main/java/com/widowcrawler/exo/model/SitemapURL.java
Adding equals(), hashCode(), and toString() implementations on SitemapURL
Java
apache-2.0
7c50372a52bfba8cb835f0bc0e83f5c56f69a641
0
drewcassidy/APCS-group-project
package NotDoom; import NotDoom.Map.Map; import NotDoom.Renderer.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import javax.swing.*; public class GUI{ private JFrame frame; private JPanel mainPanel, screen, hotBar, ammoPanel, healthPanel; private Map m; private JLabel ammo, health, armor; private MainScreen image, image2, main, blank; private int WIDTH = 800, HEIGHT = 600; private boolean running, tab; private int tick, tickTimer; private int key; private KeyListener keys; private GridBagConstraints c; private DoomRenderer renderer; private BufferedImage buffer; public GUI(Map m){ this.m = m; c = new GridBagConstraints(); frame = new JFrame(); frame.setSize(WIDTH, HEIGHT); frame.setTitle("DOOM"); buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); main = new MainScreen(buffer); renderer = new DoomRenderer(buffer); image = new MainScreen("nb.png"); image2 = new MainScreen("nb.png"); blank = new MainScreen("blank.png"); ammo = new JLabel("0"); health = new JLabel("100%"); armor = new JLabel("0%"); keys = new Key(); healthPanel = new JPanel(); //healthPanel.add(health); healthPanel.add(image); ammoPanel = new JPanel(); //ammoPanel.add(ammo); ammoPanel.add(image2); //hotBar = new JPanel(); //hotBar.setLayout(new GridLayout(1,2)); //hotBar.add(healthPanel); //hotBar.add(ammoPanel); screen = new JPanel(); screen.add(main); mainPanel = new JPanel(); mainPanel.setLayout(new GridBagLayout()); c.gridx = 0; c.gridy = 0; mainPanel.add(screen, c); //mainPanel.add(hotBar, c); //panel.add(image); mainPanel.addKeyListener(keys); mainPanel.setFocusable(true); frame.add(mainPanel); tickTimer = 60; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(false); run(); } private class Key implements KeyListener{ @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { key = e.getKeyCode(); if (key == KeyEvent.VK_U){ blank.tabed(true); } System.out.println("typed"); } @Override public void keyReleased(KeyEvent e) { key = -1; tab = false; blank.tabed(false); } } public void tick(){ tick++; if (tick > tickTimer){ //ammo.setLocation(20, 500); tick = 0; System.out.println("Word"); //label.setText(key+""); } } public void paint(Graphics g){ Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle ( 50, 20, 100, 75); g2.draw(box); } public void render(){ mainPanel.removeAll(); if (tab == true){ mainPanel.add(blank); } else { //healthPanel.add(health); healthPanel.add(image); //ammoPanel.add(ammo); ammoPanel.add(image2); //hotBar.setLayout(new GridLayout(1,2)); //hotBar.add(healthPanel); //hotBar.add(ammoPanel); screen.add(main); mainPanel.setLayout(new GridBagLayout()); c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; //c.gridheight = 2; c.ipady = HEIGHT-100; c.ipadx = WIDTH; mainPanel.add(screen, c); //c.fill = GridBagConstraints.VERTICAL; c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.ipady = 300; c.ipadx = WIDTH/2; c.anchor = GridBagConstraints.FIRST_LINE_START; mainPanel.add(healthPanel,c); //c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.anchor = GridBagConstraints.FIRST_LINE_START; mainPanel.add(ammoPanel,c); } mainPanel.invalidate(); mainPanel.validate(); mainPanel.repaint(); } public void run(){ int fps = 60; double timePerTick = 1000000000 / fps; double delta = 0; long now; long lastTime = System.nanoTime(); //display fps (2 lines) long timer = 0; int ticks = 0; running = true; //main game loop while (running == true){ now = System.nanoTime(); delta += (now - lastTime) / timePerTick; //display fps (1 line) timer += now - lastTime; lastTime = now; if (delta >= 1){ tick(); render(); //display fps(1 line) ticks++; delta = 0; } //display fps if (timer >= 1000000000){ System.out.println("Ticks and Frames " + ticks); ticks = 0; timer = 0; } } //create YOU LOST GUI JOptionPane.showMessageDialog(null, "YOU LOST"); int again = JOptionPane.showConfirmDialog(null, "Do you want to play again?"); if (again==JOptionPane.YES_OPTION){ running =true; //reset variables tickTimer=60; run(); } } }
Source/src/NotDoom/GUI.java
package NotDoom; import NotDoom.Map.Map; import NotDoom.Renderer.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import javax.swing.*; public class GUI{ private JFrame frame; private JPanel mainPanel, screen, hotBar, ammoPanel, healthPanel; private Map m; private JLabel ammo, health, armor; private MainScreen image, image2, main, blank; private int WIDTH = 800, HEIGHT = 600; private boolean running, tab; private int tick, tickTimer; private int key; private KeyListener keys; private GridBagConstraints c; private DoomRenderer renderer; private BufferedImage buffer; public GUI(Map m){ this.m = m; c = new GridBagConstraints(); frame = new JFrame(); frame.setSize(WIDTH, HEIGHT); frame.setTitle("DOOM"); buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); main = new MainScreen(buffer); renderer = new DoomRenderer(buffer); image = new MainScreen("nb.png"); image2 = new MainScreen("nb.png"); blank = new MainScreen("blank.png"); ammo = new JLabel("0"); health = new JLabel("100%"); armor = new JLabel("0%"); keys = new Key(); healthPanel = new JPanel(); //healthPanel.add(health); healthPanel.add(image); ammoPanel = new JPanel(); //ammoPanel.add(ammo); ammoPanel.add(image2); //hotBar = new JPanel(); //hotBar.setLayout(new GridLayout(1,2)); //hotBar.add(healthPanel); //hotBar.add(ammoPanel); screen = new JPanel(); screen.add(main); mainPanel = new JPanel(); mainPanel.setLayout(new GridBagLayout()); c.gridx = 0; c.gridy = 0; mainPanel.add(screen, c); //mainPanel.add(hotBar, c); //panel.add(image); mainPanel.addKeyListener(keys); mainPanel.setFocusable(true); frame.add(mainPanel); tickTimer = 60; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(false); run(); } private class Key implements KeyListener{ @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { key = e.getKeyCode(); if (key == KeyEvent.VK_U){ blank.tabed(true); } System.out.println("typed"); } @Override public void keyReleased(KeyEvent e) { key = -1; tab = false; blank.tabed(false); } } public void tick(){ tick++; if (tick > tickTimer){ //ammo.setLocation(20, 500); tick = 0; System.out.println("Word"); //label.setText(key+""); } } public void paint(Graphics g){ Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle ( 50, 20, 100, 75); g2.draw(box); } public void render(){ mainPanel.removeAll(); if (tab == true){ mainPanel.add(blank); } else { //healthPanel.add(health); healthPanel.add(image); //ammoPanel.add(ammo); ammoPanel.add(image2); ; //hotBar.setLayout(new GridLayout(1,2)); //hotBar.add(healthPanel); //hotBar.add(ammoPanel); screen.add(main); mainPanel.setLayout(new GridBagLayout()); c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; //c.gridheight = 2; c.ipady = HEIGHT-100; c.ipadx = WIDTH; mainPanel.add(screen, c); //c.fill = GridBagConstraints.VERTICAL; c.gridx = 0; c.gridy = 1; c.gridwidth = 1; c.ipady = 300; c.ipadx = WIDTH/2; c.anchor = GridBagConstraints.FIRST_LINE_START; mainPanel.add(healthPanel,c); //c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.anchor = GridBagConstraints.FIRST_LINE_START; mainPanel.add(ammoPanel,c); } mainPanel.invalidate(); mainPanel.validate(); mainPanel.repaint(); } public void run(){ int fps = 60; double timePerTick = 1000000000 / fps; double delta = 0; long now; long lastTime = System.nanoTime(); //display fps (2 lines) long timer = 0; int ticks = 0; running = true; //main game loop while (running == true){ now = System.nanoTime(); delta += (now - lastTime) / timePerTick; //display fps (1 line) timer += now - lastTime; lastTime = now; if (delta >= 1){ tick(); render(); //display fps(1 line) ticks++; delta = 0; } //display fps if (timer >= 1000000000){ System.out.println("Ticks and Frames " + ticks); ticks = 0; timer = 0; } } //create YOU LOST GUI JOptionPane.showMessageDialog(null, "YOU LOST"); int again = JOptionPane.showConfirmDialog(null, "Do you want to play again?"); if (again==JOptionPane.YES_OPTION){ running =true; //reset variables tickTimer=60; run(); } } }
Too much whitespace :O
Source/src/NotDoom/GUI.java
Too much whitespace :O
Java
apache-2.0
d90f28738213dc0800b1250899a1078dae7d802e
0
MaxRau/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,Tycheo/coffeemud
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2005-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings("rawtypes") public class Addictions extends StdAbility { @Override public String ID() { return "Addictions"; } private final static String localizedName = CMLib.lang().L("Addictions"); @Override public String name() { return localizedName; } private long lastFix=System.currentTimeMillis(); @Override public String displayText(){ return craving()?"(Addiction to "+text()+")":"";} @Override protected int canAffectCode(){return CAN_MOBS;} @Override protected int canTargetCode(){return 0;} @Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;} @Override public int classificationCode(){return Ability.ACODE_PROPERTY;} @Override public boolean isAutoInvoked(){return true;} @Override public boolean canBeUninvoked(){return false;} private Item puffCredit=null; private final static long CRAVE_TIME=TimeManager.MILI_HOUR; private final static long WITHDRAW_TIME=TimeManager.MILI_DAY; private boolean craving(){return (System.currentTimeMillis()-lastFix)>CRAVE_TIME;} @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((craving()) &&(CMLib.dice().rollPercentage()<=((System.currentTimeMillis()-lastFix)/TimeManager.MILI_HOUR)) &&(ticking instanceof MOB)) { if((System.currentTimeMillis()-lastFix)>WITHDRAW_TIME) { ((MOB)ticking).tell(L("You've managed to kick your addiction.")); canBeUninvoked=true; unInvoke(); ((MOB)ticking).delEffect(this); return false; } if((puffCredit!=null) &&(puffCredit.amDestroyed() ||puffCredit.amWearingAt(Wearable.IN_INVENTORY) ||puffCredit.owner()!=(MOB)affected)) puffCredit=null; switch(CMLib.dice().roll(1,7,0)) { case 1: ((MOB)ticking).tell(L("Man, you could sure use some @x1.",text())); break; case 2: ((MOB)ticking).tell(L("Wouldn't some @x1 be great right about now?",text())); break; case 3: ((MOB)ticking).tell(L("You are seriously craving @x1.",text())); break; case 4: ((MOB)ticking).tell(L("There's got to be some @x1 around here somewhere.",text())); break; case 5: ((MOB)ticking).tell(L("You REALLY want some @x1.",text())); break; case 6: ((MOB)ticking).tell(L("You NEED some @x1, NOW!",text())); break; case 7: ((MOB)ticking).tell(L("Some @x1 would be lovely.",text())); break; } } return true; } @Override public boolean okMessage(Environmental host, CMMsg msg) { if(affected instanceof MOB) { if((msg.source()==affected) &&(msg.targetMinor()==CMMsg.TYP_WEAR) &&(msg.target() instanceof Light) &&(msg.target() instanceof Container) &&(CMath.bset(((Item)msg.target()).rawProperLocationBitmap(),Wearable.WORN_MOUTH))) { final List<Item> contents=((Container)msg.target()).getContents(); if(contents.size()>0) { final Environmental content=contents.get(0); if(CMLib.english().containsString(content.Name(),text())) puffCredit=(Item)msg.target(); } } } return true; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if(affected instanceof MOB) { if(msg.source()==affected) { if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.target() instanceof Food)||(msg.target() instanceof Drink)) &&(msg.target() instanceof Item) &&(CMLib.english().containsString(msg.target().Name(),text()))) lastFix=System.currentTimeMillis(); if((msg.amISource((MOB)affected)) &&(msg.targetMinor()==CMMsg.TYP_HANDS) &&(msg.target() instanceof Light) &&(msg.tool() instanceof Light) &&(msg.target()==msg.tool()) &&(((Light)msg.target()).amWearingAt(Wearable.WORN_MOUTH)) &&(((Light)msg.target()).isLit()) &&((puffCredit!=null)||CMLib.english().containsString(msg.target().Name(),text()))) lastFix=System.currentTimeMillis(); } } super.executeMsg(myHost,msg); } @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { final Physical target=givenTarget; if(target==null) return false; if(target.fetchEffect(ID())!=null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { String addiction=target.Name().toUpperCase(); if(addiction.toUpperCase().startsWith("A POUND OF ")) addiction=addiction.substring(11); if(addiction.toUpperCase().startsWith("A ")) addiction=addiction.substring(2); if(addiction.toUpperCase().startsWith("AN ")) addiction=addiction.substring(3); if(addiction.toUpperCase().startsWith("SOME ")) addiction=addiction.substring(5); final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_OK_VISUAL,""); if(mob.location()!=null) { if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final Ability A=(Ability)copyOf(); A.setMiscText(addiction.trim()); mob.addNonUninvokableEffect(A); } } else { final Ability A=(Ability)copyOf(); A.setMiscText(addiction.trim()); mob.addNonUninvokableEffect(A); } } return success; } }
com/planet_ink/coffee_mud/Abilities/Misc/Addictions.java
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2005-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings("rawtypes") public class Addictions extends StdAbility { @Override public String ID() { return "Addictions"; } private final static String localizedName = CMLib.lang().L("Addictions"); @Override public String name() { return localizedName; } private long lastFix=System.currentTimeMillis(); @Override public String displayText(){ return craving()?"(Addiction to "+text()+")":"";} @Override protected int canAffectCode(){return CAN_MOBS;} @Override protected int canTargetCode(){return 0;} @Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;} @Override public int classificationCode(){return Ability.ACODE_PROPERTY;} @Override public boolean isAutoInvoked(){return true;} @Override public boolean canBeUninvoked(){return false;} private Item puffCredit=null; private final static long CRAVE_TIME=TimeManager.MILI_HOUR; private final static long WITHDRAW_TIME=TimeManager.MILI_DAY; private boolean craving(){return (System.currentTimeMillis()-lastFix)>CRAVE_TIME;} @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((craving()) &&(CMLib.dice().rollPercentage()<=((System.currentTimeMillis()-lastFix)/TimeManager.MILI_HOUR)) &&(ticking instanceof MOB)) { if((System.currentTimeMillis()-lastFix)>WITHDRAW_TIME) { ((MOB)ticking).tell(L("You've managed to kick your addiction.")); canBeUninvoked=true; unInvoke(); ((MOB)ticking).delEffect(this); return false; } if((puffCredit!=null) &&(puffCredit.amDestroyed() ||puffCredit.amWearingAt(Wearable.IN_INVENTORY) ||puffCredit.owner()!=(MOB)affected)) puffCredit=null; switch(CMLib.dice().roll(1,7,0)) { case 1: ((MOB)ticking).tell(L("Man, you could sure use some @x1.",text())); break; case 2: ((MOB)ticking).tell(L("Wouldn't some @x1 be great right about now?",text())); break; case 3: ((MOB)ticking).tell(L("You are seriously craving @x1.",text())); break; case 4: ((MOB)ticking).tell(L("There's got to be some @x1 around here somewhere.",text())); break; case 5: ((MOB)ticking).tell(L("You REALLY want some @x1.",text())); break; case 6: ((MOB)ticking).tell(L("You NEED some @x1, NOW!",text())); break; case 7: ((MOB)ticking).tell(L("Some @x1 would be lovely.",text())); break; } } return true; } @Override public boolean okMessage(Environmental host, CMMsg msg) { if(affected instanceof MOB) { if((msg.source()==affected) &&(msg.targetMinor()==CMMsg.TYP_WEAR) &&(msg.target() instanceof Light) &&(msg.target() instanceof Container) &&(CMath.bset(((Item)msg.target()).rawProperLocationBitmap(),Wearable.WORN_MOUTH))) { final List<Item> contents=((Container)msg.target()).getContents(); if(CMLib.english().containsString(((Environmental)contents.get(0)).Name(),text())) puffCredit=(Item)msg.target(); } } return true; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if(affected instanceof MOB) { if(msg.source()==affected) { if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.target() instanceof Food)||(msg.target() instanceof Drink)) &&(msg.target() instanceof Item) &&(CMLib.english().containsString(msg.target().Name(),text()))) lastFix=System.currentTimeMillis(); if((msg.amISource((MOB)affected)) &&(msg.targetMinor()==CMMsg.TYP_HANDS) &&(msg.target() instanceof Light) &&(msg.tool() instanceof Light) &&(msg.target()==msg.tool()) &&(((Light)msg.target()).amWearingAt(Wearable.WORN_MOUTH)) &&(((Light)msg.target()).isLit()) &&((puffCredit!=null)||CMLib.english().containsString(msg.target().Name(),text()))) lastFix=System.currentTimeMillis(); } } super.executeMsg(myHost,msg); } @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { final Physical target=givenTarget; if(target==null) return false; if(target.fetchEffect(ID())!=null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { String addiction=target.Name().toUpperCase(); if(addiction.toUpperCase().startsWith("A POUND OF ")) addiction=addiction.substring(11); if(addiction.toUpperCase().startsWith("A ")) addiction=addiction.substring(2); if(addiction.toUpperCase().startsWith("AN ")) addiction=addiction.substring(3); if(addiction.toUpperCase().startsWith("SOME ")) addiction=addiction.substring(5); final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_OK_VISUAL,""); if(mob.location()!=null) { if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final Ability A=(Ability)copyOf(); A.setMiscText(addiction.trim()); mob.addNonUninvokableEffect(A); } } else { final Ability A=(Ability)copyOf(); A.setMiscText(addiction.trim()); mob.addNonUninvokableEffect(A); } } return success; } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@12625 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Abilities/Misc/Addictions.java
Java
apache-2.0
6cc68d119f7e23b01fd51f0e885504e9aa085a94
0
lucastheisen/apache-directory-server,drankye/directory-server,darranl/directory-server,drankye/directory-server,apache/directory-server,apache/directory-server,lucastheisen/apache-directory-server,darranl/directory-server
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.server.ldap; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.naming.Context; import org.apache.directory.server.core.configuration.StartupConfiguration; import org.apache.directory.server.ldap.support.AbandonHandler; import org.apache.directory.server.ldap.support.AddHandler; import org.apache.directory.server.ldap.support.BindHandler; import org.apache.directory.server.ldap.support.CompareHandler; import org.apache.directory.server.ldap.support.DeleteHandler; import org.apache.directory.server.ldap.support.ExtendedHandler; import org.apache.directory.server.ldap.support.LdapMessageHandler; import org.apache.directory.server.ldap.support.ModifyDnHandler; import org.apache.directory.server.ldap.support.ModifyHandler; import org.apache.directory.server.ldap.support.SearchHandler; import org.apache.directory.server.ldap.support.UnbindHandler; import org.apache.directory.shared.asn1.codec.Asn1CodecDecoder; import org.apache.directory.shared.asn1.codec.Asn1CodecEncoder; import org.apache.directory.shared.ldap.exception.LdapNamingException; import org.apache.directory.shared.ldap.message.AbandonRequest; import org.apache.directory.shared.ldap.message.AbandonRequestImpl; import org.apache.directory.shared.ldap.message.AddRequest; import org.apache.directory.shared.ldap.message.AddRequestImpl; import org.apache.directory.shared.ldap.message.BindRequest; import org.apache.directory.shared.ldap.message.BindRequestImpl; import org.apache.directory.shared.ldap.message.CompareRequest; import org.apache.directory.shared.ldap.message.CompareRequestImpl; import org.apache.directory.shared.ldap.message.Control; import org.apache.directory.shared.ldap.message.DeleteRequest; import org.apache.directory.shared.ldap.message.DeleteRequestImpl; import org.apache.directory.shared.ldap.message.EntryChangeControl; import org.apache.directory.shared.ldap.message.ExtendedRequest; import org.apache.directory.shared.ldap.message.ExtendedRequestImpl; import org.apache.directory.shared.ldap.message.ManageDsaITControl; import org.apache.directory.shared.ldap.message.MessageDecoder; import org.apache.directory.shared.ldap.message.MessageEncoder; import org.apache.directory.shared.ldap.message.ModifyDnRequest; import org.apache.directory.shared.ldap.message.ModifyDnRequestImpl; import org.apache.directory.shared.ldap.message.ModifyRequest; import org.apache.directory.shared.ldap.message.ModifyRequestImpl; import org.apache.directory.shared.ldap.message.PersistentSearchControl; import org.apache.directory.shared.ldap.message.Request; import org.apache.directory.shared.ldap.message.ResponseCarryingMessageException; import org.apache.directory.shared.ldap.message.ResultCodeEnum; import org.apache.directory.shared.ldap.message.ResultResponse; import org.apache.directory.shared.ldap.message.ResultResponseRequest; import org.apache.directory.shared.ldap.message.SearchRequest; import org.apache.directory.shared.ldap.message.SearchRequestImpl; import org.apache.directory.shared.ldap.message.UnbindRequest; import org.apache.directory.shared.ldap.message.UnbindRequestImpl; import org.apache.directory.shared.ldap.message.extended.NoticeOfDisconnect; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; import org.apache.mina.filter.LoggingFilter; import org.apache.mina.filter.SSLFilter; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.handler.demux.DemuxingIoHandler; import org.apache.mina.util.SessionLog; /** * An LDAP protocol provider implementation which dynamically associates * handlers. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$ */ public class LdapProtocolProvider { //TM private static long cumul = 0L; //TM private static long count = 0; //TM private static Object lock = new Object(); /** the constant service name of this ldap protocol provider **/ public static final String SERVICE_NAME = "ldap"; /** a map of the default request object class name to the handler class name */ private static final Map DEFAULT_HANDLERS; /** a set of supported controls */ private static final Set SUPPORTED_CONTROLS; static { HashMap map = new HashMap(); /* * Note: * * By mapping the implementation class in addition to the interface * for the request type to the handler Class we're bypassing the need * to iterate through Interface[] looking for handlers. For the default * cases here the name of the request object's class will look up * immediately. */ map.put( AbandonRequest.class.getName(), AbandonHandler.class ); map.put( AbandonRequestImpl.class.getName(), AbandonHandler.class ); map.put( AddRequest.class.getName(), AddHandler.class ); map.put( AddRequestImpl.class.getName(), AddHandler.class ); map.put( BindRequest.class.getName(), BindHandler.class ); map.put( BindRequestImpl.class.getName(), BindHandler.class ); map.put( CompareRequest.class.getName(), CompareHandler.class ); map.put( CompareRequestImpl.class.getName(), CompareHandler.class ); map.put( DeleteRequest.class.getName(), DeleteHandler.class ); map.put( DeleteRequestImpl.class.getName(), DeleteHandler.class ); map.put( ExtendedRequest.class.getName(), ExtendedHandler.class ); map.put( ExtendedRequestImpl.class.getName(), ExtendedHandler.class ); map.put( ModifyRequest.class.getName(), ModifyHandler.class ); map.put( ModifyRequestImpl.class.getName(), ModifyHandler.class ); map.put( ModifyDnRequest.class.getName(), ModifyDnHandler.class ); map.put( ModifyDnRequestImpl.class.getName(), ModifyDnHandler.class ); map.put( SearchRequest.class.getName(), SearchHandler.class ); map.put( SearchRequestImpl.class.getName(), SearchHandler.class ); map.put( UnbindRequest.class.getName(), UnbindHandler.class ); map.put( UnbindRequestImpl.class.getName(), UnbindHandler.class ); DEFAULT_HANDLERS = Collections.unmodifiableMap( map ); HashSet set = new HashSet(); set.add( PersistentSearchControl.CONTROL_OID ); set.add( EntryChangeControl.CONTROL_OID ); set.add( ManageDsaITControl.CONTROL_OID ); SUPPORTED_CONTROLS = Collections.unmodifiableSet( set ); } /** the underlying provider codec factory */ private final ProtocolCodecFactory codecFactory; /** the MINA protocol handler */ private final LdapProtocolHandler handler = new LdapProtocolHandler(); // ------------------------------------------------------------------------ // C O N S T R U C T O R S // ------------------------------------------------------------------------ /** * Creates a MINA LDAP protocol provider. * * @param env environment properties used to configure the provider and * underlying codec providers if any */ public LdapProtocolProvider( StartupConfiguration cfg, Hashtable env) throws LdapNamingException { Hashtable copy = ( Hashtable ) env.clone(); copy.put( Context.PROVIDER_URL, "" ); SessionRegistry.releaseSingleton(); new SessionRegistry( copy ); Iterator requestTypes = DEFAULT_HANDLERS.keySet().iterator(); while ( requestTypes.hasNext() ) { LdapMessageHandler handler = null; String type = ( String ) requestTypes.next(); Class clazz = null; if ( copy.containsKey( type ) ) { try { clazz = Class.forName( ( String ) copy.get( type ) ); } catch ( ClassNotFoundException e ) { LdapNamingException lne; String msg = "failed to load class " + clazz; msg += " for processing " + type + " objects."; lne = new LdapNamingException( msg, ResultCodeEnum.OTHER ); lne.setRootCause( e ); throw lne; } } else { clazz = ( Class ) DEFAULT_HANDLERS.get( type ); } try { Class typeClass = Class.forName( type ); handler = ( LdapMessageHandler ) clazz.newInstance(); handler.init( cfg ); this.handler.addMessageHandler( typeClass, handler ); } catch ( Exception e ) { LdapNamingException lne; String msg = "failed to create handler instance of " + clazz; msg += " for processing " + type + " objects."; lne = new LdapNamingException( msg, ResultCodeEnum.OTHER ); lne.setRootCause( e ); throw lne; } } this.codecFactory = new ProtocolCodecFactoryImpl( copy ); } // ------------------------------------------------------------------------ // ProtocolProvider Methods // ------------------------------------------------------------------------ public String getName() { return SERVICE_NAME; } public ProtocolCodecFactory getCodecFactory() { return codecFactory; } public IoHandler getHandler() { return handler; } /** * Registeres the specified {@link ExtendedOperationHandler} to this * protocol provider to provide a specific LDAP extended operation. */ public void addExtendedOperationHandler( ExtendedOperationHandler eoh ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); eh.addHandler( eoh ); eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequestImpl.class ); eh.addHandler( eoh ); } /** * Deregisteres an {@link ExtendedOperationHandler} with the specified <tt>oid</tt> * from this protocol provider. */ public void removeExtendedOperationHandler( String oid ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); eh.removeHandler( oid ); eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequestImpl.class ); eh.removeHandler( oid ); } /** * Returns an {@link ExtendedOperationHandler} with the specified <tt>oid</tt> * which is registered to this protocol provider. */ public ExtendedOperationHandler getExtendedOperationHandler( String oid ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); return eh.getHandler( oid ); } /** * Returns a {@link Map} of all registered OID-{@link ExtendedOperationHandler} * pairs. */ public Map getExtendedOperationHandlerMap() { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); return eh.getHandlerMap(); } /** * A snickers based BER Decoder factory. */ private static final class ProtocolCodecFactoryImpl implements ProtocolCodecFactory { final Hashtable env; public ProtocolCodecFactoryImpl() { this.env = null; } ProtocolCodecFactoryImpl(Hashtable env) { this.env = env; } public ProtocolEncoder getEncoder() { return new Asn1CodecEncoder( new MessageEncoder( env ) ); } public ProtocolDecoder getDecoder() { //TM long t0 = System.nanoTime(); ProtocolDecoder decoder = new Asn1CodecDecoder( new MessageDecoder( env ) ); //TM long t1 = System.nanoTime(); //TM System.out.println( "New Asn1Decoder cost : " + (t1-t0) ); //TM synchronized (lock) //TM { //TM cumul += (t1 - t0); //TM count++; //TM //TM if ( count % 1000L == 0) //TM { //TM System.out.println( "New Asn1Decoder cost : " + (cumul/count) ); //TM cumul = 0L; //TM } //TM } return decoder; } } private class LdapProtocolHandler extends DemuxingIoHandler { public void sessionCreated( IoSession session ) throws Exception { IoFilterChain filters = session.getFilterChain(); filters.addLast( "codec", new ProtocolCodecFilter( codecFactory ) ); // TODO : The filter is logging too much information. // Right now, I have commented it, but it may be // used with some parameter to disable it filters.addLast( "logger", new LoggingFilter() ); } public void sessionClosed( IoSession session ) { SessionRegistry.getSingleton().remove( session ); } public void messageReceived( IoSession session, Object message ) throws Exception { // Translate SSLFilter messages into LDAP extended request // defined in RFC #2830, 'Lightweight Directory Access Protocol (v3): // Extension for Transport Layer Security'. // // The RFC specifies the payload should be empty, but we use // it to notify the TLS state changes. This hack should be // OK from the viewpoint of security because StartTLS // handler should react to only SESSION_UNSECURED message // and degrade authentication level to 'anonymous' as specified // in the RFC, and this is no threat. if ( message == SSLFilter.SESSION_SECURED ) { ExtendedRequest req = new ExtendedRequestImpl( 0 ); req.setOid( "1.3.6.1.4.1.1466.20037" ); req.setPayload( "SECURED".getBytes( "ISO-8859-1" ) ); message = req; } else if ( message == SSLFilter.SESSION_UNSECURED ) { ExtendedRequest req = new ExtendedRequestImpl( 0 ); req.setOid( "1.3.6.1.4.1.1466.20037" ); req.setPayload( "UNSECURED".getBytes( "ISO-8859-1" ) ); message = req; } if ( ( ( Request ) message ).getControls().size() > 0 && message instanceof ResultResponseRequest ) { ResultResponseRequest req = ( ResultResponseRequest ) message; Iterator controls = req.getControls().values().iterator(); while ( controls.hasNext() ) { Control control = ( Control ) controls.next(); if ( control.isCritical() && !SUPPORTED_CONTROLS.contains( control.getID() ) ) { ResultResponse resp = req.getResultResponse(); resp.getLdapResult().setErrorMessage( "Unsupport critical control: " + control.getID() ); resp.getLdapResult().setResultCode( ResultCodeEnum.UNAVAILABLE_CRITICAL_EXTENSION ); session.write( resp ); return; } } } super.messageReceived( session, message ); } public void exceptionCaught( IoSession session, Throwable cause ) { if ( cause.getCause() instanceof ResponseCarryingMessageException ) { ResponseCarryingMessageException rcme = ( ResponseCarryingMessageException ) cause.getCause(); session.write( rcme.getResponse() ); return; } SessionLog.warn( session, "Unexpected exception forcing session to close: sending disconnect notice to client.", cause ); session.write( NoticeOfDisconnect.PROTOCOLERROR ); SessionRegistry.getSingleton().remove( session ); session.close(); } } }
protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.server.ldap; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.naming.Context; import org.apache.directory.server.core.configuration.StartupConfiguration; import org.apache.directory.server.ldap.support.AbandonHandler; import org.apache.directory.server.ldap.support.AddHandler; import org.apache.directory.server.ldap.support.BindHandler; import org.apache.directory.server.ldap.support.CompareHandler; import org.apache.directory.server.ldap.support.DeleteHandler; import org.apache.directory.server.ldap.support.ExtendedHandler; import org.apache.directory.server.ldap.support.LdapMessageHandler; import org.apache.directory.server.ldap.support.ModifyDnHandler; import org.apache.directory.server.ldap.support.ModifyHandler; import org.apache.directory.server.ldap.support.SearchHandler; import org.apache.directory.server.ldap.support.UnbindHandler; import org.apache.directory.shared.asn1.codec.Asn1CodecDecoder; import org.apache.directory.shared.asn1.codec.Asn1CodecEncoder; import org.apache.directory.shared.ldap.exception.LdapNamingException; import org.apache.directory.shared.ldap.message.AbandonRequest; import org.apache.directory.shared.ldap.message.AbandonRequestImpl; import org.apache.directory.shared.ldap.message.AddRequest; import org.apache.directory.shared.ldap.message.AddRequestImpl; import org.apache.directory.shared.ldap.message.BindRequest; import org.apache.directory.shared.ldap.message.BindRequestImpl; import org.apache.directory.shared.ldap.message.CompareRequest; import org.apache.directory.shared.ldap.message.CompareRequestImpl; import org.apache.directory.shared.ldap.message.Control; import org.apache.directory.shared.ldap.message.DeleteRequest; import org.apache.directory.shared.ldap.message.DeleteRequestImpl; import org.apache.directory.shared.ldap.message.EntryChangeControl; import org.apache.directory.shared.ldap.message.ExtendedRequest; import org.apache.directory.shared.ldap.message.ExtendedRequestImpl; import org.apache.directory.shared.ldap.message.ManageDsaITControl; import org.apache.directory.shared.ldap.message.MessageDecoder; import org.apache.directory.shared.ldap.message.MessageEncoder; import org.apache.directory.shared.ldap.message.ModifyDnRequest; import org.apache.directory.shared.ldap.message.ModifyDnRequestImpl; import org.apache.directory.shared.ldap.message.ModifyRequest; import org.apache.directory.shared.ldap.message.ModifyRequestImpl; import org.apache.directory.shared.ldap.message.PersistentSearchControl; import org.apache.directory.shared.ldap.message.Request; import org.apache.directory.shared.ldap.message.ResponseCarryingMessageException; import org.apache.directory.shared.ldap.message.ResultCodeEnum; import org.apache.directory.shared.ldap.message.ResultResponse; import org.apache.directory.shared.ldap.message.ResultResponseRequest; import org.apache.directory.shared.ldap.message.SearchRequest; import org.apache.directory.shared.ldap.message.SearchRequestImpl; import org.apache.directory.shared.ldap.message.UnbindRequest; import org.apache.directory.shared.ldap.message.UnbindRequestImpl; import org.apache.directory.shared.ldap.message.extended.NoticeOfDisconnect; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoSession; import org.apache.mina.filter.SSLFilter; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.handler.demux.DemuxingIoHandler; import org.apache.mina.util.SessionLog; /** * An LDAP protocol provider implementation which dynamically associates * handlers. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$ */ public class LdapProtocolProvider { /** the constant service name of this ldap protocol provider **/ public static final String SERVICE_NAME = "ldap"; /** a map of the default request object class name to the handler class name */ private static final Map DEFAULT_HANDLERS; /** a set of supported controls */ private static final Set SUPPORTED_CONTROLS; static { HashMap map = new HashMap(); /* * Note: * * By mapping the implementation class in addition to the interface * for the request type to the handler Class we're bypassing the need * to iterate through Interface[] looking for handlers. For the default * cases here the name of the request object's class will look up * immediately. */ map.put( AbandonRequest.class.getName(), AbandonHandler.class ); map.put( AbandonRequestImpl.class.getName(), AbandonHandler.class ); map.put( AddRequest.class.getName(), AddHandler.class ); map.put( AddRequestImpl.class.getName(), AddHandler.class ); map.put( BindRequest.class.getName(), BindHandler.class ); map.put( BindRequestImpl.class.getName(), BindHandler.class ); map.put( CompareRequest.class.getName(), CompareHandler.class ); map.put( CompareRequestImpl.class.getName(), CompareHandler.class ); map.put( DeleteRequest.class.getName(), DeleteHandler.class ); map.put( DeleteRequestImpl.class.getName(), DeleteHandler.class ); map.put( ExtendedRequest.class.getName(), ExtendedHandler.class ); map.put( ExtendedRequestImpl.class.getName(), ExtendedHandler.class ); map.put( ModifyRequest.class.getName(), ModifyHandler.class ); map.put( ModifyRequestImpl.class.getName(), ModifyHandler.class ); map.put( ModifyDnRequest.class.getName(), ModifyDnHandler.class ); map.put( ModifyDnRequestImpl.class.getName(), ModifyDnHandler.class ); map.put( SearchRequest.class.getName(), SearchHandler.class ); map.put( SearchRequestImpl.class.getName(), SearchHandler.class ); map.put( UnbindRequest.class.getName(), UnbindHandler.class ); map.put( UnbindRequestImpl.class.getName(), UnbindHandler.class ); DEFAULT_HANDLERS = Collections.unmodifiableMap( map ); HashSet set = new HashSet(); set.add( PersistentSearchControl.CONTROL_OID ); set.add( EntryChangeControl.CONTROL_OID ); set.add( ManageDsaITControl.CONTROL_OID ); SUPPORTED_CONTROLS = Collections.unmodifiableSet( set ); } /** the underlying provider codec factory */ private final ProtocolCodecFactory codecFactory; /** the MINA protocol handler */ private final LdapProtocolHandler handler = new LdapProtocolHandler(); // ------------------------------------------------------------------------ // C O N S T R U C T O R S // ------------------------------------------------------------------------ /** * Creates a MINA LDAP protocol provider. * * @param env environment properties used to configure the provider and * underlying codec providers if any */ public LdapProtocolProvider( StartupConfiguration cfg, Hashtable env) throws LdapNamingException { Hashtable copy = ( Hashtable ) env.clone(); copy.put( Context.PROVIDER_URL, "" ); SessionRegistry.releaseSingleton(); new SessionRegistry( copy ); Iterator requestTypes = DEFAULT_HANDLERS.keySet().iterator(); while ( requestTypes.hasNext() ) { LdapMessageHandler handler = null; String type = ( String ) requestTypes.next(); Class clazz = null; if ( copy.containsKey( type ) ) { try { clazz = Class.forName( ( String ) copy.get( type ) ); } catch ( ClassNotFoundException e ) { LdapNamingException lne; String msg = "failed to load class " + clazz; msg += " for processing " + type + " objects."; lne = new LdapNamingException( msg, ResultCodeEnum.OTHER ); lne.setRootCause( e ); throw lne; } } else { clazz = ( Class ) DEFAULT_HANDLERS.get( type ); } try { Class typeClass = Class.forName( type ); handler = ( LdapMessageHandler ) clazz.newInstance(); handler.init( cfg ); this.handler.addMessageHandler( typeClass, handler ); } catch ( Exception e ) { LdapNamingException lne; String msg = "failed to create handler instance of " + clazz; msg += " for processing " + type + " objects."; lne = new LdapNamingException( msg, ResultCodeEnum.OTHER ); lne.setRootCause( e ); throw lne; } } this.codecFactory = new ProtocolCodecFactoryImpl( copy ); } // ------------------------------------------------------------------------ // ProtocolProvider Methods // ------------------------------------------------------------------------ public String getName() { return SERVICE_NAME; } public ProtocolCodecFactory getCodecFactory() { return codecFactory; } public IoHandler getHandler() { return handler; } /** * Registeres the specified {@link ExtendedOperationHandler} to this * protocol provider to provide a specific LDAP extended operation. */ public void addExtendedOperationHandler( ExtendedOperationHandler eoh ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); eh.addHandler( eoh ); eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequestImpl.class ); eh.addHandler( eoh ); } /** * Deregisteres an {@link ExtendedOperationHandler} with the specified <tt>oid</tt> * from this protocol provider. */ public void removeExtendedOperationHandler( String oid ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); eh.removeHandler( oid ); eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequestImpl.class ); eh.removeHandler( oid ); } /** * Returns an {@link ExtendedOperationHandler} with the specified <tt>oid</tt> * which is registered to this protocol provider. */ public ExtendedOperationHandler getExtendedOperationHandler( String oid ) { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); return eh.getHandler( oid ); } /** * Returns a {@link Map} of all registered OID-{@link ExtendedOperationHandler} * pairs. */ public Map getExtendedOperationHandlerMap() { ExtendedHandler eh = ( ExtendedHandler ) handler.getMessageHandler( ExtendedRequest.class ); return eh.getHandlerMap(); } /** * A snickers based BER Decoder factory. */ private static final class ProtocolCodecFactoryImpl implements ProtocolCodecFactory { final Hashtable env; public ProtocolCodecFactoryImpl() { this.env = null; } ProtocolCodecFactoryImpl(Hashtable env) { this.env = env; } public ProtocolEncoder getEncoder() { return new Asn1CodecEncoder( new MessageEncoder( env ) ); } public ProtocolDecoder getDecoder() { return new Asn1CodecDecoder( new MessageDecoder( env ) ); } } private class LdapProtocolHandler extends DemuxingIoHandler { public void sessionCreated( IoSession session ) throws Exception { IoFilterChain filters = session.getFilterChain(); filters.addLast( "codec", new ProtocolCodecFilter( codecFactory ) ); // TODO : The filter is logging too much information. // Right now, I have commented it, but it may be // used with some parameter to disable it //filters.addLast( "logger", new LoggingFilter() ); } public void sessionClosed( IoSession session ) { SessionRegistry.getSingleton().remove( session ); } public void messageReceived( IoSession session, Object message ) throws Exception { // Translate SSLFilter messages into LDAP extended request // defined in RFC #2830, 'Lightweight Directory Access Protocol (v3): // Extension for Transport Layer Security'. // // The RFC specifies the payload should be empty, but we use // it to notify the TLS state changes. This hack should be // OK from the viewpoint of security because StartTLS // handler should react to only SESSION_UNSECURED message // and degrade authentication level to 'anonymous' as specified // in the RFC, and this is no threat. if ( message == SSLFilter.SESSION_SECURED ) { ExtendedRequest req = new ExtendedRequestImpl( 0 ); req.setOid( "1.3.6.1.4.1.1466.20037" ); req.setPayload( "SECURED".getBytes( "ISO-8859-1" ) ); message = req; } else if ( message == SSLFilter.SESSION_UNSECURED ) { ExtendedRequest req = new ExtendedRequestImpl( 0 ); req.setOid( "1.3.6.1.4.1.1466.20037" ); req.setPayload( "UNSECURED".getBytes( "ISO-8859-1" ) ); message = req; } if ( ( ( Request ) message ).getControls().size() > 0 && message instanceof ResultResponseRequest ) { ResultResponseRequest req = ( ResultResponseRequest ) message; Iterator controls = req.getControls().values().iterator(); while ( controls.hasNext() ) { Control control = ( Control ) controls.next(); if ( control.isCritical() && !SUPPORTED_CONTROLS.contains( control.getID() ) ) { ResultResponse resp = req.getResultResponse(); resp.getLdapResult().setErrorMessage( "Unsupport critical control: " + control.getID() ); resp.getLdapResult().setResultCode( ResultCodeEnum.UNAVAILABLE_CRITICAL_EXTENSION ); session.write( resp ); return; } } } super.messageReceived( session, message ); } public void exceptionCaught( IoSession session, Throwable cause ) { if ( cause.getCause() instanceof ResponseCarryingMessageException ) { ResponseCarryingMessageException rcme = ( ResponseCarryingMessageException ) cause.getCause(); session.write( rcme.getResponse() ); return; } SessionLog.warn( session, "Unexpected exception forcing session to close: sending disconnect notice to client.", cause ); session.write( NoticeOfDisconnect.PROTOCOLERROR ); SessionRegistry.getSingleton().remove( session ); session.close(); } } }
Added some timing instructions, commented (to use them, one should simply uncomment the //TM ) git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@526138 13f79535-47bb-0310-9956-ffa450edef68
protocol-ldap/src/main/java/org/apache/directory/server/ldap/LdapProtocolProvider.java
Added some timing instructions, commented (to use them, one should simply uncomment the //TM )
Java
apache-2.0
c6547fcfd974cc49e55c2dfac7d79f7483fefc66
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.session; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.model.application.provider.DeployData; import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.config.provision.AllocatedHosts; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.TenantName; import com.yahoo.io.IOUtils; import com.yahoo.lang.SettableOptional; import com.yahoo.path.Path; import com.yahoo.transaction.AbstractTransaction; import com.yahoo.transaction.NestedTransaction; import com.yahoo.transaction.Transaction; import com.yahoo.vespa.config.server.GlobalComponentRegistry; import com.yahoo.vespa.config.server.TimeoutBudget; import com.yahoo.vespa.config.server.application.ApplicationSet; import com.yahoo.vespa.config.server.application.TenantApplications; import com.yahoo.vespa.config.server.configchange.ConfigChangeActions; import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs; import com.yahoo.vespa.config.server.filedistribution.FileDirectory; import com.yahoo.vespa.config.server.modelfactory.ActivatedModelsBuilder; import com.yahoo.vespa.config.server.monitoring.MetricUpdater; import com.yahoo.vespa.config.server.monitoring.Metrics; import com.yahoo.vespa.config.server.tenant.TenantRepository; import com.yahoo.vespa.config.server.zookeeper.ConfigCurator; import com.yahoo.vespa.config.server.zookeeper.SessionCounter; import com.yahoo.vespa.curator.Curator; import com.yahoo.vespa.defaults.Defaults; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.zookeeper.KeeperException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * * Session repository for a tenant. Stores session state in zookeeper and file system. There are two * different session types (RemoteSession and LocalSession). * * @author Ulf Lilleengen * @author hmusum * */ public class SessionRepository { private static final Logger log = Logger.getLogger(SessionRepository.class.getName()); private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+"); private static final long nonExistingActiveSessionId = 0; private final Map<Long, LocalSession> localSessionCache = new ConcurrentHashMap<>(); private final Map<Long, RemoteSession> remoteSessionCache = new ConcurrentHashMap<>(); private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>(); private final Duration sessionLifetime; private final Clock clock; private final Curator curator; private final Executor zkWatcherExecutor; private final TenantFileSystemDirs tenantFileSystemDirs; private final MetricUpdater metrics; private final Curator.DirectoryCache directoryCache; private final TenantApplications applicationRepo; private final SessionPreparer sessionPreparer; private final Path sessionsPath; private final TenantName tenantName; private final GlobalComponentRegistry componentRegistry; public SessionRepository(TenantName tenantName, GlobalComponentRegistry componentRegistry, TenantApplications applicationRepo, SessionPreparer sessionPreparer) { this.tenantName = tenantName; this.componentRegistry = componentRegistry; this.sessionsPath = TenantRepository.getSessionsPath(tenantName); this.clock = componentRegistry.getClock(); this.curator = componentRegistry.getCurator(); this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime()); this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command); this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName); this.applicationRepo = applicationRepo; this.sessionPreparer = sessionPreparer; this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName)); loadSessions(); // Needs to be done before creating cache below this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor()); this.directoryCache.addListener(this::childEvent); this.directoryCache.start(); } private void loadSessions() { loadLocalSessions(); loadRemoteSessions(); } // ---------------- Local sessions ---------------------------------------------------------------- public synchronized void addLocalSession(LocalSession session) { long sessionId = session.getSessionId(); localSessionCache.put(sessionId, session); if (remoteSessionCache.get(sessionId) == null) { createRemoteSession(sessionId); } } public LocalSession getLocalSession(long sessionId) { return localSessionCache.get(sessionId); } public Collection<LocalSession> getLocalSessions() { return localSessionCache.values(); } private void loadLocalSessions() { File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter); if (sessions == null) return; for (File session : sessions) { try { createSessionFromId(Long.parseLong(session.getName())); } catch (IllegalArgumentException e) { log.log(Level.WARNING, "Could not load session '" + session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it."); } } } public ConfigChangeActions prepareLocalSession(LocalSession session, DeployLogger logger, PrepareParams params, Path tenantPath, Instant now) { applicationRepo.createApplication(params.getApplicationId()); // TODO jvenstad: This is wrong, but it has to be done now, since preparation can change the application ID of a session :( logger.log(Level.FINE, "Created application " + params.getApplicationId()); long sessionId = session.getSessionId(); SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId); Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter(); Optional<ApplicationSet> activeApplicationSet = getActiveApplicationSet(params.getApplicationId()); ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params, activeApplicationSet, tenantPath, now, getSessionAppDir(sessionId), session.getApplicationPackage(), sessionZooKeeperClient) .getConfigChangeActions(); setPrepared(session); waiter.awaitCompletion(params.getTimeoutBudget().timeLeft()); return actions; } /** * Creates a new deployment session from an already existing session. * * @param existingSession the session to use as base * @param logger a deploy logger where the deploy log will be written. * @param internalRedeploy whether this session is for a system internal redeploy — not an application package change * @param timeoutBudget timeout for creating session and waiting for other servers. * @return a new session */ public LocalSession createSessionFromExisting(Session existingSession, DeployLogger logger, boolean internalRedeploy, TimeoutBudget timeoutBudget) { ApplicationId existingApplicationId = existingSession.getApplicationId(); Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId); logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId); File existingApp = getSessionAppDir(existingSession.getSessionId()); LocalSession session = createSessionFromApplication(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget); // Note: Setters below need to be kept in sync with calls in SessionPreparer.writeStateToZooKeeper() session.setApplicationId(existingApplicationId); session.setApplicationPackageReference(existingSession.getApplicationPackageReference()); session.setVespaVersion(existingSession.getVespaVersion()); session.setDockerImageRepository(existingSession.getDockerImageRepository()); session.setAthenzDomain(existingSession.getAthenzDomain()); return session; } /** * Creates a new deployment session from an application package. * * @param applicationDirectory a File pointing to an application. * @param applicationId application id for this new session. * @param timeoutBudget Timeout for creating session and waiting for other servers. * @return a new session */ public LocalSession createSessionFromApplicationPackage(File applicationDirectory, ApplicationId applicationId, TimeoutBudget timeoutBudget) { applicationRepo.createApplication(applicationId); Optional<Long> activeSessionId = applicationRepo.activeSessionOf(applicationId); return createSessionFromApplication(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget); } /** * This method is used when creating a session based on a remote session and the distributed application package * It does not wait for session being created on other servers */ private void createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) { try { Optional<Long> activeSessionId = getActiveSessionId(applicationId); ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId, sessionId, activeSessionId, false); createLocalSession(sessionId, applicationPackage); } catch (Exception e) { throw new RuntimeException("Error creating session " + sessionId, e); } } // Will delete session data in ZooKeeper and file system public void deleteLocalSession(LocalSession session) { long sessionId = session.getSessionId(); log.log(Level.FINE, () -> "Deleting local session " + sessionId); SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId); if (watcher != null) watcher.close(); localSessionCache.remove(sessionId); NestedTransaction transaction = new NestedTransaction(); transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath()))); transaction.commit(); } private void deleteAllSessions() { List<LocalSession> sessions = new ArrayList<>(localSessionCache.values()); for (LocalSession session : sessions) { deleteLocalSession(session); } } // ---------------- Remote sessions ---------------------------------------------------------------- public RemoteSession getRemoteSession(long sessionId) { return remoteSessionCache.get(sessionId); } public List<Long> getRemoteSessions() { return getSessionList(curator.getChildren(sessionsPath)); } public synchronized RemoteSession createRemoteSession(long sessionId) { SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient); remoteSessionCache.put(sessionId, session); loadSessionIfActive(session); updateSessionStateWatcher(sessionId, session); return session; } public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) { int deleted = 0; for (long sessionId : getRemoteSessions()) { RemoteSession session = remoteSessionCache.get(sessionId); if (session == null) continue; // Internal sessions not in sync with zk, continue if (session.getStatus() == Session.Status.ACTIVATE) continue; if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) { log.log(Level.FINE, () -> "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it"); deleteRemoteSessionFromZooKeeper(session); deleted++; } } return deleted; } public void deactivateAndUpdateCache(RemoteSession remoteSession) { RemoteSession session = remoteSession.deactivated(); remoteSessionCache.put(session.getSessionId(), session); } public void deleteRemoteSessionFromZooKeeper(RemoteSession session) { SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); Transaction transaction = sessionZooKeeperClient.deleteTransaction(); transaction.commit(); transaction.close(); } private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) { return (created.plus(expiryTime).isBefore(clock.instant())); } private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) { return getSessionList(children.stream() .map(child -> Path.fromString(child.getPath()).getName()) .collect(Collectors.toList())); } private List<Long> getSessionList(List<String> children) { return children.stream().map(Long::parseLong).collect(Collectors.toList()); } private void loadRemoteSessions() throws NumberFormatException { getRemoteSessions().forEach(this::sessionAdded); } /** * A session for which we don't have a watcher, i.e. hitherto unknown to us. * * @param sessionId session id for the new session */ public synchronized void sessionAdded(long sessionId) { log.log(Level.FINE, () -> "Adding remote session " + sessionId); RemoteSession session = createRemoteSession(sessionId); if (session.getStatus() == Session.Status.NEW) { log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId); confirmUpload(session); } createLocalSessionFromDistributedApplicationPackage(sessionId); } void activate(RemoteSession session) { long sessionId = session.getSessionId(); Curator.CompletionWaiter waiter = createSessionZooKeeperClient(sessionId).getActiveWaiter(); log.log(Level.FINE, () -> session.logPre() + "Getting session from repo: " + session); ApplicationSet app = ensureApplicationLoaded(session); log.log(Level.FINE, () -> session.logPre() + "Reloading config for " + sessionId); applicationRepo.reloadConfig(app); log.log(Level.FINE, () -> session.logPre() + "Notifying " + waiter); notifyCompletion(waiter, session); log.log(Level.INFO, session.logPre() + "Session activated: " + sessionId); } public void delete(RemoteSession remoteSession) { long sessionId = remoteSession.getSessionId(); // TODO: Change log level to FINE when debugging is finished log.log(Level.INFO, () -> remoteSession.logPre() + "Deactivating and deleting remote session " + sessionId); deleteRemoteSessionFromZooKeeper(remoteSession); remoteSessionCache.remove(sessionId); LocalSession localSession = getLocalSession(sessionId); if (localSession != null) { // TODO: Change log level to FINE when debugging is finished log.log(Level.INFO, () -> localSession.logPre() + "Deleting local session " + sessionId); deleteLocalSession(localSession); } } private void sessionRemoved(long sessionId) { SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId); if (watcher != null) watcher.close(); remoteSessionCache.remove(sessionId); metrics.incRemovedSessions(); } private void loadSessionIfActive(RemoteSession session) { for (ApplicationId applicationId : applicationRepo.activeApplications()) { if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) { log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it"); applicationRepo.reloadConfig(ensureApplicationLoaded(session)); log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")"); return; } } } void prepareRemoteSession(RemoteSession session) { SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); Curator.CompletionWaiter waiter = sessionZooKeeperClient.getPrepareWaiter(); ensureApplicationLoaded(session); notifyCompletion(waiter, session); } public ApplicationSet ensureApplicationLoaded(RemoteSession session) { if (session.applicationSet().isPresent()) { return session.applicationSet().get(); } ApplicationSet applicationSet = loadApplication(session); RemoteSession activated = session.activated(applicationSet); long sessionId = activated.getSessionId(); remoteSessionCache.put(sessionId, activated); updateSessionStateWatcher(sessionId, activated); return applicationSet; } void confirmUpload(RemoteSession session) { Curator.CompletionWaiter waiter = session.getSessionZooKeeperClient().getUploadWaiter(); long sessionId = session.getSessionId(); log.log(Level.FINE, "Notifying upload waiter for session " + sessionId); notifyCompletion(waiter, session); log.log(Level.FINE, "Done notifying upload for session " + sessionId); } void notifyCompletion(Curator.CompletionWaiter completionWaiter, RemoteSession session) { try { completionWaiter.notifyCompletion(); } catch (RuntimeException e) { // Throw only if we get something else than NoNodeException or NodeExistsException. // NoNodeException might happen when the session is no longer in use (e.g. the app using this session // has been deleted) and this method has not been called yet for the previous session operation on a // minority of the config servers. // NodeExistsException might happen if an event for this node is delivered more than once, in that case // this is a no-op Set<Class<? extends KeeperException>> acceptedExceptions = Set.of(KeeperException.NoNodeException.class, KeeperException.NodeExistsException.class); Class<? extends Throwable> exceptionClass = e.getCause().getClass(); if (acceptedExceptions.contains(exceptionClass)) log.log(Level.FINE, "Not able to notify completion for session " + session.getSessionId() + " (" + completionWaiter + ")," + " node " + (exceptionClass.equals(KeeperException.NoNodeException.class) ? "has been deleted" : "already exists")); else throw e; } } private ApplicationSet loadApplication(RemoteSession session) { log.log(Level.FINE, () -> "Loading application for " + session); SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); ApplicationPackage applicationPackage = sessionZooKeeperClient.loadApplicationPackage(); ActivatedModelsBuilder builder = new ActivatedModelsBuilder(session.getTenantName(), session.getSessionId(), sessionZooKeeperClient, componentRegistry); // Read hosts allocated on the config server instance which created this SettableOptional<AllocatedHosts> allocatedHosts = new SettableOptional<>(applicationPackage.getAllocatedHosts()); return ApplicationSet.fromList(builder.buildModels(session.getApplicationId(), sessionZooKeeperClient.readDockerImageRepository(), sessionZooKeeperClient.readVespaVersion(), applicationPackage, allocatedHosts, clock.instant())); } private void nodeChanged() { zkWatcherExecutor.execute(() -> { Multiset<Session.Status> sessionMetrics = HashMultiset.create(); for (RemoteSession session : remoteSessionCache.values()) { sessionMetrics.add(session.getStatus()); } metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW)); metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE)); metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE)); metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE)); }); } @SuppressWarnings("unused") private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) { zkWatcherExecutor.execute(() -> { log.log(Level.FINE, () -> "Got child event: " + event); switch (event.getType()) { case CHILD_ADDED: case CHILD_REMOVED: case CONNECTION_RECONNECTED: sessionsChanged(); break; default: break; } }); } // ---------------- Common stuff ---------------------------------------------------------------- public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) { log.log(Level.FINE, () -> "Purging old sessions for tenant '" + tenantName + "'"); try { for (LocalSession candidate : localSessionCache.values()) { Instant createTime = candidate.getCreateTime(); log.log(Level.FINE, () -> "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime); // Sessions with state other than ACTIVATE if (hasExpired(candidate) && !isActiveSession(candidate)) { deleteLocalSession(candidate); } else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) { // Sessions with state ACTIVATE, but which are not actually active Optional<ApplicationId> applicationId = candidate.getOptionalApplicationId(); if (applicationId.isEmpty()) continue; Long activeSession = activeSessions.get(applicationId.get()); if (activeSession == null || activeSession != candidate.getSessionId()) { deleteLocalSession(candidate); log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " + createTime + " for '" + applicationId + "'"); } } } // Make sure to catch here, to avoid executor just dying in case of issues ... } catch (Throwable e) { log.log(Level.WARNING, "Error when purging old sessions ", e); } log.log(Level.FINE, () -> "Done purging old sessions"); } private boolean hasExpired(LocalSession candidate) { return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant())); } private boolean isActiveSession(LocalSession candidate) { return candidate.getStatus() == Session.Status.ACTIVATE; } private void ensureSessionPathDoesNotExist(long sessionId) { Path sessionPath = getSessionPath(sessionId); if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) { throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper"); } } private ApplicationPackage createApplication(File userDir, File configApplicationDir, ApplicationId applicationId, long sessionId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy) { long deployTimestamp = System.currentTimeMillis(); String user = System.getenv("USER"); if (user == null) { user = "unknown"; } DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp, internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId)); return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData); } private LocalSession createSessionFromApplication(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy, TimeoutBudget timeoutBudget) { long sessionId = getNextSessionId(); try { ensureSessionPathDoesNotExist(sessionId); ApplicationPackage app = createApplicationPackage(applicationFile, applicationId, sessionId, currentlyActiveSessionId, internalRedeploy); log.log(Level.FINE, () -> TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper"); SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); sessionZKClient.createNewSession(clock.instant()); Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter(); LocalSession session = new LocalSession(tenantName, sessionId, app, sessionZKClient); waiter.awaitCompletion(timeoutBudget.timeLeft()); return session; } catch (Exception e) { throw new RuntimeException("Error creating session " + sessionId, e); } } private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId, long sessionId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy) throws IOException { File userApplicationDir = getSessionAppDir(sessionId); copyApp(applicationFile, userApplicationDir); ApplicationPackage applicationPackage = createApplication(applicationFile, userApplicationDir, applicationId, sessionId, currentlyActiveSessionId, internalRedeploy); applicationPackage.writeMetaData(); return applicationPackage; } public Optional<ApplicationSet> getActiveApplicationSet(ApplicationId appId) { Optional<ApplicationSet> currentActiveApplicationSet = Optional.empty(); try { long currentActiveSessionId = applicationRepo.requireActiveSessionOf(appId); RemoteSession currentActiveSession = getRemoteSession(currentActiveSessionId); currentActiveApplicationSet = Optional.ofNullable(ensureApplicationLoaded(currentActiveSession)); } catch (IllegalArgumentException e) { // Do nothing if we have no currently active session } return currentActiveApplicationSet; } private void copyApp(File sourceDir, File destinationDir) throws IOException { if (destinationDir.exists()) throw new RuntimeException("Destination dir " + destinationDir + " already exists"); if (! sourceDir.isDirectory()) throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory"); // Copy app atomically: Copy to a temp dir and move to destination java.nio.file.Path tempDestinationDir = null; try { tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package"); log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath()); IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile()); log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath()); Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE); } finally { // In case some of the operations above fail if (tempDestinationDir != null) IOUtils.recursiveDeleteDir(tempDestinationDir.toFile()); } } /** * Returns a new session instance for the given session id. */ void createSessionFromId(long sessionId) { File sessionDir = getAndValidateExistingSessionAppDir(sessionId); ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir); createLocalSession(sessionId, applicationPackage); } void createLocalSession(long sessionId, ApplicationPackage applicationPackage) { SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient); addLocalSession(session); } /** * Returns a new local session for the given session id if it does not already exist. * Will also add the session to the local session cache if necessary */ public void createLocalSessionFromDistributedApplicationPackage(long sessionId) { if (applicationRepo.sessionExistsInFileSystem(sessionId)) { log.log(Level.FINE, () -> "Local session for session id " + sessionId + " already exists"); createSessionFromId(sessionId); return; } SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); FileReference fileReference = sessionZKClient.readApplicationPackageReference(); log.log(Level.FINE, () -> "File reference for session id " + sessionId + ": " + fileReference); if (fileReference != null) { File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir())); File sessionDir; FileDirectory fileDirectory = new FileDirectory(rootDir); try { sessionDir = fileDirectory.getFile(fileReference); } catch (IllegalArgumentException e) { // We cannot be guaranteed that the file reference exists (it could be that it has not // been downloaded yet), and e.g when bootstrapping we cannot throw an exception in that case log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory); return; } ApplicationId applicationId = sessionZKClient.readApplicationId() .orElseThrow(() -> new RuntimeException("Could not find application id for session " + sessionId)); log.log(Level.FINE, () -> "Creating local session for tenant '" + tenantName + "' with session id " + sessionId); createLocalSession(sessionDir, applicationId, sessionId); } } private Optional<Long> getActiveSessionId(ApplicationId applicationId) { List<ApplicationId> applicationIds = applicationRepo.activeApplications(); return applicationIds.contains(applicationId) ? Optional.of(applicationRepo.requireActiveSessionOf(applicationId)) : Optional.empty(); } private long getNextSessionId() { return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId(); } public Path getSessionPath(long sessionId) { return sessionsPath.append(String.valueOf(sessionId)); } Path getSessionStatePath(long sessionId) { return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH); } private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) { String serverId = componentRegistry.getConfigserverConfig().serverId(); return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), tenantName, sessionId, serverId); } private File getAndValidateExistingSessionAppDir(long sessionId) { File appDir = getSessionAppDir(sessionId); if (!appDir.exists() || !appDir.isDirectory()) { throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId); } return appDir; } private File getSessionAppDir(long sessionId) { return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId); } private void updateSessionStateWatcher(long sessionId, RemoteSession remoteSession) { SessionStateWatcher sessionStateWatcher = sessionStateWatchers.get(sessionId); if (sessionStateWatcher == null) { Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false); fileCache.addListener(this::nodeChanged); sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, remoteSession, metrics, zkWatcherExecutor, this)); } else { sessionStateWatcher.updateRemoteSession(remoteSession); } } @Override public String toString() { return getLocalSessions().toString(); } public Clock clock() { return clock; } public void close() { deleteAllSessions(); tenantFileSystemDirs.delete(); try { if (directoryCache != null) { directoryCache.close(); } } catch (Exception e) { log.log(Level.WARNING, "Exception when closing path cache", e); } finally { checkForRemovedSessions(new ArrayList<>()); } } private synchronized void sessionsChanged() throws NumberFormatException { List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData()); checkForRemovedSessions(sessions); checkForAddedSessions(sessions); } private void checkForRemovedSessions(List<Long> sessions) { for (RemoteSession session : remoteSessionCache.values()) if ( ! sessions.contains(session.getSessionId())) sessionRemoved(session.getSessionId()); } private void checkForAddedSessions(List<Long> sessions) { for (Long sessionId : sessions) if (remoteSessionCache.get(sessionId) == null) sessionAdded(sessionId); } public Transaction createActivateTransaction(Session session) { Transaction transaction = createSetStatusTransaction(session, Session.Status.ACTIVATE); transaction.add(applicationRepo.createPutTransaction(session.getApplicationId(), session.getSessionId()).operations()); return transaction; } private Transaction createSetStatusTransaction(Session session, Session.Status status) { return session.sessionZooKeeperClient.createWriteStatusTransaction(status); } void setPrepared(Session session) { session.setStatus(Session.Status.PREPARE); } private static class FileTransaction extends AbstractTransaction { public static FileTransaction from(FileOperation operation) { FileTransaction transaction = new FileTransaction(); transaction.add(operation); return transaction; } @Override public void prepare() { } @Override public void commit() { for (Operation operation : operations()) ((FileOperation)operation).commit(); } } /** Factory for file operations */ private static class FileOperations { /** Creates an operation which recursively deletes the given path */ public static DeleteOperation delete(String pathToDelete) { return new DeleteOperation(pathToDelete); } } private interface FileOperation extends Transaction.Operation { void commit(); } /** * Recursively deletes this path and everything below. * Succeeds with no action if the path does not exist. */ private static class DeleteOperation implements FileOperation { private final String pathToDelete; DeleteOperation(String pathToDelete) { this.pathToDelete = pathToDelete; } @Override public void commit() { // TODO: Check delete access in prepare() IOUtils.recursiveDeleteDir(new File(pathToDelete)); } } }
configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.session; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.model.application.provider.DeployData; import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.config.provision.AllocatedHosts; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.TenantName; import com.yahoo.io.IOUtils; import com.yahoo.lang.SettableOptional; import com.yahoo.path.Path; import com.yahoo.transaction.AbstractTransaction; import com.yahoo.transaction.NestedTransaction; import com.yahoo.transaction.Transaction; import com.yahoo.vespa.config.server.GlobalComponentRegistry; import com.yahoo.vespa.config.server.TimeoutBudget; import com.yahoo.vespa.config.server.application.ApplicationSet; import com.yahoo.vespa.config.server.application.TenantApplications; import com.yahoo.vespa.config.server.configchange.ConfigChangeActions; import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs; import com.yahoo.vespa.config.server.filedistribution.FileDirectory; import com.yahoo.vespa.config.server.modelfactory.ActivatedModelsBuilder; import com.yahoo.vespa.config.server.monitoring.MetricUpdater; import com.yahoo.vespa.config.server.monitoring.Metrics; import com.yahoo.vespa.config.server.tenant.TenantRepository; import com.yahoo.vespa.config.server.zookeeper.ConfigCurator; import com.yahoo.vespa.config.server.zookeeper.SessionCounter; import com.yahoo.vespa.curator.Curator; import com.yahoo.vespa.defaults.Defaults; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.zookeeper.KeeperException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * * Session repository for a tenant. Stores session state in zookeeper and file system. There are two * different session types (RemoteSession and LocalSession). * * @author Ulf Lilleengen * @author hmusum * */ public class SessionRepository { private static final Logger log = Logger.getLogger(SessionRepository.class.getName()); private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+"); private static final long nonExistingActiveSessionId = 0; private final Map<Long, LocalSession> localSessionCache = new ConcurrentHashMap<>(); private final Map<Long, RemoteSession> remoteSessionCache = new ConcurrentHashMap<>(); private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>(); private final Duration sessionLifetime; private final Clock clock; private final Curator curator; private final Executor zkWatcherExecutor; private final TenantFileSystemDirs tenantFileSystemDirs; private final MetricUpdater metrics; private final Curator.DirectoryCache directoryCache; private final TenantApplications applicationRepo; private final SessionPreparer sessionPreparer; private final Path sessionsPath; private final TenantName tenantName; private final GlobalComponentRegistry componentRegistry; public SessionRepository(TenantName tenantName, GlobalComponentRegistry componentRegistry, TenantApplications applicationRepo, SessionPreparer sessionPreparer) { this.tenantName = tenantName; this.componentRegistry = componentRegistry; this.sessionsPath = TenantRepository.getSessionsPath(tenantName); this.clock = componentRegistry.getClock(); this.curator = componentRegistry.getCurator(); this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime()); this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command); this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName); this.applicationRepo = applicationRepo; this.sessionPreparer = sessionPreparer; this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName)); loadSessions(); // Needs to be done before creating cache below this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor()); this.directoryCache.addListener(this::childEvent); this.directoryCache.start(); } private void loadSessions() { loadLocalSessions(); loadRemoteSessions(); } // ---------------- Local sessions ---------------------------------------------------------------- public synchronized void addLocalSession(LocalSession session) { long sessionId = session.getSessionId(); localSessionCache.put(sessionId, session); if (remoteSessionCache.get(sessionId) == null) { createRemoteSession(sessionId); } } public LocalSession getLocalSession(long sessionId) { return localSessionCache.get(sessionId); } public Collection<LocalSession> getLocalSessions() { return localSessionCache.values(); } private void loadLocalSessions() { File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter); if (sessions == null) return; for (File session : sessions) { try { createSessionFromId(Long.parseLong(session.getName())); } catch (IllegalArgumentException e) { log.log(Level.WARNING, "Could not load session '" + session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it."); } } } public ConfigChangeActions prepareLocalSession(LocalSession session, DeployLogger logger, PrepareParams params, Path tenantPath, Instant now) { applicationRepo.createApplication(params.getApplicationId()); // TODO jvenstad: This is wrong, but it has to be done now, since preparation can change the application ID of a session :( logger.log(Level.FINE, "Created application " + params.getApplicationId()); long sessionId = session.getSessionId(); SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId); Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter(); Optional<ApplicationSet> activeApplicationSet = getActiveApplicationSet(params.getApplicationId()); ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params, activeApplicationSet, tenantPath, now, getSessionAppDir(sessionId), session.getApplicationPackage(), sessionZooKeeperClient) .getConfigChangeActions(); setPrepared(session); waiter.awaitCompletion(params.getTimeoutBudget().timeLeft()); return actions; } /** * Creates a new deployment session from an already existing session. * * @param existingSession the session to use as base * @param logger a deploy logger where the deploy log will be written. * @param internalRedeploy whether this session is for a system internal redeploy — not an application package change * @param timeoutBudget timeout for creating session and waiting for other servers. * @return a new session */ public LocalSession createSessionFromExisting(Session existingSession, DeployLogger logger, boolean internalRedeploy, TimeoutBudget timeoutBudget) { ApplicationId existingApplicationId = existingSession.getApplicationId(); Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId); logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId); File existingApp = getSessionAppDir(existingSession.getSessionId()); LocalSession session = createSessionFromApplication(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget); // Note: Setters below need to be kept in sync with calls in SessionPreparer.writeStateToZooKeeper() session.setApplicationId(existingApplicationId); session.setApplicationPackageReference(existingSession.getApplicationPackageReference()); session.setVespaVersion(existingSession.getVespaVersion()); session.setDockerImageRepository(existingSession.getDockerImageRepository()); session.setAthenzDomain(existingSession.getAthenzDomain()); return session; } /** * Creates a new deployment session from an application package. * * @param applicationDirectory a File pointing to an application. * @param applicationId application id for this new session. * @param timeoutBudget Timeout for creating session and waiting for other servers. * @return a new session */ public LocalSession createSessionFromApplicationPackage(File applicationDirectory, ApplicationId applicationId, TimeoutBudget timeoutBudget) { applicationRepo.createApplication(applicationId); Optional<Long> activeSessionId = applicationRepo.activeSessionOf(applicationId); return createSessionFromApplication(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget); } /** * This method is used when creating a session based on a remote session and the distributed application package * It does not wait for session being created on other servers */ private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) { try { Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId); ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId, sessionId, currentlyActiveSessionId, false); SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId); return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient); } catch (Exception e) { throw new RuntimeException("Error creating session " + sessionId, e); } } // Will delete session data in ZooKeeper and file system public void deleteLocalSession(LocalSession session) { long sessionId = session.getSessionId(); log.log(Level.FINE, () -> "Deleting local session " + sessionId); SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId); if (watcher != null) watcher.close(); localSessionCache.remove(sessionId); NestedTransaction transaction = new NestedTransaction(); transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath()))); transaction.commit(); } private void deleteAllSessions() { List<LocalSession> sessions = new ArrayList<>(localSessionCache.values()); for (LocalSession session : sessions) { deleteLocalSession(session); } } // ---------------- Remote sessions ---------------------------------------------------------------- public RemoteSession getRemoteSession(long sessionId) { return remoteSessionCache.get(sessionId); } public List<Long> getRemoteSessions() { return getSessionList(curator.getChildren(sessionsPath)); } public synchronized RemoteSession createRemoteSession(long sessionId) { SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient); remoteSessionCache.put(sessionId, session); loadSessionIfActive(session); updateSessionStateWatcher(sessionId, session); return session; } public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) { int deleted = 0; for (long sessionId : getRemoteSessions()) { RemoteSession session = remoteSessionCache.get(sessionId); if (session == null) continue; // Internal sessions not in sync with zk, continue if (session.getStatus() == Session.Status.ACTIVATE) continue; if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) { log.log(Level.FINE, () -> "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it"); deleteRemoteSessionFromZooKeeper(session); deleted++; } } return deleted; } public void deactivateAndUpdateCache(RemoteSession remoteSession) { RemoteSession session = remoteSession.deactivated(); remoteSessionCache.put(session.getSessionId(), session); } public void deleteRemoteSessionFromZooKeeper(RemoteSession session) { SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); Transaction transaction = sessionZooKeeperClient.deleteTransaction(); transaction.commit(); transaction.close(); } private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) { return (created.plus(expiryTime).isBefore(clock.instant())); } private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) { return getSessionList(children.stream() .map(child -> Path.fromString(child.getPath()).getName()) .collect(Collectors.toList())); } private List<Long> getSessionList(List<String> children) { return children.stream().map(Long::parseLong).collect(Collectors.toList()); } private void loadRemoteSessions() throws NumberFormatException { getRemoteSessions().forEach(this::sessionAdded); } /** * A session for which we don't have a watcher, i.e. hitherto unknown to us. * * @param sessionId session id for the new session */ public synchronized void sessionAdded(long sessionId) { log.log(Level.FINE, () -> "Adding remote session " + sessionId); RemoteSession session = createRemoteSession(sessionId); if (session.getStatus() == Session.Status.NEW) { log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId); confirmUpload(session); } createLocalSessionFromDistributedApplicationPackage(sessionId); } void activate(RemoteSession session) { long sessionId = session.getSessionId(); Curator.CompletionWaiter waiter = createSessionZooKeeperClient(sessionId).getActiveWaiter(); log.log(Level.FINE, () -> session.logPre() + "Getting session from repo: " + session); ApplicationSet app = ensureApplicationLoaded(session); log.log(Level.FINE, () -> session.logPre() + "Reloading config for " + sessionId); applicationRepo.reloadConfig(app); log.log(Level.FINE, () -> session.logPre() + "Notifying " + waiter); notifyCompletion(waiter, session); log.log(Level.INFO, session.logPre() + "Session activated: " + sessionId); } public void delete(RemoteSession remoteSession) { long sessionId = remoteSession.getSessionId(); // TODO: Change log level to FINE when debugging is finished log.log(Level.INFO, () -> remoteSession.logPre() + "Deactivating and deleting remote session " + sessionId); deleteRemoteSessionFromZooKeeper(remoteSession); remoteSessionCache.remove(sessionId); LocalSession localSession = getLocalSession(sessionId); if (localSession != null) { // TODO: Change log level to FINE when debugging is finished log.log(Level.INFO, () -> localSession.logPre() + "Deleting local session " + sessionId); deleteLocalSession(localSession); } } private void sessionRemoved(long sessionId) { SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId); if (watcher != null) watcher.close(); remoteSessionCache.remove(sessionId); metrics.incRemovedSessions(); } private void loadSessionIfActive(RemoteSession session) { for (ApplicationId applicationId : applicationRepo.activeApplications()) { if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) { log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it"); applicationRepo.reloadConfig(ensureApplicationLoaded(session)); log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")"); return; } } } void prepareRemoteSession(RemoteSession session) { SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); Curator.CompletionWaiter waiter = sessionZooKeeperClient.getPrepareWaiter(); ensureApplicationLoaded(session); notifyCompletion(waiter, session); } public ApplicationSet ensureApplicationLoaded(RemoteSession session) { if (session.applicationSet().isPresent()) { return session.applicationSet().get(); } ApplicationSet applicationSet = loadApplication(session); RemoteSession activated = session.activated(applicationSet); long sessionId = activated.getSessionId(); remoteSessionCache.put(sessionId, activated); updateSessionStateWatcher(sessionId, activated); return applicationSet; } void confirmUpload(RemoteSession session) { Curator.CompletionWaiter waiter = session.getSessionZooKeeperClient().getUploadWaiter(); long sessionId = session.getSessionId(); log.log(Level.FINE, "Notifying upload waiter for session " + sessionId); notifyCompletion(waiter, session); log.log(Level.FINE, "Done notifying upload for session " + sessionId); } void notifyCompletion(Curator.CompletionWaiter completionWaiter, RemoteSession session) { try { completionWaiter.notifyCompletion(); } catch (RuntimeException e) { // Throw only if we get something else than NoNodeException or NodeExistsException. // NoNodeException might happen when the session is no longer in use (e.g. the app using this session // has been deleted) and this method has not been called yet for the previous session operation on a // minority of the config servers. // NodeExistsException might happen if an event for this node is delivered more than once, in that case // this is a no-op Set<Class<? extends KeeperException>> acceptedExceptions = Set.of(KeeperException.NoNodeException.class, KeeperException.NodeExistsException.class); Class<? extends Throwable> exceptionClass = e.getCause().getClass(); if (acceptedExceptions.contains(exceptionClass)) log.log(Level.FINE, "Not able to notify completion for session " + session.getSessionId() + " (" + completionWaiter + ")," + " node " + (exceptionClass.equals(KeeperException.NoNodeException.class) ? "has been deleted" : "already exists")); else throw e; } } private ApplicationSet loadApplication(RemoteSession session) { log.log(Level.FINE, () -> "Loading application for " + session); SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId()); ApplicationPackage applicationPackage = sessionZooKeeperClient.loadApplicationPackage(); ActivatedModelsBuilder builder = new ActivatedModelsBuilder(session.getTenantName(), session.getSessionId(), sessionZooKeeperClient, componentRegistry); // Read hosts allocated on the config server instance which created this SettableOptional<AllocatedHosts> allocatedHosts = new SettableOptional<>(applicationPackage.getAllocatedHosts()); return ApplicationSet.fromList(builder.buildModels(session.getApplicationId(), sessionZooKeeperClient.readDockerImageRepository(), sessionZooKeeperClient.readVespaVersion(), applicationPackage, allocatedHosts, clock.instant())); } private void nodeChanged() { zkWatcherExecutor.execute(() -> { Multiset<Session.Status> sessionMetrics = HashMultiset.create(); for (RemoteSession session : remoteSessionCache.values()) { sessionMetrics.add(session.getStatus()); } metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW)); metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE)); metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE)); metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE)); }); } @SuppressWarnings("unused") private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) { zkWatcherExecutor.execute(() -> { log.log(Level.FINE, () -> "Got child event: " + event); switch (event.getType()) { case CHILD_ADDED: case CHILD_REMOVED: case CONNECTION_RECONNECTED: sessionsChanged(); break; default: break; } }); } // ---------------- Common stuff ---------------------------------------------------------------- public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) { log.log(Level.FINE, () -> "Purging old sessions for tenant '" + tenantName + "'"); try { for (LocalSession candidate : localSessionCache.values()) { Instant createTime = candidate.getCreateTime(); log.log(Level.FINE, () -> "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime); // Sessions with state other than ACTIVATE if (hasExpired(candidate) && !isActiveSession(candidate)) { deleteLocalSession(candidate); } else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) { // Sessions with state ACTIVATE, but which are not actually active Optional<ApplicationId> applicationId = candidate.getOptionalApplicationId(); if (applicationId.isEmpty()) continue; Long activeSession = activeSessions.get(applicationId.get()); if (activeSession == null || activeSession != candidate.getSessionId()) { deleteLocalSession(candidate); log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " + createTime + " for '" + applicationId + "'"); } } } // Make sure to catch here, to avoid executor just dying in case of issues ... } catch (Throwable e) { log.log(Level.WARNING, "Error when purging old sessions ", e); } log.log(Level.FINE, () -> "Done purging old sessions"); } private boolean hasExpired(LocalSession candidate) { return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant())); } private boolean isActiveSession(LocalSession candidate) { return candidate.getStatus() == Session.Status.ACTIVATE; } private void ensureSessionPathDoesNotExist(long sessionId) { Path sessionPath = getSessionPath(sessionId); if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) { throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper"); } } private ApplicationPackage createApplication(File userDir, File configApplicationDir, ApplicationId applicationId, long sessionId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy) { long deployTimestamp = System.currentTimeMillis(); String user = System.getenv("USER"); if (user == null) { user = "unknown"; } DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp, internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId)); return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData); } private LocalSession createSessionFromApplication(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy, TimeoutBudget timeoutBudget) { long sessionId = getNextSessionId(); try { ensureSessionPathDoesNotExist(sessionId); ApplicationPackage app = createApplicationPackage(applicationFile, applicationId, sessionId, currentlyActiveSessionId, internalRedeploy); log.log(Level.FINE, () -> TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper"); SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); sessionZKClient.createNewSession(clock.instant()); Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter(); LocalSession session = new LocalSession(tenantName, sessionId, app, sessionZKClient); waiter.awaitCompletion(timeoutBudget.timeLeft()); return session; } catch (Exception e) { throw new RuntimeException("Error creating session " + sessionId, e); } } private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId, long sessionId, Optional<Long> currentlyActiveSessionId, boolean internalRedeploy) throws IOException { File userApplicationDir = getSessionAppDir(sessionId); copyApp(applicationFile, userApplicationDir); ApplicationPackage applicationPackage = createApplication(applicationFile, userApplicationDir, applicationId, sessionId, currentlyActiveSessionId, internalRedeploy); applicationPackage.writeMetaData(); return applicationPackage; } public Optional<ApplicationSet> getActiveApplicationSet(ApplicationId appId) { Optional<ApplicationSet> currentActiveApplicationSet = Optional.empty(); try { long currentActiveSessionId = applicationRepo.requireActiveSessionOf(appId); RemoteSession currentActiveSession = getRemoteSession(currentActiveSessionId); currentActiveApplicationSet = Optional.ofNullable(ensureApplicationLoaded(currentActiveSession)); } catch (IllegalArgumentException e) { // Do nothing if we have no currently active session } return currentActiveApplicationSet; } private void copyApp(File sourceDir, File destinationDir) throws IOException { if (destinationDir.exists()) throw new RuntimeException("Destination dir " + destinationDir + " already exists"); if (! sourceDir.isDirectory()) throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory"); // Copy app atomically: Copy to a temp dir and move to destination java.nio.file.Path tempDestinationDir = null; try { tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package"); log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath()); IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile()); log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath()); Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE); } finally { // In case some of the operations above fail if (tempDestinationDir != null) IOUtils.recursiveDeleteDir(tempDestinationDir.toFile()); } } /** * Returns a new session instance for the given session id. */ void createSessionFromId(long sessionId) { File sessionDir = getAndValidateExistingSessionAppDir(sessionId); ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir); createLocalSession(sessionId, applicationPackage); } void createLocalSession(long sessionId, ApplicationPackage applicationPackage) { SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient); addLocalSession(session); } /** * Returns a new local session for the given session id if it does not already exist. * Will also add the session to the local session cache if necessary */ public void createLocalSessionFromDistributedApplicationPackage(long sessionId) { if (applicationRepo.sessionExistsInFileSystem(sessionId)) { log.log(Level.FINE, () -> "Local session for session id " + sessionId + " already exists"); createSessionFromId(sessionId); return; } SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId); FileReference fileReference = sessionZKClient.readApplicationPackageReference(); log.log(Level.FINE, () -> "File reference for session id " + sessionId + ": " + fileReference); if (fileReference != null) { File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir())); File sessionDir; FileDirectory fileDirectory = new FileDirectory(rootDir); try { sessionDir = fileDirectory.getFile(fileReference); } catch (IllegalArgumentException e) { // We cannot be guaranteed that the file reference exists (it could be that it has not // been downloaded yet), and e.g when bootstrapping we cannot throw an exception in that case log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory); return; } ApplicationId applicationId = sessionZKClient.readApplicationId() .orElseThrow(() -> new RuntimeException("Could not find application id for session " + sessionId)); log.log(Level.FINE, () -> "Creating local session for tenant '" + tenantName + "' with session id " + sessionId); LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId); addLocalSession(localSession); } } private Optional<Long> getActiveSessionId(ApplicationId applicationId) { List<ApplicationId> applicationIds = applicationRepo.activeApplications(); return applicationIds.contains(applicationId) ? Optional.of(applicationRepo.requireActiveSessionOf(applicationId)) : Optional.empty(); } private long getNextSessionId() { return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId(); } public Path getSessionPath(long sessionId) { return sessionsPath.append(String.valueOf(sessionId)); } Path getSessionStatePath(long sessionId) { return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH); } private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) { String serverId = componentRegistry.getConfigserverConfig().serverId(); return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), tenantName, sessionId, serverId); } private File getAndValidateExistingSessionAppDir(long sessionId) { File appDir = getSessionAppDir(sessionId); if (!appDir.exists() || !appDir.isDirectory()) { throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId); } return appDir; } private File getSessionAppDir(long sessionId) { return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId); } private void updateSessionStateWatcher(long sessionId, RemoteSession remoteSession) { SessionStateWatcher sessionStateWatcher = sessionStateWatchers.get(sessionId); if (sessionStateWatcher == null) { Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false); fileCache.addListener(this::nodeChanged); sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, remoteSession, metrics, zkWatcherExecutor, this)); } else { sessionStateWatcher.updateRemoteSession(remoteSession); } } @Override public String toString() { return getLocalSessions().toString(); } public Clock clock() { return clock; } public void close() { deleteAllSessions(); tenantFileSystemDirs.delete(); try { if (directoryCache != null) { directoryCache.close(); } } catch (Exception e) { log.log(Level.WARNING, "Exception when closing path cache", e); } finally { checkForRemovedSessions(new ArrayList<>()); } } private synchronized void sessionsChanged() throws NumberFormatException { List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData()); checkForRemovedSessions(sessions); checkForAddedSessions(sessions); } private void checkForRemovedSessions(List<Long> sessions) { for (RemoteSession session : remoteSessionCache.values()) if ( ! sessions.contains(session.getSessionId())) sessionRemoved(session.getSessionId()); } private void checkForAddedSessions(List<Long> sessions) { for (Long sessionId : sessions) if (remoteSessionCache.get(sessionId) == null) sessionAdded(sessionId); } public Transaction createActivateTransaction(Session session) { Transaction transaction = createSetStatusTransaction(session, Session.Status.ACTIVATE); transaction.add(applicationRepo.createPutTransaction(session.getApplicationId(), session.getSessionId()).operations()); return transaction; } private Transaction createSetStatusTransaction(Session session, Session.Status status) { return session.sessionZooKeeperClient.createWriteStatusTransaction(status); } void setPrepared(Session session) { session.setStatus(Session.Status.PREPARE); } private static class FileTransaction extends AbstractTransaction { public static FileTransaction from(FileOperation operation) { FileTransaction transaction = new FileTransaction(); transaction.add(operation); return transaction; } @Override public void prepare() { } @Override public void commit() { for (Operation operation : operations()) ((FileOperation)operation).commit(); } } /** Factory for file operations */ private static class FileOperations { /** Creates an operation which recursively deletes the given path */ public static DeleteOperation delete(String pathToDelete) { return new DeleteOperation(pathToDelete); } } private interface FileOperation extends Transaction.Operation { void commit(); } /** * Recursively deletes this path and everything below. * Succeeds with no action if the path does not exist. */ private static class DeleteOperation implements FileOperation { private final String pathToDelete; DeleteOperation(String pathToDelete) { this.pathToDelete = pathToDelete; } @Override public void commit() { // TODO: Check delete access in prepare() IOUtils.recursiveDeleteDir(new File(pathToDelete)); } } }
Use createLocalSession()
configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java
Use createLocalSession()
Java
bsd-2-clause
21480d418c990882296541d6c26e43166a53f452
0
dzidzitop/ant_modular
/* Copyright (c) 2013, Dźmitry Laŭčuk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package afc.ant.modular; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; public class SerialDependencyResolver implements DependencyResolver { private ArrayList<Module> moduleOrder; private Module moduleAcquired; private int pos; 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."); } } moduleOrder = orderModules(rootModules); pos = 0; 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 (pos == moduleOrder.size()) { return null; } return moduleAcquired = moduleOrder.get(pos); } 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())); } ++pos; moduleAcquired = null; } private void ensureInitialised() { if (moduleOrder == null) { throw new IllegalStateException("Resolver is not initialised."); } } // Returns modules in the order so that each module's dependee modules are located before this module. private static ArrayList<Module> orderModules(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException { final Context ctx = new Context(); for (final Module module : rootModules) { addModuleDeep(module, ctx); } return ctx.moduleOrder; } // Data that is used by addModuleDeep. These objects are the same at each step of the recusion. private static class Context { public final IdentityHashMap<Module, ?> registry = new IdentityHashMap<Module, Object>(); public final LinkedHashSet<Module> path = new LinkedHashSet<Module>(); public final ArrayList<Module> moduleOrder = new ArrayList<Module>(); } /* TODO think if path could be used as an array-based stack and the status of the modules is set as registry module. However, the current implementation shows itself to be slightly faster.*/ private static void addModuleDeep(final Module module, final Context ctx) throws CyclicDependenciesDetectedException { if (ctx.registry.containsKey(module)) { return; // the module is already processed } if (ctx.path.add(module)) { // the dependee modules are added before this module for (int i = 0, n = module.dependencies.size(); i < n; ++i) { final Module dep = module.dependencies.get(i); addModuleDeep(dep, ctx); } ctx.path.remove(module); ctx.registry.put(module, null); ctx.moduleOrder.add(module); return; } /* A loop is detected. It does not necessarily end with the starting node, some leading nodes could be truncated. */ int loopSize = ctx.path.size(); final Iterator<Module> it = ctx.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); } }
src/java/afc/ant/modular/SerialDependencyResolver.java
/* Copyright (c) 2013, Dźmitry Laŭčuk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package afc.ant.modular; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; public class SerialDependencyResolver implements DependencyResolver { private ArrayList<Module> moduleOrder; private Module moduleAcquired; private int pos; 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."); } } moduleOrder = orderModules(rootModules); pos = 0; 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 (pos == moduleOrder.size()) { return null; } return moduleAcquired = moduleOrder.get(pos); } 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())); } ++pos; moduleAcquired = null; } private void ensureInitialised() { if (moduleOrder == null) { throw new IllegalStateException("Resolver is not initialised."); } } // Returns modules in the order so that each module's dependee modules are located before this module. private static ArrayList<Module> orderModules(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException { final IdentityHashMap<Module, ?> registry = new IdentityHashMap<Module, Object>(); final LinkedHashSet<Module> path = new LinkedHashSet<Module>(); final ArrayList<Module> moduleOrder = new ArrayList<Module>(); for (final Module module : rootModules) { addModuleDeep(module, moduleOrder, registry, path); } return moduleOrder; } /* TODO think if path could be used as an array-based stack and the status of the modules is set as registry module. However, the current implementation shows itself to be slightly faster.*/ private static void addModuleDeep(final Module module, final ArrayList<Module> moduleOrder, final IdentityHashMap<Module, ?> registry, final LinkedHashSet<Module> path) throws CyclicDependenciesDetectedException { if (registry.containsKey(module)) { return; // the module is already processed } if (path.add(module)) { // the dependee modules are added before this module for (int i = 0, n = module.dependencies.size(); i < n; ++i) { final Module dep = module.dependencies.get(i); addModuleDeep(dep, moduleOrder, registry, path); } path.remove(module); registry.put(module, null); moduleOrder.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); } }
SerialDependencyResolver: less parameters are passed to #addModuleDeep() so that recusion is more efficient.
src/java/afc/ant/modular/SerialDependencyResolver.java
SerialDependencyResolver: less parameters are passed to #addModuleDeep() so that recusion is more efficient.
Java
bsd-2-clause
2101169c03f9da73604290569467ac0f7562a28a
0
octavianiLocator/g3m,AeroGlass/g3m,octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m,AeroGlass/g3m,octavianiLocator/g3m,octavianiLocator/g3m,octavianiLocator/g3m,AeroGlass/g3m,AeroGlass/g3m,AeroGlass/g3m
package org.glob3.mobile.generated; // // CompositeTileImageContribution.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/26/14. // // // // CompositeTileImageContribution.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/26/14. // // public class CompositeTileImageContribution extends TileImageContribution { public static class ChildContribution { public final int _childIndex; public final TileImageContribution _contribution; public ChildContribution(int childIndex, TileImageContribution contribution) { _childIndex = childIndex; _contribution = contribution; } public void dispose() { TileImageContribution.deleteContribution(_contribution); } } public static TileImageContribution create(java.util.ArrayList<ChildContribution> contributions) { final int contributionsSize = contributions.size(); if (contributionsSize == 0) { //return TileImageContribution::none(); return null; } return new CompositeTileImageContribution(contributions); } private final java.util.ArrayList<ChildContribution> _contributions; private CompositeTileImageContribution(java.util.ArrayList<ChildContribution> contributions) { super(false, 1); _contributions = contributions; } public void dispose() { final int size = _contributions.size(); for (int i = 0; i < size; i++) { final ChildContribution contribution = _contributions.get(i); contribution.dispose(); } } public final int size() { return _contributions.size(); } public final ChildContribution get(int index) { return _contributions.get(index); } }
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/CompositeTileImageContribution.java
package org.glob3.mobile.generated; // // CompositeTileImageContribution.cpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/26/14. // // // // CompositeTileImageContribution.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/26/14. // // public class CompositeTileImageContribution extends TileImageContribution { public static class ChildContribution { public final int _childIndex; public final TileImageContribution _contribution; public ChildContribution(int childIndex, TileImageContribution contribution) { _childIndex = childIndex; _contribution = contribution; } public void dispose() { TileImageContribution.deleteContribution(_contribution); } } public static TileImageContribution create(java.util.ArrayList<ChildContribution> contributions) { final int contributionsSize = contributions.size(); if (contributionsSize == 0) { //return TileImageContribution::none(); return null; } return new CompositeTileImageContribution(contributions); } private final java.util.ArrayList<ChildContribution> _contributions; private CompositeTileImageContribution(java.util.ArrayList<ChildContribution> contributions) { super(false, 1); _contributions = contributions; } public void dispose() { final int size = _contributions.size(); for (int i = 0; i < size; i++) { final ChildContribution contribution = _contributions.get(i); contribution = null; } } public final int size() { return _contributions.size(); } public final ChildContribution get(int index) { return _contributions.get(index); } }
Generated
Commons/G3MSharedSDK/src/org/glob3/mobile/generated/CompositeTileImageContribution.java
Generated
Java
mit
0ae9d6b49ecf4c722d70f36c2f127a79e9935550
0
lasarobotics/FTCVision
package org.lasarobotics.vision.ftc.resq; import org.lasarobotics.vision.util.color.ColorHSV; /** * Res-Q field and object constants */ public abstract class Constants { //BEACON public static double BEACON_WIDTH = 21.8; //entire beacon width public static double BEACON_HEIGHT = 14.5; //entire beacon height public static double BEACON_WH_RATIO = BEACON_WIDTH / BEACON_HEIGHT; //entire beacon ratio public static ColorHSV COLOR_RED_LOWER = new ColorHSV((int) (300.0 / 360.0 * 255.0), (int) (0.090 * 255.0), (int) (0.500 * 255.0)); public static ColorHSV COLOR_RED_UPPER = new ColorHSV((int) (400.0 / 360.0 * 255.0), 255, 255); public static ColorHSV COLOR_BLUE_LOWER = new ColorHSV((int) (170.0 / 360.0 * 255.0), (int) (0.090 * 255.0), (int) (0.500 * 255.0)); public static ColorHSV COLOR_BLUE_UPPER = new ColorHSV((int) (270.0 / 360.0 * 255.0), 255, 255); //FAST static final double ELLIPSE_SCORE_REQ = 10.0; static final double DETECTION_MIN_DISTANCE = 0.1; static final double ELLIPSE_MIN_DISTANCE = 0.3; static final double ELLIPSE_PRESENCE_BIAS = 1.5; static final double FAST_HEIGHT_DELTA_FACTOR = 4.0; static final double FAST_CONFIDENCE_NORM = 5.0; static final double FAST_CONFIDENCE_ROUNDNESS = 2.0; //COMPLEX static final double CONFIDENCE_DIVISOR = 800; static final double CONTOUR_RATIO_BEST = BEACON_WH_RATIO; //best ratio for 100% score static final double CONTOUR_RATIO_NORM = 0.2; //normal distribution variance for ratio static final double CONTOUR_RATIO_BIAS = 3.0; //points given at best ratio static final double CONTOUR_AREA_MIN = Math.log10(0.01); static final double CONTOUR_AREA_MAX = Math.log10(25.00); static final double CONTOUR_AREA_NORM = 0.4; static final double CONTOUR_AREA_BIAS = 6.0; static final double CONTOUR_SCORE_MIN = 1; static final double ELLIPSE_ECCENTRICITY_BEST = 0.4; //best eccentricity for 100% score static final double ELLIPSE_ECCENTRICITY_BIAS = 3.0; //points given at best eccentricity static final double ELLIPSE_ECCENTRICITY_NORM = 0.1; //normal distribution variance for eccentricity static final double ELLIPSE_AREA_MIN = 0.0001; //minimum area as percentage of screen (0 points) static final double ELLIPSE_AREA_MAX = 0.01; //maximum area (0 points given) static final double ELLIPSE_AREA_NORM = 1; static final double ELLIPSE_AREA_BIAS = 2.0; static final double ELLIPSE_CONTRAST_THRESHOLD = 60.0; static final double ELLIPSE_CONTRAST_BIAS = 7.0; static final double ELLIPSE_CONTRAST_NORM = 0.1; static final double ELLIPSE_SCORE_MIN = 1; //minimum score to keep the ellipse - theoretically, should be 1 static final double ASSOCIATION_MAX_DISTANCE = 0.10; //as fraction of screen static final double ASSOCIATION_NO_ELLIPSE_FACTOR = 0.50; static final double ASSOCIATION_ELLIPSE_SCORE_MULTIPLIER = 0.75; }
ftc-visionlib/src/main/java/org/lasarobotics/vision/ftc/resq/Constants.java
package org.lasarobotics.vision.ftc.resq; import org.lasarobotics.vision.util.color.ColorHSV; /** * Res-Q field and object constants */ public abstract class Constants { //FAST static final double ELLIPSE_SCORE_REQ = 10.0; static final double DETECTION_MIN_DISTANCE = 0.1; static final double ELLIPSE_MIN_DISTANCE = 0.3; static final double ELLIPSE_PRESENCE_BIAS = 1.5; static final double FAST_HEIGHT_DELTA_FACTOR = 4.0; static final double FAST_CONFIDENCE_NORM = 5.0; static final double FAST_CONFIDENCE_ROUNDNESS = 2.0; //COMPLEX static final double CONFIDENCE_DIVISOR = 800; static final double CONTOUR_RATIO_NORM = 0.2; //normal distribution variance for ratio static final double CONTOUR_RATIO_BIAS = 3.0; //points given at best ratio static final double CONTOUR_AREA_MIN = Math.log10(0.01); static final double CONTOUR_AREA_MAX = Math.log10(25.00); static final double CONTOUR_AREA_NORM = 0.4; static final double CONTOUR_AREA_BIAS = 6.0; static final double CONTOUR_SCORE_MIN = 1; static final double ELLIPSE_ECCENTRICITY_BEST = 0.4; //best eccentricity for 100% score static final double ELLIPSE_ECCENTRICITY_BIAS = 3.0; //points given at best eccentricity static final double ELLIPSE_ECCENTRICITY_NORM = 0.1; //normal distribution variance for eccentricity static final double ELLIPSE_AREA_MIN = 0.0001; //minimum area as percentage of screen (0 points) static final double ELLIPSE_AREA_MAX = 0.01; //maximum area (0 points given) static final double ELLIPSE_AREA_NORM = 1; static final double ELLIPSE_AREA_BIAS = 2.0; static final double ELLIPSE_CONTRAST_THRESHOLD = 60.0; static final double ELLIPSE_CONTRAST_BIAS = 7.0; static final double ELLIPSE_CONTRAST_NORM = 0.1; static final double ELLIPSE_SCORE_MIN = 1; //minimum score to keep the ellipse - theoretically, should be 1 static final double ASSOCIATION_MAX_DISTANCE = 0.10; //as fraction of screen static final double ASSOCIATION_NO_ELLIPSE_FACTOR = 0.50; static final double ASSOCIATION_ELLIPSE_SCORE_MULTIPLIER = 0.75; //BEACON public static double BEACON_WIDTH = 21.8; //entire beacon width public static double BEACON_HEIGHT = 14.5; //entire beacon height public static double BEACON_WH_RATIO = BEACON_WIDTH / BEACON_HEIGHT; //entire beacon ratio static final double CONTOUR_RATIO_BEST = BEACON_WH_RATIO; //best ratio for 100% score public static ColorHSV COLOR_RED_LOWER = new ColorHSV((int) (300.0 / 360.0 * 255.0), (int) (0.090 * 255.0), (int) (0.500 * 255.0)); public static ColorHSV COLOR_RED_UPPER = new ColorHSV((int) (400.0 / 360.0 * 255.0), 255, 255); public static ColorHSV COLOR_BLUE_LOWER = new ColorHSV((int) (170.0 / 360.0 * 255.0), (int) (0.090 * 255.0), (int) (0.500 * 255.0)); public static ColorHSV COLOR_BLUE_UPPER = new ColorHSV((int) (270.0 / 360.0 * 255.0), 255, 255); }
Reorder constants
ftc-visionlib/src/main/java/org/lasarobotics/vision/ftc/resq/Constants.java
Reorder constants
Java
mit
ac00e9b90504f702b1da9197d8adf16a2cf6313c
0
ultcyber/prk,ultcyber/prk
package task.timer.model; import javax.persistence.*; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; @Entity @Table(name="USERS") public class User extends AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column (name = "login") private String login; @Column (name="firstName") private String firstName; @Column (name="lastName") private String lastName; @Column (name="password") private String password; @Column (name="permissions") private String permissions; //@OneToMany(mappedBy="user") //private Set<User> users; public User(String login, String password, String firstName, String lastName, String permissions) { this.login = login; this.password = password; this.firstName = firstName; this.lastName = lastName; this.permissions = permissions; } public User(int id, String login, String password, String firstName, String lastName, String permissions) { this.id = id; this.login = login; this.password = password; this.firstName = firstName; this.lastName = lastName; this.permissions = permissions; } public User(){ } public int getId() { return id; } public IntegerProperty getIdProperty(){ SimpleIntegerProperty idProperty = new SimpleIntegerProperty(id); return idProperty; } public String getLogin() { return login; } public String getFirstName() { return firstName; } public StringProperty getFirstNameProperty(){ SimpleStringProperty firstNameProperty = new SimpleStringProperty(firstName); return firstNameProperty; } public String getLastName() { return lastName; } public StringProperty getLastNameProperty(){ SimpleStringProperty lastNameProperty = new SimpleStringProperty(lastName); return lastNameProperty; } public String getPassword() { return password; } public String getPermissions() { return permissions; } public void setId(int id) { this.id = id; } public void setLogin(String login) { this.login = login; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setPassword(String password) { this.password = password; } public void setPermissions(String permissions) { this.permissions = permissions; } @Override public boolean equals(Object other){ if (other == this) return true; if (other == null) return false; if (getClass() != other.getClass()) return false; User user = (User) other; return getLogin().equals(user.getLogin()) && getPassword().equals(user.getPassword()) && getFirstName().equals(user.getFirstName()) && getLastName().equals(user.getLastName()) && getPermissions().equals(user.getPermissions()); } @Override public int hashCode(){ return (int) (id*Math.random()*13*lastName.hashCode()); } }
prk/src/main/java/task/timer/model/User.java
package task.timer.model; import javax.persistence.*; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; @Entity @Table(name="USERS") public class User extends AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column (name = "login") private String login; @Column (name="firstName") private String firstName; @Column (name="lastName") private String lastName; @Column (name="password") private String password; @Column (name="permissions") private String permissions; //@OneToMany(mappedBy="user") //private Set<User> users; public User(String login, String password, String firstName, String lastName, String permissions) { this.login = login; this.password = password; this.firstName = firstName; this.lastName = lastName; this.permissions = permissions; } public User(){ } public int getId() { return id; } public IntegerProperty getIdProperty(){ SimpleIntegerProperty idProperty = new SimpleIntegerProperty(id); return idProperty; } public String getLogin() { return login; } public String getFirstName() { return firstName; } public StringProperty getFirstNameProperty(){ SimpleStringProperty firstNameProperty = new SimpleStringProperty(firstName); return firstNameProperty; } public String getLastName() { return lastName; } public StringProperty getLastNameProperty(){ SimpleStringProperty lastNameProperty = new SimpleStringProperty(lastName); return lastNameProperty; } public String getPassword() { return password; } public String getPermissions() { return permissions; } public void setId(int id) { this.id = id; } public void setLogin(String login) { this.login = login; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setPassword(String password) { this.password = password; } public void setPermissions(String permissions) { this.permissions = permissions; } @Override public boolean equals(Object other){ if (other == this) return true; if (other == null) return false; if (getClass() != other.getClass()) return false; User user = (User) other; return getLogin().equals(user.getLogin()) && getPassword().equals(user.getPassword()) && getFirstName().equals(user.getFirstName()) && getLastName().equals(user.getLastName()) && getPermissions().equals(user.getPermissions()); } @Override public int hashCode(){ return (int) (id*Math.random()*13*lastName.hashCode()); } }
add new constructor - with id
prk/src/main/java/task/timer/model/User.java
add new constructor - with id
Java
mit
0cef775570576038f35e370af6c97be0226e0e4a
0
LTTPP/Eemory,prairie/Eemory,LTTPP/Eemory,prairie/Eemory
package com.prairie.eevernote.ui; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.fieldassist.SimpleContentProposalProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import com.prairie.eevernote.Constants; import com.prairie.eevernote.Messages; import com.prairie.eevernote.client.EDAMLimits; import com.prairie.eevernote.client.EEClipper; import com.prairie.eevernote.client.EEClipperFactory; import com.prairie.eevernote.client.ENNote; import com.prairie.eevernote.client.impl.ENNoteImpl; import com.prairie.eevernote.exception.EDAMNotFoundHandler; import com.prairie.eevernote.exception.ThrowableHandler; import com.prairie.eevernote.util.ColorUtil; import com.prairie.eevernote.util.ConstantsUtil; import com.prairie.eevernote.util.EclipseUtil; import com.prairie.eevernote.util.HTMLUtil; import com.prairie.eevernote.util.IDialogSettingsUtil; import com.prairie.eevernote.util.ListUtil; import com.prairie.eevernote.util.MapUtil; import com.prairie.eevernote.util.StringUtil; public class ConfigurationsDialog extends TitleAreaDialog implements Constants { private final Shell shell; private EEClipper globalClipper; private Map<String, String> notebooks; // <Name, Guid> private Map<String, ENNote> notes; // <Name, Guid> private List<String> tags; private SimpleContentProposalProvider notebookProposalProvider; private SimpleContentProposalProvider noteProposalProvider; private SimpleContentProposalProvider tagsProposalProvider; private Map<String, TextField> fields; // <Field Property, <Field Property, Field Value>> private Map<String, Map<String, String>> matrix; // <Field Property, User Input> private Map<String, Boolean> inputMatrix; // <Field Property, Hint Message Property> private Map<String, String> hintPropMap; private boolean canceled = false; public ConfigurationsDialog(final Shell parentShell) { super(parentShell); shell = parentShell; notebooks = MapUtil.map(); notes = MapUtil.map(); tags = ListUtil.list(); globalClipper = EEClipperFactory.getInstance().getEEClipper(); buildHintPropMap(); } @Override public void create() { super.create(); setTitle(getString(PLUGIN_CONFIGS_TITLE)); setMessage(getString(PLUGIN_CONFIGS_MESSAGE), IMessageProvider.NONE); } @Override protected void configureShell(final Shell newShell) { super.configureShell(newShell); newShell.setText(getString(PLUGIN_CONFIGS_SHELL_TITLE)); } @Override protected void setShellStyle(final int newShellStyle) { super.setShellStyle(newShellStyle | SWT.RESIZE); } @Override protected Control createDialogArea(final Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); // container.setLayoutData(new GridData(GridData.FILL_BOTH)); container.setLayout(new GridLayout(1, false)); container.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); // ---------------------- Group groupAuth = new Group(container, SWT.NONE); groupAuth.setText(getString(PLUGIN_CONFIGS_OAUTH)); groupAuth.setLayout(new GridLayout(2, false)); groupAuth.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); TextField tokenField = createLabelHyperlinkTextField(groupAuth, PLUGIN_CONFIGS_TOKEN, EDAM_OAUTH_ADDRESS, Messages.getString(PLUGIN_CONFIGS_CLICKTOAUTH)); addField(PLUGIN_CONFIGS_TOKEN, tokenField); tokenField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { clearHintText(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } }); restoreSettings(PLUGIN_CONFIGS_TOKEN); // ---------------------- Group groupPref = new Group(container, SWT.NONE); groupPref.setText(getString(PLUGIN_CONFIGS_ORGANIZE)); groupPref.setLayout(new GridLayout(2, false)); groupPref.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true)); // ---------------------- // Auth authInProgress(); final LabelCheckTextField notebookField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_NOTEBOOK); notebookField.setTextLimit(EDAMLimits.EDAM_NOTEBOOK_NAME_LEN_MAX); addField(PLUGIN_CONFIGS_NOTEBOOK, notebookField); fetchNotebooksInProgres(); notebookProposalProvider = EclipseUtil.enableFilteringContentAssist(notebookField.getTextControl(), notebooks.keySet().toArray(new String[notebooks.size()])); notebookField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent event) { clearHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); try { if (shouldRefresh(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_TOKEN)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); notebooks = clipper.listNotebooks(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } String[] nbs = notebooks.keySet().toArray(new String[notebooks.size()]); Arrays.sort(nbs); notebookProposalProvider.setProposals(nbs); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); } }); notebookField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (notebookField.isEditable()) { showHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_NOTEBOOK); // ---------------------- final LabelCheckTextField noteField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_NOTE); noteField.setTextLimit(EDAMLimits.EDAM_NOTE_TITLE_LEN_MAX); addField(PLUGIN_CONFIGS_NOTE, noteField); fetchNotesInProgres(); noteProposalProvider = EclipseUtil.enableFilteringContentAssist(noteField.getTextControl(), notes.keySet().toArray(new String[notes.size()])); noteField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { clearHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); if (shouldRefresh(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTEBOOK)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); final String hotebook = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); notes = clipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(notebooks.get(hotebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } String[] ns = notes.keySet().toArray(new String[notes.size()]); Arrays.sort(ns); noteProposalProvider.setProposals(ns); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); } }); noteField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (noteField.isEditable()) { showHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_NOTE); // ---------------------- final LabelCheckTextField tagsField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_TAGS); tagsField.setTextLimit(EDAMLimits.EDAM_TAG_NAME_LEN_MAX); addField(PLUGIN_CONFIGS_TAGS, tagsField); fetchTagsInProgress(); tagsProposalProvider = EclipseUtil.enableFilteringContentAssist(tagsField.getTextControl(), tags.toArray(new String[tags.size()]), TAGS_SEPARATOR); tagsField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent event) { clearHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); try { if (shouldRefresh(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TOKEN)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); tags = clipper.listTags(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } String[] tagArray = tags.toArray(new String[tags.size()]); Arrays.sort(tagArray); tagsProposalProvider.setProposals(tagArray); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); } }); tagsField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (tagsField.isEditable()) { showHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_TAGS); TextField commentsField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_COMMENTS); addField(PLUGIN_CONFIGS_COMMENTS, commentsField); restoreSettings(PLUGIN_CONFIGS_COMMENTS); // ---------------------- postCreateDialogArea(); // ---------------------- return area; } private void buildHintPropMap() { if (hintPropMap == null) { hintPropMap = MapUtil.map(); } hintPropMap.put(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); hintPropMap.put(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); hintPropMap.put(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); hintPropMap.put(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } private void authInProgress() { if (isCanceled()) { return; } final String token = getFieldInput(PLUGIN_CONFIGS_TOKEN); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_AUTHENTICATING), 1); try { globalClipper = EEClipperFactory.getInstance().getEEClipper(token, false); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchNotebooksInProgres() { if (isCanceled()) { return; } try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGNOTEBOOKS), 1); try { notebooks = globalClipper.listNotebooks(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchNotesInProgres() { if (isCanceled()) { return; } final String notebook = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGNOTES), 1); try { notes = globalClipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(notebooks.get(notebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchTagsInProgress() { if (isCanceled()) { return; } try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGTAGS), 1); try { tags = globalClipper.listTags(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } protected void postCreateDialogArea() { for (Entry<String, String> e : hintPropMap.entrySet()) { showHintText(e.getKey(), e.getValue()); } } private void showHintText(final String property, final String hintMsg) { if (getField(property).isEditable() && StringUtils.isBlank(getFieldValue(property))) { getField(property).setForeground(shell.getDisplay().getSystemColor(ColorUtil.SWT_COLOR_GRAY)); setFieldValue(property, getString(hintMsg)); setHasInput(property, false); } else { setHasInput(property, true); } } private void clearHintText(final String property, final String hintMsg) { if (!isHasInput(property)) { setFieldValue(property, StringUtils.EMPTY); // Sets foreground color to the default system color for this control. getField(property).setForeground(null); } } @Override protected void createButtonsForButtonBar(final Composite parent) { createButton(parent, PLUGIN_CONFIGS_REFRESH_ID, getString(PLUGIN_CONFIGS_REFRESH), false); createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @Override protected void buttonPressed(final int buttonId) { if (buttonId == PLUGIN_CONFIGS_REFRESH_ID) { refreshPressed(); } else { super.buttonPressed(buttonId); } } protected void refreshPressed() { authInProgress(); // refresh notebook fetchNotebooksInProgres(); String nbName = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); diagnoseNotebook(nbName); // refresh note nbName = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); fetchNotesInProgres(); String nName = getFieldInput(PLUGIN_CONFIGS_NOTE); diagnoseNote(nName); // refresh tags fetchTagsInProgress(); } private void diagnoseNotebook(final String nbName) { if (!StringUtils.isBlank(nbName)) { if (!notebooks.containsKey(nbName) && notebooks.containsValue(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_GUID))) { // rename case String key = MapUtil.getKey(notebooks, IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_GUID)); if (!StringUtils.isBlank(nbName) && isHasInput(PLUGIN_CONFIGS_NOTEBOOK) && !nbName.equals(key)) { setFieldValue(PLUGIN_CONFIGS_NOTEBOOK, key); } } } } private void diagnoseNote(final String nName) { if (!isOk(nName)) { if (!StringUtils.equals(getFieldInput(PLUGIN_CONFIGS_NOTE), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID))) { // user changed input refreshGuidByName(nName); } else { // user make nothing change, but maybe something changed in Evernote, needs to be synced if (notes.containsValue(ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)))) { // override equals() of ENNote, assume ENNote equals if guid equals refreshNameByGuid(); } else { refreshGuidByName(nName); } } } } // diagnose if everything is fine, nothing needs to change private boolean isOk(final String nName) { return StringUtils.isBlank(nName) || notes.containsKey(nName) && (StringUtils.equals(notes.get(nName).getName(), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_NAME)) || StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_NAME))) && (StringUtils.equals(notes.get(nName).getGuid(), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)) || StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID))); } /* * @param nName uuid of note */ private void refreshGuidByName(final String nName) { // recreate, delete cases ENNote noteFound = EDAMNotFoundHandler.findNote(notes, nName); // NOTICE: pass in uuid here, so should not work for name repetition case if (noteFound != null && !StringUtils.isBlank(noteFound.getGuid())) { notes.put(nName, noteFound); saveNoteSettings(nName); } } private void refreshNameByGuid() { // rename case if (notes.containsValue(ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)))) { // override equals() of ENNote, assume ENNote equals if guid equals String key = MapUtil.getKey(notes, ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID))); // override equals() of ENNote, assume ENNote equals if guid equals if (isHasInput(PLUGIN_CONFIGS_NOTE)) { setFieldValue(PLUGIN_CONFIGS_NOTE, key); saveNoteSettings(key); } } } @Override protected void okPressed() { saveSettings(); super.okPressed(); } @Override protected Point getInitialSize() { return new Point(550, 400); } public static int show(final Shell shell) { ConfigurationsDialog dialog = new ConfigurationsDialog(shell); return dialog.open(); } private boolean shouldRefresh(final String uniqueKey, final String property) { return fieldValueChanged(uniqueKey, property); } private boolean fieldValueChanged(final String uniqueKey, final String property) { if (matrix == null) { matrix = MapUtil.map(); } Map<String, String> map = matrix.get(uniqueKey); if (map == null) { map = MapUtil.map(); matrix.put(uniqueKey, map); } if (!StringUtil.equalsInLogic(getFieldValue(property), map.get(property))) { map.put(property, getFieldValue(property)); return true; } return false; } private void saveSettings() { IDialogSettingsUtil.set(PLUGIN_SETTINGS_KEY_TOKEN, getFieldInput(PLUGIN_CONFIGS_TOKEN)); String notebookValue = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); setSection(PLUGIN_SETTINGS_SECTION_NOTEBOOK, notebookValue, isFieldEditable(PLUGIN_CONFIGS_NOTEBOOK), notebooks.get(notebookValue)); String noteValue = getFieldInput(PLUGIN_CONFIGS_NOTE); diagnoseNote(noteValue); noteValue = getFieldInput(PLUGIN_CONFIGS_NOTE); saveNoteSettings(noteValue); String tagsValue = getFieldInput(PLUGIN_CONFIGS_TAGS); setSection(PLUGIN_SETTINGS_SECTION_TAGS, tagsValue, isFieldEditable(PLUGIN_CONFIGS_TAGS), null); setSection(PLUGIN_SETTINGS_SECTION_COMMENTS, getFieldInput(PLUGIN_CONFIGS_COMMENTS), isFieldEditable(PLUGIN_CONFIGS_COMMENTS), null); } private void saveNoteSettings(final String noteValue) { ENNote note = notes.get(noteValue); setSection(PLUGIN_SETTINGS_SECTION_NOTE, note != null ? note.getName() : null, isFieldEditable(PLUGIN_CONFIGS_NOTE), note != null ? note.getGuid() : null); IDialogSettingsUtil.set(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID, noteValue); } private void restoreSettings(final String label) { if (label.equals(PLUGIN_CONFIGS_TOKEN)) { if (!StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_KEY_TOKEN))) { setFieldValue(PLUGIN_CONFIGS_TOKEN, IDialogSettingsUtil.get(PLUGIN_SETTINGS_KEY_TOKEN)); setHasInput(PLUGIN_CONFIGS_TOKEN, true); } } else if (label.equals(PLUGIN_CONFIGS_NOTEBOOK)) { editableField(PLUGIN_CONFIGS_NOTEBOOK, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_NOTEBOOK) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_NOTEBOOK, value); setHasInput(PLUGIN_CONFIGS_NOTEBOOK, true); } } else if (label.equals(PLUGIN_CONFIGS_NOTE)) { editableField(PLUGIN_CONFIGS_NOTE, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID); if (isFieldEditable(PLUGIN_CONFIGS_NOTE) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_NOTE, value); setHasInput(PLUGIN_CONFIGS_NOTE, true); } } else if (label.equals(PLUGIN_CONFIGS_TAGS)) { editableField(PLUGIN_CONFIGS_TAGS, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_TAGS, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_TAGS, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_TAGS) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_TAGS, value); setHasInput(PLUGIN_CONFIGS_TAGS, true); } } else if (label.equals(PLUGIN_CONFIGS_COMMENTS)) { editableField(PLUGIN_CONFIGS_COMMENTS, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_COMMENTS, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_COMMENTS, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_COMMENTS) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_COMMENTS, value); } } } private void setSection(final String sectionName, final String name, final boolean isChecked, final String guid) { IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_NAME, name); IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_CHECKED, isChecked); IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_GUID, guid); } protected LabelCheckTextField createLabelCheckTextField(final Composite container, final String labelText) { final Button button = new Button(container, SWT.CHECK); button.setText(getString(labelText) + ConstantsUtil.COLON); button.setSelection(true); final Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); text.setEnabled(button.getSelection()); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { if (!button.getSelection()) { text.setText(StringUtils.EMPTY); } text.setEnabled(button.getSelection()); /* * Workaround for Eclipse Bug 193933: Text is not grayed out * when disabled if custom foreground color is set. */ text.setBackground(button.getSelection() ? null : shell.getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_FOREGROUND)); } }); return new LabelCheckTextField(button, text); } protected TextField createLabelTextField(final Composite container, final String labelText) { Label label = new Label(container, SWT.NONE); label.setText(getString(labelText) + ConstantsUtil.COLON); Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); return new LabelTextField(text); } protected TextField createLabelHyperlinkTextField(final Composite container, final String labelText, final String hyperlink, final String tip) { Link link = new Link(container, SWT.NONE); link.setText(HTMLUtil.hyperlink(getString(labelText) + ConstantsUtil.COLON, hyperlink)); link.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { try { // Open default external browser PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(event.text)); } catch (Throwable e) { ThrowableHandler.openError(shell, Messages.getString(PLUGIN_THROWABLE_LINKNOTOPENABLE_MESSAGE)); } } }); link.setToolTipText(tip); Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); return new LabelTextField(text); } protected boolean isFieldEditable(final String property) { TextField f = getField(property); return f != null && f.isEditable(); } protected void editableField(final String property, final boolean check) { TextField f = getField(property); if (f != null) { f.setEditable(check); } } protected String getFieldValue(final String property) { return getField(property).getValue().trim(); } protected String getFieldInput(final String property) { if (hintPropMap.containsKey(property)) { return isHasInput(property) ? getFieldValue(property) : StringUtils.EMPTY; } else { return getFieldValue(property); } } protected void setFieldValue(final String property, final String value) { TextField f = getField(property); if (f != null) { f.setValue(value); } } protected TextField getField(final String property) { if (fields == null) { return null; } return fields.get(property); } protected void addField(final String property, final TextField field) { if (fields == null) { fields = MapUtil.map(); } fields.put(property, field); } protected boolean isHasInput(final String property) { if (inputMatrix == null) { return false; } Boolean has = inputMatrix.get(property); return has == null ? false : has; } protected void setHasInput(final String property, final boolean hasInput) { if (inputMatrix == null) { inputMatrix = MapUtil.map(); } inputMatrix.put(property, hasInput); } protected String getString(final String key) { return Messages.getString(key); } public boolean isCanceled() { return canceled; } public void setCanceled(final boolean canceled) { this.canceled = canceled; } }
com.prairie.eevernote/src/com/prairie/eevernote/ui/ConfigurationsDialog.java
package com.prairie.eevernote.ui; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.fieldassist.SimpleContentProposalProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import com.prairie.eevernote.Constants; import com.prairie.eevernote.Messages; import com.prairie.eevernote.client.EDAMLimits; import com.prairie.eevernote.client.EEClipper; import com.prairie.eevernote.client.EEClipperFactory; import com.prairie.eevernote.client.ENNote; import com.prairie.eevernote.client.impl.ENNoteImpl; import com.prairie.eevernote.exception.EDAMNotFoundHandler; import com.prairie.eevernote.exception.ThrowableHandler; import com.prairie.eevernote.util.ColorUtil; import com.prairie.eevernote.util.ConstantsUtil; import com.prairie.eevernote.util.EclipseUtil; import com.prairie.eevernote.util.HTMLUtil; import com.prairie.eevernote.util.IDialogSettingsUtil; import com.prairie.eevernote.util.ListUtil; import com.prairie.eevernote.util.MapUtil; import com.prairie.eevernote.util.StringUtil; public class ConfigurationsDialog extends TitleAreaDialog implements Constants { private final Shell shell; private EEClipper globalClipper; private Map<String, String> notebooks; // <Name, Guid> private Map<String, ENNote> notes; // <Name, Guid> private List<String> tags; private SimpleContentProposalProvider notebookProposalProvider; private SimpleContentProposalProvider noteProposalProvider; private SimpleContentProposalProvider tagsProposalProvider; private Map<String, TextField> fields; // <Field Property, <Field Property, Field Value>> private Map<String, Map<String, String>> matrix; // <Field Property, User Input> private Map<String, Boolean> inputMatrix; // <Field Property, Hint Message Property> private Map<String, String> hintPropMap; private boolean canceled = false; public ConfigurationsDialog(final Shell parentShell) { super(parentShell); shell = parentShell; notebooks = MapUtil.map(); notes = MapUtil.map(); tags = ListUtil.list(); globalClipper = EEClipperFactory.getInstance().getEEClipper(); buildHintPropMap(); } @Override public void create() { super.create(); setTitle(getString(PLUGIN_CONFIGS_TITLE)); setMessage(getString(PLUGIN_CONFIGS_MESSAGE), IMessageProvider.NONE); } @Override protected void configureShell(final Shell newShell) { super.configureShell(newShell); newShell.setText(getString(PLUGIN_CONFIGS_SHELL_TITLE)); } @Override protected void setShellStyle(final int newShellStyle) { super.setShellStyle(newShellStyle | SWT.RESIZE); } @Override protected Control createDialogArea(final Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); // container.setLayoutData(new GridData(GridData.FILL_BOTH)); container.setLayout(new GridLayout(1, false)); container.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); // ---------------------- Group groupAuth = new Group(container, SWT.NONE); groupAuth.setText(getString(PLUGIN_CONFIGS_OAUTH)); groupAuth.setLayout(new GridLayout(2, false)); groupAuth.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); TextField tokenField = createLabelHyperlinkTextField(groupAuth, PLUGIN_CONFIGS_TOKEN, EDAM_OAUTH_ADDRESS, Messages.getString(PLUGIN_CONFIGS_CLICKTOAUTH)); addField(PLUGIN_CONFIGS_TOKEN, tokenField); tokenField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { clearHintText(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } }); restoreSettings(PLUGIN_CONFIGS_TOKEN); // ---------------------- Group groupPref = new Group(container, SWT.NONE); groupPref.setText(getString(PLUGIN_CONFIGS_ORGANIZE)); groupPref.setLayout(new GridLayout(2, false)); groupPref.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true)); // ---------------------- // Auth authInProgress(); final LabelCheckTextField notebookField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_NOTEBOOK); notebookField.setTextLimit(EDAMLimits.EDAM_NOTEBOOK_NAME_LEN_MAX); addField(PLUGIN_CONFIGS_NOTEBOOK, notebookField); fetchNotebooksInProgres(); notebookProposalProvider = EclipseUtil.enableFilteringContentAssist(notebookField.getTextControl(), notebooks.keySet().toArray(new String[notebooks.size()])); notebookField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent event) { clearHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); try { if (shouldRefresh(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_TOKEN)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); notebooks = clipper.listNotebooks(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } String[] nbs = notebooks.keySet().toArray(new String[notebooks.size()]); Arrays.sort(nbs); notebookProposalProvider.setProposals(nbs); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); } }); notebookField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (notebookField.isEditable()) { showHintText(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_NOTEBOOK); // ---------------------- final LabelCheckTextField noteField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_NOTE); noteField.setTextLimit(EDAMLimits.EDAM_NOTE_TITLE_LEN_MAX); addField(PLUGIN_CONFIGS_NOTE, noteField); fetchNotesInProgres(); noteProposalProvider = EclipseUtil.enableFilteringContentAssist(noteField.getTextControl(), notes.keySet().toArray(new String[notes.size()])); noteField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { clearHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); if (shouldRefresh(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTEBOOK)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); final String hotebook = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); notes = clipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(notebooks.get(hotebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } String[] ns = notes.keySet().toArray(new String[notes.size()]); Arrays.sort(ns); noteProposalProvider.setProposals(ns); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); } }); noteField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (noteField.isEditable()) { showHintText(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_NOTE); // ---------------------- final LabelCheckTextField tagsField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_TAGS); tagsField.setTextLimit(EDAMLimits.EDAM_TAG_NAME_LEN_MAX); addField(PLUGIN_CONFIGS_TAGS, tagsField); fetchTagsInProgress(); tagsProposalProvider = EclipseUtil.enableFilteringContentAssist(tagsField.getTextControl(), tags.toArray(new String[tags.size()]), TAGS_SEPARATOR); tagsField.getTextControl().addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent event) { clearHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); try { if (shouldRefresh(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TOKEN)) { final String hotoken = getFieldInput(PLUGIN_CONFIGS_TOKEN); BusyIndicator.showWhile(Display.getDefault(), new Runnable() { @Override public void run() { EEClipper clipper = null; try { clipper = EEClipperFactory.getInstance().getEEClipper(hotoken, false); tags = clipper.listTags(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, clipper); } } }); } } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } String[] tagArray = tags.toArray(new String[tags.size()]); Arrays.sort(tagArray); tagsProposalProvider.setProposals(tagArray); } @Override public void focusLost(final FocusEvent e) { showHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); } }); tagsField.getCheckControl().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { if (tagsField.isEditable()) { showHintText(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); } } }); restoreSettings(PLUGIN_CONFIGS_TAGS); TextField commentsField = createLabelCheckTextField(groupPref, PLUGIN_CONFIGS_COMMENTS); addField(PLUGIN_CONFIGS_COMMENTS, commentsField); restoreSettings(PLUGIN_CONFIGS_COMMENTS); // ---------------------- postCreateDialogArea(); // ---------------------- return area; } private void buildHintPropMap() { if (hintPropMap == null) { hintPropMap = MapUtil.map(); } hintPropMap.put(PLUGIN_CONFIGS_NOTEBOOK, PLUGIN_CONFIGS_NOTEBOOK_HINT); hintPropMap.put(PLUGIN_CONFIGS_NOTE, PLUGIN_CONFIGS_NOTE_HINT); hintPropMap.put(PLUGIN_CONFIGS_TAGS, PLUGIN_CONFIGS_TAGS_HINT); hintPropMap.put(PLUGIN_CONFIGS_TOKEN, PLUGIN_CONFIGS_TOKEN_HINT); } private void authInProgress() { if (isCanceled()) { return; } final String token = getFieldInput(PLUGIN_CONFIGS_TOKEN); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_AUTHENTICATING), 1); try { globalClipper = EEClipperFactory.getInstance().getEEClipper(token, false); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchNotebooksInProgres() { if (isCanceled()) { return; } try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGNOTEBOOKS), 1); try { notebooks = globalClipper.listNotebooks(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchNotesInProgres() { if (isCanceled()) { return; } final String notebook = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGNOTES), 1); try { notes = globalClipper.listNotesWithinNotebook(ENNoteImpl.forNotebookGuid(notebooks.get(notebook))); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } private void fetchTagsInProgress() { if (isCanceled()) { return; } try { new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) { monitor.beginTask(Messages.getString(PLUGIN_CONFIGS_FETCHINGTAGS), 1); try { tags = globalClipper.listTags(); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e, globalClipper); } setCanceled(monitor.isCanceled()); monitor.done(); } }); } catch (Throwable e) { ThrowableHandler.handleDesignTimeErr(shell, e); } } protected void postCreateDialogArea() { for (Entry<String, String> e : hintPropMap.entrySet()) { showHintText(e.getKey(), e.getValue()); } } private void showHintText(final String property, final String hintMsg) { if (getField(property).isEditable() && StringUtils.isBlank(getFieldValue(property))) { getField(property).setForeground(shell.getDisplay().getSystemColor(ColorUtil.SWT_COLOR_GRAY)); setFieldValue(property, getString(hintMsg)); setHasInput(property, false); } else { setHasInput(property, true); } } private void clearHintText(final String property, final String hintMsg) { if (!isHasInput(property)) { setFieldValue(property, StringUtils.EMPTY); // Sets foreground color to the default system color for this control. getField(property).setForeground(null); } } @Override protected void createButtonsForButtonBar(final Composite parent) { createButton(parent, PLUGIN_CONFIGS_REFRESH_ID, getString(PLUGIN_CONFIGS_REFRESH), false); createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @Override protected void buttonPressed(final int buttonId) { if (buttonId == PLUGIN_CONFIGS_REFRESH_ID) { refreshPressed(); } else { super.buttonPressed(buttonId); } } protected void refreshPressed() { authInProgress(); // refresh notebook fetchNotebooksInProgres(); String nbName = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); diagnoseNotebook(nbName); // refresh note nbName = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); fetchNotesInProgres(); String nName = getFieldInput(PLUGIN_CONFIGS_NOTE); diagnoseNote(nName); // refresh tags fetchTagsInProgress(); } private void diagnoseNotebook(final String nbName) { if (!StringUtils.isBlank(nbName)) { if (!notebooks.containsKey(nbName) && notebooks.containsValue(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_GUID))) { // rename case String key = MapUtil.getKey(notebooks, IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_GUID)); if (!StringUtils.isBlank(nbName) && isHasInput(PLUGIN_CONFIGS_NOTEBOOK) && !nbName.equals(key)) { setFieldValue(PLUGIN_CONFIGS_NOTEBOOK, key); } } } } private void diagnoseNote(final String nName) { if (!isOk(nName)) { if (!StringUtils.equals(getFieldInput(PLUGIN_CONFIGS_NOTE), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID))) { // user changed input refreshGuidByName(nName); } else { // user make nothing change, but maybe something changed in Evernote, needs to be synced if (notes.containsValue(ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)))) { // override equals() of ENNote, assume ENNote equals if guid equals refreshNameByGuid(); } else { refreshGuidByName(nName); } } } } // diagnose if everything is fine, nothing needs to change private boolean isOk(final String nName) { return StringUtils.isBlank(nName) || notes.containsKey(nName) && (StringUtils.equals(notes.get(nName).getName(), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_NAME)) || StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_NAME))) && (StringUtils.equals(notes.get(nName).getGuid(), IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)) || StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID))); } /* * @param nName uuid of note */ private void refreshGuidByName(final String nName) { // recreate, delete cases ENNote noteFound = EDAMNotFoundHandler.findNote(notes, nName); // NOTICE: pass in uuid here, so should not work for duplicate name case if (noteFound != null && !StringUtils.isBlank(noteFound.getGuid())) { notes.put(nName, noteFound); saveNoteSettings(nName); } else { notes.put(nName, null); } } private void refreshNameByGuid() { // rename case if (notes.containsValue(ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID)))) { // override equals() of ENNote, assume ENNote equals if guid equals String key = MapUtil.getKey(notes, ENNoteImpl.forGuid(IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_GUID))); // override equals() of ENNote, assume ENNote equals if guid equals if (isHasInput(PLUGIN_CONFIGS_NOTE)) { setFieldValue(PLUGIN_CONFIGS_NOTE, key); saveNoteSettings(key); } } } @Override protected void okPressed() { saveSettings(); super.okPressed(); } @Override protected Point getInitialSize() { return new Point(550, 400); } public static int show(final Shell shell) { ConfigurationsDialog dialog = new ConfigurationsDialog(shell); return dialog.open(); } private boolean shouldRefresh(final String uniqueKey, final String property) { return fieldValueChanged(uniqueKey, property); } private boolean fieldValueChanged(final String uniqueKey, final String property) { if (matrix == null) { matrix = MapUtil.map(); } Map<String, String> map = matrix.get(uniqueKey); if (map == null) { map = MapUtil.map(); matrix.put(uniqueKey, map); } if (!StringUtil.equalsInLogic(getFieldValue(property), map.get(property))) { map.put(property, getFieldValue(property)); return true; } return false; } private void saveSettings() { IDialogSettingsUtil.set(PLUGIN_SETTINGS_KEY_TOKEN, getFieldInput(PLUGIN_CONFIGS_TOKEN)); String notebookValue = getFieldInput(PLUGIN_CONFIGS_NOTEBOOK); setSection(PLUGIN_SETTINGS_SECTION_NOTEBOOK, notebookValue, isFieldEditable(PLUGIN_CONFIGS_NOTEBOOK), notebooks.get(notebookValue)); String noteValue = getFieldInput(PLUGIN_CONFIGS_NOTE); diagnoseNote(noteValue); noteValue = getFieldInput(PLUGIN_CONFIGS_NOTE); saveNoteSettings(noteValue); String tagsValue = getFieldInput(PLUGIN_CONFIGS_TAGS); setSection(PLUGIN_SETTINGS_SECTION_TAGS, tagsValue, isFieldEditable(PLUGIN_CONFIGS_TAGS), null); setSection(PLUGIN_SETTINGS_SECTION_COMMENTS, getFieldInput(PLUGIN_CONFIGS_COMMENTS), isFieldEditable(PLUGIN_CONFIGS_COMMENTS), null); } private void saveNoteSettings(final String noteValue) { ENNote note = notes.get(noteValue); setSection(PLUGIN_SETTINGS_SECTION_NOTE, note != null ? note.getName() : null, isFieldEditable(PLUGIN_CONFIGS_NOTE), note != null ? note.getGuid() : null); IDialogSettingsUtil.set(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID, noteValue); } private void restoreSettings(final String label) { if (label.equals(PLUGIN_CONFIGS_TOKEN)) { if (!StringUtils.isBlank(IDialogSettingsUtil.get(PLUGIN_SETTINGS_KEY_TOKEN))) { setFieldValue(PLUGIN_CONFIGS_TOKEN, IDialogSettingsUtil.get(PLUGIN_SETTINGS_KEY_TOKEN)); setHasInput(PLUGIN_CONFIGS_TOKEN, true); } } else if (label.equals(PLUGIN_CONFIGS_NOTEBOOK)) { editableField(PLUGIN_CONFIGS_NOTEBOOK, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTEBOOK, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_NOTEBOOK) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_NOTEBOOK, value); setHasInput(PLUGIN_CONFIGS_NOTEBOOK, true); } } else if (label.equals(PLUGIN_CONFIGS_NOTE)) { editableField(PLUGIN_CONFIGS_NOTE, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_NOTE, PLUGIN_SETTINGS_KEY_UUID); if (isFieldEditable(PLUGIN_CONFIGS_NOTE) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_NOTE, value); setHasInput(PLUGIN_CONFIGS_NOTE, true); } } else if (label.equals(PLUGIN_CONFIGS_TAGS)) { editableField(PLUGIN_CONFIGS_TAGS, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_TAGS, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_TAGS, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_TAGS) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_TAGS, value); setHasInput(PLUGIN_CONFIGS_TAGS, true); } } else if (label.equals(PLUGIN_CONFIGS_COMMENTS)) { editableField(PLUGIN_CONFIGS_COMMENTS, IDialogSettingsUtil.getBoolean(PLUGIN_SETTINGS_SECTION_COMMENTS, PLUGIN_SETTINGS_KEY_CHECKED)); String value = IDialogSettingsUtil.get(PLUGIN_SETTINGS_SECTION_COMMENTS, PLUGIN_SETTINGS_KEY_NAME); if (isFieldEditable(PLUGIN_CONFIGS_COMMENTS) && !StringUtils.isBlank(value)) { setFieldValue(PLUGIN_CONFIGS_COMMENTS, value); } } } private void setSection(final String sectionName, final String name, final boolean isChecked, final String guid) { IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_NAME, name); IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_CHECKED, isChecked); IDialogSettingsUtil.set(sectionName, PLUGIN_SETTINGS_KEY_GUID, guid); } protected LabelCheckTextField createLabelCheckTextField(final Composite container, final String labelText) { final Button button = new Button(container, SWT.CHECK); button.setText(getString(labelText) + ConstantsUtil.COLON); button.setSelection(true); final Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); text.setEnabled(button.getSelection()); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { if (!button.getSelection()) { text.setText(StringUtils.EMPTY); } text.setEnabled(button.getSelection()); /* * Workaround for Eclipse Bug 193933: Text is not grayed out * when disabled if custom foreground color is set. */ text.setBackground(button.getSelection() ? null : shell.getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_FOREGROUND)); } }); return new LabelCheckTextField(button, text); } protected TextField createLabelTextField(final Composite container, final String labelText) { Label label = new Label(container, SWT.NONE); label.setText(getString(labelText) + ConstantsUtil.COLON); Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); return new LabelTextField(text); } protected TextField createLabelHyperlinkTextField(final Composite container, final String labelText, final String hyperlink, final String tip) { Link link = new Link(container, SWT.NONE); link.setText(HTMLUtil.hyperlink(getString(labelText) + ConstantsUtil.COLON, hyperlink)); link.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent event) { try { // Open default external browser PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(event.text)); } catch (Throwable e) { ThrowableHandler.openError(shell, Messages.getString(PLUGIN_THROWABLE_LINKNOTOPENABLE_MESSAGE)); } } }); link.setToolTipText(tip); Text text = new Text(container, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false)); return new LabelTextField(text); } protected boolean isFieldEditable(final String property) { TextField f = getField(property); return f != null && f.isEditable(); } protected void editableField(final String property, final boolean check) { TextField f = getField(property); if (f != null) { f.setEditable(check); } } protected String getFieldValue(final String property) { return getField(property).getValue().trim(); } protected String getFieldInput(final String property) { if (hintPropMap.containsKey(property)) { return isHasInput(property) ? getFieldValue(property) : StringUtils.EMPTY; } else { return getFieldValue(property); } } protected void setFieldValue(final String property, final String value) { TextField f = getField(property); if (f != null) { f.setValue(value); } } protected TextField getField(final String property) { if (fields == null) { return null; } return fields.get(property); } protected void addField(final String property, final TextField field) { if (fields == null) { fields = MapUtil.map(); } fields.put(property, field); } protected boolean isHasInput(final String property) { if (inputMatrix == null) { return false; } Boolean has = inputMatrix.get(property); return has == null ? false : has; } protected void setHasInput(final String property, final boolean hasInput) { if (inputMatrix == null) { inputMatrix = MapUtil.map(); } inputMatrix.put(property, hasInput); } protected String getString(final String key) { return Messages.getString(key); } public boolean isCanceled() { return canceled; } public void setCanceled(final boolean canceled) { this.canceled = canceled; } }
revert change 2984f30304879cd928542049ac0d106a1a468fc9
com.prairie.eevernote/src/com/prairie/eevernote/ui/ConfigurationsDialog.java
revert change 2984f30304879cd928542049ac0d106a1a468fc9
Java
mit
d47a3142e9153afc47fdc3eab047f620f7b96467
0
issei-m/idea-php-symfony2-plugin,issei-m/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin,gencer/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin,gencer/idea-php-symfony2-plugin,gencer/idea-php-symfony2-plugin,issei-m/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin,issei-m/idea-php-symfony2-plugin,gencer/idea-php-symfony2-plugin,Haehnchen/idea-php-symfony2-plugin
package fr.adrienbrault.idea.symfony2plugin.config; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.psi.elements.*; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons; import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil; import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent; import fr.adrienbrault.idea.symfony2plugin.dic.XmlServiceParser; import fr.adrienbrault.idea.symfony2plugin.form.util.FormUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import fr.adrienbrault.idea.symfony2plugin.stubs.ServiceIndexUtil; import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class ServiceLineMarkerProvider extends RelatedItemLineMarkerProvider { protected void collectNavigationMarkers(@NotNull PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { if(!Symfony2ProjectComponent.isEnabled(psiElement)) { return; } if(PhpElementsUtil.getClassNamePattern().accepts(psiElement)) { this.classNameMarker(psiElement, result); } if(psiElement instanceof StringLiteralExpression && PhpElementsUtil.getMethodReturnPattern().accepts(psiElement)) { this.formNameMarker(psiElement, result); } if (!Settings.getInstance(psiElement.getProject()).phpHighlightServices || !(psiElement instanceof StringLiteralExpression) || !(psiElement.getContext() instanceof ParameterList)) { return; } ParameterList parameterList = (ParameterList) psiElement.getContext(); if (parameterList == null || !(parameterList.getContext() instanceof MethodReference)) { return; } MethodReference method = (MethodReference) parameterList.getContext(); if(!new Symfony2InterfacesUtil().isContainerGetCall(method)) { return; } String serviceId = ((StringLiteralExpression) psiElement).getContents(); String serviceClass = ServiceXmlParserFactory.getInstance(psiElement.getProject(), XmlServiceParser.class).getServiceMap().getMap().get(serviceId.toLowerCase()); if (null == serviceClass) { return; } PsiElement[] resolveResults = PhpElementsUtil.getClassInterfacePsiElements(psiElement.getProject(), serviceClass); if(resolveResults.length == 0) { return; } NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SERVICE_LINE_MARKER). setTargets(resolveResults). setTooltipText("Navigate to service"); result.add(builder.createLineMarkerInfo(psiElement)); } private void classNameMarker(PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { PsiElement phpClassContext = psiElement.getContext(); if(!(phpClassContext instanceof PhpClass)) { return; } PsiElement[] psiElements = ServiceIndexUtil.findServiceDefinitions((PhpClass) phpClassContext); if(psiElements.length == 0) { return; } NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SERVICE_LINE_MARKER). setTargets(psiElements). setTooltipText("Navigate to definition"); result.add(builder.createLineMarkerInfo(psiElement)); } private void formNameMarker(PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { Method method = PsiTreeUtil.getParentOfType(psiElement, Method.class); if(method == null) { return; } if(new Symfony2InterfacesUtil().isCallTo(method, "\\Symfony\\Component\\Form\\FormTypeInterface", "getParent")) { PsiElement psiElement1 = FormUtil.getFormTypeToClass(psiElement.getProject(), ((StringLiteralExpression) psiElement).getContents()); if(psiElement1 != null) { NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.FORM_TYPE_LINE_MARKER). setTargets(psiElement1). setTooltipText("Navigate to form type"); result.add(builder.createLineMarkerInfo(psiElement)); } } } }
src/fr/adrienbrault/idea/symfony2plugin/config/ServiceLineMarkerProvider.java
package fr.adrienbrault.idea.symfony2plugin.config; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.psi.elements.*; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons; import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil; import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent; import fr.adrienbrault.idea.symfony2plugin.dic.XmlServiceParser; import fr.adrienbrault.idea.symfony2plugin.form.util.FormUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import fr.adrienbrault.idea.symfony2plugin.stubs.ServiceIndexUtil; import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class ServiceLineMarkerProvider extends RelatedItemLineMarkerProvider { protected void collectNavigationMarkers(@NotNull PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { if(!Symfony2ProjectComponent.isEnabled(psiElement)) { return; } if(PhpElementsUtil.getClassNamePattern().accepts(psiElement)) { this.classNameMarker(psiElement, result); } if(psiElement instanceof StringLiteralExpression && PhpElementsUtil.getMethodReturnPattern().accepts(psiElement)) { this.formNameMarker(psiElement, result); } if (!Settings.getInstance(psiElement.getProject()).phpHighlightServices || !(psiElement instanceof StringLiteralExpression) || !(psiElement.getContext() instanceof ParameterList)) { return; } ParameterList parameterList = (ParameterList) psiElement.getContext(); if (parameterList == null || !(parameterList.getContext() instanceof MethodReference)) { return; } MethodReference method = (MethodReference) parameterList.getContext(); if(!new Symfony2InterfacesUtil().isContainerGetCall(method)) { return; } String serviceId = ((StringLiteralExpression) psiElement).getContents(); String serviceClass = ServiceXmlParserFactory.getInstance(psiElement.getProject(), XmlServiceParser.class).getServiceMap().getMap().get(serviceId.toLowerCase()); if (null == serviceClass) { return; } PsiElement[] resolveResults = PhpElementsUtil.getClassInterfacePsiElements(psiElement.getProject(), serviceClass); if(resolveResults.length == 0) { return; } NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SERVICE_LINE_MARKER). setTargets(resolveResults). setTooltipText("Navigate to service"); result.add(builder.createLineMarkerInfo(psiElement)); } private void classNameMarker(PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { PsiElement[] psiElements = ServiceIndexUtil.findServiceDefinitions((PhpClass) psiElement.getContext()); if(psiElements.length == 0) { return; } NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SERVICE_LINE_MARKER). setTargets(psiElements). setTooltipText("Navigate to definition"); result.add(builder.createLineMarkerInfo(psiElement)); } private void formNameMarker(PsiElement psiElement, Collection<? super RelatedItemLineMarkerInfo> result) { Method method = PsiTreeUtil.getParentOfType(psiElement, Method.class); if(method == null) { return; } if(new Symfony2InterfacesUtil().isCallTo(method, "\\Symfony\\Component\\Form\\FormTypeInterface", "getParent")) { PsiElement psiElement1 = FormUtil.getFormTypeToClass(psiElement.getProject(), ((StringLiteralExpression) psiElement).getContents()); if(psiElement1 != null) { NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.FORM_TYPE_LINE_MARKER). setTargets(psiElement1). setTooltipText("Navigate to form type"); result.add(builder.createLineMarkerInfo(psiElement)); } } } }
service line marker double check null value #198
src/fr/adrienbrault/idea/symfony2plugin/config/ServiceLineMarkerProvider.java
service line marker double check null value #198
Java
mpl-2.0
d22d7882d0cc2b0a8d73188d6634986fa9c7043e
0
tuchida/rhino,tuchida/rhino,tuchida/rhino,tuchida/rhino,tuchida/rhino,tuchida/rhino,tuchida/rhino
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // API class package org.mozilla.javascript; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Closeable; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.UnaryOperator; import org.mozilla.classfile.ClassFileWriter.ClassFileFormatException; import org.mozilla.javascript.ast.AstRoot; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.javascript.debug.DebuggableScript; import org.mozilla.javascript.debug.Debugger; import org.mozilla.javascript.xml.XMLLib; /** * This class represents the runtime context of an executing script. * * <p>Before executing a script, an instance of Context must be created and associated with the * thread that will be executing the script. The Context will be used to store information about the * executing of the script such as the call stack. Contexts are associated with the current thread * using the {@link #call(ContextAction)} or {@link #enter()} methods. * * <p>Different forms of script execution are supported. Scripts may be evaluated from the source * directly, or first compiled and then later executed. Interactive execution is also supported. * * <p>Some aspects of script execution, such as type conversions and object creation, may be * accessed directly through methods of Context. * * @see Scriptable * @author Norris Boyd * @author Brendan Eich */ public class Context implements Closeable { /** * Language versions. * * <p>All integral values are reserved for future version numbers. */ /** * The unknown version. * * <p>Be aware, this version will not support many of the newer language features and will not * change in the future. * * <p>Please use one of the other constants like VERSION_ES6 to get support for recent language * features. */ public static final int VERSION_UNKNOWN = -1; /** The default version. */ public static final int VERSION_DEFAULT = 0; /** JavaScript 1.0 */ public static final int VERSION_1_0 = 100; /** JavaScript 1.1 */ public static final int VERSION_1_1 = 110; /** JavaScript 1.2 */ public static final int VERSION_1_2 = 120; /** JavaScript 1.3 */ public static final int VERSION_1_3 = 130; /** JavaScript 1.4 */ public static final int VERSION_1_4 = 140; /** JavaScript 1.5 */ public static final int VERSION_1_5 = 150; /** JavaScript 1.6 */ public static final int VERSION_1_6 = 160; /** JavaScript 1.7 */ public static final int VERSION_1_7 = 170; /** JavaScript 1.8 */ public static final int VERSION_1_8 = 180; /** ECMAScript 6. */ public static final int VERSION_ES6 = 200; /** * Controls behaviour of <code>Date.prototype.getYear()</code>. If <code> * hasFeature(FEATURE_NON_ECMA_GET_YEAR)</code> returns true, Date.prototype.getYear subtructs * 1900 only if 1900 &lt;= date &lt; 2000. The default behavior of {@link #hasFeature(int)} is * always to subtruct 1900 as rquired by ECMAScript B.2.4. */ public static final int FEATURE_NON_ECMA_GET_YEAR = 1; /** * Control if member expression as function name extension is available. If <code> * hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)</code> returns true, allow <code> * function memberExpression(args) { body }</code> to be syntax sugar for <code> * memberExpression = function(args) { body }</code>, when memberExpression is not a simple * identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By default * {@link #hasFeature(int)} returns false. */ public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2; /** * Control if reserved keywords are treated as identifiers. If <code> * hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)</code> returns true, treat future reserved keyword * (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage. * * <p>By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3; /** * Control if <code>toString()</code> should returns the same result as <code>toSource()</code> * when applied to objects and arrays. If <code>hasFeature(FEATURE_TO_STRING_AS_SOURCE)</code> * returns true, calling <code>toString()</code> on JS objects gives the same result as calling * <code>toSource()</code>. That is it returns JS source with code to create an object with all * enumeratable fields of the original object instead of printing <code>[object <i>result of * {@link Scriptable#getClassName()}</i>]</code>. * * <p>By default {@link #hasFeature(int)} returns true only if the current JS version is set to * {@link #VERSION_1_2}. */ public static final int FEATURE_TO_STRING_AS_SOURCE = 4; /** * Control if properties <code>__proto__</code> and <code>__parent__</code> are treated * specially. If <code>hasFeature(FEATURE_PARENT_PROTO_PROPERTIES)</code> returns true, treat * <code>__parent__</code> and <code>__proto__</code> as special properties. * * <p>The properties allow to query and set scope and prototype chains for the objects. The * special meaning of the properties is available only when they are used as the right hand side * of the dot operator. For example, while <code>x.__proto__ = y</code> changes the prototype * chain of the object <code>x</code> to point to <code>y</code>, <code>x["__proto__"] = y * </code> simply assigns a new value to the property <code>__proto__</code> in <code>x</code> * even when the feature is on. * * <p>By default {@link #hasFeature(int)} returns true. */ public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5; /** @deprecated In previous releases, this name was given to FEATURE_PARENT_PROTO_PROPERTIES. */ @Deprecated public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5; /** * Control if support for E4X(ECMAScript for XML) extension is available. If * hasFeature(FEATURE_E4X) returns true, the XML syntax is available. * * <p>By default {@link #hasFeature(int)} returns true if the current JS version is set to * {@link #VERSION_DEFAULT} or is at least {@link #VERSION_1_6}. * * @since 1.6 Release 1 */ public static final int FEATURE_E4X = 6; /** * Control if dynamic scope should be used for name access. If hasFeature(FEATURE_DYNAMIC_SCOPE) * returns true, then the name lookup during name resolution will use the top scope of the * script or function which is at the top of JS execution stack instead of the top scope of the * script or function from the current stack frame if the top scope of the top stack frame * contains the top scope of the current stack frame on its prototype chain. * * <p>This is useful to define shared scope containing functions that can be called from scripts * and functions using private scopes. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_DYNAMIC_SCOPE = 7; /** * Control if strict variable mode is enabled. When the feature is on Rhino reports runtime * errors if assignment to a global variable that does not exist is executed. When the feature * is off such assignments create a new variable in the global scope as required by ECMA 262. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_VARS = 8; /** * Control if strict eval mode is enabled. When the feature is on Rhino reports runtime errors * if non-string argument is passed to the eval function. When the feature is off eval simply * return non-string argument as is without performing any evaluation as required by ECMA 262. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_EVAL = 9; /** * When the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error * objects automatically. When the feature is off, you have to explicitly pass them as the * second and third argument to the Error constructor. Note that neither behavior is fully ECMA * 262 compliant (as 262 doesn't specify a three-arg constructor), but keeping the feature off * results in Error objects that don't have additional non-ECMA properties when constructed * using the ECMA-defined single-arg constructor and is thus desirable if a stricter ECMA * compliance is desired, specifically adherence to the point 15.11.5. of the standard. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 6 */ public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10; /** * Controls whether JS 1.5 'strict mode' is enabled. When the feature is on, Rhino reports more * than a dozen different warnings. When the feature is off, these warnings are not generated. * FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 6 */ public static final int FEATURE_STRICT_MODE = 11; /** * Controls whether a warning should be treated as an error. * * @since 1.6 Release 6 */ public static final int FEATURE_WARNING_AS_ERROR = 12; /** * Enables enhanced access to Java. Specifically, controls whether private and protected members * can be accessed, and whether scripts can catch all Java exceptions. * * <p>Note that this feature should only be enabled for trusted scripts. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.7 Release 1 */ public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13; /** * Enables access to JavaScript features from ECMAscript 6 that are present in JavaScript * engines that do not yet support version 6, such as V8. This includes support for typed * arrays. Default is true. * * @since 1.7 Release 3 */ public static final int FEATURE_V8_EXTENSIONS = 14; /** * Defines how an undefined "this" parameter is handled in certain calls. Previously Rhino would * convert an undefined "this" to null, whereas recent specs call for it to be treated * differently. Default is to be set if language version &lt;= 1.7. * * @since 1.7.7 */ public static final int FEATURE_OLD_UNDEF_NULL_THIS = 15; /** * If set, then the order of property key enumeration will be first numeric keys in numeric * order, followed by string keys in order of creation, and finally Symbol keys, as specified in * ES6. Default is true for language version &gt;= "ES6" and false otherwise. * * @since 1.7.7.1 */ public static final int FEATURE_ENUMERATE_IDS_FIRST = 16; /** * If set, then all objects will have a thread-safe property map. (Note that this doesn't make * everything else that they do thread-safe -- that depends on the specific implementation. If * not set, users should not share Rhino objects between threads, unless the "sync" function is * used to wrap them with an explicit synchronizer. The default is false, which means that by * default, individual objects are not thread-safe. * * @since 1.7.8 */ public static final int FEATURE_THREAD_SAFE_OBJECTS = 17; /** * If set, then all integer numbers will be returned without decimal place. For instance assume * there is a function like this: <code>function foo() {return 5;}</code> 5 will be returned if * feature is set, 5.0 otherwise. */ public static final int FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE = 18; /** * TypedArray buffer uses little/big endian depending on the platform. The default is big endian * for Rhino. * * @since 1.7 Release 11 */ public static final int FEATURE_LITTLE_ENDIAN = 19; /** * Configure the XMLProcessor to parse XML with security features or not. Security features * include not fetching remote entity references and disabling XIncludes * * @since 1.7 Release 12 */ public static final int FEATURE_ENABLE_XML_SECURE_PARSING = 20; /** * Configure whether the entries in a Java Map can be accessed by properties. * * <p>Not enabled: * * <p>var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // undefined * * <p>Enabled: * * <p>var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // 1 * * <p>WARNING: This feature is similar to the one in Nashorn, but incomplete. * * <p>1. A entry has priority over method. * * <p>map.put("put", "abc"); map.put; // abc map.put("put", "efg"); // ERROR * * <p>2. The distinction between numeric keys and string keys is ambiguous. * * <p>map.put('1', 123); map['1']; // Not found. This means `map[1]`. * * @since 1.7 Release 14 */ public static final int FEATURE_ENABLE_JAVA_MAP_ACCESS = 21; public static final String languageVersionProperty = "language version"; public static final String errorReporterProperty = "error reporter"; /** Convenient value to use as zero-length array of objects. */ public static final Object[] emptyArgs = ScriptRuntime.emptyArgs; /** * Creates a new Context. The context will be associated with the {@link * ContextFactory#getGlobal() global context factory}. * * <p>Note that the Context must be associated with a thread before it can be used to execute a * script. * * @deprecated this constructor is deprecated because it creates a dependency on a static * singleton context factory. Use {@link ContextFactory#enter()} or {@link * ContextFactory#call(ContextAction)} instead. If you subclass this class, consider using * {@link #Context(ContextFactory)} constructor instead in the subclasses' constructors. */ @Deprecated public Context() { this(ContextFactory.getGlobal()); } /** * Creates a new context. Provided as a preferred super constructor for subclasses in place of * the deprecated default public constructor. * * @param factory the context factory associated with this context (most likely, the one that * created the context). Can not be null. The context features are inherited from the * factory, and the context will also otherwise use its factory's services. * @throws IllegalArgumentException if factory parameter is null. */ protected Context(ContextFactory factory) { if (factory == null) { throw new IllegalArgumentException("factory == null"); } this.factory = factory; version = VERSION_DEFAULT; optimizationLevel = codegenClass != null ? 0 : -1; maximumInterpreterStackDepth = Integer.MAX_VALUE; } /** * Get the current Context. * * <p>The current Context is per-thread; this method looks up the Context associated with the * current thread. * * <p> * * @return the Context associated with the current thread, or null if no context is associated * with the current thread. * @see ContextFactory#enterContext() * @see ContextFactory#call(ContextAction) */ public static Context getCurrentContext() { Object helper = VMBridge.instance.getThreadContextHelper(); return VMBridge.instance.getContext(helper); } /** * Same as calling {@link ContextFactory#enterContext()} on the global ContextFactory instance. * * @return a Context associated with the current thread * @see #getCurrentContext() * @see #exit() * @see #call(ContextAction) */ public static Context enter() { return enter(null, ContextFactory.getGlobal()); } /** * Get a Context associated with the current thread, using the given Context if need be. * * <p>The same as <code>enter()</code> except that <code>cx</code> is associated with the * current thread and returned if the current thread has no associated context and <code>cx * </code> is not associated with any other thread. * * @param cx a Context to associate with the thread if possible * @return a Context associated with the current thread * @deprecated use {@link ContextFactory#enterContext(Context)} instead as this method relies on * usage of a static singleton "global" ContextFactory. * @see ContextFactory#enterContext(Context) * @see ContextFactory#call(ContextAction) */ @Deprecated public static Context enter(Context cx) { return enter(cx, ContextFactory.getGlobal()); } static final Context enter(Context cx, ContextFactory factory) { Object helper = VMBridge.instance.getThreadContextHelper(); Context old = VMBridge.instance.getContext(helper); if (old != null) { cx = old; } else { if (cx == null) { cx = factory.makeContext(); if (cx.enterCount != 0) { throw new IllegalStateException( "factory.makeContext() returned Context instance already associated with some thread"); } factory.onContextCreated(cx); if (factory.isSealed() && !cx.isSealed()) { cx.seal(null); } } else { if (cx.enterCount != 0) { throw new IllegalStateException( "can not use Context instance already associated with some thread"); } } VMBridge.instance.setContext(helper, cx); } ++cx.enterCount; return cx; } /** * Exit a block of code requiring a Context. * * <p>Calling <code>exit()</code> will remove the association between the current thread and a * Context if the prior call to {@link ContextFactory#enterContext()} on this thread newly * associated a Context with this thread. Once the current thread no longer has an associated * Context, it cannot be used to execute JavaScript until it is again associated with a Context. * * @see ContextFactory#enterContext() */ public static void exit() { Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx == null) { throw new IllegalStateException("Calling Context.exit without previous Context.enter"); } if (cx.enterCount < 1) Kit.codeBug(); if (--cx.enterCount == 0) { VMBridge.instance.setContext(helper, null); cx.factory.onContextReleased(cx); } } @Override public void close() { exit(); } /** * Call {@link ContextAction#run(Context cx)} using the Context instance associated with the * current thread. If no Context is associated with the thread, then <code> * ContextFactory.getGlobal().makeContext()</code> will be called to construct new Context * instance. The instance will be temporary associated with the thread during call to {@link * ContextAction#run(Context)}. * * @deprecated use {@link ContextFactory#call(ContextAction)} instead as this method relies on * usage of a static singleton "global" ContextFactory. * @return The result of {@link ContextAction#run(Context)}. */ @Deprecated public static <T> T call(ContextAction<T> action) { return call(ContextFactory.getGlobal(), action); } /** * Call {@link Callable#call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)} * using the Context instance associated with the current thread. If no Context is associated * with the thread, then {@link ContextFactory#makeContext()} will be called to construct new * Context instance. The instance will be temporary associated with the thread during call to * {@link ContextAction#run(Context)}. * * <p>It is allowed but not advisable to use null for <code>factory</code> argument in which * case the global static singleton ContextFactory instance will be used to create new context * instances. * * @see ContextFactory#call(ContextAction) */ public static Object call( ContextFactory factory, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if (factory == null) { factory = ContextFactory.getGlobal(); } return call(factory, cx -> callable.call(cx, scope, thisObj, args)); } /** The method implements {@link ContextFactory#call(ContextAction)} logic. */ static <T> T call(ContextFactory factory, ContextAction<T> action) { Context cx = enter(null, factory); try { return action.run(cx); } finally { exit(); } } /** * @deprecated * @see ContextFactory#addListener(org.mozilla.javascript.ContextFactory.Listener) * @see ContextFactory#getGlobal() */ @Deprecated public static void addContextListener(ContextListener listener) { // Special workaround for the debugger String DBG = "org.mozilla.javascript.tools.debugger.Main"; if (DBG.equals(listener.getClass().getName())) { Class<?> cl = listener.getClass(); Class<?> factoryClass = Kit.classOrNull("org.mozilla.javascript.ContextFactory"); Class<?>[] sig = {factoryClass}; Object[] args = {ContextFactory.getGlobal()}; try { Method m = cl.getMethod("attachTo", sig); m.invoke(listener, args); } catch (Exception ex) { throw new RuntimeException(ex); } return; } ContextFactory.getGlobal().addListener(listener); } /** * @deprecated * @see ContextFactory#removeListener(org.mozilla.javascript.ContextFactory.Listener) * @see ContextFactory#getGlobal() */ @Deprecated public static void removeContextListener(ContextListener listener) { ContextFactory.getGlobal().addListener(listener); } /** Return {@link ContextFactory} instance used to create this Context. */ public final ContextFactory getFactory() { return factory; } /** * Checks if this is a sealed Context. A sealed Context instance does not allow to modify any of * its properties and will throw an exception on any such attempt. * * @see #seal(Object sealKey) */ public final boolean isSealed() { return sealed; } /** * Seal this Context object so any attempt to modify any of its properties including calling * {@link #enter()} and {@link #exit()} methods will throw an exception. * * <p>If <code>sealKey</code> is not null, calling {@link #unseal(Object sealKey)} with the same * key unseals the object. If <code>sealKey</code> is null, unsealing is no longer possible. * * @see #isSealed() * @see #unseal(Object) */ public final void seal(Object sealKey) { if (sealed) onSealedMutation(); sealed = true; this.sealKey = sealKey; } /** * Unseal previously sealed Context object. The <code>sealKey</code> argument should not be null * and should match <code>sealKey</code> suplied with the last call to {@link #seal(Object)} or * an exception will be thrown. * * @see #isSealed() * @see #seal(Object sealKey) */ public final void unseal(Object sealKey) { if (sealKey == null) throw new IllegalArgumentException(); if (this.sealKey != sealKey) throw new IllegalArgumentException(); if (!sealed) throw new IllegalStateException(); sealed = false; this.sealKey = null; } static void onSealedMutation() { throw new IllegalStateException(); } /** * Get the current language version. * * <p>The language version number affects JavaScript semantics as detailed in the overview * documentation. * * @return an integer that is one of VERSION_1_0, VERSION_1_1, etc. */ public final int getLanguageVersion() { return version; } /** * Set the language version. * * <p>Setting the language version will affect functions and scripts compiled subsequently. See * the overview documentation for version-specific behavior. * * @param version the version as specified by VERSION_1_0, VERSION_1_1, etc. */ public void setLanguageVersion(int version) { if (sealed) onSealedMutation(); checkLanguageVersion(version); Object listeners = propertyListeners; if (listeners != null && version != this.version) { firePropertyChangeImpl( listeners, languageVersionProperty, Integer.valueOf(this.version), Integer.valueOf(version)); } this.version = version; } public static boolean isValidLanguageVersion(int version) { switch (version) { case VERSION_DEFAULT: case VERSION_1_0: case VERSION_1_1: case VERSION_1_2: case VERSION_1_3: case VERSION_1_4: case VERSION_1_5: case VERSION_1_6: case VERSION_1_7: case VERSION_1_8: case VERSION_ES6: return true; } return false; } public static void checkLanguageVersion(int version) { if (isValidLanguageVersion(version)) { return; } throw new IllegalArgumentException("Bad language version: " + version); } /** * Get the implementation version. * * <p>The implementation version is of the form * * <pre> * "<i>name langVer</i> <code>release</code> <i>relNum date</i>" * </pre> * * where <i>name</i> is the name of the product, <i>langVer</i> is the language version, * <i>relNum</i> is the release number, and <i>date</i> is the release date for that specific * release in the form "yyyy mm dd". * * @return a string that encodes the product, language version, release number, and date. */ public final String getImplementationVersion() { return ImplementationVersion.get(); } /** * Get the current error reporter. * * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter getErrorReporter() { if (errorReporter == null) { return DefaultErrorReporter.instance; } return errorReporter; } /** * Change the current error reporter. * * @return the previous error reporter * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter setErrorReporter(ErrorReporter reporter) { if (sealed) onSealedMutation(); if (reporter == null) throw new IllegalArgumentException(); ErrorReporter old = getErrorReporter(); if (reporter == old) { return old; } Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl( listeners, errorReporterProperty, old, reporter); } this.errorReporter = reporter; return old; } /** * Get the current locale. Returns the default locale if none has been set. * * @see java.util.Locale */ public final Locale getLocale() { if (locale == null) locale = Locale.getDefault(); return locale; } /** * Set the current locale. * * @see java.util.Locale */ public final Locale setLocale(Locale loc) { if (sealed) onSealedMutation(); Locale result = locale; locale = loc; return result; } /** * Register an object to receive notifications when a bound property has changed * * @see java.beans.PropertyChangeEvent * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void addPropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.addListener(propertyListeners, l); } /** * Remove an object from the list of objects registered to receive notification of changes to a * bounded property * * @see java.beans.PropertyChangeEvent * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void removePropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.removeListener(propertyListeners, l); } /** * Notify any registered listeners that a bounded property has changed * * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @see java.beans.PropertyChangeListener * @see java.beans.PropertyChangeEvent * @param property the bound property * @param oldValue the old value * @param newValue the new value */ final void firePropertyChange(String property, Object oldValue, Object newValue) { Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, property, oldValue, newValue); } } private void firePropertyChangeImpl( Object listeners, String property, Object oldValue, Object newValue) { for (int i = 0; ; ++i) { Object l = Kit.getListener(listeners, i); if (l == null) break; if (l instanceof PropertyChangeListener) { PropertyChangeListener pcl = (PropertyChangeListener) l; pcl.propertyChange(new PropertyChangeEvent(this, property, oldValue, newValue)); } } } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = Context.getContext(); if (cx.hasFeature(FEATURE_WARNING_AS_ERROR)) reportError(message, sourceName, lineno, lineSource, lineOffset); else cx.getErrorReporter().warning(message, sourceName, lineno, lineSource, lineOffset); } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Context.reportWarning(message, filename, linep[0], null, 0); } public static void reportWarning(String message, Throwable t) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Writer sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(message); t.printStackTrace(pw); pw.flush(); Context.reportWarning(sw.toString(), filename, linep[0], null, 0); } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportError( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { cx.getErrorReporter().error(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Context.reportError(message, filename, linep[0], null, 0); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @return a runtime exception that will be thrown to terminate the execution of the script * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { return cx.getErrorReporter() .runtimeError(message, sourceName, lineno, lineSource, lineOffset); } throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } static EvaluatorException reportRuntimeErrorById(String messageId, Object... args) { String msg = ScriptRuntime.getMessageById(messageId, args); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError0(String messageId) { String msg = ScriptRuntime.getMessageById(messageId); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError1(String messageId, Object arg1) { String msg = ScriptRuntime.getMessageById(messageId, arg1); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError2(String messageId, Object arg1, Object arg2) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError3( String messageId, Object arg1, Object arg2, Object arg3) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2, arg3); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError4( String messageId, Object arg1, Object arg2, Object arg3, Object arg4) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2, arg3, arg4); return reportRuntimeError(msg); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); return Context.reportRuntimeError(message, filename, linep[0], null, 0); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initStandardObjects() { return initStandardObjects(null, false); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initSafeStandardObjects() { return initSafeStandardObjects(null, false); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object which is an instance {@link ScriptableObject}. */ public final Scriptable initStandardObjects(ScriptableObject scope) { return initStandardObjects(scope, false); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object which is an instance {@link ScriptableObject}. */ public final Scriptable initSafeStandardObjects(ScriptableObject scope) { return initSafeStandardObjects(scope, false); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * <p>This form of the method also allows for creating "sealed" standard objects. An object that * is sealed cannot have properties added, changed, or removed. This is useful to create a * "superglobal" that can be shared among several top-level objects. Note that sealing is not * allowed in the current ECMA/ISO language specification, but is likely for the next version. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @param sealed whether or not to create sealed standard objects that cannot be modified. * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object. * @since 1.4R3 */ public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initStandardObjects(this, scope, sealed); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * <p>This form of the method also allows for creating "sealed" standard objects. An object that * is sealed cannot have properties added, changed, or removed. This is useful to create a * "superglobal" that can be shared among several top-level objects. Note that sealing is not * allowed in the current ECMA/ISO language specification, but is likely for the next version. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @param sealed whether or not to create sealed standard objects that cannot be modified. * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object. * @since 1.7.6 */ public ScriptableObject initSafeStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initSafeStandardObjects(this, scope, sealed); } /** Get the singleton object that represents the JavaScript Undefined value. */ public static Object getUndefinedValue() { return Undefined.instance; } /** * Evaluate a JavaScript source string. * * <p>The provided source name and line number are used for error messages and for producing * debug information. * * @param scope the scope to execute in * @param source the JavaScript source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return the result of evaluating the string * @see org.mozilla.javascript.SecurityController */ public final Object evaluateString( Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { Script script = compileString(source, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } return null; } /** * Evaluate a reader as JavaScript source. * * <p>All characters of the reader are consumed. * * @param scope the scope to execute in * @param in the Reader to get JavaScript source from * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return the result of evaluating the source * @exception IOException if an IOException was generated by the Reader */ public final Object evaluateReader( Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { Script script = compileReader(scope, in, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } return null; } /** * Execute script that may pause execution by capturing a continuation. Caller must be prepared * to catch a ContinuationPending exception and resume execution by calling {@link * #resumeContinuation(Object, Scriptable, Object)}. * * @param script The script to execute. Script must have been compiled with interpreted mode * (optimization level -1) * @param scope The scope to execute the script against * @throws ContinuationPending if the script calls a function that results in a call to {@link * #captureContinuation()} * @since 1.7 Release 2 */ public Object executeScriptWithContinuations(Script script, Scriptable scope) throws ContinuationPending { if (!(script instanceof InterpretedFunction) || !((InterpretedFunction) script).isScript()) { // Can only be applied to scripts throw new IllegalArgumentException( "Script argument was not" + " a script or was not created by interpreted mode "); } return callFunctionWithContinuations( (InterpretedFunction) script, scope, ScriptRuntime.emptyArgs); } /** * Call function that may pause execution by capturing a continuation. Caller must be prepared * to catch a ContinuationPending exception and resume execution by calling {@link * #resumeContinuation(Object, Scriptable, Object)}. * * @param function The function to call. The function must have been compiled with interpreted * mode (optimization level -1) * @param scope The scope to execute the script against * @param args The arguments for the function * @throws ContinuationPending if the script calls a function that results in a call to {@link * #captureContinuation()} * @since 1.7 Release 2 */ public Object callFunctionWithContinuations(Callable function, Scriptable scope, Object[] args) throws ContinuationPending { if (!(function instanceof InterpretedFunction)) { // Can only be applied to scripts throw new IllegalArgumentException( "Function argument was not" + " created by interpreted mode "); } if (ScriptRuntime.hasTopCall(this)) { throw new IllegalStateException( "Cannot have any pending top " + "calls when executing a script with continuations"); } // Annotate so we can check later to ensure no java code in // intervening frames isContinuationsTopCall = true; return ScriptRuntime.doTopCall(function, this, scope, scope, args, isTopLevelStrict); } /** * Capture a continuation from the current execution. The execution must have been started via a * call to {@link #executeScriptWithContinuations(Script, Scriptable)} or {@link * #callFunctionWithContinuations(Callable, Scriptable, Object[])}. This implies that the code * calling this method must have been called as a function from the JavaScript script. Also, * there cannot be any non-JavaScript code between the JavaScript frames (e.g., a call to * eval()). The ContinuationPending exception returned must be thrown. * * @return A ContinuationPending exception that must be thrown * @since 1.7 Release 2 */ public ContinuationPending captureContinuation() { return new ContinuationPending(Interpreter.captureContinuation(this)); } /** * Restarts execution of the JavaScript suspended at the call to {@link #captureContinuation()}. * Execution of the code will resume with the functionResult as the result of the call that * captured the continuation. Execution of the script will either conclude normally and the * result returned, another continuation will be captured and thrown, or the script will * terminate abnormally and throw an exception. * * @param continuation The value returned by {@link ContinuationPending#getContinuation()} * @param functionResult This value will appear to the code being resumed as the result of the * function that captured the continuation * @throws ContinuationPending if another continuation is captured before the code terminates * @since 1.7 Release 2 */ public Object resumeContinuation(Object continuation, Scriptable scope, Object functionResult) throws ContinuationPending { Object[] args = {functionResult}; return Interpreter.restartContinuation( (org.mozilla.javascript.NativeContinuation) continuation, this, scope, args); } /** * Check whether a string is ready to be compiled. * * <p>stringIsCompilableUnit is intended to support interactive compilation of JavaScript. If * compiling the string would result in an error that might be fixed by appending more source, * this method returns false. In every other case, it returns true. * * <p>Interactive shells may accumulate source lines, using this method after each new line is * appended to check whether the statement being entered is complete. * * @param source the source buffer to check * @return whether the source is ready for compilation * @since 1.4 Release 2 */ public final boolean stringIsCompilableUnit(String source) { boolean errorseen = false; CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); // no source name or source text manager, because we're just // going to throw away the result. compilerEnv.setGeneratingSource(false); Parser p = new Parser(compilerEnv, DefaultErrorReporter.instance); try { p.parse(source, null, 1); } catch (EvaluatorException ee) { errorseen = true; } // Return false only if an error occurred as a result of reading past // the end of the file, i.e. if the source could be fixed by // appending more source. return !(errorseen && p.eof()); } /** * @deprecated * @see #compileReader(Reader in, String sourceName, int lineno, Object securityDomain) */ @Deprecated public final Script compileReader( Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { return compileReader(in, sourceName, lineno, securityDomain); } /** * Compiles the source in the given reader. * * <p>Returns a script that may later be executed. Will consume all the source in the reader. * * @param in the input reader * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a script that may later be executed * @exception IOException if an IOException was generated by the Reader * @see org.mozilla.javascript.Script */ public final Script compileReader( Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return (Script) compileImpl( null, Kit.readReader(in), sourceName, lineno, securityDomain, false, null, null); } /** * Compiles the source in the given string. * * <p>Returns a script that may later be executed. * * @param source the source string * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors. Use 0 if the line number is * unknown. * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a script that may later be executed * @see org.mozilla.javascript.Script */ public final Script compileString( String source, String sourceName, int lineno, Object securityDomain) { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return compileString(source, null, null, sourceName, lineno, securityDomain); } final Script compileString( String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Script) compileImpl( null, source, sourceName, lineno, securityDomain, false, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should not happen when dealing with source as string throw new RuntimeException(ioe); } } /** * Compile a JavaScript function. * * <p>The function source must be a function definition as defined by ECMA (e.g., "function f(a) * { return a; }"). * * @param scope the scope to compile relative to * @param source the function definition source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a Function that may later be called * @see org.mozilla.javascript.Function */ public final Function compileFunction( Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { return compileFunction(scope, source, null, null, sourceName, lineno, securityDomain); } final Function compileFunction( Scriptable scope, String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Function) compileImpl( scope, source, sourceName, lineno, securityDomain, true, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should never happen because we just made the reader // from a String throw new RuntimeException(ioe); } } /** * Decompile the script. * * <p>The canonical source of the script is returned. * * @param script the script to decompile * @param indent the number of spaces to indent the result * @return a string representing the script source */ public final String decompileScript(Script script, int indent) { NativeFunction scriptImpl = (NativeFunction) script; return scriptImpl.decompile(indent, 0); } /** * Decompile a JavaScript Function. * * <p>Decompiles a previously compiled JavaScript function object to canonical source. * * <p>Returns function body of '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function source */ public final String decompileFunction(Function fun, int indent) { if (fun instanceof BaseFunction) return ((BaseFunction) fun).decompile(indent, 0); return "function " + fun.getClassName() + "() {\n\t[native code]\n}\n"; } /** * Decompile the body of a JavaScript Function. * * <p>Decompiles the body a previously compiled JavaScript Function object to canonical source, * omitting the function header and trailing brace. * * <p>Returns '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function body source. */ public final String decompileFunctionBody(Function fun, int indent) { if (fun instanceof BaseFunction) { BaseFunction bf = (BaseFunction) fun; return bf.decompile(indent, Decompiler.ONLY_BODY_FLAG); } // ALERT: not sure what the right response here is. return "[native code]\n"; } /** * Create a new JavaScript object. * * <p>Equivalent to evaluating "new Object()". * * @param scope the scope to search for the constructor and to evaluate against * @return the new object */ public Scriptable newObject(Scriptable scope) { NativeObject result = new NativeObject(); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Object); return result; } /** * Create a new JavaScript object by executing the named constructor. * * <p>The call <code>newObject(scope, "Foo")</code> is equivalent to evaluating "new Foo()". * * @param scope the scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @return the new object */ public Scriptable newObject(Scriptable scope, String constructorName) { return newObject(scope, constructorName, ScriptRuntime.emptyArgs); } /** * Creates a new JavaScript object by executing the named constructor. * * <p>Searches <code>scope</code> for the named constructor, calls it with the given arguments, * and returns the result. * * <p>The code * * <pre> * Object[] args = { "a", "b" }; * newObject(scope, "Foo", args)</pre> * * is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo constructor has been * defined in <code>scope</code>. * * @param scope The scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @param args the array of arguments for the constructor * @return the new object */ public Scriptable newObject(Scriptable scope, String constructorName, Object[] args) { return ScriptRuntime.newObject(this, scope, constructorName, args); } /** * Create an array with a specified initial length. * * <p> * * @param scope the scope to create the object in * @param length the initial length (JavaScript arrays may have additional properties added * dynamically). * @return the new array object */ public Scriptable newArray(Scriptable scope, int length) { NativeArray result = new NativeArray(length); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array); return result; } /** * Create an array with a set of initial elements. * * @param scope the scope to create the object in. * @param elements the initial elements. Each object in this array must be an acceptable * JavaScript type and type of array should be exactly Object[], not SomeObjectSubclass[]. * @return the new array object. */ public Scriptable newArray(Scriptable scope, Object[] elements) { if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass) throw new IllegalArgumentException(); NativeArray result = new NativeArray(elements); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array); return result; } /** * Get the elements of a JavaScript array. * * <p>If the object defines a length property convertible to double number, then the number is * converted Uint32 value as defined in Ecma 9.6 and Java array of that size is allocated. The * array is initialized with the values obtained by calling get() on object for each value of i * in [0,length-1]. If there is not a defined value for a property the Undefined value is used * to initialize the corresponding element in the array. The Java array is then returned. If the * object doesn't define a length property or it is not a number, empty array is returned. * * @param object the JavaScript array or array-like object * @return a Java array of objects * @since 1.4 release 2 */ public final Object[] getElements(Scriptable object) { return ScriptRuntime.getArrayElements(object); } /** * Convert the value to a JavaScript boolean value. * * <p>See ECMA 9.2. * * @param value a JavaScript value * @return the corresponding boolean value converted using the ECMA rules */ public static boolean toBoolean(Object value) { return ScriptRuntime.toBoolean(value); } /** * Convert the value to a JavaScript Number value. * * <p>Returns a Java double for the JavaScript Number. * * <p>See ECMA 9.3. * * @param value a JavaScript value * @return the corresponding double value converted using the ECMA rules */ public static double toNumber(Object value) { return ScriptRuntime.toNumber(value); } /** * Convert the value to a JavaScript String value. * * <p>See ECMA 9.8. * * <p> * * @param value a JavaScript value * @return the corresponding String value converted using the ECMA rules */ public static String toString(Object value) { return ScriptRuntime.toString(value); } /** * Convert the value to an JavaScript object value. * * <p>Note that a scope must be provided to look up the constructors for Number, Boolean, and * String. * * <p>See ECMA 9.9. * * <p>Additionally, arbitrary Java objects and classes will be wrapped in a Scriptable object * with its Java fields and methods reflected as JavaScript properties of the object. * * @param value any Java object * @param scope global scope containing constructors for Number, Boolean, and String * @return new JavaScript object */ public static Scriptable toObject(Object value, Scriptable scope) { return ScriptRuntime.toObject(scope, value); } /** * @deprecated * @see #toObject(Object, Scriptable) */ @Deprecated public static Scriptable toObject(Object value, Scriptable scope, Class<?> staticType) { return ScriptRuntime.toObject(scope, value); } /** * Convenient method to convert java value to its closest representation in JavaScript. * * <p>If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned * as it and will be treated as the corresponding JavaScript type of string, number, boolean, * function and object. * * <p>Note that for Number instances during any arithmetic operation in JavaScript the engine * will always use the result of <code>Number.doubleValue()</code> resulting in a precision loss * if the number can not fit into double. * * <p>If value is an instance of Character, it will be converted to string of length 1 and its * JavaScript type will be string. * * <p>The rest of values will be wrapped as LiveConnect objects by calling {@link * WrapFactory#wrap(Context cx, Scriptable scope, Object obj, Class staticType)} as in: * * <pre> * Context cx = Context.getCurrentContext(); * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope) { return javaToJS(value, scope, null); } /** * Convenient method to convert java value to its closest representation in JavaScript. * * <p>If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned * as it and will be treated as the corresponding JavaScript type of string, number, boolean, * function and object. * * <p>Note that for Number instances during any arithmetic operation in JavaScript the engine * will always use the result of <code>Number.doubleValue()</code> resulting in a precision loss * if the number can not fit into double. * * <p>If value is an instance of Character, it will be converted to string of length 1 and its * JavaScript type will be string. * * <p>The rest of values will be wrapped as LiveConnect objects by calling {@link * WrapFactory#wrap(Context cx, Scriptable scope, Object obj, Class staticType)} as in: * * <pre> * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @param cx context to use for wrapping LiveConnect objects * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope, Context cx) { if (value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof Scriptable) { return value; } else if (value instanceof Character) { return String.valueOf(((Character) value).charValue()); } else { if (cx == null) { cx = Context.getContext(); } return cx.getWrapFactory().wrap(cx, scope, value, null); } } /** * Convert a JavaScript value into the desired type. Uses the semantics defined with * LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed. * * @param value the JavaScript value to convert * @param desiredType the Java type to convert to. Primitive Java types are represented using * the TYPE fields in the corresponding wrapper class in java.lang. * @return the converted value * @throws EvaluatorException if the conversion cannot be performed */ public static Object jsToJava(Object value, Class<?> desiredType) throws EvaluatorException { return NativeJavaObject.coerceTypeImpl(desiredType, value); } /** * @deprecated * @see #jsToJava(Object, Class) * @throws IllegalArgumentException if the conversion cannot be performed. Note that {@link * #jsToJava(Object, Class)} throws {@link EvaluatorException} instead. */ @Deprecated public static Object toType(Object value, Class<?> desiredType) throws IllegalArgumentException { try { return jsToJava(value, desiredType); } catch (EvaluatorException ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } /** * Returns the javaToJSONConverter for this Context. * * <p>The converter is used by the JSON.stringify method for Java objects other than instances * of {@link java.util.Map Map}, {@link java.util.Collection Collection}, or {@link * java.lang.Object Object[]}. * * <p>The default converter if unset will convert Java Objects to their toString() value. * * @return javaToJSONConverter for this Context */ public UnaryOperator<Object> getJavaToJSONConverter() { if (javaToJSONConverter == null) { return JavaToJSONConverters.STRING; } return javaToJSONConverter; } /** * Sets the javaToJSONConverter for this Context. * * <p>The converter is used by the JSON.stringify method for Java objects other than instances * of {@link java.util.Map Map}, {@link java.util.Collection Collection}, or {@link * java.lang.Object Object[]}. * * <p>Objects returned by the converter will converted with {@link #javaToJS(Object, * Scriptable)} and then stringified themselves. * * @param javaToJSONConverter * @throws IllegalArgumentException if javaToJSONConverter is null */ public void setJavaToJSONConverter(UnaryOperator<Object> javaToJSONConverter) throws IllegalArgumentException { if (javaToJSONConverter == null) { throw new IllegalArgumentException("javaToJSONConverter == null"); } this.javaToJSONConverter = javaToJSONConverter; } /** * Rethrow the exception wrapping it as the script runtime exception. Unless the exception is * instance of {@link EcmaError} or {@link EvaluatorException} it will be wrapped as {@link * WrappedException}, a subclass of {@link EvaluatorException}. The resulting exception object * always contains source name and line number of script that triggered exception. * * <p>This method always throws an exception, its return value is provided only for convenience * to allow a usage like: * * <pre> * throw Context.throwAsScriptRuntimeEx(ex); * </pre> * * to indicate that code after the method is unreachable. * * @throws EvaluatorException * @throws EcmaError */ public static RuntimeException throwAsScriptRuntimeEx(Throwable e) { while ((e instanceof InvocationTargetException)) { e = ((InvocationTargetException) e).getTargetException(); } // special handling of Error so scripts would not catch them if (e instanceof Error) { Context cx = getContext(); if (cx == null || !cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { throw (Error) e; } } if (e instanceof RhinoException) { throw (RhinoException) e; } throw new WrappedException(e); } /** * Tell whether debug information is being generated. * * @since 1.3 */ public final boolean isGeneratingDebug() { return generatingDebug; } /** * Specify whether or not debug information should be generated. * * <p>Setting the generation of debug information on will set the optimization level to zero. * * @since 1.3 */ public final void setGeneratingDebug(boolean generatingDebug) { if (sealed) onSealedMutation(); generatingDebugChanged = true; if (generatingDebug && getOptimizationLevel() > 0) setOptimizationLevel(0); this.generatingDebug = generatingDebug; } /** * Tell whether source information is being generated. * * @since 1.3 */ public final boolean isGeneratingSource() { return generatingSource; } /** * Specify whether or not source information should be generated. * * <p>Without source information, evaluating the "toString" method on JavaScript functions * produces only "[native code]" for the body of the function. Note that code generated without * source is not fully ECMA conformant. * * @since 1.3 */ public final void setGeneratingSource(boolean generatingSource) { if (sealed) onSealedMutation(); this.generatingSource = generatingSource; } /** * Get the current optimization level. * * <p>The optimization level is expressed as an integer between -1 and 9. * * @since 1.3 */ public final int getOptimizationLevel() { return optimizationLevel; } /** * Set the current optimization level. * * <p>The optimization level is expected to be an integer between -1 and 9. Any negative values * will be interpreted as -1, and any values greater than 9 will be interpreted as 9. An * optimization level of -1 indicates that interpretive mode will always be used. Levels 0 * through 9 indicate that class files may be generated. Higher optimization levels trade off * compile time performance for runtime performance. The optimizer level can't be set greater * than -1 if the optimizer package doesn't exist at run time. * * @param optimizationLevel an integer indicating the level of optimization to perform * @since 1.3 */ public final void setOptimizationLevel(int optimizationLevel) { if (sealed) onSealedMutation(); if (optimizationLevel == -2) { // To be compatible with Cocoon fork optimizationLevel = -1; } checkOptimizationLevel(optimizationLevel); if (codegenClass == null) optimizationLevel = -1; this.optimizationLevel = optimizationLevel; } public static boolean isValidOptimizationLevel(int optimizationLevel) { return -1 <= optimizationLevel && optimizationLevel <= 9; } public static void checkOptimizationLevel(int optimizationLevel) { if (isValidOptimizationLevel(optimizationLevel)) { return; } throw new IllegalArgumentException( "Optimization level outside [-1..9]: " + optimizationLevel); } /** * Returns the maximum stack depth (in terms of number of call frames) allowed in a single * invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an * EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect * for interpreted functions (those compiled with optimization level set to -1). As the * interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a * runaway recursion in interpreted code would eventually consume all available memory and cause * OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @return The current maximum interpreter stack depth. */ public final int getMaximumInterpreterStackDepth() { return maximumInterpreterStackDepth; } /** * Sets the maximum stack depth (in terms of number of call frames) allowed in a single * invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an * EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect * for interpreted functions (those compiled with optimization level set to -1). As the * interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a * runaway recursion in interpreted code would eventually consume all available memory and cause * OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @param max the new maximum interpreter stack depth * @throws IllegalStateException if this context's optimization level is not -1 * @throws IllegalArgumentException if the new depth is not at least 1 */ public final void setMaximumInterpreterStackDepth(int max) { if (sealed) onSealedMutation(); if (optimizationLevel != -1) { throw new IllegalStateException( "Cannot set maximumInterpreterStackDepth when optimizationLevel != -1"); } if (max < 1) { throw new IllegalArgumentException( "Cannot set maximumInterpreterStackDepth to less than 1"); } maximumInterpreterStackDepth = max; } /** * Set the security controller for this context. * * <p>SecurityController may only be set if it is currently null and {@link * SecurityController#hasGlobal()} is <code>false</code>. Otherwise a SecurityException is * thrown. * * @param controller a SecurityController object * @throws SecurityException if there is already a SecurityController object for this Context or * globally installed. * @see SecurityController#initGlobal(SecurityController controller) * @see SecurityController#hasGlobal() */ public final void setSecurityController(SecurityController controller) { if (sealed) onSealedMutation(); if (controller == null) throw new IllegalArgumentException(); if (securityController != null) { throw new SecurityException("Can not overwrite existing SecurityController object"); } if (SecurityController.hasGlobal()) { throw new SecurityException( "Can not overwrite existing global SecurityController object"); } securityController = controller; } /** * Set the LiveConnect access filter for this context. * * <p>{@link ClassShutter} may only be set if it is currently null. Otherwise a * SecurityException is thrown. * * @param shutter a ClassShutter object * @throws SecurityException if there is already a ClassShutter object for this Context */ public final synchronized void setClassShutter(ClassShutter shutter) { if (sealed) onSealedMutation(); if (shutter == null) throw new IllegalArgumentException(); if (hasClassShutter) { throw new SecurityException("Cannot overwrite existing " + "ClassShutter object"); } classShutter = shutter; hasClassShutter = true; } final synchronized ClassShutter getClassShutter() { return classShutter; } public interface ClassShutterSetter { public void setClassShutter(ClassShutter shutter); public ClassShutter getClassShutter(); } public final synchronized ClassShutterSetter getClassShutterSetter() { if (hasClassShutter) return null; hasClassShutter = true; return new ClassShutterSetter() { @Override public void setClassShutter(ClassShutter shutter) { classShutter = shutter; } @Override public ClassShutter getClassShutter() { return classShutter; } }; } /** * Get a value corresponding to a key. * * <p>Since the Context is associated with a thread it can be used to maintain values that can * be later retrieved using the current thread. * * <p>Note that the values are maintained with the Context, so if the Context is disassociated * from the thread the values cannot be retrieved. Also, if private data is to be maintained in * this manner the key should be a java.lang.Object whose reference is not divulged to untrusted * code. * * @param key the key used to lookup the value * @return a value previously stored using putThreadLocal. */ public final Object getThreadLocal(Object key) { if (threadLocalMap == null) return null; return threadLocalMap.get(key); } /** * Put a value that can later be retrieved using a given key. * * <p> * * @param key the key used to index the value * @param value the value to save */ public final synchronized void putThreadLocal(Object key, Object value) { if (sealed) onSealedMutation(); if (threadLocalMap == null) threadLocalMap = new HashMap<Object, Object>(); threadLocalMap.put(key, value); } /** * Remove values from thread-local storage. * * @param key the key for the entry to remove. * @since 1.5 release 2 */ public final void removeThreadLocal(Object key) { if (sealed) onSealedMutation(); if (threadLocalMap == null) return; threadLocalMap.remove(key); } /** * @deprecated * @see ClassCache#get(Scriptable) * @see ClassCache#setCachingEnabled(boolean) */ @Deprecated public static void setCachingEnabled(boolean cachingEnabled) {} /** * Set a WrapFactory for this Context. * * <p>The WrapFactory allows custom object wrapping behavior for Java object manipulated with * JavaScript. * * @see WrapFactory * @since 1.5 Release 4 */ public final void setWrapFactory(WrapFactory wrapFactory) { if (sealed) onSealedMutation(); if (wrapFactory == null) throw new IllegalArgumentException(); this.wrapFactory = wrapFactory; } /** * Return the current WrapFactory, or null if none is defined. * * @see WrapFactory * @since 1.5 Release 4 */ public final WrapFactory getWrapFactory() { if (wrapFactory == null) { wrapFactory = new WrapFactory(); } return wrapFactory; } /** * Return the current debugger. * * @return the debugger, or null if none is attached. */ public final Debugger getDebugger() { return debugger; } /** * Return the debugger context data associated with current context. * * @return the debugger data, or null if debugger is not attached */ public final Object getDebuggerContextData() { return debuggerData; } /** * Set the associated debugger. * * @param debugger the debugger to be used on callbacks from the engine. * @param contextData arbitrary object that debugger can use to store per Context data. */ public final void setDebugger(Debugger debugger, Object contextData) { if (sealed) onSealedMutation(); this.debugger = debugger; debuggerData = contextData; } /** * Return DebuggableScript instance if any associated with the script. If callable supports * DebuggableScript implementation, the method returns it. Otherwise null is returned. */ public static DebuggableScript getDebuggableView(Script script) { if (script instanceof NativeFunction) { return ((NativeFunction) script).getDebuggableView(); } return null; } /** * Controls certain aspects of script semantics. Should be overwritten to alter default * behavior. * * <p>The default implementation calls {@link ContextFactory#hasFeature(Context cx, int * featureIndex)} that allows to customize Context behavior without introducing Context * subclasses. {@link ContextFactory} documentation gives an example of hasFeature * implementation. * * @param featureIndex feature index to check * @return true if the <code>featureIndex</code> feature is turned on * @see #FEATURE_NON_ECMA_GET_YEAR * @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME * @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER * @see #FEATURE_TO_STRING_AS_SOURCE * @see #FEATURE_PARENT_PROTO_PROPRTIES * @see #FEATURE_E4X * @see #FEATURE_DYNAMIC_SCOPE * @see #FEATURE_STRICT_VARS * @see #FEATURE_STRICT_EVAL * @see #FEATURE_LOCATION_INFORMATION_IN_ERROR * @see #FEATURE_STRICT_MODE * @see #FEATURE_WARNING_AS_ERROR * @see #FEATURE_ENHANCED_JAVA_ACCESS */ public boolean hasFeature(int featureIndex) { ContextFactory f = getFactory(); return f.hasFeature(this, featureIndex); } /** * Returns an object which specifies an E4X implementation to use within this <code>Context * </code>. Note that the XMLLib.Factory interface should be considered experimental. * * <p>The default implementation uses the implementation provided by this <code>Context</code>'s * {@link ContextFactory}. * * @return An XMLLib.Factory. Should not return <code>null</code> if {@link #FEATURE_E4X} is * enabled. See {@link #hasFeature}. */ public XMLLib.Factory getE4xImplementationFactory() { return getFactory().getE4xImplementationFactory(); } /** * Get threshold of executed instructions counter that triggers call to <code> * observeInstructionCount()</code>. When the threshold is zero, instruction counting is * disabled, otherwise each time the run-time executes at least the threshold value of script * instructions, <code>observeInstructionCount()</code> will be called. */ public final int getInstructionObserverThreshold() { return instructionThreshold; } /** * Set threshold of executed instructions counter that triggers call to <code> * observeInstructionCount()</code>. When the threshold is zero, instruction counting is * disabled, otherwise each time the run-time executes at least the threshold value of script * instructions, <code>observeInstructionCount()</code> will be called.<br> * Note that the meaning of "instruction" is not guaranteed to be consistent between compiled * and interpretive modes: executing a given script or function in the different modes will * result in different instruction counts against the threshold. {@link * #setGenerateObserverCount} is called with true if <code>threshold</code> is greater than * zero, false otherwise. * * @param threshold The instruction threshold */ public final void setInstructionObserverThreshold(int threshold) { if (sealed) onSealedMutation(); if (threshold < 0) throw new IllegalArgumentException(); instructionThreshold = threshold; setGenerateObserverCount(threshold > 0); } /** * Turn on or off generation of code with callbacks to track the count of executed instructions. * Currently only affects JVM byte code generation: this slows down the generated code, but code * generated without the callbacks will not be counted toward instruction thresholds. Rhino's * interpretive mode does instruction counting without inserting callbacks, so there is no * requirement to compile code differently. * * @param generateObserverCount if true, generated code will contain calls to accumulate an * estimate of the instructions executed. */ public void setGenerateObserverCount(boolean generateObserverCount) { this.generateObserverCount = generateObserverCount; } /** * Allow application to monitor counter of executed script instructions in Context subclasses. * Run-time calls this when instruction counting is enabled and the counter reaches limit set by * <code>setInstructionObserverThreshold()</code>. The method is useful to observe long running * scripts and if necessary to terminate them. * * <p>The default implementation calls {@link ContextFactory#observeInstructionCount(Context cx, * int instructionCount)} that allows to customize Context behavior without introducing Context * subclasses. * * @param instructionCount amount of script instruction executed since last call to <code> * observeInstructionCount</code> * @throws Error to terminate the script * @see #setOptimizationLevel(int) */ protected void observeInstructionCount(int instructionCount) { ContextFactory f = getFactory(); f.observeInstructionCount(this, instructionCount); } /** * Create class loader for generated classes. The method calls {@link * ContextFactory#createClassLoader(ClassLoader)} using the result of {@link #getFactory()}. */ public GeneratedClassLoader createClassLoader(ClassLoader parent) { ContextFactory f = getFactory(); return f.createClassLoader(parent); } public final ClassLoader getApplicationClassLoader() { if (applicationClassLoader == null) { ContextFactory f = getFactory(); ClassLoader loader = f.getApplicationClassLoader(); if (loader == null) { ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); if (threadLoader != null && Kit.testIfCanLoadRhinoClasses(threadLoader)) { // Thread.getContextClassLoader is not cached since // its caching prevents it from GC which may lead to // a memory leak and hides updates to // Thread.getContextClassLoader return threadLoader; } // Thread.getContextClassLoader can not load Rhino classes, // try to use the loader of ContextFactory or Context // subclasses. Class<?> fClass = f.getClass(); if (fClass != ScriptRuntime.ContextFactoryClass) { loader = fClass.getClassLoader(); } else { loader = getClass().getClassLoader(); } } applicationClassLoader = loader; } return applicationClassLoader; } public final void setApplicationClassLoader(ClassLoader loader) { if (sealed) onSealedMutation(); if (loader == null) { // restore default behaviour applicationClassLoader = null; return; } if (!Kit.testIfCanLoadRhinoClasses(loader)) { throw new IllegalArgumentException("Loader can not resolve Rhino classes"); } applicationClassLoader = loader; } /* ******** end of API ********* */ /** Internal method that reports an error for missing calls to enter(). */ static Context getContext() { Context cx = getCurrentContext(); if (cx == null) { throw new RuntimeException("No Context associated with current Thread"); } return cx; } protected Object compileImpl( Scriptable scope, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException { if (sourceName == null) { sourceName = "unnamed script"; } if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } ScriptNode tree = parse( sourceString, sourceName, lineno, compilerEnv, compilationErrorReporter, returnFunction); Object bytecode; try { if (compiler == null) { compiler = createCompiler(); } bytecode = compiler.compile(compilerEnv, tree, tree.getEncodedSource(), returnFunction); } catch (ClassFileFormatException e) { // we hit some class file limit, fall back to interpreter or report // we have to recreate the tree because the compile call might have changed the tree // already tree = parse( sourceString, sourceName, lineno, compilerEnv, compilationErrorReporter, returnFunction); compiler = createInterpreter(); bytecode = compiler.compile(compilerEnv, tree, tree.getEncodedSource(), returnFunction); } if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript) bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; } private ScriptNode parse( String sourceString, String sourceName, int lineno, CompilerEnvirons compilerEnv, ErrorReporter compilationErrorReporter, boolean returnFunction) throws IOException { Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } if (isStrictMode()) { p.setDefaultUseStrictDirective(true); } AstRoot ast = p.parse(sourceString, sourceName, lineno); if (returnFunction) { // parser no longer adds function to script node if (!(ast.getFirstChild() != null && ast.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just looks for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: " + sourceString); } } IRFactory irf = new IRFactory(compilerEnv, compilationErrorReporter); ScriptNode tree = irf.transformTree(ast); return tree; } private static void notifyDebugger_r(Context cx, DebuggableScript dscript, String debugSource) { cx.debugger.handleCompilationDone(cx, dscript, debugSource); for (int i = 0; i != dscript.getFunctionCount(); ++i) { notifyDebugger_r(cx, dscript.getFunction(i), debugSource); } } private static Class<?> codegenClass = Kit.classOrNull("org.mozilla.javascript.optimizer.Codegen"); private static Class<?> interpreterClass = Kit.classOrNull("org.mozilla.javascript.Interpreter"); private Evaluator createCompiler() { Evaluator result = null; if (optimizationLevel >= 0 && codegenClass != null) { result = (Evaluator) Kit.newInstanceOrNull(codegenClass); } if (result == null) { result = createInterpreter(); } return result; } static Evaluator createInterpreter() { return (Evaluator) Kit.newInstanceOrNull(interpreterClass); } static String getSourcePositionFromStack(int[] linep) { Context cx = getCurrentContext(); if (cx == null) return null; if (cx.lastInterpreterFrame != null) { Evaluator evaluator = createInterpreter(); if (evaluator != null) return evaluator.getSourcePositionFromStack(cx, linep); } /** * A bit of a hack, but the only way to get filename and line number from an enclosing * frame. */ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); for (StackTraceElement st : stackTrace) { String file = st.getFileName(); if (!(file == null || file.endsWith(".java"))) { int line = st.getLineNumber(); if (line >= 0) { linep[0] = line; return file; } } } return null; } RegExpProxy getRegExpProxy() { if (regExpProxy == null) { Class<?> cl = Kit.classOrNull("org.mozilla.javascript.regexp.RegExpImpl"); if (cl != null) { regExpProxy = (RegExpProxy) Kit.newInstanceOrNull(cl); } } return regExpProxy; } final boolean isVersionECMA1() { return version == VERSION_DEFAULT || version >= VERSION_1_3; } // The method must NOT be public or protected SecurityController getSecurityController() { SecurityController global = SecurityController.global(); if (global != null) { return global; } return securityController; } public final boolean isGeneratingDebugChanged() { return generatingDebugChanged; } /** * Add a name to the list of names forcing the creation of real activation objects for * functions. * * @param name the name of the object to add to the list */ public void addActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames == null) activationNames = new HashSet<String>(); activationNames.add(name); } /** * Check whether the name is in the list of names of objects forcing the creation of activation * objects. * * @param name the name of the object to test * @return true if an function activation object is needed. */ public final boolean isActivationNeeded(String name) { return activationNames != null && activationNames.contains(name); } /** * Remove a name from the list of names forcing the creation of real activation objects for * functions. * * @param name the name of the object to remove from the list */ public void removeActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames != null) activationNames.remove(name); } public final boolean isStrictMode() { return isTopLevelStrict || (currentActivationCall != null && currentActivationCall.isStrict); } private final ContextFactory factory; private boolean sealed; private Object sealKey; Scriptable topCallScope; boolean isContinuationsTopCall; NativeCall currentActivationCall; XMLLib cachedXMLLib; BaseFunction typeErrorThrower; // for Objects, Arrays to tag themselves as being printed out, // so they don't print themselves out recursively. // Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility ObjToIntMap iterating; Object interpreterSecurityDomain; int version; private SecurityController securityController; private boolean hasClassShutter; private ClassShutter classShutter; private ErrorReporter errorReporter; RegExpProxy regExpProxy; private Locale locale; private boolean generatingDebug; private boolean generatingDebugChanged; private boolean generatingSource = true; boolean useDynamicScope; private int optimizationLevel; private int maximumInterpreterStackDepth; private WrapFactory wrapFactory; Debugger debugger; private Object debuggerData; private int enterCount; private Object propertyListeners; private Map<Object, Object> threadLocalMap; private ClassLoader applicationClassLoader; private UnaryOperator<Object> javaToJSONConverter; /** This is the list of names of objects forcing the creation of function activation records. */ Set<String> activationNames; // For the interpreter to store the last frame for error reports etc. Object lastInterpreterFrame; // For the interpreter to store information about previous invocations // interpreter invocations ObjArray previousInterpreterInvocations; // For instruction counting (interpreter only) int instructionCount; int instructionThreshold; // It can be used to return the second uint32 result from function long scratchUint32; // It can be used to return the second Scriptable result from function Scriptable scratchScriptable; // Generate an observer count on compiled code public boolean generateObserverCount = false; boolean isTopLevelStrict; }
src/org/mozilla/javascript/Context.java
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // API class package org.mozilla.javascript; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Closeable; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.UnaryOperator; import org.mozilla.classfile.ClassFileWriter.ClassFileFormatException; import org.mozilla.javascript.ast.AstRoot; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.javascript.debug.DebuggableScript; import org.mozilla.javascript.debug.Debugger; import org.mozilla.javascript.xml.XMLLib; /** * This class represents the runtime context of an executing script. * * <p>Before executing a script, an instance of Context must be created and associated with the * thread that will be executing the script. The Context will be used to store information about the * executing of the script such as the call stack. Contexts are associated with the current thread * using the {@link #call(ContextAction)} or {@link #enter()} methods. * * <p>Different forms of script execution are supported. Scripts may be evaluated from the source * directly, or first compiled and then later executed. Interactive execution is also supported. * * <p>Some aspects of script execution, such as type conversions and object creation, may be * accessed directly through methods of Context. * * @see Scriptable * @author Norris Boyd * @author Brendan Eich */ public class Context implements Closeable { /** * Language versions. * * <p>All integral values are reserved for future version numbers. */ /** * The unknown version. * * <p>Be aware, this version will not support many of the newer language features and will not * change in the future. * * <p>Please use one of the other constants like VERSION_ES6 to get support for recent language * features. */ public static final int VERSION_UNKNOWN = -1; /** The default version. */ public static final int VERSION_DEFAULT = 0; /** JavaScript 1.0 */ public static final int VERSION_1_0 = 100; /** JavaScript 1.1 */ public static final int VERSION_1_1 = 110; /** JavaScript 1.2 */ public static final int VERSION_1_2 = 120; /** JavaScript 1.3 */ public static final int VERSION_1_3 = 130; /** JavaScript 1.4 */ public static final int VERSION_1_4 = 140; /** JavaScript 1.5 */ public static final int VERSION_1_5 = 150; /** JavaScript 1.6 */ public static final int VERSION_1_6 = 160; /** JavaScript 1.7 */ public static final int VERSION_1_7 = 170; /** JavaScript 1.8 */ public static final int VERSION_1_8 = 180; /** ECMAScript 6. */ public static final int VERSION_ES6 = 200; /** * Controls behaviour of <code>Date.prototype.getYear()</code>. If <code> * hasFeature(FEATURE_NON_ECMA_GET_YEAR)</code> returns true, Date.prototype.getYear subtructs * 1900 only if 1900 &lt;= date &lt; 2000. The default behavior of {@link #hasFeature(int)} is * always to subtruct 1900 as rquired by ECMAScript B.2.4. */ public static final int FEATURE_NON_ECMA_GET_YEAR = 1; /** * Control if member expression as function name extension is available. If <code> * hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)</code> returns true, allow <code> * function memberExpression(args) { body }</code> to be syntax sugar for <code> * memberExpression = function(args) { body }</code>, when memberExpression is not a simple * identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By default * {@link #hasFeature(int)} returns false. */ public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2; /** * Control if reserved keywords are treated as identifiers. If <code> * hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)</code> returns true, treat future reserved keyword * (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage. * * <p>By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3; /** * Control if <code>toString()</code> should returns the same result as <code>toSource()</code> * when applied to objects and arrays. If <code>hasFeature(FEATURE_TO_STRING_AS_SOURCE)</code> * returns true, calling <code>toString()</code> on JS objects gives the same result as calling * <code>toSource()</code>. That is it returns JS source with code to create an object with all * enumeratable fields of the original object instead of printing <code>[object <i>result of * {@link Scriptable#getClassName()}</i>]</code>. * * <p>By default {@link #hasFeature(int)} returns true only if the current JS version is set to * {@link #VERSION_1_2}. */ public static final int FEATURE_TO_STRING_AS_SOURCE = 4; /** * Control if properties <code>__proto__</code> and <code>__parent__</code> are treated * specially. If <code>hasFeature(FEATURE_PARENT_PROTO_PROPERTIES)</code> returns true, treat * <code>__parent__</code> and <code>__proto__</code> as special properties. * * <p>The properties allow to query and set scope and prototype chains for the objects. The * special meaning of the properties is available only when they are used as the right hand side * of the dot operator. For example, while <code>x.__proto__ = y</code> changes the prototype * chain of the object <code>x</code> to point to <code>y</code>, <code>x["__proto__"] = y * </code> simply assigns a new value to the property <code>__proto__</code> in <code>x</code> * even when the feature is on. * * <p>By default {@link #hasFeature(int)} returns true. */ public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5; /** @deprecated In previous releases, this name was given to FEATURE_PARENT_PROTO_PROPERTIES. */ @Deprecated public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5; /** * Control if support for E4X(ECMAScript for XML) extension is available. If * hasFeature(FEATURE_E4X) returns true, the XML syntax is available. * * <p>By default {@link #hasFeature(int)} returns true if the current JS version is set to * {@link #VERSION_DEFAULT} or is at least {@link #VERSION_1_6}. * * @since 1.6 Release 1 */ public static final int FEATURE_E4X = 6; /** * Control if dynamic scope should be used for name access. If hasFeature(FEATURE_DYNAMIC_SCOPE) * returns true, then the name lookup during name resolution will use the top scope of the * script or function which is at the top of JS execution stack instead of the top scope of the * script or function from the current stack frame if the top scope of the top stack frame * contains the top scope of the current stack frame on its prototype chain. * * <p>This is useful to define shared scope containing functions that can be called from scripts * and functions using private scopes. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_DYNAMIC_SCOPE = 7; /** * Control if strict variable mode is enabled. When the feature is on Rhino reports runtime * errors if assignment to a global variable that does not exist is executed. When the feature * is off such assignments create a new variable in the global scope as required by ECMA 262. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_VARS = 8; /** * Control if strict eval mode is enabled. When the feature is on Rhino reports runtime errors * if non-string argument is passed to the eval function. When the feature is off eval simply * return non-string argument as is without performing any evaluation as required by ECMA 262. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_EVAL = 9; /** * When the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error * objects automatically. When the feature is off, you have to explicitly pass them as the * second and third argument to the Error constructor. Note that neither behavior is fully ECMA * 262 compliant (as 262 doesn't specify a three-arg constructor), but keeping the feature off * results in Error objects that don't have additional non-ECMA properties when constructed * using the ECMA-defined single-arg constructor and is thus desirable if a stricter ECMA * compliance is desired, specifically adherence to the point 15.11.5. of the standard. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 6 */ public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10; /** * Controls whether JS 1.5 'strict mode' is enabled. When the feature is on, Rhino reports more * than a dozen different warnings. When the feature is off, these warnings are not generated. * FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.6 Release 6 */ public static final int FEATURE_STRICT_MODE = 11; /** * Controls whether a warning should be treated as an error. * * @since 1.6 Release 6 */ public static final int FEATURE_WARNING_AS_ERROR = 12; /** * Enables enhanced access to Java. Specifically, controls whether private and protected members * can be accessed, and whether scripts can catch all Java exceptions. * * <p>Note that this feature should only be enabled for trusted scripts. * * <p>By default {@link #hasFeature(int)} returns false. * * @since 1.7 Release 1 */ public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13; /** * Enables access to JavaScript features from ECMAscript 6 that are present in JavaScript * engines that do not yet support version 6, such as V8. This includes support for typed * arrays. Default is true. * * @since 1.7 Release 3 */ public static final int FEATURE_V8_EXTENSIONS = 14; /** * Defines how an undefined "this" parameter is handled in certain calls. Previously Rhino would * convert an undefined "this" to null, whereas recent specs call for it to be treated * differently. Default is to be set if language version &lt;= 1.7. * * @since 1.7.7 */ public static final int FEATURE_OLD_UNDEF_NULL_THIS = 15; /** * If set, then the order of property key enumeration will be first numeric keys in numeric * order, followed by string keys in order of creation, and finally Symbol keys, as specified in * ES6. Default is true for language version &gt;= "ES6" and false otherwise. * * @since 1.7.7.1 */ public static final int FEATURE_ENUMERATE_IDS_FIRST = 16; /** * If set, then all objects will have a thread-safe property map. (Note that this doesn't make * everything else that they do thread-safe -- that depends on the specific implementation. If * not set, users should not share Rhino objects between threads, unless the "sync" function is * used to wrap them with an explicit synchronizer. The default is false, which means that by * default, individual objects are not thread-safe. * * @since 1.7.8 */ public static final int FEATURE_THREAD_SAFE_OBJECTS = 17; /** * If set, then all integer numbers will be returned without decimal place. For instance assume * there is a function like this: <code>function foo() {return 5;}</code> 5 will be returned if * feature is set, 5.0 otherwise. */ public static final int FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE = 18; /** * TypedArray buffer uses little/big endian depending on the platform. The default is big endian * for Rhino. * * @since 1.7 Release 11 */ public static final int FEATURE_LITTLE_ENDIAN = 19; /** * Configure the XMLProcessor to parse XML with security features or not. Security features * include not fetching remote entity references and disabling XIncludes * * @since 1.7 Release 12 */ public static final int FEATURE_ENABLE_XML_SECURE_PARSING = 20; /** * Configure whether the entries in a Java Map can be accessed by properties. * * <p>Not enabled: * * <p>var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // undefined * * <p>Enabled: * * <p>var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // 1 * * <p>WARNING: This feature is similar to the one in Nashorn, but incomplete. * * <p>1. A entry has priority over method. * * <p>map.put("put", "abc"); map.put; // abc map.put("put", "efg"); // ERROR * * <p>2. The distinction between numeric keys and string keys is ambiguous. * * <p>map.put('1', 123); map['1']; // Not found. This means `map[1]`. * * @since 1.7 Release 14 */ public static final int FEATURE_ENABLE_JAVA_MAP_ACCESS = 21; public static final String languageVersionProperty = "language version"; public static final String errorReporterProperty = "error reporter"; /** Convenient value to use as zero-length array of objects. */ public static final Object[] emptyArgs = ScriptRuntime.emptyArgs; /** * Creates a new Context. The context will be associated with the {@link * ContextFactory#getGlobal() global context factory}. * * <p>Note that the Context must be associated with a thread before it can be used to execute a * script. * * @deprecated this constructor is deprecated because it creates a dependency on a static * singleton context factory. Use {@link ContextFactory#enter()} or {@link * ContextFactory#call(ContextAction)} instead. If you subclass this class, consider using * {@link #Context(ContextFactory)} constructor instead in the subclasses' constructors. */ @Deprecated public Context() { this(ContextFactory.getGlobal()); } /** * Creates a new context. Provided as a preferred super constructor for subclasses in place of * the deprecated default public constructor. * * @param factory the context factory associated with this context (most likely, the one that * created the context). Can not be null. The context features are inherited from the * factory, and the context will also otherwise use its factory's services. * @throws IllegalArgumentException if factory parameter is null. */ protected Context(ContextFactory factory) { if (factory == null) { throw new IllegalArgumentException("factory == null"); } this.factory = factory; version = VERSION_DEFAULT; optimizationLevel = codegenClass != null ? 0 : -1; maximumInterpreterStackDepth = Integer.MAX_VALUE; } /** * Get the current Context. * * <p>The current Context is per-thread; this method looks up the Context associated with the * current thread. * * <p> * * @return the Context associated with the current thread, or null if no context is associated * with the current thread. * @see ContextFactory#enterContext() * @see ContextFactory#call(ContextAction) */ public static Context getCurrentContext() { Object helper = VMBridge.instance.getThreadContextHelper(); return VMBridge.instance.getContext(helper); } /** * Same as calling {@link ContextFactory#enterContext()} on the global ContextFactory instance. * * @return a Context associated with the current thread * @see #getCurrentContext() * @see #exit() * @see #call(ContextAction) */ public static Context enter() { return enter(null, ContextFactory.getGlobal()); } /** * Get a Context associated with the current thread, using the given Context if need be. * * <p>The same as <code>enter()</code> except that <code>cx</code> is associated with the * current thread and returned if the current thread has no associated context and <code>cx * </code> is not associated with any other thread. * * @param cx a Context to associate with the thread if possible * @return a Context associated with the current thread * @deprecated use {@link ContextFactory#enterContext(Context)} instead as this method relies on * usage of a static singleton "global" ContextFactory. * @see ContextFactory#enterContext(Context) * @see ContextFactory#call(ContextAction) */ @Deprecated public static Context enter(Context cx) { return enter(cx, ContextFactory.getGlobal()); } static final Context enter(Context cx, ContextFactory factory) { Object helper = VMBridge.instance.getThreadContextHelper(); Context old = VMBridge.instance.getContext(helper); if (old != null) { cx = old; } else { if (cx == null) { cx = factory.makeContext(); if (cx.enterCount != 0) { throw new IllegalStateException( "factory.makeContext() returned Context instance already associated with some thread"); } factory.onContextCreated(cx); if (factory.isSealed() && !cx.isSealed()) { cx.seal(null); } } else { if (cx.enterCount != 0) { throw new IllegalStateException( "can not use Context instance already associated with some thread"); } } VMBridge.instance.setContext(helper, cx); } ++cx.enterCount; return cx; } /** * Exit a block of code requiring a Context. * * <p>Calling <code>exit()</code> will remove the association between the current thread and a * Context if the prior call to {@link ContextFactory#enterContext()} on this thread newly * associated a Context with this thread. Once the current thread no longer has an associated * Context, it cannot be used to execute JavaScript until it is again associated with a Context. * * @see ContextFactory#enterContext() */ public static void exit() { Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx == null) { throw new IllegalStateException("Calling Context.exit without previous Context.enter"); } if (cx.enterCount < 1) Kit.codeBug(); if (--cx.enterCount == 0) { VMBridge.instance.setContext(helper, null); cx.factory.onContextReleased(cx); } } @Override public void close() { exit(); } /** * Call {@link ContextAction#run(Context cx)} using the Context instance associated with the * current thread. If no Context is associated with the thread, then <code> * ContextFactory.getGlobal().makeContext()</code> will be called to construct new Context * instance. The instance will be temporary associated with the thread during call to {@link * ContextAction#run(Context)}. * * @deprecated use {@link ContextFactory#call(ContextAction)} instead as this method relies on * usage of a static singleton "global" ContextFactory. * @return The result of {@link ContextAction#run(Context)}. */ @Deprecated public static <T> T call(ContextAction<T> action) { return call(ContextFactory.getGlobal(), action); } /** * Call {@link Callable#call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)} * using the Context instance associated with the current thread. If no Context is associated * with the thread, then {@link ContextFactory#makeContext()} will be called to construct new * Context instance. The instance will be temporary associated with the thread during call to * {@link ContextAction#run(Context)}. * * <p>It is allowed but not advisable to use null for <code>factory</code> argument in which * case the global static singleton ContextFactory instance will be used to create new context * instances. * * @see ContextFactory#call(ContextAction) */ public static Object call( ContextFactory factory, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if (factory == null) { factory = ContextFactory.getGlobal(); } return call(factory, cx -> callable.call(cx, scope, thisObj, args)); } /** The method implements {@link ContextFactory#call(ContextAction)} logic. */ static <T> T call(ContextFactory factory, ContextAction<T> action) { Context cx = enter(null, factory); try { return action.run(cx); } finally { exit(); } } /** * @deprecated * @see ContextFactory#addListener(org.mozilla.javascript.ContextFactory.Listener) * @see ContextFactory#getGlobal() */ @Deprecated public static void addContextListener(ContextListener listener) { // Special workaround for the debugger String DBG = "org.mozilla.javascript.tools.debugger.Main"; if (DBG.equals(listener.getClass().getName())) { Class<?> cl = listener.getClass(); Class<?> factoryClass = Kit.classOrNull("org.mozilla.javascript.ContextFactory"); Class<?>[] sig = {factoryClass}; Object[] args = {ContextFactory.getGlobal()}; try { Method m = cl.getMethod("attachTo", sig); m.invoke(listener, args); } catch (Exception ex) { throw new RuntimeException(ex); } return; } ContextFactory.getGlobal().addListener(listener); } /** * @deprecated * @see ContextFactory#removeListener(org.mozilla.javascript.ContextFactory.Listener) * @see ContextFactory#getGlobal() */ @Deprecated public static void removeContextListener(ContextListener listener) { ContextFactory.getGlobal().addListener(listener); } /** Return {@link ContextFactory} instance used to create this Context. */ public final ContextFactory getFactory() { return factory; } /** * Checks if this is a sealed Context. A sealed Context instance does not allow to modify any of * its properties and will throw an exception on any such attempt. * * @see #seal(Object sealKey) */ public final boolean isSealed() { return sealed; } /** * Seal this Context object so any attempt to modify any of its properties including calling * {@link #enter()} and {@link #exit()} methods will throw an exception. * * <p>If <code>sealKey</code> is not null, calling {@link #unseal(Object sealKey)} with the same * key unseals the object. If <code>sealKey</code> is null, unsealing is no longer possible. * * @see #isSealed() * @see #unseal(Object) */ public final void seal(Object sealKey) { if (sealed) onSealedMutation(); sealed = true; this.sealKey = sealKey; } /** * Unseal previously sealed Context object. The <code>sealKey</code> argument should not be null * and should match <code>sealKey</code> suplied with the last call to {@link #seal(Object)} or * an exception will be thrown. * * @see #isSealed() * @see #seal(Object sealKey) */ public final void unseal(Object sealKey) { if (sealKey == null) throw new IllegalArgumentException(); if (this.sealKey != sealKey) throw new IllegalArgumentException(); if (!sealed) throw new IllegalStateException(); sealed = false; this.sealKey = null; } static void onSealedMutation() { throw new IllegalStateException(); } /** * Get the current language version. * * <p>The language version number affects JavaScript semantics as detailed in the overview * documentation. * * @return an integer that is one of VERSION_1_0, VERSION_1_1, etc. */ public final int getLanguageVersion() { return version; } /** * Set the language version. * * <p>Setting the language version will affect functions and scripts compiled subsequently. See * the overview documentation for version-specific behavior. * * @param version the version as specified by VERSION_1_0, VERSION_1_1, etc. */ public void setLanguageVersion(int version) { if (sealed) onSealedMutation(); checkLanguageVersion(version); Object listeners = propertyListeners; if (listeners != null && version != this.version) { firePropertyChangeImpl( listeners, languageVersionProperty, Integer.valueOf(this.version), Integer.valueOf(version)); } this.version = version; } public static boolean isValidLanguageVersion(int version) { switch (version) { case VERSION_DEFAULT: case VERSION_1_0: case VERSION_1_1: case VERSION_1_2: case VERSION_1_3: case VERSION_1_4: case VERSION_1_5: case VERSION_1_6: case VERSION_1_7: case VERSION_1_8: case VERSION_ES6: return true; } return false; } public static void checkLanguageVersion(int version) { if (isValidLanguageVersion(version)) { return; } throw new IllegalArgumentException("Bad language version: " + version); } /** * Get the implementation version. * * <p>The implementation version is of the form * * <pre> * "<i>name langVer</i> <code>release</code> <i>relNum date</i>" * </pre> * * where <i>name</i> is the name of the product, <i>langVer</i> is the language version, * <i>relNum</i> is the release number, and <i>date</i> is the release date for that specific * release in the form "yyyy mm dd". * * @return a string that encodes the product, language version, release number, and date. */ public final String getImplementationVersion() { return ImplementationVersion.get(); } /** * Get the current error reporter. * * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter getErrorReporter() { if (errorReporter == null) { return DefaultErrorReporter.instance; } return errorReporter; } /** * Change the current error reporter. * * @return the previous error reporter * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter setErrorReporter(ErrorReporter reporter) { if (sealed) onSealedMutation(); if (reporter == null) throw new IllegalArgumentException(); ErrorReporter old = getErrorReporter(); if (reporter == old) { return old; } Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl( listeners, errorReporterProperty, old, reporter); } this.errorReporter = reporter; return old; } /** * Get the current locale. Returns the default locale if none has been set. * * @see java.util.Locale */ public final Locale getLocale() { if (locale == null) locale = Locale.getDefault(); return locale; } /** * Set the current locale. * * @see java.util.Locale */ public final Locale setLocale(Locale loc) { if (sealed) onSealedMutation(); Locale result = locale; locale = loc; return result; } /** * Register an object to receive notifications when a bound property has changed * * @see java.beans.PropertyChangeEvent * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void addPropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.addListener(propertyListeners, l); } /** * Remove an object from the list of objects registered to receive notification of changes to a * bounded property * * @see java.beans.PropertyChangeEvent * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void removePropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.removeListener(propertyListeners, l); } /** * Notify any registered listeners that a bounded property has changed * * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @see java.beans.PropertyChangeListener * @see java.beans.PropertyChangeEvent * @param property the bound property * @param oldValue the old value * @param newValue the new value */ final void firePropertyChange(String property, Object oldValue, Object newValue) { Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, property, oldValue, newValue); } } private void firePropertyChangeImpl( Object listeners, String property, Object oldValue, Object newValue) { for (int i = 0; ; ++i) { Object l = Kit.getListener(listeners, i); if (l == null) break; if (l instanceof PropertyChangeListener) { PropertyChangeListener pcl = (PropertyChangeListener) l; pcl.propertyChange(new PropertyChangeEvent(this, property, oldValue, newValue)); } } } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = Context.getContext(); if (cx.hasFeature(FEATURE_WARNING_AS_ERROR)) reportError(message, sourceName, lineno, lineSource, lineOffset); else cx.getErrorReporter().warning(message, sourceName, lineno, lineSource, lineOffset); } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Context.reportWarning(message, filename, linep[0], null, 0); } public static void reportWarning(String message, Throwable t) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Writer sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(message); t.printStackTrace(pw); pw.flush(); Context.reportWarning(sw.toString(), filename, linep[0], null, 0); } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportError( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { cx.getErrorReporter().error(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); Context.reportError(message, filename, linep[0], null, 0); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @return a runtime exception that will be thrown to terminate the execution of the script * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError( String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { return cx.getErrorReporter() .runtimeError(message, sourceName, lineno, lineSource, lineOffset); } throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } static EvaluatorException reportRuntimeErrorById(String messageId, Object... args) { String msg = ScriptRuntime.getMessageById(messageId, args); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError0(String messageId) { String msg = ScriptRuntime.getMessageById(messageId); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError1(String messageId, Object arg1) { String msg = ScriptRuntime.getMessageById(messageId, arg1); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError2(String messageId, Object arg1, Object arg2) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError3( String messageId, Object arg1, Object arg2, Object arg3) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2, arg3); return reportRuntimeError(msg); } /** @deprecated Use {@link #reportRuntimeErrorById(String messageId, Object... args)} instead */ @Deprecated static EvaluatorException reportRuntimeError4( String messageId, Object arg1, Object arg2, Object arg3, Object arg4) { String msg = ScriptRuntime.getMessageById(messageId, arg1, arg2, arg3, arg4); return reportRuntimeError(msg); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message) { int[] linep = {0}; String filename = getSourcePositionFromStack(linep); return Context.reportRuntimeError(message, filename, linep[0], null, 0); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initStandardObjects() { return initStandardObjects(null, false); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initSafeStandardObjects() { return initSafeStandardObjects(null, false); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object which is an instance {@link ScriptableObject}. */ public final Scriptable initStandardObjects(ScriptableObject scope) { return initStandardObjects(scope, false); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object which is an instance {@link ScriptableObject}. */ public final Scriptable initSafeStandardObjects(ScriptableObject scope) { return initSafeStandardObjects(scope, false); } /** * Initialize the standard objects. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * <p>This form of the method also allows for creating "sealed" standard objects. An object that * is sealed cannot have properties added, changed, or removed. This is useful to create a * "superglobal" that can be shared among several top-level objects. Note that sealing is not * allowed in the current ECMA/ISO language specification, but is likely for the next version. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @param sealed whether or not to create sealed standard objects that cannot be modified. * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object. * @since 1.4R3 */ public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initStandardObjects(this, scope, sealed); } /** * Initialize the standard objects, leaving out those that offer access directly to Java * classes. This sets up "scope" to have access to all the standard JavaScript classes, but does * not create global objects for any top-level Java packages. In addition, the "Packages," * "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized. * * <p>The result of this function is a scope that may be safely used in a "sandbox" environment * where it is not desirable to give access to Java code from JavaScript. * * <p>Creates instances of the standard objects and their constructors (Object, String, Number, * Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. * * <p>This method must be called to initialize a scope before scripts can be evaluated in that * scope. * * <p>This method does not affect the Context it is called upon. * * <p>This form of the method also allows for creating "sealed" standard objects. An object that * is sealed cannot have properties added, changed, or removed. This is useful to create a * "superglobal" that can be shared among several top-level objects. Note that sealing is not * allowed in the current ECMA/ISO language specification, but is likely for the next version. * * @param scope the scope to initialize, or null, in which case a new object will be created to * serve as the scope * @param sealed whether or not to create sealed standard objects that cannot be modified. * @return the initialized scope. The method returns the value of the scope argument if it is * not null or newly allocated scope object. * @since 1.7.6 */ public ScriptableObject initSafeStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initSafeStandardObjects(this, scope, sealed); } /** Get the singleton object that represents the JavaScript Undefined value. */ public static Object getUndefinedValue() { return Undefined.instance; } /** * Evaluate a JavaScript source string. * * <p>The provided source name and line number are used for error messages and for producing * debug information. * * @param scope the scope to execute in * @param source the JavaScript source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return the result of evaluating the string * @see org.mozilla.javascript.SecurityController */ public final Object evaluateString( Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { Script script = compileString(source, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } return null; } /** * Evaluate a reader as JavaScript source. * * <p>All characters of the reader are consumed. * * @param scope the scope to execute in * @param in the Reader to get JavaScript source from * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return the result of evaluating the source * @exception IOException if an IOException was generated by the Reader */ public final Object evaluateReader( Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { Script script = compileReader(scope, in, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } return null; } /** * Execute script that may pause execution by capturing a continuation. Caller must be prepared * to catch a ContinuationPending exception and resume execution by calling {@link * #resumeContinuation(Object, Scriptable, Object)}. * * @param script The script to execute. Script must have been compiled with interpreted mode * (optimization level -1) * @param scope The scope to execute the script against * @throws ContinuationPending if the script calls a function that results in a call to {@link * #captureContinuation()} * @since 1.7 Release 2 */ public Object executeScriptWithContinuations(Script script, Scriptable scope) throws ContinuationPending { if (!(script instanceof InterpretedFunction) || !((InterpretedFunction) script).isScript()) { // Can only be applied to scripts throw new IllegalArgumentException( "Script argument was not" + " a script or was not created by interpreted mode "); } return callFunctionWithContinuations( (InterpretedFunction) script, scope, ScriptRuntime.emptyArgs); } /** * Call function that may pause execution by capturing a continuation. Caller must be prepared * to catch a ContinuationPending exception and resume execution by calling {@link * #resumeContinuation(Object, Scriptable, Object)}. * * @param function The function to call. The function must have been compiled with interpreted * mode (optimization level -1) * @param scope The scope to execute the script against * @param args The arguments for the function * @throws ContinuationPending if the script calls a function that results in a call to {@link * #captureContinuation()} * @since 1.7 Release 2 */ public Object callFunctionWithContinuations(Callable function, Scriptable scope, Object[] args) throws ContinuationPending { if (!(function instanceof InterpretedFunction)) { // Can only be applied to scripts throw new IllegalArgumentException( "Function argument was not" + " created by interpreted mode "); } if (ScriptRuntime.hasTopCall(this)) { throw new IllegalStateException( "Cannot have any pending top " + "calls when executing a script with continuations"); } // Annotate so we can check later to ensure no java code in // intervening frames isContinuationsTopCall = true; return ScriptRuntime.doTopCall(function, this, scope, scope, args, isTopLevelStrict); } /** * Capture a continuation from the current execution. The execution must have been started via a * call to {@link #executeScriptWithContinuations(Script, Scriptable)} or {@link * #callFunctionWithContinuations(Callable, Scriptable, Object[])}. This implies that the code * calling this method must have been called as a function from the JavaScript script. Also, * there cannot be any non-JavaScript code between the JavaScript frames (e.g., a call to * eval()). The ContinuationPending exception returned must be thrown. * * @return A ContinuationPending exception that must be thrown * @since 1.7 Release 2 */ public ContinuationPending captureContinuation() { return new ContinuationPending(Interpreter.captureContinuation(this)); } /** * Restarts execution of the JavaScript suspended at the call to {@link #captureContinuation()}. * Execution of the code will resume with the functionResult as the result of the call that * captured the continuation. Execution of the script will either conclude normally and the * result returned, another continuation will be captured and thrown, or the script will * terminate abnormally and throw an exception. * * @param continuation The value returned by {@link ContinuationPending#getContinuation()} * @param functionResult This value will appear to the code being resumed as the result of the * function that captured the continuation * @throws ContinuationPending if another continuation is captured before the code terminates * @since 1.7 Release 2 */ public Object resumeContinuation(Object continuation, Scriptable scope, Object functionResult) throws ContinuationPending { Object[] args = {functionResult}; return Interpreter.restartContinuation( (org.mozilla.javascript.NativeContinuation) continuation, this, scope, args); } /** * Check whether a string is ready to be compiled. * * <p>stringIsCompilableUnit is intended to support interactive compilation of JavaScript. If * compiling the string would result in an error that might be fixed by appending more source, * this method returns false. In every other case, it returns true. * * <p>Interactive shells may accumulate source lines, using this method after each new line is * appended to check whether the statement being entered is complete. * * @param source the source buffer to check * @return whether the source is ready for compilation * @since 1.4 Release 2 */ public final boolean stringIsCompilableUnit(String source) { boolean errorseen = false; CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); // no source name or source text manager, because we're just // going to throw away the result. compilerEnv.setGeneratingSource(false); Parser p = new Parser(compilerEnv, DefaultErrorReporter.instance); try { p.parse(source, null, 1); } catch (EvaluatorException ee) { errorseen = true; } // Return false only if an error occurred as a result of reading past // the end of the file, i.e. if the source could be fixed by // appending more source. return !(errorseen && p.eof()); } /** * @deprecated * @see #compileReader(Reader in, String sourceName, int lineno, Object securityDomain) */ @Deprecated public final Script compileReader( Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { return compileReader(in, sourceName, lineno, securityDomain); } /** * Compiles the source in the given reader. * * <p>Returns a script that may later be executed. Will consume all the source in the reader. * * @param in the input reader * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a script that may later be executed * @exception IOException if an IOException was generated by the Reader * @see org.mozilla.javascript.Script */ public final Script compileReader( Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return (Script) compileImpl( null, Kit.readReader(in), sourceName, lineno, securityDomain, false, null, null); } /** * Compiles the source in the given string. * * <p>Returns a script that may later be executed. * * @param source the source string * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors. Use 0 if the line number is * unknown. * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a script that may later be executed * @see org.mozilla.javascript.Script */ public final Script compileString( String source, String sourceName, int lineno, Object securityDomain) { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return compileString(source, null, null, sourceName, lineno, securityDomain); } final Script compileString( String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Script) compileImpl( null, source, sourceName, lineno, securityDomain, false, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should not happen when dealing with source as string throw new RuntimeException(ioe); } } /** * Compile a JavaScript function. * * <p>The function source must be a function definition as defined by ECMA (e.g., "function f(a) * { return a; }"). * * @param scope the scope to compile relative to * @param source the function definition source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security information about the * origin or owner of the script. For implementations that don't care about security, this * value may be null. * @return a Function that may later be called * @see org.mozilla.javascript.Function */ public final Function compileFunction( Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { return compileFunction(scope, source, null, null, sourceName, lineno, securityDomain); } final Function compileFunction( Scriptable scope, String source, Evaluator compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Function) compileImpl( scope, source, sourceName, lineno, securityDomain, true, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should never happen because we just made the reader // from a String throw new RuntimeException(ioe); } } /** * Decompile the script. * * <p>The canonical source of the script is returned. * * @param script the script to decompile * @param indent the number of spaces to indent the result * @return a string representing the script source */ public final String decompileScript(Script script, int indent) { NativeFunction scriptImpl = (NativeFunction) script; return scriptImpl.decompile(indent, 0); } /** * Decompile a JavaScript Function. * * <p>Decompiles a previously compiled JavaScript function object to canonical source. * * <p>Returns function body of '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function source */ public final String decompileFunction(Function fun, int indent) { if (fun instanceof BaseFunction) return ((BaseFunction) fun).decompile(indent, 0); return "function " + fun.getClassName() + "() {\n\t[native code]\n}\n"; } /** * Decompile the body of a JavaScript Function. * * <p>Decompiles the body a previously compiled JavaScript Function object to canonical source, * omitting the function header and trailing brace. * * <p>Returns '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function body source. */ public final String decompileFunctionBody(Function fun, int indent) { if (fun instanceof BaseFunction) { BaseFunction bf = (BaseFunction) fun; return bf.decompile(indent, Decompiler.ONLY_BODY_FLAG); } // ALERT: not sure what the right response here is. return "[native code]\n"; } /** * Create a new JavaScript object. * * <p>Equivalent to evaluating "new Object()". * * @param scope the scope to search for the constructor and to evaluate against * @return the new object */ public Scriptable newObject(Scriptable scope) { NativeObject result = new NativeObject(); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Object); return result; } /** * Create a new JavaScript object by executing the named constructor. * * <p>The call <code>newObject(scope, "Foo")</code> is equivalent to evaluating "new Foo()". * * @param scope the scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @return the new object */ public Scriptable newObject(Scriptable scope, String constructorName) { return newObject(scope, constructorName, ScriptRuntime.emptyArgs); } /** * Creates a new JavaScript object by executing the named constructor. * * <p>Searches <code>scope</code> for the named constructor, calls it with the given arguments, * and returns the result. * * <p>The code * * <pre> * Object[] args = { "a", "b" }; * newObject(scope, "Foo", args)</pre> * * is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo constructor has been * defined in <code>scope</code>. * * @param scope The scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @param args the array of arguments for the constructor * @return the new object */ public Scriptable newObject(Scriptable scope, String constructorName, Object[] args) { return ScriptRuntime.newObject(this, scope, constructorName, args); } /** * Create an array with a specified initial length. * * <p> * * @param scope the scope to create the object in * @param length the initial length (JavaScript arrays may have additional properties added * dynamically). * @return the new array object */ public Scriptable newArray(Scriptable scope, int length) { NativeArray result = new NativeArray(length); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array); return result; } /** * Create an array with a set of initial elements. * * @param scope the scope to create the object in. * @param elements the initial elements. Each object in this array must be an acceptable * JavaScript type and type of array should be exactly Object[], not SomeObjectSubclass[]. * @return the new array object. */ public Scriptable newArray(Scriptable scope, Object[] elements) { if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass) throw new IllegalArgumentException(); NativeArray result = new NativeArray(elements); ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array); return result; } /** * Get the elements of a JavaScript array. * * <p>If the object defines a length property convertible to double number, then the number is * converted Uint32 value as defined in Ecma 9.6 and Java array of that size is allocated. The * array is initialized with the values obtained by calling get() on object for each value of i * in [0,length-1]. If there is not a defined value for a property the Undefined value is used * to initialize the corresponding element in the array. The Java array is then returned. If the * object doesn't define a length property or it is not a number, empty array is returned. * * @param object the JavaScript array or array-like object * @return a Java array of objects * @since 1.4 release 2 */ public final Object[] getElements(Scriptable object) { return ScriptRuntime.getArrayElements(object); } /** * Convert the value to a JavaScript boolean value. * * <p>See ECMA 9.2. * * @param value a JavaScript value * @return the corresponding boolean value converted using the ECMA rules */ public static boolean toBoolean(Object value) { return ScriptRuntime.toBoolean(value); } /** * Convert the value to a JavaScript Number value. * * <p>Returns a Java double for the JavaScript Number. * * <p>See ECMA 9.3. * * @param value a JavaScript value * @return the corresponding double value converted using the ECMA rules */ public static double toNumber(Object value) { return ScriptRuntime.toNumber(value); } /** * Convert the value to a JavaScript String value. * * <p>See ECMA 9.8. * * <p> * * @param value a JavaScript value * @return the corresponding String value converted using the ECMA rules */ public static String toString(Object value) { return ScriptRuntime.toString(value); } /** * Convert the value to an JavaScript object value. * * <p>Note that a scope must be provided to look up the constructors for Number, Boolean, and * String. * * <p>See ECMA 9.9. * * <p>Additionally, arbitrary Java objects and classes will be wrapped in a Scriptable object * with its Java fields and methods reflected as JavaScript properties of the object. * * @param value any Java object * @param scope global scope containing constructors for Number, Boolean, and String * @return new JavaScript object */ public static Scriptable toObject(Object value, Scriptable scope) { return ScriptRuntime.toObject(scope, value); } /** * @deprecated * @see #toObject(Object, Scriptable) */ @Deprecated public static Scriptable toObject(Object value, Scriptable scope, Class<?> staticType) { return ScriptRuntime.toObject(scope, value); } /** * Convenient method to convert java value to its closest representation in JavaScript. * * <p>If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned * as it and will be treated as the corresponding JavaScript type of string, number, boolean, * function and object. * * <p>Note that for Number instances during any arithmetic operation in JavaScript the engine * will always use the result of <code>Number.doubleValue()</code> resulting in a precision loss * if the number can not fit into double. * * <p>If value is an instance of Character, it will be converted to string of length 1 and its * JavaScript type will be string. * * <p>The rest of values will be wrapped as LiveConnect objects by calling {@link * WrapFactory#wrap(Context cx, Scriptable scope, Object obj, Class staticType)} as in: * * <pre> * Context cx = Context.getCurrentContext(); * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope) { return javaToJS(value, scope, null); } /** * Convenient method to convert java value to its closest representation in JavaScript. * * <p>If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned * as it and will be treated as the corresponding JavaScript type of string, number, boolean, * function and object. * * <p>Note that for Number instances during any arithmetic operation in JavaScript the engine * will always use the result of <code>Number.doubleValue()</code> resulting in a precision loss * if the number can not fit into double. * * <p>If value is an instance of Character, it will be converted to string of length 1 and its * JavaScript type will be string. * * <p>The rest of values will be wrapped as LiveConnect objects by calling {@link * WrapFactory#wrap(Context cx, Scriptable scope, Object obj, Class staticType)} as in: * * <pre> * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @param cx context to use for wrapping LiveConnect objects * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope, Context cx) { if (value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof Scriptable) { return value; } else if (value instanceof Character) { return String.valueOf(((Character) value).charValue()); } else { if (cx == null) { cx = Context.getContext(); } return cx.getWrapFactory().wrap(cx, scope, value, null); } } /** * Convert a JavaScript value into the desired type. Uses the semantics defined with * LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed. * * @param value the JavaScript value to convert * @param desiredType the Java type to convert to. Primitive Java types are represented using * the TYPE fields in the corresponding wrapper class in java.lang. * @return the converted value * @throws EvaluatorException if the conversion cannot be performed */ public static Object jsToJava(Object value, Class<?> desiredType) throws EvaluatorException { return NativeJavaObject.coerceTypeImpl(desiredType, value); } /** * @deprecated * @see #jsToJava(Object, Class) * @throws IllegalArgumentException if the conversion cannot be performed. Note that {@link * #jsToJava(Object, Class)} throws {@link EvaluatorException} instead. */ @Deprecated public static Object toType(Object value, Class<?> desiredType) throws IllegalArgumentException { try { return jsToJava(value, desiredType); } catch (EvaluatorException ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } /** * Returns the javaToJSONConverter for this Context. * * <p>The converter is used by the JSON.stringify method for Java objects other than instances * of {@link java.util.Map Map}, {@link java.util.Collection Collection}, or {@link * java.lang.Object Object[]}. * * <p>The default converter if unset will convert Java Objects to their toString() value. * * @return javaToJSONConverter for this Context */ public UnaryOperator<Object> getJavaToJSONConverter() { if (javaToJSONConverter == null) { return JavaToJSONConverters.STRING; } return javaToJSONConverter; } /** * Sets the javaToJSONConverter for this Context. * * <p>The converter is used by the JSON.stringify method for Java objects other than instances * of {@link java.util.Map Map}, {@link java.util.Collection Collection}, or {@link * java.lang.Object Object[]}. * * <p>Objects returned by the converter will converted with {@link #javaToJS(Object, * Scriptable)} and then stringified themselves. * * @param javaToJSONConverter * @throws IllegalArgumentException if javaToJSONConverter is null */ public void setJavaToJSONConverter(UnaryOperator<Object> javaToJSONConverter) throws IllegalArgumentException { if (javaToJSONConverter == null) { throw new IllegalArgumentException("javaToJSONConverter == null"); } this.javaToJSONConverter = javaToJSONConverter; } /** * Rethrow the exception wrapping it as the script runtime exception. Unless the exception is * instance of {@link EcmaError} or {@link EvaluatorException} it will be wrapped as {@link * WrappedException}, a subclass of {@link EvaluatorException}. The resulting exception object * always contains source name and line number of script that triggered exception. * * <p>This method always throws an exception, its return value is provided only for convenience * to allow a usage like: * * <pre> * throw Context.throwAsScriptRuntimeEx(ex); * </pre> * * to indicate that code after the method is unreachable. * * @throws EvaluatorException * @throws EcmaError */ public static RuntimeException throwAsScriptRuntimeEx(Throwable e) { while ((e instanceof InvocationTargetException)) { e = ((InvocationTargetException) e).getTargetException(); } // special handling of Error so scripts would not catch them if (e instanceof Error) { Context cx = getContext(); if (cx == null || !cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { throw (Error) e; } } if (e instanceof RhinoException) { throw (RhinoException) e; } throw new WrappedException(e); } /** * Tell whether debug information is being generated. * * @since 1.3 */ public final boolean isGeneratingDebug() { return generatingDebug; } /** * Specify whether or not debug information should be generated. * * <p>Setting the generation of debug information on will set the optimization level to zero. * * @since 1.3 */ public final void setGeneratingDebug(boolean generatingDebug) { if (sealed) onSealedMutation(); generatingDebugChanged = true; if (generatingDebug && getOptimizationLevel() > 0) setOptimizationLevel(0); this.generatingDebug = generatingDebug; } /** * Tell whether source information is being generated. * * @since 1.3 */ public final boolean isGeneratingSource() { return generatingSource; } /** * Specify whether or not source information should be generated. * * <p>Without source information, evaluating the "toString" method on JavaScript functions * produces only "[native code]" for the body of the function. Note that code generated without * source is not fully ECMA conformant. * * @since 1.3 */ public final void setGeneratingSource(boolean generatingSource) { if (sealed) onSealedMutation(); this.generatingSource = generatingSource; } /** * Get the current optimization level. * * <p>The optimization level is expressed as an integer between -1 and 9. * * @since 1.3 */ public final int getOptimizationLevel() { return optimizationLevel; } /** * Set the current optimization level. * * <p>The optimization level is expected to be an integer between -1 and 9. Any negative values * will be interpreted as -1, and any values greater than 9 will be interpreted as 9. An * optimization level of -1 indicates that interpretive mode will always be used. Levels 0 * through 9 indicate that class files may be generated. Higher optimization levels trade off * compile time performance for runtime performance. The optimizer level can't be set greater * than -1 if the optimizer package doesn't exist at run time. * * @param optimizationLevel an integer indicating the level of optimization to perform * @since 1.3 */ public final void setOptimizationLevel(int optimizationLevel) { if (sealed) onSealedMutation(); if (optimizationLevel == -2) { // To be compatible with Cocoon fork optimizationLevel = -1; } checkOptimizationLevel(optimizationLevel); if (codegenClass == null) optimizationLevel = -1; this.optimizationLevel = optimizationLevel; } public static boolean isValidOptimizationLevel(int optimizationLevel) { return -1 <= optimizationLevel && optimizationLevel <= 9; } public static void checkOptimizationLevel(int optimizationLevel) { if (isValidOptimizationLevel(optimizationLevel)) { return; } throw new IllegalArgumentException( "Optimization level outside [-1..9]: " + optimizationLevel); } /** * Returns the maximum stack depth (in terms of number of call frames) allowed in a single * invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an * EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect * for interpreted functions (those compiled with optimization level set to -1). As the * interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a * runaway recursion in interpreted code would eventually consume all available memory and cause * OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @return The current maximum interpreter stack depth. */ public final int getMaximumInterpreterStackDepth() { return maximumInterpreterStackDepth; } /** * Sets the maximum stack depth (in terms of number of call frames) allowed in a single * invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an * EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect * for interpreted functions (those compiled with optimization level set to -1). As the * interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a * runaway recursion in interpreted code would eventually consume all available memory and cause * OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @param max the new maximum interpreter stack depth * @throws IllegalStateException if this context's optimization level is not -1 * @throws IllegalArgumentException if the new depth is not at least 1 */ public final void setMaximumInterpreterStackDepth(int max) { if (sealed) onSealedMutation(); if (optimizationLevel != -1) { throw new IllegalStateException( "Cannot set maximumInterpreterStackDepth when optimizationLevel != -1"); } if (max < 1) { throw new IllegalArgumentException( "Cannot set maximumInterpreterStackDepth to less than 1"); } maximumInterpreterStackDepth = max; } /** * Set the security controller for this context. * * <p>SecurityController may only be set if it is currently null and {@link * SecurityController#hasGlobal()} is <code>false</code>. Otherwise a SecurityException is * thrown. * * @param controller a SecurityController object * @throws SecurityException if there is already a SecurityController object for this Context or * globally installed. * @see SecurityController#initGlobal(SecurityController controller) * @see SecurityController#hasGlobal() */ public final void setSecurityController(SecurityController controller) { if (sealed) onSealedMutation(); if (controller == null) throw new IllegalArgumentException(); if (securityController != null) { throw new SecurityException("Can not overwrite existing SecurityController object"); } if (SecurityController.hasGlobal()) { throw new SecurityException( "Can not overwrite existing global SecurityController object"); } securityController = controller; } /** * Set the LiveConnect access filter for this context. * * <p>{@link ClassShutter} may only be set if it is currently null. Otherwise a * SecurityException is thrown. * * @param shutter a ClassShutter object * @throws SecurityException if there is already a ClassShutter object for this Context */ public final synchronized void setClassShutter(ClassShutter shutter) { if (sealed) onSealedMutation(); if (shutter == null) throw new IllegalArgumentException(); if (hasClassShutter) { throw new SecurityException("Cannot overwrite existing " + "ClassShutter object"); } classShutter = shutter; hasClassShutter = true; } final synchronized ClassShutter getClassShutter() { return classShutter; } public interface ClassShutterSetter { public void setClassShutter(ClassShutter shutter); public ClassShutter getClassShutter(); } public final synchronized ClassShutterSetter getClassShutterSetter() { if (hasClassShutter) return null; hasClassShutter = true; return new ClassShutterSetter() { @Override public void setClassShutter(ClassShutter shutter) { classShutter = shutter; } @Override public ClassShutter getClassShutter() { return classShutter; } }; } /** * Get a value corresponding to a key. * * <p>Since the Context is associated with a thread it can be used to maintain values that can * be later retrieved using the current thread. * * <p>Note that the values are maintained with the Context, so if the Context is disassociated * from the thread the values cannot be retrieved. Also, if private data is to be maintained in * this manner the key should be a java.lang.Object whose reference is not divulged to untrusted * code. * * @param key the key used to lookup the value * @return a value previously stored using putThreadLocal. */ public final Object getThreadLocal(Object key) { if (threadLocalMap == null) return null; return threadLocalMap.get(key); } /** * Put a value that can later be retrieved using a given key. * * <p> * * @param key the key used to index the value * @param value the value to save */ public final synchronized void putThreadLocal(Object key, Object value) { if (sealed) onSealedMutation(); if (threadLocalMap == null) threadLocalMap = new HashMap<Object, Object>(); threadLocalMap.put(key, value); } /** * Remove values from thread-local storage. * * @param key the key for the entry to remove. * @since 1.5 release 2 */ public final void removeThreadLocal(Object key) { if (sealed) onSealedMutation(); if (threadLocalMap == null) return; threadLocalMap.remove(key); } /** * @deprecated * @see ClassCache#get(Scriptable) * @see ClassCache#setCachingEnabled(boolean) */ @Deprecated public static void setCachingEnabled(boolean cachingEnabled) {} /** * Set a WrapFactory for this Context. * * <p>The WrapFactory allows custom object wrapping behavior for Java object manipulated with * JavaScript. * * @see WrapFactory * @since 1.5 Release 4 */ public final void setWrapFactory(WrapFactory wrapFactory) { if (sealed) onSealedMutation(); if (wrapFactory == null) throw new IllegalArgumentException(); this.wrapFactory = wrapFactory; } /** * Return the current WrapFactory, or null if none is defined. * * @see WrapFactory * @since 1.5 Release 4 */ public final WrapFactory getWrapFactory() { if (wrapFactory == null) { wrapFactory = new WrapFactory(); } return wrapFactory; } /** * Return the current debugger. * * @return the debugger, or null if none is attached. */ public final Debugger getDebugger() { return debugger; } /** * Return the debugger context data associated with current context. * * @return the debugger data, or null if debugger is not attached */ public final Object getDebuggerContextData() { return debuggerData; } /** * Set the associated debugger. * * @param debugger the debugger to be used on callbacks from the engine. * @param contextData arbitrary object that debugger can use to store per Context data. */ public final void setDebugger(Debugger debugger, Object contextData) { if (sealed) onSealedMutation(); this.debugger = debugger; debuggerData = contextData; } /** * Return DebuggableScript instance if any associated with the script. If callable supports * DebuggableScript implementation, the method returns it. Otherwise null is returned. */ public static DebuggableScript getDebuggableView(Script script) { if (script instanceof NativeFunction) { return ((NativeFunction) script).getDebuggableView(); } return null; } /** * Controls certain aspects of script semantics. Should be overwritten to alter default * behavior. * * <p>The default implementation calls {@link ContextFactory#hasFeature(Context cx, int * featureIndex)} that allows to customize Context behavior without introducing Context * subclasses. {@link ContextFactory} documentation gives an example of hasFeature * implementation. * * @param featureIndex feature index to check * @return true if the <code>featureIndex</code> feature is turned on * @see #FEATURE_NON_ECMA_GET_YEAR * @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME * @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER * @see #FEATURE_TO_STRING_AS_SOURCE * @see #FEATURE_PARENT_PROTO_PROPRTIES * @see #FEATURE_E4X * @see #FEATURE_DYNAMIC_SCOPE * @see #FEATURE_STRICT_VARS * @see #FEATURE_STRICT_EVAL * @see #FEATURE_LOCATION_INFORMATION_IN_ERROR * @see #FEATURE_STRICT_MODE * @see #FEATURE_WARNING_AS_ERROR * @see #FEATURE_ENHANCED_JAVA_ACCESS */ public boolean hasFeature(int featureIndex) { ContextFactory f = getFactory(); return f.hasFeature(this, featureIndex); } /** * Returns an object which specifies an E4X implementation to use within this <code>Context * </code>. Note that the XMLLib.Factory interface should be considered experimental. * * <p>The default implementation uses the implementation provided by this <code>Context</code>'s * {@link ContextFactory}. * * @return An XMLLib.Factory. Should not return <code>null</code> if {@link #FEATURE_E4X} is * enabled. See {@link #hasFeature}. */ public XMLLib.Factory getE4xImplementationFactory() { return getFactory().getE4xImplementationFactory(); } /** * Get threshold of executed instructions counter that triggers call to <code> * observeInstructionCount()</code>. When the threshold is zero, instruction counting is * disabled, otherwise each time the run-time executes at least the threshold value of script * instructions, <code>observeInstructionCount()</code> will be called. */ public final int getInstructionObserverThreshold() { return instructionThreshold; } /** * Set threshold of executed instructions counter that triggers call to <code> * observeInstructionCount()</code>. When the threshold is zero, instruction counting is * disabled, otherwise each time the run-time executes at least the threshold value of script * instructions, <code>observeInstructionCount()</code> will be called.<br> * Note that the meaning of "instruction" is not guaranteed to be consistent between compiled * and interpretive modes: executing a given script or function in the different modes will * result in different instruction counts against the threshold. {@link * #setGenerateObserverCount} is called with true if <code>threshold</code> is greater than * zero, false otherwise. * * @param threshold The instruction threshold */ public final void setInstructionObserverThreshold(int threshold) { if (sealed) onSealedMutation(); if (threshold < 0) throw new IllegalArgumentException(); instructionThreshold = threshold; setGenerateObserverCount(threshold > 0); } /** * Turn on or off generation of code with callbacks to track the count of executed instructions. * Currently only affects JVM byte code generation: this slows down the generated code, but code * generated without the callbacks will not be counted toward instruction thresholds. Rhino's * interpretive mode does instruction counting without inserting callbacks, so there is no * requirement to compile code differently. * * @param generateObserverCount if true, generated code will contain calls to accumulate an * estimate of the instructions executed. */ public void setGenerateObserverCount(boolean generateObserverCount) { this.generateObserverCount = generateObserverCount; } /** * Allow application to monitor counter of executed script instructions in Context subclasses. * Run-time calls this when instruction counting is enabled and the counter reaches limit set by * <code>setInstructionObserverThreshold()</code>. The method is useful to observe long running * scripts and if necessary to terminate them. * * <p>The default implementation calls {@link ContextFactory#observeInstructionCount(Context cx, * int instructionCount)} that allows to customize Context behavior without introducing Context * subclasses. * * @param instructionCount amount of script instruction executed since last call to <code> * observeInstructionCount</code> * @throws Error to terminate the script * @see #setOptimizationLevel(int) */ protected void observeInstructionCount(int instructionCount) { ContextFactory f = getFactory(); f.observeInstructionCount(this, instructionCount); } /** * Create class loader for generated classes. The method calls {@link * ContextFactory#createClassLoader(ClassLoader)} using the result of {@link #getFactory()}. */ public GeneratedClassLoader createClassLoader(ClassLoader parent) { ContextFactory f = getFactory(); return f.createClassLoader(parent); } public final ClassLoader getApplicationClassLoader() { if (applicationClassLoader == null) { ContextFactory f = getFactory(); ClassLoader loader = f.getApplicationClassLoader(); if (loader == null) { ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); if (threadLoader != null && Kit.testIfCanLoadRhinoClasses(threadLoader)) { // Thread.getContextClassLoader is not cached since // its caching prevents it from GC which may lead to // a memory leak and hides updates to // Thread.getContextClassLoader return threadLoader; } // Thread.getContextClassLoader can not load Rhino classes, // try to use the loader of ContextFactory or Context // subclasses. Class<?> fClass = f.getClass(); if (fClass != ScriptRuntime.ContextFactoryClass) { loader = fClass.getClassLoader(); } else { loader = getClass().getClassLoader(); } } applicationClassLoader = loader; } return applicationClassLoader; } public final void setApplicationClassLoader(ClassLoader loader) { if (sealed) onSealedMutation(); if (loader == null) { // restore default behaviour applicationClassLoader = null; return; } if (!Kit.testIfCanLoadRhinoClasses(loader)) { throw new IllegalArgumentException("Loader can not resolve Rhino classes"); } applicationClassLoader = loader; } /********** end of API **********/ /** Internal method that reports an error for missing calls to enter(). */ static Context getContext() { Context cx = getCurrentContext(); if (cx == null) { throw new RuntimeException("No Context associated with current Thread"); } return cx; } protected Object compileImpl( Scriptable scope, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws IOException { if (sourceName == null) { sourceName = "unnamed script"; } if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } ScriptNode tree = parse( sourceString, sourceName, lineno, compilerEnv, compilationErrorReporter, returnFunction); Object bytecode; try { if (compiler == null) { compiler = createCompiler(); } bytecode = compiler.compile(compilerEnv, tree, tree.getEncodedSource(), returnFunction); } catch (ClassFileFormatException e) { // we hit some class file limit, fall back to interpreter or report // we have to recreate the tree because the compile call might have changed the tree // already tree = parse( sourceString, sourceName, lineno, compilerEnv, compilationErrorReporter, returnFunction); compiler = createInterpreter(); bytecode = compiler.compile(compilerEnv, tree, tree.getEncodedSource(), returnFunction); } if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript) bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; } private ScriptNode parse( String sourceString, String sourceName, int lineno, CompilerEnvirons compilerEnv, ErrorReporter compilationErrorReporter, boolean returnFunction) throws IOException { Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } if (isStrictMode()) { p.setDefaultUseStrictDirective(true); } AstRoot ast = p.parse(sourceString, sourceName, lineno); if (returnFunction) { // parser no longer adds function to script node if (!(ast.getFirstChild() != null && ast.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just looks for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: " + sourceString); } } IRFactory irf = new IRFactory(compilerEnv, compilationErrorReporter); ScriptNode tree = irf.transformTree(ast); return tree; } private static void notifyDebugger_r(Context cx, DebuggableScript dscript, String debugSource) { cx.debugger.handleCompilationDone(cx, dscript, debugSource); for (int i = 0; i != dscript.getFunctionCount(); ++i) { notifyDebugger_r(cx, dscript.getFunction(i), debugSource); } } private static Class<?> codegenClass = Kit.classOrNull("org.mozilla.javascript.optimizer.Codegen"); private static Class<?> interpreterClass = Kit.classOrNull("org.mozilla.javascript.Interpreter"); private Evaluator createCompiler() { Evaluator result = null; if (optimizationLevel >= 0 && codegenClass != null) { result = (Evaluator) Kit.newInstanceOrNull(codegenClass); } if (result == null) { result = createInterpreter(); } return result; } static Evaluator createInterpreter() { return (Evaluator) Kit.newInstanceOrNull(interpreterClass); } static String getSourcePositionFromStack(int[] linep) { Context cx = getCurrentContext(); if (cx == null) return null; if (cx.lastInterpreterFrame != null) { Evaluator evaluator = createInterpreter(); if (evaluator != null) return evaluator.getSourcePositionFromStack(cx, linep); } /** * A bit of a hack, but the only way to get filename and line number from an enclosing * frame. */ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); for (StackTraceElement st : stackTrace) { String file = st.getFileName(); if (!(file == null || file.endsWith(".java"))) { int line = st.getLineNumber(); if (line >= 0) { linep[0] = line; return file; } } } return null; } RegExpProxy getRegExpProxy() { if (regExpProxy == null) { Class<?> cl = Kit.classOrNull("org.mozilla.javascript.regexp.RegExpImpl"); if (cl != null) { regExpProxy = (RegExpProxy) Kit.newInstanceOrNull(cl); } } return regExpProxy; } final boolean isVersionECMA1() { return version == VERSION_DEFAULT || version >= VERSION_1_3; } // The method must NOT be public or protected SecurityController getSecurityController() { SecurityController global = SecurityController.global(); if (global != null) { return global; } return securityController; } public final boolean isGeneratingDebugChanged() { return generatingDebugChanged; } /** * Add a name to the list of names forcing the creation of real activation objects for * functions. * * @param name the name of the object to add to the list */ public void addActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames == null) activationNames = new HashSet<String>(); activationNames.add(name); } /** * Check whether the name is in the list of names of objects forcing the creation of activation * objects. * * @param name the name of the object to test * @return true if an function activation object is needed. */ public final boolean isActivationNeeded(String name) { return activationNames != null && activationNames.contains(name); } /** * Remove a name from the list of names forcing the creation of real activation objects for * functions. * * @param name the name of the object to remove from the list */ public void removeActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames != null) activationNames.remove(name); } public final boolean isStrictMode() { return isTopLevelStrict || (currentActivationCall != null && currentActivationCall.isStrict); } private final ContextFactory factory; private boolean sealed; private Object sealKey; Scriptable topCallScope; boolean isContinuationsTopCall; NativeCall currentActivationCall; XMLLib cachedXMLLib; BaseFunction typeErrorThrower; // for Objects, Arrays to tag themselves as being printed out, // so they don't print themselves out recursively. // Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility ObjToIntMap iterating; Object interpreterSecurityDomain; int version; private SecurityController securityController; private boolean hasClassShutter; private ClassShutter classShutter; private ErrorReporter errorReporter; RegExpProxy regExpProxy; private Locale locale; private boolean generatingDebug; private boolean generatingDebugChanged; private boolean generatingSource = true; boolean useDynamicScope; private int optimizationLevel; private int maximumInterpreterStackDepth; private WrapFactory wrapFactory; Debugger debugger; private Object debuggerData; private int enterCount; private Object propertyListeners; private Map<Object, Object> threadLocalMap; private ClassLoader applicationClassLoader; private UnaryOperator<Object> javaToJSONConverter; /** This is the list of names of objects forcing the creation of function activation records. */ Set<String> activationNames; // For the interpreter to store the last frame for error reports etc. Object lastInterpreterFrame; // For the interpreter to store information about previous invocations // interpreter invocations ObjArray previousInterpreterInvocations; // For instruction counting (interpreter only) int instructionCount; int instructionThreshold; // It can be used to return the second uint32 result from function long scratchUint32; // It can be used to return the second Scriptable result from function Scriptable scratchScriptable; // Generate an observer count on compiled code public boolean generateObserverCount = false; boolean isTopLevelStrict; }
Trying to make spotless happy
src/org/mozilla/javascript/Context.java
Trying to make spotless happy
Java
mpl-2.0
5cbdbf97a150a03bcf5ee2847d8576ab28dd2563
0
mozilla-mobile/focus-android,layely/focus-android,layely/focus-android,Benestar/focus-android,mastizada/focus-android,liuche/focus-android,layely/focus-android,codebu5ter/focus-android,Benestar/focus-android,ekager/focus-android,liuche/focus-android,pocmo/focus-android,codebu5ter/focus-android,mozilla-mobile/focus-android,mastizada/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,Benestar/focus-android,layely/focus-android,Achintya999/focus-android,mastizada/focus-android,Achintya999/focus-android,Achintya999/focus-android,mozilla-mobile/focus-android,pocmo/focus-android,Benestar/focus-android,jonalmeida/focus-android,liuche/focus-android,codebu5ter/focus-android,jonalmeida/focus-android,layely/focus-android,jonalmeida/focus-android,mastizada/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,Benestar/focus-android,ekager/focus-android,liuche/focus-android,mozilla-mobile/focus-android,pocmo/focus-android,ekager/focus-android,ekager/focus-android,liuche/focus-android,jonalmeida/focus-android,ekager/focus-android,pocmo/focus-android,pocmo/focus-android,Achintya999/focus-android,pocmo/focus-android,mastizada/focus-android,codebu5ter/focus-android,liuche/focus-android,ekager/focus-android
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.net.Uri; import android.text.TextUtils; public class UrlUtils { public static String normalize(String input) { Uri uri = Uri.parse(input); if (TextUtils.isEmpty(uri.getScheme())) { uri = Uri.parse("http://" + input); } return uri.toString(); } public static boolean isHttps(String url) { // TODO: This should actually check the certificate! return url.startsWith("https:"); } /** * Is the given string a URL or should we perform a search? * * TODO: This is a super simple and probably stupid implementation. */ public static boolean isUrl(String url) { if (url.contains(" ")) { return false; } return url.contains("."); } public static boolean isSearchQuery(String text) { return text.contains(" "); } public static String createSearchUrl(String rawUrl) { return Uri.parse("https://duckduckgo.com/").buildUpon() .appendQueryParameter("q", rawUrl) .build() .toString(); } }
app/src/main/java/org/mozilla/focus/utils/UrlUtils.java
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.net.Uri; import android.text.TextUtils; public class UrlUtils { public static String normalize(String input) { Uri uri = Uri.parse(input); if (TextUtils.isEmpty(uri.getScheme())) { uri = uri.buildUpon().scheme("http").build(); } return uri.toString(); } public static boolean isHttps(String url) { // TODO: This should actually check the certificate! return url.startsWith("https:"); } /** * Is the given string a URL or should we perform a search? * * TODO: This is a super simple and probably stupid implementation. */ public static boolean isUrl(String url) { if (url.contains(" ")) { return false; } return url.contains("."); } public static boolean isSearchQuery(String text) { return text.contains(" "); } public static String createSearchUrl(String rawUrl) { return Uri.parse("https://duckduckgo.com/").buildUpon() .appendQueryParameter("q", rawUrl) .build() .toString(); } }
Manually prepend http:// as necessary For some reason the URI build is not working correctly, we end up with bbc.com turning into http:/bbc.com, which is not a valid URL.
app/src/main/java/org/mozilla/focus/utils/UrlUtils.java
Manually prepend http:// as necessary
Java
agpl-3.0
6a0e15b20c1f2659e23834fcdaed000959ff2eac
0
OpenLMIS/openlmis-referencedata,OpenLMIS/openlmis-referencedata,OpenLMIS/openlmis-referencedata,OpenLMIS/openlmis-referencedata
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org. */ package org.openlmis.referencedata.security; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; public class CustomTokenServices extends RemoteTokenServices { private int invalidTokenRetryLimit; public CustomTokenServices(int invalidTokenRetryLimit) { super(); this.invalidTokenRetryLimit = invalidTokenRetryLimit; } @Override public OAuth2Authentication loadAuthentication(String accessToken) { return loadAuthentication(accessToken, 0); } private OAuth2Authentication loadAuthentication(String accessToken, int attempt) { try { return super.loadAuthentication(accessToken); } catch (InvalidTokenException e) { if (attempt < invalidTokenRetryLimit) { attempt++; logger.debug("Retrying authentication load. Retry number: " + attempt); return loadAuthentication(accessToken, attempt); } else { throw e; } } } }
src/main/java/org/openlmis/referencedata/security/CustomTokenServices.java
package org.openlmis.referencedata.security; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; public class CustomTokenServices extends RemoteTokenServices { private int invalidTokenRetryLimit; public CustomTokenServices(int invalidTokenRetryLimit) { super(); this.invalidTokenRetryLimit = invalidTokenRetryLimit; } @Override public OAuth2Authentication loadAuthentication(String accessToken) { return loadAuthentication(accessToken, 0); } private OAuth2Authentication loadAuthentication(String accessToken, int attempt) { try { return super.loadAuthentication(accessToken); } catch (InvalidTokenException e) { if (attempt < invalidTokenRetryLimit) { attempt++; logger.debug("Retrying authentication load. Retry number: " + attempt); return loadAuthentication(accessToken, attempt); } else throw e; } } }
OLMIS-6776: Added license header
src/main/java/org/openlmis/referencedata/security/CustomTokenServices.java
OLMIS-6776: Added license header
Java
agpl-3.0
0bf2444d4c5515c062b3ddb641446f8ff036f179
0
zuowang/voltdb,simonzhangsm/voltdb,creative-quant/voltdb,wolffcm/voltdb,migue/voltdb,deerwalk/voltdb,zuowang/voltdb,VoltDB/voltdb,paulmartel/voltdb,migue/voltdb,zuowang/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,migue/voltdb,ingted/voltdb,migue/voltdb,VoltDB/voltdb,creative-quant/voltdb,flybird119/voltdb,wolffcm/voltdb,paulmartel/voltdb,kumarrus/voltdb,wolffcm/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,ingted/voltdb,VoltDB/voltdb,ingted/voltdb,creative-quant/voltdb,kumarrus/voltdb,ingted/voltdb,deerwalk/voltdb,ingted/voltdb,creative-quant/voltdb,kumarrus/voltdb,flybird119/voltdb,flybird119/voltdb,deerwalk/voltdb,zuowang/voltdb,paulmartel/voltdb,zuowang/voltdb,wolffcm/voltdb,wolffcm/voltdb,deerwalk/voltdb,migue/voltdb,simonzhangsm/voltdb,flybird119/voltdb,zuowang/voltdb,zuowang/voltdb,deerwalk/voltdb,kumarrus/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,paulmartel/voltdb,flybird119/voltdb,wolffcm/voltdb,ingted/voltdb,zuowang/voltdb,kumarrus/voltdb,wolffcm/voltdb,flybird119/voltdb,migue/voltdb,creative-quant/voltdb,deerwalk/voltdb,VoltDB/voltdb,kumarrus/voltdb,deerwalk/voltdb,paulmartel/voltdb,migue/voltdb,ingted/voltdb,wolffcm/voltdb,VoltDB/voltdb,deerwalk/voltdb,ingted/voltdb,flybird119/voltdb,creative-quant/voltdb,flybird119/voltdb,migue/voltdb,kumarrus/voltdb,VoltDB/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.Map.Entry; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientImpl; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.client.ReplicaProcCaller; import org.voltdb.client.SyncCallback; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.iv2.MpInitiator; import org.voltdb.iv2.UniqueIdGenerator; import org.voltdb.utils.VoltFile; public class TestReplicatedInvocation { ServerThread server; File root; ReplicationRole role = ReplicationRole.REPLICA; @Before public void setUp() throws IOException { VoltProjectBuilder builder = new VoltProjectBuilder(); String schema = " create table A (i integer not null, primary key (i));"; builder.addLiteralSchema(schema); builder.addPartitionInfo("A", "i"); builder.addProcedures(ReplicatedProcedure.class); root = File.createTempFile("temp", "replicatedinvocation"); root.delete(); assertTrue(root.mkdir()); File cat = File.createTempFile("temp", "replicatedinvocationcat"); cat.deleteOnExit(); assertTrue(builder.compile(cat.getAbsolutePath(), 2, 1, 0, root.getAbsolutePath())); String deployment = builder.getPathToDeployment(); // start server server = new ServerThread(cat.getAbsolutePath(), deployment, BackendTarget.NATIVE_EE_JNI); server.m_config.m_replicationRole = role; server.start(); server.waitForInitialization(); } @After public void tearDown() throws IOException, InterruptedException { server.shutdown(); VoltFile.recursivelyDelete(root); } /** * Test promoting a replica to master * @throws Exception */ @Test public void testPromote() throws Exception { if (role != ReplicationRole.REPLICA) { return; } Client client = ClientFactory.createClient(); client.createConnection("localhost"); ClientResponse resp = client.callProcedure("@SystemInformation", "overview"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); VoltTable result = resp.getResults()[0]; while (result.advanceRow()) { if (result.getString("KEY").equalsIgnoreCase("replicationrole")) { assertTrue(result.getString("VALUE").equalsIgnoreCase("replica")); } } resp = client.callProcedure("@Promote"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); resp = client.callProcedure("@SystemInformation", "overview"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); result = resp.getResults()[0]; while (result.advanceRow()) { if (result.getString("KEY").equalsIgnoreCase("replicationrole")) { assertTrue(result.getString("VALUE").equalsIgnoreCase("none")); } } } /** * Send a replicated procedure invocation and checks if the procedure sees * the specified txn ID. */ @Test public void testReplicatedInvocation() throws Exception { ClientImpl client = (ClientImpl) ClientFactory.createClient(); client.createConnection("localhost"); ReplicaProcCaller pc = client; SyncCallback callback = new SyncCallback(); long uid = UniqueIdGenerator.makeIdFromComponents(System.currentTimeMillis(), 4, MpInitiator.MP_INIT_PID); pc.callProcedure(3, uid, callback, "ReplicatedProcedure", 1, "haha"); callback.waitForResponse(); ClientResponse response = callback.getResponse(); assertEquals(ClientResponse.SUCCESS, response.getStatus()); VoltTable result = VoltTable.fromJSONString(response.getAppStatusString()); result.advanceRow(); assertEquals(3, result.getLong("txnId")); assertEquals(uid, result.getLong("timestamp")); client.close(); } @Test public void testAcceptanceOnPrimary() throws Exception { Client client = ClientFactory.createClient(); client.createConnection("localhost"); try { client.callProcedure("A.insert", 1); } catch (ProcCallException e) { if (role == ReplicationRole.REPLICA) { client.close(); return; } else { throw e; } } if (role == ReplicationRole.REPLICA) { fail("Should not succeed on replica cluster"); } } @Test public void testSysprocAcceptanceOnReplica() { ReplicaInvocationAcceptancePolicy policy = new ReplicaInvocationAcceptancePolicy(true); for (Entry<String, Config> e : SystemProcedureCatalog.listing.entrySet()) { StoredProcedureInvocation invocation = new StoredProcedureInvocation(); invocation.procName = e.getKey(); if (e.getKey().equalsIgnoreCase("@UpdateApplicationCatalog") || e.getKey().equalsIgnoreCase("@SnapshotRestore") || e.getKey().equalsIgnoreCase("@BalancePartitions") || e.getKey().equalsIgnoreCase("@LoadMultipartitionTable") || e.getKey().equalsIgnoreCase("@LoadSinglePartitionTable") || e.getKey().equalsIgnoreCase("@UpdateTopology")) { // Rejected assertTrue(policy.shouldAccept(null, invocation, e.getValue().asCatalogProcedure()) != null); } else if (e.getKey().equalsIgnoreCase("@AdHoc")) { // Accepted invocation.setParams("select * from A"); assertTrue(policy.shouldAccept(null, invocation, e.getValue().asCatalogProcedure()) == null); // Rejected invocation.setParams("insert into A values (1, 2, 3)"); assertTrue(policy.shouldAccept(null, invocation, e.getValue().asCatalogProcedure()) != null); } else { // Accepted assertTrue(policy.shouldAccept(null, invocation, e.getValue().asCatalogProcedure()) == null); } } } }
tests/frontend/org/voltdb/TestReplicatedInvocation.java
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.Map.Entry; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientImpl; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.client.ReplicaProcCaller; import org.voltdb.client.SyncCallback; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.iv2.MpInitiator; import org.voltdb.iv2.UniqueIdGenerator; import org.voltdb.utils.VoltFile; public class TestReplicatedInvocation { ServerThread server; File root; ReplicationRole role = ReplicationRole.REPLICA; @Before public void setUp() throws IOException { VoltProjectBuilder builder = new VoltProjectBuilder(); String schema = " create table A (i integer not null, primary key (i));"; builder.addLiteralSchema(schema); builder.addPartitionInfo("A", "i"); builder.addProcedures(ReplicatedProcedure.class); root = File.createTempFile("temp", "replicatedinvocation"); root.delete(); assertTrue(root.mkdir()); File cat = File.createTempFile("temp", "replicatedinvocationcat"); cat.deleteOnExit(); assertTrue(builder.compile(cat.getAbsolutePath(), 2, 1, 0, root.getAbsolutePath())); String deployment = builder.getPathToDeployment(); // start server server = new ServerThread(cat.getAbsolutePath(), deployment, BackendTarget.NATIVE_EE_JNI); server.m_config.m_replicationRole = role; server.start(); server.waitForInitialization(); } @After public void tearDown() throws IOException, InterruptedException { server.shutdown(); VoltFile.recursivelyDelete(root); } /** * Test promoting a replica to master * @throws Exception */ @Test public void testPromote() throws Exception { if (role != ReplicationRole.REPLICA) { return; } Client client = ClientFactory.createClient(); client.createConnection("localhost"); ClientResponse resp = client.callProcedure("@SystemInformation", "overview"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); VoltTable result = resp.getResults()[0]; while (result.advanceRow()) { if (result.getString("KEY").equalsIgnoreCase("replicationrole")) { assertTrue(result.getString("VALUE").equalsIgnoreCase("replica")); } } resp = client.callProcedure("@Promote"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); resp = client.callProcedure("@SystemInformation", "overview"); assertEquals(ClientResponse.SUCCESS, resp.getStatus()); result = resp.getResults()[0]; while (result.advanceRow()) { if (result.getString("KEY").equalsIgnoreCase("replicationrole")) { assertTrue(result.getString("VALUE").equalsIgnoreCase("none")); } } } /** * Send a replicated procedure invocation and checks if the procedure sees * the specified txn ID. */ @Test public void testReplicatedInvocation() throws Exception { ClientImpl client = (ClientImpl) ClientFactory.createClient(); client.createConnection("localhost"); ReplicaProcCaller pc = client; SyncCallback callback = new SyncCallback(); long uid = UniqueIdGenerator.makeIdFromComponents(System.currentTimeMillis(), 4, MpInitiator.MP_INIT_PID); pc.callProcedure(3, uid, callback, "ReplicatedProcedure", 1, "haha"); callback.waitForResponse(); ClientResponse response = callback.getResponse(); assertEquals(ClientResponse.SUCCESS, response.getStatus()); VoltTable result = VoltTable.fromJSONString(response.getAppStatusString()); result.advanceRow(); assertEquals(3, result.getLong("txnId")); assertEquals(uid, result.getLong("timestamp")); client.close(); } @Test public void testAcceptanceOnPrimary() throws Exception { Client client = ClientFactory.createClient(); client.createConnection("localhost"); try { client.callProcedure("A.insert", 1); } catch (ProcCallException e) { if (role == ReplicationRole.REPLICA) { client.close(); return; } else { throw e; } } if (role == ReplicationRole.REPLICA) { fail("Should not succeed on replica cluster"); } } @Test public void testSysprocAcceptanceOnReplica() { ReplicaInvocationAcceptancePolicy policy = new ReplicaInvocationAcceptancePolicy(true); for (Entry<String, Config> e : SystemProcedureCatalog.listing.entrySet()) { StoredProcedureInvocation invocation = new StoredProcedureInvocation(); invocation.procName = e.getKey(); if (e.getKey().equalsIgnoreCase("@UpdateApplicationCatalog") || e.getKey().equalsIgnoreCase("@SnapshotRestore") || e.getKey().equalsIgnoreCase("@BalancePartitions") || e.getKey().equalsIgnoreCase("@LoadMultipartitionTable") || e.getKey().equalsIgnoreCase("@LoadSinglePartitionTable") || e.getKey().equalsIgnoreCase("@UpdateTopology")) { // Rejected assertTrue(policy.shouldAccept(null, invocation, e.getValue()) != null); } else if (e.getKey().equalsIgnoreCase("@AdHoc")) { // Accepted invocation.setParams("select * from A"); assertTrue(policy.shouldAccept(null, invocation, e.getValue()) == null); // Rejected invocation.setParams("insert into A values (1, 2, 3)"); assertTrue(policy.shouldAccept(null, invocation, e.getValue()) != null); } else { // Accepted assertTrue(policy.shouldAccept(null, invocation, e.getValue()) == null); } } } }
ENG-4449: Test fix ups due to interface changes.
tests/frontend/org/voltdb/TestReplicatedInvocation.java
ENG-4449: Test fix ups due to interface changes.
Java
lgpl-2.1
31ba037f1c88a3924a5a86f3b59ab3648c6302e0
0
egonw/ops4j
/* Copyright (C) 2014 Egon Willighagen <egonw@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * All we ask is that proper credit is given for our work, which includes * - but is not limited to - adding the above copyright notice to the beginning * of your source code files, and to any copyright notice that you may distribute * with programs based on this work. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.github.egonw.ops4j; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpException; import org.apache.http.client.ClientProtocolException; public class ActivityUnits extends AbstractOPS4JClient { private ActivityUnits(String server, String appID, String appKey) throws MalformedURLException { super(server, appID, appKey, null); } public static ActivityUnits getInstance(String server, String apiID, String appKey) throws MalformedURLException { return new ActivityUnits(server, apiID, appKey); } public static ActivityUnits getInstance(Server server) throws MalformedURLException { return new ActivityUnits(server.getServer(), server.getAppID(), server.getAppKey()); } public String count(Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); return runRequest(server + "pharmacology/filters/count", params, objects); } public String countForType(String type, Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); params.put("activity_type", type); return runRequest(server + "pharmacology/filters/count", params, objects); } public String list(int page, int pageSize, Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); params.put("_page", Integer.toString(page)); params.put("_pageSize", Integer.toString(pageSize)); return runRequest(server + "pharmacology/filters/units", params, objects); } public String forType(String type, Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); params.put("activity_type", type); return runRequest(server + "pharmacology/filters/units/pages" + type, params, objects); } }
src/main/java/com/github/egonw/ops4j/ActivityUnits.java
/* Copyright (C) 2014 Egon Willighagen <egonw@users.sf.net> * * Contact: cdk-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * All we ask is that proper credit is given for our work, which includes * - but is not limited to - adding the above copyright notice to the beginning * of your source code files, and to any copyright notice that you may distribute * with programs based on this work. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.github.egonw.ops4j; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpException; import org.apache.http.client.ClientProtocolException; public class ActivityUnits extends AbstractOPS4JClient { private ActivityUnits(String server, String appID, String appKey) throws MalformedURLException { super(server, appID, appKey, null); } public static ActivityUnits getInstance(String server, String apiID, String appKey) throws MalformedURLException { return new ActivityUnits(server, apiID, appKey); } public static ActivityUnits getInstance(Server server) throws MalformedURLException { return new ActivityUnits(server.getServer(), server.getAppID(), server.getAppKey()); } public String count(Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); return runRequest(server + "pharmacology/filters/count_units", params, objects); } public String list(int page, int pageSize, Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); params.put("_page", Integer.toString(page)); params.put("_pageSize", Integer.toString(pageSize)); return runRequest(server + "pharmacology/filters/units", params, objects); } public String forType(String type, Object... objects) throws ClientProtocolException, IOException, HttpException { Map<String,String> params = new HashMap<String,String>(); return runRequest(server + "pharmacology/filters/units/" + type, params, objects); } }
Updated the methods for the 2.1 API
src/main/java/com/github/egonw/ops4j/ActivityUnits.java
Updated the methods for the 2.1 API
Java
unlicense
c0c12824837800e4d4ba8fa1e057b58262d6699f
0
mezz/EnderIO,Samernieve/EnderIO,HenryLoenwind/EnderIO,Joccob/EnderIO,Joccob/EnderIO,MatthiasMann/EnderIO,MrNuggelz/EnderIO,SleepyTrousers/EnderIO,D-Inc/EnderIO,torteropaid/EnderIO,Vexatos/EnderIO,Vexatos/EnderIO,Quantum64/EnderIO,eduardog3000/EnderIO,mmelvin0/EnderIO,eduardog3000/EnderIO
package crazypants.enderio.conduit; import static crazypants.enderio.ModObject.blockPainter; import static crazypants.enderio.ModObject.itemConduitFacade; import static crazypants.enderio.ModObject.itemItemConduit; import static crazypants.enderio.ModObject.itemLiquidConduit; import static crazypants.enderio.ModObject.itemMeConduit; import static crazypants.enderio.ModObject.itemPowerConduit; import static crazypants.enderio.ModObject.itemRedstoneConduit; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; import crazypants.enderio.Config; import crazypants.enderio.ModObject; import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadePainterRecipe; import crazypants.enderio.machine.MachineRecipeRegistry; import crazypants.enderio.material.Alloy; import crazypants.enderio.material.BlockFusedQuartz; import crazypants.enderio.material.Material; public class ConduitRecipes { public static void addRecipes() { //Crafting Components ItemStack redstoneConduit = new ItemStack(itemRedstoneConduit.actualId, 1, 0); ItemStack conduitBinder = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.CONDUIT_BINDER.ordinal()); ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0); ItemStack fusedGlass = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, BlockFusedQuartz.Type.GLASS.ordinal()); ItemStack conductiveIron = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.CONDUCTIVE_IRON.ordinal()); ItemStack energeticGold = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.ENERGETIC_ALLOY.ordinal()); ItemStack phasedGold = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.PHASED_GOLD.ordinal()); ItemStack phasedIron = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.PHASED_IRON.ordinal()); ItemStack phasedIronNugget = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.PHASED_IRON_NUGGET.ordinal()); ItemStack redstoneAlloy = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.REDSTONE_ALLOY.ordinal()); ItemStack electricalSteel = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.ELECTRICAL_STEEL.ordinal()); //Recipes GameRegistry.addShapedRecipe(new ItemStack(itemConduitFacade.actualId, 1, 0), "bbb", "b b", "bbb", 'b', conduitBinder); int numConduits = Config.numConduitsPerRecipe; GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedGlass); GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedQuartz); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', conductiveIron); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', energeticGold); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedGold); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, numConduits, 0), " ", "###", " ", 'b', conduitBinder, '#', redstoneAlloy); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, 1, 1), "lbl", "bcb", "lbl", 'b', conduitBinder, 'c', redstoneConduit, 'l', Block.lever); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', redstoneAlloy); ItemStack itemConduit = new ItemStack(itemItemConduit.actualId, numConduits, 0); GameRegistry.addShapedRecipe(itemConduit, "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedIronNugget); ItemStack itemConduitAdvanced = new ItemStack(itemItemConduit.actualId, numConduits, 1); GameRegistry.addShapedRecipe(itemConduitAdvanced, "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedIron); MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, new FacadePainterRecipe()); } public static void addOreDictionaryRecipes() { Item i = GameRegistry.findItem("AppliedEnergistics", "AppEngMaterials"); if(i != null) { ItemStack conduitBinder = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.CONDUIT_BINDER.ordinal()); ItemStack flux = new ItemStack(i.itemID, 1, 14); GameRegistry.addShapedRecipe(new ItemStack(itemMeConduit.actualId, 3, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', flux); } } }
common/crazypants/enderio/conduit/ConduitRecipes.java
package crazypants.enderio.conduit; import static crazypants.enderio.ModObject.blockPainter; import static crazypants.enderio.ModObject.itemConduitFacade; import static crazypants.enderio.ModObject.itemItemConduit; import static crazypants.enderio.ModObject.itemLiquidConduit; import static crazypants.enderio.ModObject.itemMeConduit; import static crazypants.enderio.ModObject.itemPowerConduit; import static crazypants.enderio.ModObject.itemRedstoneConduit; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; import crazypants.enderio.Config; import crazypants.enderio.ModObject; import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadePainterRecipe; import crazypants.enderio.machine.MachineRecipeRegistry; import crazypants.enderio.material.Alloy; import crazypants.enderio.material.BlockFusedQuartz; import crazypants.enderio.material.Material; public class ConduitRecipes { public static void addRecipes() { //Crafting Components ItemStack redstoneConduit = new ItemStack(itemRedstoneConduit.actualId, 1, 0); ItemStack conduitBinder = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.CONDUIT_BINDER.ordinal()); ItemStack fusedQuartz = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, 0); ItemStack fusedGlass = new ItemStack(ModObject.blockFusedQuartz.actualId, 1, BlockFusedQuartz.Type.GLASS.ordinal()); ItemStack conductiveIron = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.CONDUCTIVE_IRON.ordinal()); ItemStack energeticGold = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.ENERGETIC_ALLOY.ordinal()); ItemStack phasedGold = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.PHASED_GOLD.ordinal()); ItemStack phasedIron = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.PHASED_IRON.ordinal()); ItemStack phasedIronNugget = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.PHASED_IRON_NUGGET.ordinal()); ItemStack redstoneAlloy = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.REDSTONE_ALLOY.ordinal()); ItemStack electricalSteel = new ItemStack(ModObject.itemAlloy.actualId, 1, Alloy.ELECTRICAL_STEEL.ordinal()); //Recipes GameRegistry.addShapedRecipe(new ItemStack(itemConduitFacade.actualId, 1, 0), "bbb", "b b", "bbb", 'b', conduitBinder); int numConduits = Config.numConduitsPerRecipe; GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedGlass); GameRegistry.addShapedRecipe(new ItemStack(itemLiquidConduit.actualId, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', fusedQuartz); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', conductiveIron); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 1), "bbb", "###", "bbb", 'b', conduitBinder, '#', energeticGold); GameRegistry.addShapedRecipe(new ItemStack(itemPowerConduit.actualId, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedGold); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, numConduits, 0), " ", "###", " ", 'b', conduitBinder, '#', redstoneAlloy); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, 1, 1), "lbl", "bcb", "lbl", 'b', conduitBinder, 'c', redstoneConduit, 'l', Block.lever); GameRegistry.addShapedRecipe(new ItemStack(itemRedstoneConduit.actualId, numConduits, 2), "bbb", "###", "bbb", 'b', conduitBinder, '#', redstoneAlloy); ItemStack itemConduit = new ItemStack(itemItemConduit.actualId, numConduits, 0); GameRegistry.addShapedRecipe(itemConduit, "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedIronNugget); ItemStack itemConduitAdvanced = new ItemStack(itemItemConduit.actualId, numConduits, 1); GameRegistry.addShapedRecipe(itemConduitAdvanced, "bbb", "###", "bbb", 'b', conduitBinder, '#', phasedIron); MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, new FacadePainterRecipe()); } public static void addOreDictionaryRecipes() { Item i = GameRegistry.findItem("AppliedEnergistics", "AppEngMaterials"); if(i != null) { ItemStack conduitBinder = new ItemStack(ModObject.itemMaterial.actualId, 1, Material.CONDUIT_BINDER.ordinal()); ItemStack flux = new ItemStack(4362, 1, 14); GameRegistry.addShapedRecipe(new ItemStack(itemMeConduit.actualId, 3, 0), "bbb", "###", "bbb", 'b', conduitBinder, '#', flux); } } }
#466 #464 ME conduit recipe not working correctly with non-default IDs.
common/crazypants/enderio/conduit/ConduitRecipes.java
#466 #464 ME conduit recipe not working correctly with non-default IDs.
Java
apache-2.0
36ac9fa6400990ac0e4d1674a1c25d42b270df78
0
bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.common.actions; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.EmptyAction; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import java.util.function.Predicate; /** Helper class to conditionally replace/hide existing actions. */ public class ReplaceActionHelper { /** Conditionally hides the action with the given ID, if one exists. */ public static void conditionallyHideAction( ActionManager actionManager, String actionId, Predicate<Project> shouldHide) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction != null) { replaceAction(actionManager, actionId, new RemovedAction(oldAction, shouldHide)); } } /** * Conditionally replaces the action with the given ID with the new action. If there's no existing * action with the given ID, the new action is registered, and conditionally visible. */ public static void conditionallyReplaceAction( ActionManager actionManager, String actionId, AnAction newAction, Predicate<Project> shouldReplace) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction == null) { oldAction = new EmptyAction(false); } replaceAction(actionManager, actionId, new ReplacedAction(oldAction, newAction, shouldReplace)); } /** * Registers a new action against the provided action ID, unregistering any existing action with * this ID, if one exists. */ public static void replaceAction( ActionManager actionManager, String actionId, AnAction newAction) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction != null) { newAction.getTemplatePresentation().setIcon(oldAction.getTemplatePresentation().getIcon()); actionManager.replaceAction(actionId, newAction); } else { actionManager.registerAction(actionId, newAction); } } /** Wraps an action and makes it conditionally invisible. */ private static class RemovedAction extends AnAction { private final AnAction delegate; private final Predicate<Project> shouldHide; private RemovedAction(AnAction delegate, Predicate<Project> shouldHide) { super( delegate.getTemplatePresentation().getTextWithMnemonic(), delegate.getTemplatePresentation().getDescription(), delegate.getTemplatePresentation().getIcon()); this.delegate = delegate; this.shouldHide = shouldHide; } @Override public void actionPerformed(AnActionEvent e) { delegate.actionPerformed(e); } @Override public void update(AnActionEvent e) { Project project = e.getProject(); if (project != null && shouldHide.test(project)) { e.getPresentation().setEnabledAndVisible(false); } else { // default to visible and enabled, to handle the case where the delegate's update method // doesn't make changes to this. e.getPresentation().setEnabledAndVisible(true); delegate.update(e); } } @Override public boolean isDumbAware() { return delegate.isDumbAware(); } } /** Conditionally replaces one action with another. */ private static class ReplacedAction extends AnAction { private final AnAction originalAction; private final AnAction replacementAction; private final Predicate<Project> shouldReplace; private ReplacedAction( AnAction originalAction, AnAction replacementAction, Predicate<Project> shouldReplace) { this.originalAction = originalAction; this.replacementAction = replacementAction; this.shouldReplace = shouldReplace; } @Override public void update(AnActionEvent e) { // default to visible and enabled, to handle the case where the delegate's update method // doesn't make changes to this. e.getPresentation().setEnabledAndVisible(true); Project project = e.getProject(); if (project != null && shouldReplace.test(e.getProject())) { applyPresentation(e.getPresentation(), replacementAction.getTemplatePresentation()); replacementAction.update(e); } else { applyPresentation(e.getPresentation(), originalAction.getTemplatePresentation()); originalAction.update(e); } } @Override public void actionPerformed(AnActionEvent e) { if (shouldReplace.test(e.getProject())) { replacementAction.actionPerformed(e); } else { originalAction.actionPerformed(e); } } private static void applyPresentation( Presentation presentation, Presentation templatePresentation) { presentation.restoreTextWithMnemonic(templatePresentation); presentation.setDescription(templatePresentation.getDescription()); presentation.setIcon(templatePresentation.getIcon()); } } }
common/actions/src/com/google/idea/common/actions/ReplaceActionHelper.java
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.common.actions; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.EmptyAction; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.Project; import java.util.function.Predicate; /** Helper class to conditionally replace/hide existing actions. */ public class ReplaceActionHelper { /** Conditionally hides the action with the given ID, if one exists. */ public static void conditionallyHideAction( ActionManager actionManager, String actionId, Predicate<Project> shouldHide) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction != null) { replaceAction(actionManager, actionId, new RemovedAction(oldAction, shouldHide)); } } /** * Conditionally replaces the action with the given ID with the new action. If there's no existing * action with the given ID, the new action is registered, and conditionally visible. */ public static void conditionallyReplaceAction( ActionManager actionManager, String actionId, AnAction newAction, Predicate<Project> shouldReplace) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction == null) { oldAction = new EmptyAction(false); } replaceAction(actionManager, actionId, new ReplacedAction(oldAction, newAction, shouldReplace)); } /** * Registers a new action against the provided action ID, unregistering any existing action with * this ID, if one exists. */ public static void replaceAction( ActionManager actionManager, String actionId, AnAction newAction) { AnAction oldAction = actionManager.getAction(actionId); if (oldAction != null) { newAction.getTemplatePresentation().setIcon(oldAction.getTemplatePresentation().getIcon()); actionManager.replaceAction(actionId, newAction); } else { actionManager.registerAction(actionId, newAction); } } /** Wraps an action and makes it conditionally invisible. */ private static class RemovedAction extends AnAction { private final AnAction delegate; private final Predicate<Project> shouldHide; private RemovedAction(AnAction delegate, Predicate<Project> shouldHide) { super( delegate.getTemplatePresentation().getTextWithMnemonic(), delegate.getTemplatePresentation().getDescription(), delegate.getTemplatePresentation().getIcon()); this.delegate = delegate; this.shouldHide = shouldHide; } @Override public void actionPerformed(AnActionEvent e) { delegate.actionPerformed(e); } @Override public void update(AnActionEvent e) { Project project = e.getProject(); if (project != null && shouldHide.test(project)) { e.getPresentation().setEnabledAndVisible(false); } else { // default to visible and enabled, to handle the case where the delegate's update method // doesn't make changes to this. e.getPresentation().setEnabledAndVisible(true); delegate.update(e); } } } /** Conditionally replaces one action with another. */ private static class ReplacedAction extends AnAction { private final AnAction originalAction; private final AnAction replacementAction; private final Predicate<Project> shouldReplace; private ReplacedAction( AnAction originalAction, AnAction replacementAction, Predicate<Project> shouldReplace) { this.originalAction = originalAction; this.replacementAction = replacementAction; this.shouldReplace = shouldReplace; } @Override public void update(AnActionEvent e) { // default to visible and enabled, to handle the case where the delegate's update method // doesn't make changes to this. e.getPresentation().setEnabledAndVisible(true); Project project = e.getProject(); if (project != null && shouldReplace.test(e.getProject())) { applyPresentation(e.getPresentation(), replacementAction.getTemplatePresentation()); replacementAction.update(e); } else { applyPresentation(e.getPresentation(), originalAction.getTemplatePresentation()); originalAction.update(e); } } @Override public void actionPerformed(AnActionEvent e) { if (shouldReplace.test(e.getProject())) { replacementAction.actionPerformed(e); } else { originalAction.actionPerformed(e); } } private static void applyPresentation( Presentation presentation, Presentation templatePresentation) { presentation.restoreTextWithMnemonic(templatePresentation); presentation.setDescription(templatePresentation.getDescription()); presentation.setIcon(templatePresentation.getIcon()); } } }
RemovedAction should delegate isDumbAware (#3789) RemovedAction should delegate isDumbAware Fixes #3788
common/actions/src/com/google/idea/common/actions/ReplaceActionHelper.java
RemovedAction should delegate isDumbAware (#3789)
Java
apache-2.0
0981cd6716db1b864e2114304082e8f53a939f7a
0
cniesen/rice,ewestfal/rice,shahess/rice,bsmith83/rice-1,jwillia/kc-rice1,ewestfal/rice-svn2git-test,rojlarge/rice-kc,ewestfal/rice,shahess/rice,gathreya/rice-kc,smith750/rice,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,UniversityOfHawaiiORS/rice,bsmith83/rice-1,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,gathreya/rice-kc,kuali/kc-rice,ewestfal/rice-svn2git-test,bhutchinson/rice,gathreya/rice-kc,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,smith750/rice,UniversityOfHawaiiORS/rice,smith750/rice,cniesen/rice,bhutchinson/rice,ewestfal/rice,cniesen/rice,ewestfal/rice-svn2git-test,bsmith83/rice-1,smith750/rice,cniesen/rice,shahess/rice,kuali/kc-rice,rojlarge/rice-kc,sonamuthu/rice-1,shahess/rice,kuali/kc-rice,rojlarge/rice-kc,rojlarge/rice-kc,kuali/kc-rice,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,cniesen/rice,gathreya/rice-kc,jwillia/kc-rice1,jwillia/kc-rice1,ewestfal/rice-svn2git-test,jwillia/kc-rice1,geothomasp/kualico-rice-kc,shahess/rice,bhutchinson/rice,rojlarge/rice-kc,gathreya/rice-kc,kuali/kc-rice,geothomasp/kualico-rice-kc,bsmith83/rice-1,smith750/rice,ewestfal/rice,bhutchinson/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,ewestfal/rice
/* * Copyright 2005-2006 The Kuali Foundation. * * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.actionlist.web; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.lang.StringUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.displaytag.pagination.PaginatedList; import org.displaytag.properties.SortOrderEnum; import org.displaytag.util.LookupUtil; import org.kuali.rice.core.config.ConfigContext; import org.kuali.rice.core.util.JSTLConstants; import org.kuali.rice.ken.service.KENServiceConstants; import org.kuali.rice.kew.actionitem.ActionItem; import org.kuali.rice.kew.actionitem.ActionItemActionListExtension; import org.kuali.rice.kew.actionlist.ActionListFilter; import org.kuali.rice.kew.actionlist.ActionToTake; import org.kuali.rice.kew.actionlist.CustomActionListAttribute; import org.kuali.rice.kew.actionlist.PaginatedActionList; import org.kuali.rice.kew.actionlist.service.ActionListService; import org.kuali.rice.kew.actions.ActionSet; import org.kuali.rice.kew.actions.asyncservices.ActionInvocation; import org.kuali.rice.kew.docsearch.DocumentSearchGenerator; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kew.preferences.Preferences; import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValueActionListExtension; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kew.util.PerformanceLogger; import org.kuali.rice.kew.util.Utilities; import org.kuali.rice.kew.util.WebFriendlyRecipient; import org.kuali.rice.kew.web.session.UserSession; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.bo.DocumentHeader; import org.kuali.rice.kns.exception.AuthorizationException; import org.kuali.rice.kns.service.KNSServiceLocator; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.RiceKeyConstants; import org.kuali.rice.kns.web.struts.action.KualiAction; import org.kuali.rice.kns.web.ui.ExtraButton; /** * Action doing Action list stuff * * @author Kuali Rice Team (kuali-rice@googlegroups.com) * */ public class ActionListAction extends KualiAction { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ActionListAction.class); private static String ACTION_LIST_KEY = "actionList"; private static String ACTION_LIST_PAGE_KEY = "actionListPage"; private static String ACTION_LIST_USER_KEY = "actionList.user"; private static String REQUERY_ACTION_LIST_KEY = "requeryActionList"; private static String ROUTEHEADERID = "routeHeaderId"; private static String ACTIONITEM_ROUTEHEADERID_INVALID = "actionitem.routeheaderid.invalid"; private static String ACTIONREQUESTCD = "actionRequestCd"; private static String DOCTITLE = "docTitle"; private static String ACTIONITEM_DOCTITLENAME_EMPTY = "actionitem.doctitlename.empty"; private static String ACTIONITEM_ACTIONREQUESTCD_INVALID = "actionitem.actionrequestcd.invalid"; public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm frm = (ActionListForm)actionForm; request.setAttribute("Constants", new JSTLConstants(KEWConstants.class)); request.setAttribute("preferences", this.getUserSession(request).getPreferences()); frm.setHeaderButtons(getHeaderButtons()); return super.execute(mapping, actionForm, request, response); } private List<ExtraButton> getHeaderButtons(){ List<ExtraButton> headerButtons = new ArrayList<ExtraButton>(); ExtraButton eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-preferences.gif"); eb.setExtraButtonOnclick("../en/Preferences.do?returnMapping=viewActionList"); headerButtons.add(eb); eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-refresh.gif"); eb.setExtraButtonProperty("methodToCall.start"); headerButtons.add(eb); eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-filter.gif"); eb.setExtraButtonOnclick("javascript: window.open('..en/ActionListFilter.do?methodToCall=start');"); headerButtons.add(eb); return headerButtons; } @Override protected ActionForward defaultDispatch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return start(mapping, form, request, response); } public ActionForward start(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { PerformanceLogger plog = new PerformanceLogger(); plog.log("Starting ActionList fetch"); ActionListForm form = (ActionListForm) actionForm; ActionErrors errors = new ActionErrors(); ActionListService actionListSrv = KEWServiceLocator.getActionListService(); // process display tag parameters Integer page = form.getPage(); String sortCriterion = form.getSort(); SortOrderEnum sortOrder = SortOrderEnum.ASCENDING; if (form.getDir() != null) { sortOrder = parseSortOrder(form.getDir()); } else if ( !StringUtils.isEmpty(getUserSession(request).getSortOrder())) { sortOrder = parseSortOrder(getUserSession(request).getSortOrder()); // System.out.println("Session value for SortOrder "+sortOrder); } // if both the page and the sort criteria are null, that means its the first entry into the page, use defaults if (page == null && sortCriterion == null) { page = new Integer(1); sortCriterion = ActionItemComparator.DOCUMENT_ID; } else if ( !StringUtils.isEmpty(getUserSession(request).getSortCriteria())) { sortCriterion = getUserSession(request).getSortCriteria(); // System.out.println("Session sortCriterion variables used..."+getUserSession(request).getSortCriteria()); } // if the page is still null, that means the user just performed a sort action, pull the currentPage off of the form if (page == null) { page = form.getCurrentPage(); } // update the values of the "current" display tag parameters form.setCurrentPage(page); if (!StringUtils.isEmpty(sortCriterion)) { form.setCurrentSort(sortCriterion); form.setCurrentDir(getSortOrderValue(sortOrder)); } // reset the default action on the form form.setDefaultActionToTake("NONE"); boolean freshActionList = true; // retrieve cached action list List actionList = (List)request.getSession().getAttribute(ACTION_LIST_KEY); plog.log("Time to initialize"); try { UserSession uSession = getUserSession(request); String principalId = null; if (uSession.getActionListFilter() == null) { ActionListFilter filter = new ActionListFilter(); filter.setDelegationType(KEWConstants.DELEGATION_SECONDARY); filter.setExcludeDelegationType(true); uSession.setActionListFilter(filter); } /* 'forceListRefresh' variable used to signify that the action list filter has changed * any time the filter changes the action list must be refreshed or filter may not take effect on existing * list items... only exception is if action list has not loaded previous and fetching of the list has not * occurred yet */ boolean forceListRefresh = request.getSession().getAttribute(REQUERY_ACTION_LIST_KEY) != null; if (uSession.getHelpDeskActionListPrincipal() != null) { principalId = uSession.getHelpDeskActionListPrincipal().getPrincipalId(); } else { if (!StringUtils.isEmpty(form.getDocType())) { uSession.getActionListFilter().setDocumentType(form.getDocType()); uSession.getActionListFilter().setExcludeDocumentType(false); forceListRefresh = true; } principalId = uSession.getPerson().getPrincipalId(); } Preferences preferences = getUserSession(request).getPreferences(); if (!StringUtils.isEmpty(form.getDelegationId())) { uSession.getActionListFilter().setDelegatorId(form.getDelegationId()); uSession.getActionListFilter().setExcludeDelegatorId(false); actionList = null; } if (!StringUtils.isEmpty(form.getPrimaryDelegateId())) { uSession.getActionListFilter().setPrimaryDelegateId(form.getPrimaryDelegateId()); actionList = null; } // if the user has changed, we need to refresh the action list if (!principalId.equals((String) request.getSession().getAttribute(ACTION_LIST_USER_KEY))) { actionList = null; } if (isOutboxMode(form, request, preferences)) { actionList = new ArrayList(actionListSrv.getOutbox(principalId, uSession.getActionListFilter())); form.setOutBoxEmpty(actionList.isEmpty()); } else { if (actionList == null) { // fetch the action list actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else if (forceListRefresh) { // force a refresh... usually based on filter change or parameter specifying refresh needed actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else if (actionListSrv.refreshActionList(getUserSession(request).getPerson().getPrincipalId())) { actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else { freshActionList = false; } request.getSession().setAttribute(ACTION_LIST_KEY, actionList); } // reset the requery action list key request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, null); // build the drop-down of delegators if (KEWConstants.DELEGATORS_ON_ACTION_LIST_PAGE.equalsIgnoreCase(preferences.getDelegatorFilter())) { Collection delegators = actionListSrv.findUserSecondaryDelegators(principalId); form.setDelegators(getWebFriendlyRecipients(delegators)); form.setDelegationId(uSession.getActionListFilter().getDelegatorId()); Collection delegates = actionListSrv.findUserPrimaryDelegations(principalId); form.setPrimaryDelegates(getWebFriendlyRecipients(delegates)); form.setPrimaryDelegateId(uSession.getActionListFilter().getDelegatorId()); } form.setFilterLegend(uSession.getActionListFilter().getFilterLegend()); plog.log("Setting attributes"); int pageSize = getPageSize(preferences); // initialize the action list if necessary if (freshActionList) { initializeActionList(actionList, preferences, errors); // put this in to resolve EN-112 (http://beatles.uits.indiana.edu:8081/jira/browse/EN-112) // if the action list gets "refreshed" in between page switches, we need to be sure and re-sort it, even though we don't have sort criteria on the request if (sortCriterion == null) { sortCriterion = form.getCurrentSort(); sortOrder = parseSortOrder(form.getCurrentDir()); } } // sort the action list if necessary if (sortCriterion != null) { sortActionList(actionList, sortCriterion, sortOrder); } PaginatedList currentPage = buildCurrentPage(actionList, form.getCurrentPage(), form.getCurrentSort(), form.getCurrentDir(), pageSize, preferences, errors, form); request.setAttribute(ACTION_LIST_PAGE_KEY, currentPage); uSession.setCurrentPage(form.getCurrentPage()); uSession.setSortCriteria(form.getSort()); uSession.setSortOrder(form.getCurrentDir()); plog.log("finished setting attributes, finishing action list fetch"); } catch (Exception e) { LOG.error("Error loading action list.", e); } saveErrors(request, errors); LOG.debug("end start ActionListAction"); return mapping.findForward("viewActionList"); } private SortOrderEnum parseSortOrder(String dir) throws WorkflowException { if ("asc".equals(dir)) { return SortOrderEnum.ASCENDING; } else if ("desc".equals(dir)) { return SortOrderEnum.DESCENDING; } throw new WorkflowException("Invalid sort direction: " + dir); } private String getSortOrderValue(SortOrderEnum sortOrder) { if (SortOrderEnum.ASCENDING.equals(sortOrder)) { return "asc"; } else if (SortOrderEnum.DESCENDING.equals(sortOrder)) { return "desc"; } return null; } private static final String OUT_BOX_MODE = "_OUT_BOX_MODE"; /** * this method is setting 2 props on the {@link ActionListForm} that controls outbox behavior. * alForm.setViewOutbox("false"); -> this is set by user preferences and the actionlist.outbox.off config prop * alForm.setShowOutbox(false); -> this is set by user action clicking the ActionList vs. Outbox links. * * @param alForm * @param request * @return boolean indication whether the outbox should be fetched */ private boolean isOutboxMode(ActionListForm alForm, HttpServletRequest request, Preferences preferences) { boolean outBoxView = false; Person user = UserSession.getAuthenticatedUser().getPerson(); if (! preferences.isUsingOutbox() || ! ConfigContext.getCurrentContextConfig().getOutBoxOn()) { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(false)); alForm.setViewOutbox("false"); alForm.setShowOutbox(false); return false; } alForm.setShowOutbox(true); if (StringUtils.isNotEmpty(alForm.getViewOutbox())) { if (!new Boolean(alForm.getViewOutbox())) { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(false)); outBoxView = false; } else { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(true)); outBoxView = true; } } else { if (request.getSession().getAttribute(OUT_BOX_MODE) == null) { outBoxView = false; } else { outBoxView = (Boolean) request.getSession().getAttribute(OUT_BOX_MODE); } } if (outBoxView) { alForm.setViewOutbox("true"); } else { alForm.setViewOutbox("false"); } return outBoxView; } private void sortActionList(List actionList, String sortName, SortOrderEnum sortOrder) { if (StringUtils.isEmpty(sortName)) { return; } Comparator comparator = new ActionItemComparator(sortName); if (SortOrderEnum.DESCENDING.equals(sortOrder)) { comparator = ComparatorUtils.reversedComparator(comparator); } Collections.sort(actionList, comparator); // re-index the action items int index = 0; for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension) iterator.next(); actionItem.setActionItemIndex(new Integer(index++)); } } private void initializeActionList(List actionList, Preferences preferences, ActionErrors errors) throws WorkflowException { List actionItemProblemIds = new ArrayList(); int index = 0; generateActionItemErrors(actionList); for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension)iterator.next(); if (actionItem.getRouteHeaderId() == null) { LOG.error("Somehow there exists an ActionItem with a null document id! actionItemId=" + actionItem.getActionItemId()); iterator.remove(); continue; } try { actionItem.initialize(preferences); DocumentRouteHeaderValueActionListExtension routeHeaderExtension = (DocumentRouteHeaderValueActionListExtension)actionItem.getRouteHeader(); routeHeaderExtension.setActionListInitiatorPrincipal(routeHeaderExtension.getInitiatorPrincipal()); actionItem.setActionItemIndex(new Integer(index)); //set background colors for document statuses if (KEWConstants.ROUTE_HEADER_APPROVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorApproved())); } else if (KEWConstants.ROUTE_HEADER_CANCEL_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorCanceled())); } else if (KEWConstants.ROUTE_HEADER_DISAPPROVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorDissaproved())); } else if (KEWConstants.ROUTE_HEADER_ENROUTE_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorEnroute())); } else if (KEWConstants.ROUTE_HEADER_EXCEPTION_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorException())); } else if (KEWConstants.ROUTE_HEADER_FINAL_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorFinal())); } else if (KEWConstants.ROUTE_HEADER_INITIATED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorInitiated())); } else if (KEWConstants.ROUTE_HEADER_PROCESSED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorProccessed())); } else if (KEWConstants.ROUTE_HEADER_SAVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorSaved())); } index++; } catch (Exception e) { // if there's a problem loading the action item, we don't want to blow out the whole screen but we will remove it from the list // and display an approriate error message to the user LOG.error("Error loading action list for action item " + actionItem.getActionItemId(), e); iterator.remove(); actionItemProblemIds.add(actionItem.getRouteHeaderId()); } } generateActionItemErrors(errors, "actionlist.badActionItems", actionItemProblemIds); } /** * Gets the page size of the Action List. Uses the user's preferences for page size unless the action list * has been throttled by an application constant, in which case it uses the smaller of the two values. */ protected int getPageSize(Preferences preferences) { return Integer.parseInt(preferences.getPageSize()); } protected PaginatedList buildCurrentPage(List actionList, Integer page, String sortCriterion, String sortDirection, int pageSize, Preferences preferences, ActionErrors errors, ActionListForm form) throws WorkflowException { List currentPage = new ArrayList(pageSize); boolean haveFyis = false; boolean haveApproves = false; boolean haveAcknowledges = false; boolean haveCancels = false; boolean haveDisapproves = false; boolean haveCustomActions = false; List customActionListProblemIds = new ArrayList(); SortOrderEnum sortOrder = parseSortOrder(sortDirection); int startIndex = (page.intValue() - 1) * pageSize; int endIndex = startIndex + pageSize; generateActionItemErrors(actionList); for (int index = startIndex; index < endIndex && index < actionList.size(); index++) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension)actionList.get(index); // evaluate custom action list component for mass actions try { boolean itemHasApproves = false; boolean itemHasDisapproves = false; boolean itemHasCancels = false; boolean itemHasAcknowledges = false; boolean itemHasFyis = false; boolean itemHasCustomActions = false; CustomActionListAttribute customActionListAttribute = actionItem.getRouteHeader().getCustomActionListAttribute(); if (customActionListAttribute != null) { Map customActions = new LinkedHashMap(); customActions.put("NONE", "NONE"); ActionSet legalActions = customActionListAttribute.getLegalActions(UserSession.getAuthenticatedUser(), actionItem); if (legalActions != null && legalActions.hasApprove() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_APPROVED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_APPROVED_CD, KEWConstants.ACTION_REQUEST_APPROVE_REQ_LABEL); itemHasApproves = true; } if (legalActions != null && legalActions.hasDisapprove() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_DENIED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_DENIED_CD, KEWConstants.ACTION_REQUEST_DISAPPROVE_LABEL); itemHasDisapproves = true; } if (legalActions != null && legalActions.hasCancel() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_CANCELED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_CANCELED_CD, KEWConstants.ACTION_REQUEST_CANCEL_REQ_LABEL); itemHasCancels = true; } if (legalActions != null && legalActions.hasAcknowledge() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD, KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL); itemHasAcknowledges = true; } if (legalActions != null && legalActions.hasFyi() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_FYI_CD) && KEWConstants.PREFERENCES_YES_VAL.equalsIgnoreCase(preferences.getShowClearFyi())) { customActions.put(KEWConstants.ACTION_TAKEN_FYI_CD, KEWConstants.ACTION_REQUEST_FYI_REQ_LABEL); itemHasFyis = true; } if (customActions.size() > 1) { actionItem.setCustomActions(customActions); itemHasCustomActions = true; } actionItem.setDisplayParameters(customActionListAttribute.getDocHandlerDisplayParameters(UserSession.getAuthenticatedUser(), actionItem)); haveApproves = haveApproves || itemHasApproves; haveAcknowledges = haveAcknowledges || itemHasAcknowledges; haveFyis = haveFyis || itemHasFyis; haveDisapproves = haveDisapproves || itemHasDisapproves; haveCancels = haveCancels || itemHasCancels; haveCustomActions = haveCustomActions || itemHasCustomActions; } } catch (Exception e) { // if there's a problem loading the custom action list attribute, let's go ahead and display the vanilla action item LOG.error("Problem loading custom action list attribute", e); customActionListProblemIds.add(actionItem.getRouteHeaderId()); } currentPage.add(actionItem); } // configure custom actions on form form.setHasCustomActions(new Boolean(haveCustomActions)); Map defaultActions = new LinkedHashMap(); defaultActions.put("NONE", "NONE"); if (haveApproves) { defaultActions.put(KEWConstants.ACTION_TAKEN_APPROVED_CD, KEWConstants.ACTION_REQUEST_APPROVE_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveDisapproves) { defaultActions.put(KEWConstants.ACTION_TAKEN_DENIED_CD, KEWConstants.ACTION_REQUEST_DISAPPROVE_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveCancels) { defaultActions.put(KEWConstants.ACTION_TAKEN_CANCELED_CD, KEWConstants.ACTION_REQUEST_CANCEL_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveAcknowledges) { defaultActions.put(KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD, KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } //clearing FYI's can be done in any action list not just a customized one if (haveFyis && KEWConstants.PREFERENCES_YES_VAL.equalsIgnoreCase(preferences.getShowClearFyi())) { defaultActions.put(KEWConstants.ACTION_TAKEN_FYI_CD, KEWConstants.ACTION_REQUEST_FYI_REQ_LABEL); } if (defaultActions.size() > 1) { form.setDefaultActions(defaultActions); } generateActionItemErrors(errors, "actionlist.badCustomActionListItems", customActionListProblemIds); return new PaginatedActionList(currentPage, actionList.size(), page.intValue(), pageSize, "actionList", sortCriterion, sortOrder); } private void generateActionItemErrors(ActionErrors errors, String errorKey, List documentIds) { if (!documentIds.isEmpty()) { String documentIdsString = StringUtils.join(documentIds.iterator(), ", "); errors.add(Globals.ERROR_KEY, new ActionMessage(errorKey, documentIdsString)); } } private void generateActionItemErrors(List actionList) { for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension)iterator.next(); if (KEWServiceLocator.getRouteHeaderService().getRouteHeader(actionItem.getRouteHeaderId()) == null) { GlobalVariables.getErrorMap().putError(ROUTEHEADERID, ACTIONITEM_ROUTEHEADERID_INVALID,actionItem.getActionItemId()+""); } if(!KEWConstants.ACTION_REQUEST_CODES.containsKey(actionItem.getActionRequestCd())) { GlobalVariables.getErrorMap().putError(ACTIONREQUESTCD,ACTIONITEM_ACTIONREQUESTCD_INVALID,actionItem.getActionItemId()+""); } if (actionItem.getDocTitle() == null) { GlobalVariables.getErrorMap().putError(DOCTITLE, ACTIONITEM_DOCTITLENAME_EMPTY,actionItem.getActionItemId()+""); continue; } } } public ActionForward takeMassActions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm actionListForm = (ActionListForm) form; List actionList = (List) request.getSession().getAttribute(ACTION_LIST_KEY); if (actionList == null) { return start(mapping, new ActionListForm(), request, response); } ActionMessages messages = new ActionMessages(); List invocations = new ArrayList(); int index = 0; for (Iterator iterator = actionListForm.getActionsToTake().iterator(); iterator.hasNext();) { ActionToTake actionToTake = (ActionToTake) iterator.next(); if (actionToTake != null && actionToTake.getActionTakenCd() != null && !"".equals(actionToTake.getActionTakenCd()) && !"NONE".equalsIgnoreCase(actionToTake.getActionTakenCd()) && actionToTake.getActionItemId() != null) { ActionItem actionItem = getActionItemFromActionList(actionList, actionToTake.getActionItemId()); if (actionItem == null) { LOG.warn("Could not locate the ActionItem to take mass action against in the action list: " + actionToTake.getActionItemId()); continue; } invocations.add(new ActionInvocation(actionItem.getActionItemId(), actionToTake.getActionTakenCd())); } index++; } KEWServiceLocator.getWorkflowDocumentService().takeMassActions(getUserSession(request).getPrincipalId(), invocations); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("general.routing.processed")); saveMessages(request, messages); ActionListForm cleanForm = new ActionListForm(); request.setAttribute(mapping.getName(), cleanForm); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); return start(mapping, cleanForm, request, response); } protected ActionItem getActionItemFromActionList(List actionList, Long actionItemId) { for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItem actionItem = (ActionItem) iterator.next(); if (actionItem.getActionItemId().equals(actionItemId)) { return actionItem; } } return null; } public ActionForward helpDeskActionListLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm actionListForm = (ActionListForm) form; if (!"true".equals(request.getAttribute("helpDeskActionList"))) { throw new AuthorizationException(UserSession.getAuthenticatedUser().getPrincipalId(), "helpDeskActionListLogin", getClass().getSimpleName()); } getUserSession(request).establishHelpDeskWithPrincipalName(actionListForm.getHelpDeskActionListUserName()); actionListForm.setDelegator(null); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); return start(mapping, form, request, response); } public ActionForward clearFilter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("clearFilter ActionListAction"); UserSession session = getUserSession(request); session.setActionListFilter(null); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); KEWServiceLocator.getActionListService().saveRefreshUserOption(session.getPrincipalId()); LOG.debug("end clearFilter ActionListAction"); return start(mapping, form, request, response); } public ActionForward clearHelpDeskActionListUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("clearHelpDeskActionListUser ActionListAction"); getUserSession(request).clearHelpDesk(); LOG.debug("end clearHelpDeskActionListUser ActionListAction"); return start(mapping, form, request, response); } /** * Generates an Action List count. */ public ActionForward count(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm alForm = (ActionListForm)form; Person user = getUserSession(request).getPerson(); alForm.setCount(KEWServiceLocator.getActionListService().getCount(user.getPrincipalId())); LOG.info("Fetched Action List count of " + alForm.getCount() + " for user " + user.getPrincipalName()); return mapping.findForward("count"); } public ActionForward removeOutboxItems(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm alForm = (ActionListForm)form; if (alForm.getOutboxItems() != null) { KEWServiceLocator.getActionListService().removeOutboxItems(getUserSession(request).getPrincipal().getPrincipalId(), Arrays.asList(alForm.getOutboxItems())); } alForm.setViewOutbox("true"); return start(mapping, form, request, response); } private boolean isActionCompatibleRequest(ActionItemActionListExtension actionItem, String actionTakenCode) { boolean actionCompatible = false; String requestCd = actionItem.getActionRequestCd(); //FYI request matches FYI if (KEWConstants.ACTION_REQUEST_FYI_REQ.equals(requestCd) && KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode)) { actionCompatible = true || actionCompatible; } // ACK request matches ACK if (KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ.equals(requestCd) && KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode)) { actionCompatible = true || actionCompatible; } // APPROVE request matches all but FYI and ACK if (KEWConstants.ACTION_REQUEST_APPROVE_REQ.equals(requestCd) && !(KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode) || KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode))) { actionCompatible = true || actionCompatible; } // COMPLETE request matches all but FYI and ACK if (KEWConstants.ACTION_REQUEST_COMPLETE_REQ.equals(requestCd) && !(KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode) || KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode))) { actionCompatible = true || actionCompatible; } return actionCompatible; } private List getWebFriendlyRecipients(Collection recipients) { Collection newRecipients = new ArrayList(recipients.size()); for (Iterator iterator = recipients.iterator(); iterator.hasNext();) { newRecipients.add(new WebFriendlyRecipient(iterator.next())); } List recipientList = new ArrayList(newRecipients); Collections.sort(recipientList, new Comparator() { Comparator comp = new ComparableComparator(); public int compare(Object o1, Object o2) { return comp.compare(((WebFriendlyRecipient) o1).getDisplayName().trim().toLowerCase(), ((WebFriendlyRecipient) o2).getDisplayName().trim().toLowerCase()); } }); return recipientList; } private UserSession getUserSession(HttpServletRequest request){ return UserSession.getAuthenticatedUser(); } private class ActionItemComparator implements Comparator { private static final String DOCUMENT_ID = "routeHeaderId"; private final String sortName; public ActionItemComparator(String sortName) { if (StringUtils.isEmpty(sortName)) { sortName = DOCUMENT_ID; } this.sortName = sortName; } public int compare(Object object1, Object object2) { try { ActionItem actionItem1 = (ActionItem)object1; ActionItem actionItem2 = (ActionItem)object2; // invoke the power of the lookup functionality provided by the display tag library, this LookupUtil method allows for us // to evaulate nested bean properties (like workgroup.groupNameId.nameId) in a null-safe manner. For example, in the // example if workgroup evaluated to NULL then LookupUtil.getProperty would return null rather than blowing an exception Object property1 = LookupUtil.getProperty(actionItem1, sortName); Object property2 = LookupUtil.getProperty(actionItem2, sortName); if (property1 == null && property2 == null) { return 0; } else if (property1 == null) { return -1; } else if (property2 == null) { return 1; } if (property1 instanceof Comparable) { return ((Comparable)property1).compareTo(property2); } return property1.toString().compareTo(property2.toString()); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException("Could not sort for the given sort name: " + sortName, e); } } } }
impl/src/main/java/org/kuali/rice/kew/actionlist/web/ActionListAction.java
/* * Copyright 2005-2006 The Kuali Foundation. * * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.actionlist.web; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.lang.StringUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.displaytag.pagination.PaginatedList; import org.displaytag.properties.SortOrderEnum; import org.displaytag.util.LookupUtil; import org.kuali.rice.core.config.ConfigContext; import org.kuali.rice.core.util.JSTLConstants; import org.kuali.rice.kew.actionitem.ActionItem; import org.kuali.rice.kew.actionitem.ActionItemActionListExtension; import org.kuali.rice.kew.actionlist.ActionListFilter; import org.kuali.rice.kew.actionlist.ActionToTake; import org.kuali.rice.kew.actionlist.CustomActionListAttribute; import org.kuali.rice.kew.actionlist.PaginatedActionList; import org.kuali.rice.kew.actionlist.service.ActionListService; import org.kuali.rice.kew.actions.ActionSet; import org.kuali.rice.kew.actions.asyncservices.ActionInvocation; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kew.preferences.Preferences; import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValueActionListExtension; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kew.util.PerformanceLogger; import org.kuali.rice.kew.util.WebFriendlyRecipient; import org.kuali.rice.kew.web.session.UserSession; import org.kuali.rice.kim.bo.Person; import org.kuali.rice.kns.exception.AuthorizationException; import org.kuali.rice.kns.web.struts.action.KualiAction; import org.kuali.rice.kns.web.ui.ExtraButton; /** * Action doing Action list stuff * * @author Kuali Rice Team (kuali-rice@googlegroups.com) * */ public class ActionListAction extends KualiAction { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ActionListAction.class); private static String ACTION_LIST_KEY = "actionList"; private static String ACTION_LIST_PAGE_KEY = "actionListPage"; private static String ACTION_LIST_USER_KEY = "actionList.user"; private static String REQUERY_ACTION_LIST_KEY = "requeryActionList"; public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm frm = (ActionListForm)actionForm; request.setAttribute("Constants", new JSTLConstants(KEWConstants.class)); request.setAttribute("preferences", this.getUserSession(request).getPreferences()); frm.setHeaderButtons(getHeaderButtons()); return super.execute(mapping, actionForm, request, response); } private List<ExtraButton> getHeaderButtons(){ List<ExtraButton> headerButtons = new ArrayList<ExtraButton>(); ExtraButton eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-preferences.gif"); eb.setExtraButtonOnclick("../en/Preferences.do?returnMapping=viewActionList"); headerButtons.add(eb); eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-refresh.gif"); eb.setExtraButtonProperty("methodToCall.start"); headerButtons.add(eb); eb = new ExtraButton(); eb.setExtraButtonSource("../kr/images/tinybutton-filter.gif"); eb.setExtraButtonOnclick("javascript: window.open('..en/ActionListFilter.do?methodToCall=start');"); headerButtons.add(eb); return headerButtons; } @Override protected ActionForward defaultDispatch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return start(mapping, form, request, response); } public ActionForward start(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { PerformanceLogger plog = new PerformanceLogger(); plog.log("Starting ActionList fetch"); ActionListForm form = (ActionListForm) actionForm; ActionErrors errors = new ActionErrors(); ActionListService actionListSrv = KEWServiceLocator.getActionListService(); // process display tag parameters Integer page = form.getPage(); String sortCriterion = form.getSort(); SortOrderEnum sortOrder = SortOrderEnum.ASCENDING; if (form.getDir() != null) { sortOrder = parseSortOrder(form.getDir()); } else if ( !StringUtils.isEmpty(getUserSession(request).getSortOrder())) { sortOrder = parseSortOrder(getUserSession(request).getSortOrder()); // System.out.println("Session value for SortOrder "+sortOrder); } // if both the page and the sort criteria are null, that means its the first entry into the page, use defaults if (page == null && sortCriterion == null) { page = new Integer(1); sortCriterion = ActionItemComparator.DOCUMENT_ID; } else if ( !StringUtils.isEmpty(getUserSession(request).getSortCriteria())) { sortCriterion = getUserSession(request).getSortCriteria(); // System.out.println("Session sortCriterion variables used..."+getUserSession(request).getSortCriteria()); } // if the page is still null, that means the user just performed a sort action, pull the currentPage off of the form if (page == null) { page = form.getCurrentPage(); } // update the values of the "current" display tag parameters form.setCurrentPage(page); if (!StringUtils.isEmpty(sortCriterion)) { form.setCurrentSort(sortCriterion); form.setCurrentDir(getSortOrderValue(sortOrder)); } // reset the default action on the form form.setDefaultActionToTake("NONE"); boolean freshActionList = true; // retrieve cached action list List actionList = (List)request.getSession().getAttribute(ACTION_LIST_KEY); plog.log("Time to initialize"); try { UserSession uSession = getUserSession(request); String principalId = null; if (uSession.getActionListFilter() == null) { ActionListFilter filter = new ActionListFilter(); filter.setDelegationType(KEWConstants.DELEGATION_SECONDARY); filter.setExcludeDelegationType(true); uSession.setActionListFilter(filter); } /* 'forceListRefresh' variable used to signify that the action list filter has changed * any time the filter changes the action list must be refreshed or filter may not take effect on existing * list items... only exception is if action list has not loaded previous and fetching of the list has not * occurred yet */ boolean forceListRefresh = request.getSession().getAttribute(REQUERY_ACTION_LIST_KEY) != null; if (uSession.getHelpDeskActionListPrincipal() != null) { principalId = uSession.getHelpDeskActionListPrincipal().getPrincipalId(); } else { if (!StringUtils.isEmpty(form.getDocType())) { uSession.getActionListFilter().setDocumentType(form.getDocType()); uSession.getActionListFilter().setExcludeDocumentType(false); forceListRefresh = true; } principalId = uSession.getPerson().getPrincipalId(); } Preferences preferences = getUserSession(request).getPreferences(); if (!StringUtils.isEmpty(form.getDelegationId())) { uSession.getActionListFilter().setDelegatorId(form.getDelegationId()); uSession.getActionListFilter().setExcludeDelegatorId(false); actionList = null; } if (!StringUtils.isEmpty(form.getPrimaryDelegateId())) { uSession.getActionListFilter().setPrimaryDelegateId(form.getPrimaryDelegateId()); actionList = null; } // if the user has changed, we need to refresh the action list if (!principalId.equals((String) request.getSession().getAttribute(ACTION_LIST_USER_KEY))) { actionList = null; } if (isOutboxMode(form, request, preferences)) { actionList = new ArrayList(actionListSrv.getOutbox(principalId, uSession.getActionListFilter())); form.setOutBoxEmpty(actionList.isEmpty()); } else { if (actionList == null) { // fetch the action list actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else if (forceListRefresh) { // force a refresh... usually based on filter change or parameter specifying refresh needed actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else if (actionListSrv.refreshActionList(getUserSession(request).getPerson().getPrincipalId())) { actionList = new ArrayList(actionListSrv.getActionList(principalId, uSession.getActionListFilter())); request.getSession().setAttribute(ACTION_LIST_USER_KEY, principalId); } else { freshActionList = false; } request.getSession().setAttribute(ACTION_LIST_KEY, actionList); } // reset the requery action list key request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, null); // build the drop-down of delegators if (KEWConstants.DELEGATORS_ON_ACTION_LIST_PAGE.equalsIgnoreCase(preferences.getDelegatorFilter())) { Collection delegators = actionListSrv.findUserSecondaryDelegators(principalId); form.setDelegators(getWebFriendlyRecipients(delegators)); form.setDelegationId(uSession.getActionListFilter().getDelegatorId()); Collection delegates = actionListSrv.findUserPrimaryDelegations(principalId); form.setPrimaryDelegates(getWebFriendlyRecipients(delegates)); form.setPrimaryDelegateId(uSession.getActionListFilter().getDelegatorId()); } form.setFilterLegend(uSession.getActionListFilter().getFilterLegend()); plog.log("Setting attributes"); int pageSize = getPageSize(preferences); // initialize the action list if necessary if (freshActionList) { initializeActionList(actionList, preferences, errors); // put this in to resolve EN-112 (http://beatles.uits.indiana.edu:8081/jira/browse/EN-112) // if the action list gets "refreshed" in between page switches, we need to be sure and re-sort it, even though we don't have sort criteria on the request if (sortCriterion == null) { sortCriterion = form.getCurrentSort(); sortOrder = parseSortOrder(form.getCurrentDir()); } } // sort the action list if necessary if (sortCriterion != null) { sortActionList(actionList, sortCriterion, sortOrder); } PaginatedList currentPage = buildCurrentPage(actionList, form.getCurrentPage(), form.getCurrentSort(), form.getCurrentDir(), pageSize, preferences, errors, form); request.setAttribute(ACTION_LIST_PAGE_KEY, currentPage); uSession.setCurrentPage(form.getCurrentPage()); uSession.setSortCriteria(form.getSort()); uSession.setSortOrder(form.getCurrentDir()); plog.log("finished setting attributes, finishing action list fetch"); } catch (Exception e) { LOG.error("Error loading action list.", e); } saveErrors(request, errors); LOG.debug("end start ActionListAction"); return mapping.findForward("viewActionList"); } private SortOrderEnum parseSortOrder(String dir) throws WorkflowException { if ("asc".equals(dir)) { return SortOrderEnum.ASCENDING; } else if ("desc".equals(dir)) { return SortOrderEnum.DESCENDING; } throw new WorkflowException("Invalid sort direction: " + dir); } private String getSortOrderValue(SortOrderEnum sortOrder) { if (SortOrderEnum.ASCENDING.equals(sortOrder)) { return "asc"; } else if (SortOrderEnum.DESCENDING.equals(sortOrder)) { return "desc"; } return null; } private static final String OUT_BOX_MODE = "_OUT_BOX_MODE"; /** * this method is setting 2 props on the {@link ActionListForm} that controls outbox behavior. * alForm.setViewOutbox("false"); -> this is set by user preferences and the actionlist.outbox.off config prop * alForm.setShowOutbox(false); -> this is set by user action clicking the ActionList vs. Outbox links. * * @param alForm * @param request * @return boolean indication whether the outbox should be fetched */ private boolean isOutboxMode(ActionListForm alForm, HttpServletRequest request, Preferences preferences) { boolean outBoxView = false; Person user = UserSession.getAuthenticatedUser().getPerson(); if (! preferences.isUsingOutbox() || ! ConfigContext.getCurrentContextConfig().getOutBoxOn()) { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(false)); alForm.setViewOutbox("false"); alForm.setShowOutbox(false); return false; } alForm.setShowOutbox(true); if (StringUtils.isNotEmpty(alForm.getViewOutbox())) { if (!new Boolean(alForm.getViewOutbox())) { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(false)); outBoxView = false; } else { request.getSession().setAttribute(OUT_BOX_MODE, new Boolean(true)); outBoxView = true; } } else { if (request.getSession().getAttribute(OUT_BOX_MODE) == null) { outBoxView = false; } else { outBoxView = (Boolean) request.getSession().getAttribute(OUT_BOX_MODE); } } if (outBoxView) { alForm.setViewOutbox("true"); } else { alForm.setViewOutbox("false"); } return outBoxView; } private void sortActionList(List actionList, String sortName, SortOrderEnum sortOrder) { if (StringUtils.isEmpty(sortName)) { return; } Comparator comparator = new ActionItemComparator(sortName); if (SortOrderEnum.DESCENDING.equals(sortOrder)) { comparator = ComparatorUtils.reversedComparator(comparator); } Collections.sort(actionList, comparator); // re-index the action items int index = 0; for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension) iterator.next(); actionItem.setActionItemIndex(new Integer(index++)); } } private void initializeActionList(List actionList, Preferences preferences, ActionErrors errors) throws WorkflowException { List actionItemProblemIds = new ArrayList(); int index = 0; for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension)iterator.next(); if (actionItem.getRouteHeaderId() == null) { LOG.error("Somehow there exists an ActionItem with a null document id! actionItemId=" + actionItem.getActionItemId()); iterator.remove(); continue; } try { actionItem.initialize(preferences); DocumentRouteHeaderValueActionListExtension routeHeaderExtension = (DocumentRouteHeaderValueActionListExtension)actionItem.getRouteHeader(); routeHeaderExtension.setActionListInitiatorPrincipal(routeHeaderExtension.getInitiatorPrincipal()); actionItem.setActionItemIndex(new Integer(index)); //set background colors for document statuses if (KEWConstants.ROUTE_HEADER_APPROVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorApproved())); } else if (KEWConstants.ROUTE_HEADER_CANCEL_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorCanceled())); } else if (KEWConstants.ROUTE_HEADER_DISAPPROVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorDissaproved())); } else if (KEWConstants.ROUTE_HEADER_ENROUTE_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorEnroute())); } else if (KEWConstants.ROUTE_HEADER_EXCEPTION_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorException())); } else if (KEWConstants.ROUTE_HEADER_FINAL_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorFinal())); } else if (KEWConstants.ROUTE_HEADER_INITIATED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorInitiated())); } else if (KEWConstants.ROUTE_HEADER_PROCESSED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorProccessed())); } else if (KEWConstants.ROUTE_HEADER_SAVED_CD.equalsIgnoreCase(actionItem.getRouteHeader().getDocRouteStatus())) { actionItem.setRowStyleClass((String)KEWConstants.ACTION_LIST_COLOR_PALETTE.get(preferences.getColorSaved())); } index++; } catch (Exception e) { // if there's a problem loading the action item, we don't want to blow out the whole screen but we will remove it from the list // and display an approriate error message to the user LOG.error("Error loading action list for action item " + actionItem.getActionItemId(), e); iterator.remove(); actionItemProblemIds.add(actionItem.getRouteHeaderId()); } } generateActionItemErrors(errors, "actionlist.badActionItems", actionItemProblemIds); } /** * Gets the page size of the Action List. Uses the user's preferences for page size unless the action list * has been throttled by an application constant, in which case it uses the smaller of the two values. */ protected int getPageSize(Preferences preferences) { return Integer.parseInt(preferences.getPageSize()); } protected PaginatedList buildCurrentPage(List actionList, Integer page, String sortCriterion, String sortDirection, int pageSize, Preferences preferences, ActionErrors errors, ActionListForm form) throws WorkflowException { List currentPage = new ArrayList(pageSize); boolean haveFyis = false; boolean haveApproves = false; boolean haveAcknowledges = false; boolean haveCancels = false; boolean haveDisapproves = false; boolean haveCustomActions = false; List customActionListProblemIds = new ArrayList(); SortOrderEnum sortOrder = parseSortOrder(sortDirection); int startIndex = (page.intValue() - 1) * pageSize; int endIndex = startIndex + pageSize; for (int index = startIndex; index < endIndex && index < actionList.size(); index++) { ActionItemActionListExtension actionItem = (ActionItemActionListExtension)actionList.get(index); // evaluate custom action list component for mass actions try { boolean itemHasApproves = false; boolean itemHasDisapproves = false; boolean itemHasCancels = false; boolean itemHasAcknowledges = false; boolean itemHasFyis = false; boolean itemHasCustomActions = false; CustomActionListAttribute customActionListAttribute = actionItem.getRouteHeader().getCustomActionListAttribute(); if (customActionListAttribute != null) { Map customActions = new LinkedHashMap(); customActions.put("NONE", "NONE"); ActionSet legalActions = customActionListAttribute.getLegalActions(UserSession.getAuthenticatedUser(), actionItem); if (legalActions != null && legalActions.hasApprove() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_APPROVED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_APPROVED_CD, KEWConstants.ACTION_REQUEST_APPROVE_REQ_LABEL); itemHasApproves = true; } if (legalActions != null && legalActions.hasDisapprove() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_DENIED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_DENIED_CD, KEWConstants.ACTION_REQUEST_DISAPPROVE_LABEL); itemHasDisapproves = true; } if (legalActions != null && legalActions.hasCancel() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_CANCELED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_CANCELED_CD, KEWConstants.ACTION_REQUEST_CANCEL_REQ_LABEL); itemHasCancels = true; } if (legalActions != null && legalActions.hasAcknowledge() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD)) { customActions.put(KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD, KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL); itemHasAcknowledges = true; } if (legalActions != null && legalActions.hasFyi() && isActionCompatibleRequest(actionItem, KEWConstants.ACTION_TAKEN_FYI_CD) && KEWConstants.PREFERENCES_YES_VAL.equalsIgnoreCase(preferences.getShowClearFyi())) { customActions.put(KEWConstants.ACTION_TAKEN_FYI_CD, KEWConstants.ACTION_REQUEST_FYI_REQ_LABEL); itemHasFyis = true; } if (customActions.size() > 1) { actionItem.setCustomActions(customActions); itemHasCustomActions = true; } actionItem.setDisplayParameters(customActionListAttribute.getDocHandlerDisplayParameters(UserSession.getAuthenticatedUser(), actionItem)); haveApproves = haveApproves || itemHasApproves; haveAcknowledges = haveAcknowledges || itemHasAcknowledges; haveFyis = haveFyis || itemHasFyis; haveDisapproves = haveDisapproves || itemHasDisapproves; haveCancels = haveCancels || itemHasCancels; haveCustomActions = haveCustomActions || itemHasCustomActions; } } catch (Exception e) { // if there's a problem loading the custom action list attribute, let's go ahead and display the vanilla action item LOG.error("Problem loading custom action list attribute", e); customActionListProblemIds.add(actionItem.getRouteHeaderId()); } currentPage.add(actionItem); } // configure custom actions on form form.setHasCustomActions(new Boolean(haveCustomActions)); Map defaultActions = new LinkedHashMap(); defaultActions.put("NONE", "NONE"); if (haveApproves) { defaultActions.put(KEWConstants.ACTION_TAKEN_APPROVED_CD, KEWConstants.ACTION_REQUEST_APPROVE_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveDisapproves) { defaultActions.put(KEWConstants.ACTION_TAKEN_DENIED_CD, KEWConstants.ACTION_REQUEST_DISAPPROVE_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveCancels) { defaultActions.put(KEWConstants.ACTION_TAKEN_CANCELED_CD, KEWConstants.ACTION_REQUEST_CANCEL_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } if (haveAcknowledges) { defaultActions.put(KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD, KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL); form.setCustomActionList(Boolean.TRUE); } //clearing FYI's can be done in any action list not just a customized one if (haveFyis && KEWConstants.PREFERENCES_YES_VAL.equalsIgnoreCase(preferences.getShowClearFyi())) { defaultActions.put(KEWConstants.ACTION_TAKEN_FYI_CD, KEWConstants.ACTION_REQUEST_FYI_REQ_LABEL); } if (defaultActions.size() > 1) { form.setDefaultActions(defaultActions); } generateActionItemErrors(errors, "actionlist.badCustomActionListItems", customActionListProblemIds); return new PaginatedActionList(currentPage, actionList.size(), page.intValue(), pageSize, "actionList", sortCriterion, sortOrder); } private void generateActionItemErrors(ActionErrors errors, String errorKey, List documentIds) { if (!documentIds.isEmpty()) { String documentIdsString = StringUtils.join(documentIds.iterator(), ", "); errors.add(Globals.ERROR_KEY, new ActionMessage(errorKey, documentIdsString)); } } public ActionForward takeMassActions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm actionListForm = (ActionListForm) form; List actionList = (List) request.getSession().getAttribute(ACTION_LIST_KEY); if (actionList == null) { return start(mapping, new ActionListForm(), request, response); } ActionMessages messages = new ActionMessages(); List invocations = new ArrayList(); int index = 0; for (Iterator iterator = actionListForm.getActionsToTake().iterator(); iterator.hasNext();) { ActionToTake actionToTake = (ActionToTake) iterator.next(); if (actionToTake != null && actionToTake.getActionTakenCd() != null && !"".equals(actionToTake.getActionTakenCd()) && !"NONE".equalsIgnoreCase(actionToTake.getActionTakenCd()) && actionToTake.getActionItemId() != null) { ActionItem actionItem = getActionItemFromActionList(actionList, actionToTake.getActionItemId()); if (actionItem == null) { LOG.warn("Could not locate the ActionItem to take mass action against in the action list: " + actionToTake.getActionItemId()); continue; } invocations.add(new ActionInvocation(actionItem.getActionItemId(), actionToTake.getActionTakenCd())); } index++; } KEWServiceLocator.getWorkflowDocumentService().takeMassActions(getUserSession(request).getPrincipalId(), invocations); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("general.routing.processed")); saveMessages(request, messages); ActionListForm cleanForm = new ActionListForm(); request.setAttribute(mapping.getName(), cleanForm); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); return start(mapping, cleanForm, request, response); } protected ActionItem getActionItemFromActionList(List actionList, Long actionItemId) { for (Iterator iterator = actionList.iterator(); iterator.hasNext();) { ActionItem actionItem = (ActionItem) iterator.next(); if (actionItem.getActionItemId().equals(actionItemId)) { return actionItem; } } return null; } public ActionForward helpDeskActionListLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm actionListForm = (ActionListForm) form; if (!"true".equals(request.getAttribute("helpDeskActionList"))) { throw new AuthorizationException(UserSession.getAuthenticatedUser().getPrincipalId(), "helpDeskActionListLogin", getClass().getSimpleName()); } getUserSession(request).establishHelpDeskWithPrincipalName(actionListForm.getHelpDeskActionListUserName()); actionListForm.setDelegator(null); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); return start(mapping, form, request, response); } public ActionForward clearFilter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("clearFilter ActionListAction"); UserSession session = getUserSession(request); session.setActionListFilter(null); request.getSession().setAttribute(REQUERY_ACTION_LIST_KEY, "true"); KEWServiceLocator.getActionListService().saveRefreshUserOption(session.getPrincipalId()); LOG.debug("end clearFilter ActionListAction"); return start(mapping, form, request, response); } public ActionForward clearHelpDeskActionListUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("clearHelpDeskActionListUser ActionListAction"); getUserSession(request).clearHelpDesk(); LOG.debug("end clearHelpDeskActionListUser ActionListAction"); return start(mapping, form, request, response); } /** * Generates an Action List count. */ public ActionForward count(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm alForm = (ActionListForm)form; Person user = getUserSession(request).getPerson(); alForm.setCount(KEWServiceLocator.getActionListService().getCount(user.getPrincipalId())); LOG.info("Fetched Action List count of " + alForm.getCount() + " for user " + user.getPrincipalName()); return mapping.findForward("count"); } public ActionForward removeOutboxItems(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionListForm alForm = (ActionListForm)form; if (alForm.getOutboxItems() != null) { KEWServiceLocator.getActionListService().removeOutboxItems(getUserSession(request).getPrincipal().getPrincipalId(), Arrays.asList(alForm.getOutboxItems())); } alForm.setViewOutbox("true"); return start(mapping, form, request, response); } private boolean isActionCompatibleRequest(ActionItemActionListExtension actionItem, String actionTakenCode) { boolean actionCompatible = false; String requestCd = actionItem.getActionRequestCd(); //FYI request matches FYI if (KEWConstants.ACTION_REQUEST_FYI_REQ.equals(requestCd) && KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode)) { actionCompatible = true || actionCompatible; } // ACK request matches ACK if (KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ.equals(requestCd) && KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode)) { actionCompatible = true || actionCompatible; } // APPROVE request matches all but FYI and ACK if (KEWConstants.ACTION_REQUEST_APPROVE_REQ.equals(requestCd) && !(KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode) || KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode))) { actionCompatible = true || actionCompatible; } // COMPLETE request matches all but FYI and ACK if (KEWConstants.ACTION_REQUEST_COMPLETE_REQ.equals(requestCd) && !(KEWConstants.ACTION_TAKEN_FYI_CD.equals(actionTakenCode) || KEWConstants.ACTION_TAKEN_ACKNOWLEDGED_CD.equals(actionTakenCode))) { actionCompatible = true || actionCompatible; } return actionCompatible; } private List getWebFriendlyRecipients(Collection recipients) { Collection newRecipients = new ArrayList(recipients.size()); for (Iterator iterator = recipients.iterator(); iterator.hasNext();) { newRecipients.add(new WebFriendlyRecipient(iterator.next())); } List recipientList = new ArrayList(newRecipients); Collections.sort(recipientList, new Comparator() { Comparator comp = new ComparableComparator(); public int compare(Object o1, Object o2) { return comp.compare(((WebFriendlyRecipient) o1).getDisplayName().trim().toLowerCase(), ((WebFriendlyRecipient) o2).getDisplayName().trim().toLowerCase()); } }); return recipientList; } private UserSession getUserSession(HttpServletRequest request){ return UserSession.getAuthenticatedUser(); } private class ActionItemComparator implements Comparator { private static final String DOCUMENT_ID = "routeHeaderId"; private final String sortName; public ActionItemComparator(String sortName) { if (StringUtils.isEmpty(sortName)) { sortName = DOCUMENT_ID; } this.sortName = sortName; } public int compare(Object object1, Object object2) { try { ActionItem actionItem1 = (ActionItem)object1; ActionItem actionItem2 = (ActionItem)object2; // invoke the power of the lookup functionality provided by the display tag library, this LookupUtil method allows for us // to evaulate nested bean properties (like workgroup.groupNameId.nameId) in a null-safe manner. For example, in the // example if workgroup evaluated to NULL then LookupUtil.getProperty would return null rather than blowing an exception Object property1 = LookupUtil.getProperty(actionItem1, sortName); Object property2 = LookupUtil.getProperty(actionItem2, sortName); if (property1 == null && property2 == null) { return 0; } else if (property1 == null) { return -1; } else if (property2 == null) { return 1; } if (property1 instanceof Comparable) { return ((Comparable)property1).compareTo(property2); } return property1.toString().compareTo(property2.toString()); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException("Could not sort for the given sort name: " + sortName, e); } } } }
KULRICE-2610 Remove WorkflowMessages include from ActionListNew.jsp, replace with <kul:errors/> and <kul:messages/>
impl/src/main/java/org/kuali/rice/kew/actionlist/web/ActionListAction.java
KULRICE-2610 Remove WorkflowMessages include from ActionListNew.jsp, replace with <kul:errors/> and <kul:messages/>
Java
apache-2.0
cd7b996a0ad163beb81e4ae223eeaca4569d9945
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package biomodel.network; import java.awt.Dimension; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import lpn.parser.LhpnFile; import lpn.parser.Translator; import main.Gui; import main.util.MutableString; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.ModifierSpeciesReference; import org.sbml.libsbml.Event; import org.sbml.libsbml.EventAssignment; import org.sbml.libsbml.KineticLaw; import org.sbml.libsbml.LocalParameter; import org.sbml.libsbml.Model; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import org.sbml.libsbml.Submodel; import org.sbml.libsbml.Unit; import org.sbml.libsbml.UnitDefinition; import org.sbml.libsbml.XMLAttributes; import org.sbml.libsbml.XMLNode; import org.sbml.libsbml.XMLTriple; import org.sbml.libsbml.libsbml; import com.lowagie.text.Document; import biomodel.gui.Grid; import biomodel.gui.textualeditor.SBMLutilities; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.Utility; import biomodel.visitor.AbstractPrintVisitor; import biomodel.visitor.PrintActivatedBindingVisitor; import biomodel.visitor.PrintActivatedProductionVisitor; import biomodel.visitor.PrintComplexVisitor; import biomodel.visitor.PrintDecaySpeciesVisitor; import biomodel.visitor.PrintRepressionBindingVisitor; import biomodel.visitor.PrintSpeciesVisitor; /** * This class represents a genetic network * * @author Nam * */ public class GeneticNetwork { //private String separator; /** * Constructor * * @param species * a hashmap of species * @param stateMap * a hashmap of statename to species name * @param promoters * a hashmap of promoters */ public GeneticNetwork(HashMap<String, SpeciesInterface> species, HashMap<String, ArrayList<Influence>> complexMap, HashMap<String, ArrayList<Influence>> partsMap, HashMap<String, Promoter> promoters) { this(species, complexMap, partsMap, promoters, null); } /** * Constructor */ public GeneticNetwork() { /* if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } */ } /** * Constructor * * @param species * a hashmap of species * @param stateMap * a hashmap of statename to species name * @param promoters * a hashmap of promoters * @param gcm * a gcm file containing extra information */ public GeneticNetwork(HashMap<String, SpeciesInterface> species, HashMap<String, ArrayList<Influence>> complexMap, HashMap<String, ArrayList<Influence>> partsMap, HashMap<String, Promoter> promoters, BioModel gcm) { /* if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } */ this.species = species; interestingSpecies = new String[species.size()]; this.promoters = promoters; this.complexMap = complexMap; this.partsMap = partsMap; this.properties = gcm; // TODO: THIS IS BROKEN this.compartments = new HashMap<String,Properties>(); for (long i=0; i < gcm.getSBMLDocument().getModel().getNumCompartments(); i++) { compartments.put(gcm.getSBMLDocument().getModel().getCompartment(i).getId(), null); } AbstractPrintVisitor.setGCMFile(gcm); buildComplexes(); buildComplexInfluences(); } public void buildTemplate(HashMap<String, SpeciesInterface> species, HashMap<String, Promoter> promoters, String gcm, String filename) { BioModel file = new BioModel(currentRoot); file.load(currentRoot+gcm); AbstractPrintVisitor.setGCMFile(file); setSpecies(species); setPromoters(promoters); SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION); currentDocument = document; Model m = document.createModel(); document.setModel(m); Utility.addCompartments(document, "default"); document.getModel().getCompartment("default").setSize(1); document.getModel().getCompartment("default").setConstant(true); SBMLWriter writer = new SBMLWriter(); printSpecies(document); printOnlyPromoters(document); try { PrintStream p = new PrintStream(new FileOutputStream(filename)); m.setName("Created from " + gcm); m.setId(new File(filename).getName().replace(".xml", "")); m.setVolumeUnits("litre"); m.setSubstanceUnits("mole"); p.print(writer.writeSBMLToString(document)); p.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Loads in a properties file * * @param filename * the file to load */ public void loadProperties(BioModel gcm) { properties = gcm; } public void loadProperties(BioModel gcm, ArrayList<String> gcmAbstractions, String[] interestingSpecies, String property) { properties = gcm; for (String abstractionOption : gcmAbstractions) { if (abstractionOption.equals("complex-formation-and-sequestering-abstraction")) complexAbstraction = true; else if (abstractionOption.equals("operator-site-reduction-abstraction")) operatorAbstraction = true; } this.interestingSpecies = interestingSpecies; this.property = property; } public void setSBMLFile(String file) { sbmlDocument = file; } public void setSBML(SBMLDocument doc) { document = doc; } public String getSBMLFile() { return sbmlDocument; } public SBMLDocument getSBML() { return document; } /** * Outputs the network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument outputSBML(String filename) { SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION); currentDocument = document; Model m = document.createModel(); document.setModel(m); Utility.addCompartments(document, "default"); document.getModel().getCompartment("default").setSize(1); return outputSBML(filename, document); } public SBMLDocument outputSBML(String filename, SBMLDocument document) { try { Model m = document.getModel(); SBMLWriter writer = new SBMLWriter(); printSpecies(document); if (!operatorAbstraction) { if (promoters.size()>0) { printPromoters(document); printRNAP(document); } } printDecay(document); printPromoterProduction(document); if (!operatorAbstraction) printPromoterBinding(document); printComplexBinding(document); reformatArrayContent(document, filename); PrintStream p = new PrintStream(new FileOutputStream(filename),true,"UTF-8"); m.setName("Created from " + new File(filename).getName().replace("xml", "gcm")); m.setId(new File(filename).getName().replace(".xml", "")); m.setVolumeUnits("litre"); m.setSubstanceUnits("mole"); if (property != null && !property.equals("")) { ArrayList<String> species = new ArrayList<String>(); ArrayList<Object[]> levels = new ArrayList<Object[]>(); for (String spec : properties.getSpecies()) { species.add(spec); levels.add(new Object[0]); } MutableString prop = new MutableString(property); LhpnFile lpn = properties.convertToLHPN(species, levels, prop); property = prop.getString(); Translator.generateSBMLConstraints(document, property, lpn); } if (document != null) { document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, true); document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, true); document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, true); long numErrors = document.checkConsistency(); if (numErrors > 0) { String message = ""; for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // .replace(". ", // ".\n"); message += i + ":" + error + "\n"; } JTextArea messageArea = new JTextArea(message); messageArea.setLineWrap(true); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "Generated SBML Has Errors", JOptionPane.ERROR_MESSAGE); } } p.print(writer.writeSBMLToString(document)); p.close(); return document; } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Merges an SBML file network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument mergeSBML(String filename) { try { if (document == null) { if (sbmlDocument.equals("")) { return outputSBML(filename); } SBMLDocument document = Gui.readSBML(currentRoot + sbmlDocument); // checkConsistancy(document); currentDocument = document; return outputSBML(filename, document); } else { currentDocument = document; return outputSBML(filename, document); } } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Merges an SBML file network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument mergeSBML(String filename, SBMLDocument document) { try { currentDocument = document; return outputSBML(filename, document); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Prints each promoter binding * * @param document * the SBMLDocument to print to */ private void printPromoterBinding(SBMLDocument document) { for (Promoter p : promoters.values()) { // First setup RNAP binding if (p.getOutputs().size()==0) continue; String compartment = p.getCompartment(); String rnapName = "RNAP"; if (!compartment.equals(document.getModel().getCompartment(0).getId())) rnapName = compartment + "__RNAP"; org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(Gui.SBML_LEVEL, Gui.SBML_VERSION); r.setCompartment(compartment); r.setId("R_" + p.getId() + "_RNAP"); r.addReactant(Utility.SpeciesReference(rnapName, 1)); r.addReactant(Utility.SpeciesReference(p.getId(), 1)); r.addProduct(Utility.SpeciesReference(p.getId() + "_RNAP", 1)); r.setReversible(true); r.setFast(false); KineticLaw kl = r.createKineticLaw(); double[] Krnap = p.getKrnap(); if (Krnap[0] >= 0) { kl.addParameter(Utility.Parameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING, Krnap[0], GeneticNetwork.getMoleTimeParameter(2))); if (Krnap.length == 2) { kl.addParameter(Utility.Parameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING, Krnap[1], GeneticNetwork.getMoleTimeParameter(1))); } else { kl.addParameter(Utility.Parameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING, 1, GeneticNetwork.getMoleTimeParameter(1))); } } kl.setFormula(GlobalConstants.FORWARD_RNAP_BINDING_STRING + "*" + rnapName + "*" + p.getId() + "-"+ GlobalConstants.REVERSE_RNAP_BINDING_STRING + "*" + p.getId() + "_RNAP"); Utility.addReaction(document, r); // Next setup activated binding PrintActivatedBindingVisitor v = new PrintActivatedBindingVisitor( document, p, species, compartment, complexMap, partsMap); v.setComplexAbstraction(complexAbstraction); v.run(); // Next setup repression binding PrintRepressionBindingVisitor v2 = new PrintRepressionBindingVisitor( document, p, species, compartment, complexMap, partsMap); v2.setComplexAbstraction(complexAbstraction); v2.run(); } } /** * does lots of formatting -- mostly to bring the model into compliance with JSBML and to replace * the Type=Grid annotation with better information * * @param document */ private void reformatArrayContent(SBMLDocument document, String filename) { ArrayList<Reaction> membraneDiffusionReactions = new ArrayList<Reaction>(); //find all individual membrane diffusion reactions for (int i = 0; i < document.getModel().getNumReactions(); ++i) { if (document.getModel().getReaction(i).getId().contains("MembraneDiffusion")) membraneDiffusionReactions.add(document.getModel().getReaction(i)); } HashSet<String> reactionsToRemove = new HashSet<String>(); //turn the individual membrane diffusion reactions into arrays for each species for (Reaction membraneDiffusionReaction : membraneDiffusionReactions) { String reactionID = membraneDiffusionReaction.getId(); ArrayList<String> validSubmodels = new ArrayList<String>(); //loop through submodels to see if they have this same membrane diffusion reaction ID for (int submodelIndex = 0; submodelIndex < properties.getSBMLCompModel().getNumSubmodels(); ++submodelIndex) { SBMLReader sbmlReader = new SBMLReader(); Model submodel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getSBMLCompModel().getSubmodel(submodelIndex).getModelRef() + ".xml").getModel(); if (submodel.getReaction(reactionID) != null) validSubmodels.add(submodel.getId()); } membraneDiffusionReaction.setAnnotation(""); //now go through this list of valid submodels, find their locations, and add those to the reaction's annotation for (String validSubmodelID : validSubmodels) { if (properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations") != null) { validSubmodelID = validSubmodelID.replace("GRID__",""); if (membraneDiffusionReaction.getAnnotationString().length() > 0) membraneDiffusionReaction.appendAnnotation(", " + properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","")); else membraneDiffusionReaction.setAnnotation( properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","")); } } //fix the array annotation that was just created String reactionAnnotation = membraneDiffusionReaction.getAnnotationString(); ArrayList<String> components = new ArrayList<String>(); String[] splitAnnotation = reactionAnnotation.replace("\"","").split("array:"); //find all components in the annotation for (int j = 2; j < splitAnnotation.length; ++j) { components.add(splitAnnotation[j].split("=")[0].trim()); } //handle/fix non-grid membrane diffusion reactions //if it doesn't have a product then it's a non-grid reaction //so we need to see if the appropriate product is available //if it isn't, the reaction needs to be deleted as it shouldn't exist //unless the species exists on both sides of the membrane if (membraneDiffusionReaction.getNumProducts() == 0) { //take off the immediate compartment ID String[] splitReactantID = membraneDiffusionReaction.getReactant(0).getSpecies().split("__"); String potentialProductID = ""; for (int i = 1; i < splitReactantID.length; ++i) potentialProductID += splitReactantID[i]; //if the potential product is there and is diffusible if (document.getModel().getSpecies(potentialProductID) != null && document.getModel().getReaction("MembraneDiffusion_" + potentialProductID) != null) { SpeciesReference newProduct = membraneDiffusionReaction.createProduct(); newProduct.setSpecies(potentialProductID); newProduct.setStoichiometry(1.0); newProduct.setConstant(true); //add the product into the kinetic law membraneDiffusionReaction.getKineticLaw().setFormula( membraneDiffusionReaction.getKineticLaw().getFormula() + " * " + potentialProductID); //take off the annotation so it's not mistaken as a grid-based memdiff reaction membraneDiffusionReaction.setAnnotation(""); } else reactionsToRemove.add(membraneDiffusionReaction.getId()); } } ArrayList<Event> dynamicEvents = new ArrayList<Event>(); //look through all submodels for dynamic events for (int submodelIndex = 0; submodelIndex < properties.getSBMLCompModel().getNumSubmodels(); ++submodelIndex) { SBMLReader sbmlReader = new SBMLReader(); Model submodel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getSBMLCompModel().getSubmodel(submodelIndex).getModelRef() + ".xml").getModel(); if (properties.getSBMLCompModel().getSubmodel(submodelIndex).getId().contains("GRID__") == false) submodel.setId(properties.getSBMLCompModel().getSubmodel(submodelIndex).getId()); //find all individual dynamic events (within submodels) for (int i = 0; i < submodel.getNumEvents(); ++i) { Event event = submodel.getEvent(i); if (event.getAnnotationString().length() > 0 && ( event.getAnnotationString().contains("Division") || event.getAnnotationString().contains("Death"))) { if (event.getAnnotationString().contains("Symmetric Division")) event.setId(submodel.getId() + "__SymmetricDivision__" + event.getId()); if (event.getAnnotationString().contains("Asymmetric Division")) event.setId(submodel.getId() + "__AsymmetricDivision__" + event.getId()); else if (event.getAnnotationString().contains("Death")) event.setId(submodel.getId() + "__Death__" + event.getId()); dynamicEvents.add(event); } } } //make arrays out of the dynamic events (for the top-level model) for (Event dynEvent : dynamicEvents) { Event e = dynEvent.cloneObject(); e.setNamespaces(document.getNamespaces()); document.getModel().addEvent(e); Event dynamicEvent = document.getModel().getEvent(dynEvent.getId()); String[] splitID = dynamicEvent.getId().split("__"); String submodelID = splitID[0]; //length of 3 indicates an array/grid boolean isGrid = (splitID.length == 3); if (isGrid) dynamicEvent.setId(dynamicEvent.getId().replace(submodelID + "__","")); if (properties.getSBMLDocument().getModel().getParameter(submodelID + "__locations") != null) { dynamicEvent.setAnnotation(", " + properties.getSBMLDocument().getModel().getParameter(submodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","").trim()); } // String reactionAnnotation = dynamicEvent.getAnnotationString(); // ArrayList<String> components = new ArrayList<String>(); // // String[] splitAnnotation = reactionAnnotation.replace("\"","").split("array:"); // // //find all components in the annotation // for (int j = 2; j < splitAnnotation.length; ++j) { // // components.add(splitAnnotation[j].split("=")[0].trim()); // } // // //replace the annotation with a better-formatted version (for jsbml) // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:array", "http://www.fakeuri.com"); // // for (String componentID : components) // attr.add("array:" + componentID, "(" + properties.getSubmodelRow(componentID) + "," + // properties.getSubmodelCol(componentID) + ")"); // // XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); // // if (isGrid) // dynamicEvent.setAnnotation(node); } //replace all Type=Grid occurences with more complete information for (int i = 0; i < document.getModel().getNumReactions(); ++i) { if (document.getModel().getReaction(i).getAnnotationString() != null && document.getModel().getReaction(i).getAnnotationString().contains("type=\"grid\"")) { document.getModel().getReaction(i).setAnnotation(""); } } //replace all Type=Grid occurences with more complete information for (int i = 0; i < document.getModel().getNumSpecies(); ++i) { if (document.getModel().getSpecies(i).getAnnotationString() != null && document.getModel().getSpecies(i).getAnnotationString().contains("type=\"grid\"")) { XMLAttributes attr = new XMLAttributes(); attr.add("xmlns:array", "http://www.fakeuri.com"); attr.add("array:rowsLowerLimit", "0"); attr.add("array:colsLowerLimit", "0"); attr.add("array:rowsUpperLimit", String.valueOf(properties.getGrid().getNumRows() - 1)); attr.add("array:colsUpperLimit", String.valueOf(properties.getGrid().getNumCols() - 1)); XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); document.getModel().getSpecies(i).setAnnotation(node); } } //get a list of all components //ArrayList<String> components = new ArrayList<String>(); ArrayList<String> allComponents = new ArrayList<String>(); //search through the parameter location arrays for (int i = 0; i < document.getModel().getNumParameters(); ++i) { Parameter parameter = document.getModel().getParameter(i); //if it's a location parameter if (parameter.getId().contains("__locations")) { String[] splitAnnotation = parameter.getAnnotationString().replace("\"","").split("array:"); for (int j = 2; j < splitAnnotation.length; ++j) { allComponents.add(splitAnnotation[j].split("=")[0].trim()); } // //replace the locations arrays with correctly-formated versions // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:array", "http://www.fakeuri.com"); // // for (String componentID : components) // attr.add("array:" + componentID, "(" + properties.getSubmodelRow(componentID) + "," + // properties.getSubmodelCol(componentID) + ")"); // // XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); // parameter.setAnnotation(node); } } // //convert the compartment annotations so that they can be preserved in jsbml // for (int i = 0; i < document.getModel().getNumCompartments(); ++i) { // // if (document.getModel().getCompartment(i).getAnnotationString() != null && // document.getModel().getCompartment(i).getAnnotationString().contains("EnclosingCompartment")) { // // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:compartment", "http://www.fakeuri.com"); // attr.add("compartment:type", "enclosing"); // XMLNode node = new XMLNode(new XMLTriple("compartment","","compartment"), attr); // document.getModel().getCompartment(i).setAnnotation(node); // } // } for (String componentID : allComponents) { SBMLReader sbmlReader = new SBMLReader(); Model compModel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getModelFileName(componentID)).getModel(); //update the kmdiff values for membrane diffusion reactions //takes rates from the internal model for (int j = 0; j < compModel.getNumReactions(); ++j) { if (compModel.getReaction(j).getId().contains("MembraneDiffusion")) { Reaction reaction = compModel.getReaction(j); LocalParameter kmdiff_r = reaction.getKineticLaw().getLocalParameter("kmdiff_r"); LocalParameter kmdiff_f = reaction.getKineticLaw().getLocalParameter("kmdiff_f"); String speciesID = reaction.getReactant(0).getSpecies(); Parameter parameter_r = document.getModel().createParameter(); Parameter parameter_f = document.getModel().createParameter(); parameter_r.setId(componentID + "__" + speciesID + "__kmdiff_r"); parameter_f.setId(componentID + "__" + speciesID + "__kmdiff_f"); parameter_r.setName("Reverse membrane diffusion rate"); parameter_f.setName("Forward membrane diffusion rate"); parameter_r.setConstant(true); parameter_f.setConstant(true); if (kmdiff_r == null) { parameter_r.setValue(compModel.getParameter("kmdiff_r").getValue()); parameter_f.setValue(compModel.getParameter("kmdiff_f").getValue()); } else { parameter_r.setValue(kmdiff_r.getValue()); parameter_f.setValue(kmdiff_f.getValue()); } } } } for (String rtr : reactionsToRemove) document.getModel().removeReaction(rtr); SBMLWriter writer = new SBMLWriter(); PrintStream p; try { p = new PrintStream(new FileOutputStream(filename), true, "UTF-8"); p.print(writer.writeSBMLToString(document)); } catch (Exception e) { //e.printStackTrace(); } } /** * Prints each promoter production values * * @param document * the SBMLDocument to print to */ private void printPromoterProduction(SBMLDocument document) { for (Promoter p : promoters.values()) { if (p.getOutputs().size()==0) continue; String compartment = p.getCompartment(); org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(Gui.SBML_LEVEL, Gui.SBML_VERSION); r.setCompartment(compartment); for (SpeciesInterface species : p.getOutputs()) { r.addProduct(Utility.SpeciesReference(species.getId(), p.getStoich())); } r.setReversible(false); r.setFast(false); KineticLaw kl = r.createKineticLaw(); if (operatorAbstraction) { r.setId("R_abstracted_production_" + p.getId()); double rnap = 30; if (properties != null) rnap = Double.parseDouble(properties.getParameter(GlobalConstants.RNAP_STRING)); AbstractionEngine e = new AbstractionEngine(species, complexMap, partsMap, rnap, r, kl); kl.setFormula(e.abstractOperatorSite(p)); Utility.addReaction(document, r); } else { r.addModifier(Utility.ModifierSpeciesReference(p.getId() + "_RNAP")); if (p.getActivators().size() > 0) { r.setId("R_basal_production_" + p.getId()); kl.addParameter(Utility.Parameter(kBasalString, p.getKbasal(), getMoleTimeParameter(1))); kl.setFormula(kBasalString + "*" + p.getId() + "_RNAP"); } else { r.setId("R_constitutive_production_" + p.getId()); kl.addParameter(Utility.Parameter(kOcString, p.getKoc(), getMoleTimeParameter(1))); kl.setFormula(kOcString + "*" + p.getId() + "_RNAP"); } Utility.addReaction(document, r); if (p.getActivators().size() > 0) { PrintActivatedProductionVisitor v = new PrintActivatedProductionVisitor( document, p, compartment); v.run(); } } } } /** * Prints the decay reactions * * @param document * the SBML document */ private void printDecay(SBMLDocument document) { PrintDecaySpeciesVisitor visitor = new PrintDecaySpeciesVisitor(document, species, compartments, complexMap, partsMap); visitor.setComplexAbstraction(complexAbstraction); visitor.run(); } /** * Prints the species in the network * * @param document * the SBML document */ private void printSpecies(SBMLDocument document) { PrintSpeciesVisitor visitor = new PrintSpeciesVisitor(document, species, compartments); visitor.setComplexAbstraction(complexAbstraction); visitor.run(); } private void printComplexBinding(SBMLDocument document) { PrintComplexVisitor v = new PrintComplexVisitor(document, species, compartments, complexMap, partsMap); v.setComplexAbstraction(complexAbstraction); v.run(); } /** * Prints the promoters in the network * * @param document * the SBML document */ private void printPromoters(SBMLDocument document) { for (Promoter p : promoters.values()) { if (p.getOutputs().size()==0) continue; // First print out the promoter, and promoter bound to RNAP // But first check if promoter belongs to a compartment other than default String compartment = p.getCompartment(); Species s = Utility.makeSpecies(p.getId(), compartment, p.getInitialAmount(), -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); s = Utility.makeSpecies(p.getId() + "_RNAP", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); // Now cycle through all activators and repressors and add // those species bound to promoter for (SpeciesInterface specie : p.getActivators()) { String activator = specie.getId(); String[] splitted = activator.split("__"); if (splitted.length > 1) activator = splitted[1]; s = Utility.makeSpecies(p.getId() + "_" + activator + "_RNAP", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } for (SpeciesInterface specie : p.getRepressors()) { String repressor = specie.getId(); String[] splitted = repressor.split("__"); if (splitted.length > 1) repressor = splitted[1]; s = Utility.makeSpecies(p.getId() + "_" + repressor + "_bound", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } } } /** * Prints the promoters in the network * * @param document * the SBML document */ private void printOnlyPromoters(SBMLDocument document) { for (Promoter p : promoters.values()) { Species s = Utility.makeSpecies(p.getId(), document.getModel().getCompartment(0).getId(), p.getInitialAmount(), -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } } /** * Prints the RNAP molecule to the document * * @param document * the SBML document */ private void printRNAP(SBMLDocument document) { double rnap = 30; if (properties != null) { rnap = Double.parseDouble(properties.getParameter(GlobalConstants.RNAP_STRING)); } Species s = Utility.makeSpecies("RNAP", document.getModel().getCompartment(0).getId(), rnap, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); //Adds RNA polymerase for compartments other than default for (String compartment : compartments.keySet()) { Properties prop = compartments.get(compartment); if (prop != null && prop.containsKey(GlobalConstants.RNAP_STRING)) { rnap = Double.parseDouble((String)prop.get(GlobalConstants.RNAP_STRING)); } Species sc = Utility.makeSpecies(compartment + "__RNAP", compartment, rnap, -1); sc.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, sc); } } /** * Checks if species belongs in a compartment other than default */ private String checkCompartments(String species) { String compartment = document.getModel().getCompartment(0).getId(); //String[] splitted = species.split("__"); String component = species; while (component.contains("__")) { component = component.substring(0,component.lastIndexOf("__")); for (String compartmentName : compartments.keySet()) { if (compartmentName.equals(component)) return compartmentName; else if (compartmentName.contains("__") && compartmentName.substring(0, compartmentName.lastIndexOf("__")) .equals(component)) { return compartmentName; } } } /* if (compartments.contains(splitted[0])) compartment = splitted[0]; */ return compartment; } public AbstractionEngine createAbstractionEngine() { return new AbstractionEngine(species, complexMap, partsMap, Double.parseDouble(properties .getParameter(GlobalConstants.RNAP_STRING))); } /** * Builds the complex species * */ private void buildComplexes() { for (String complexId : complexMap.keySet()) { ComplexSpecies c = new ComplexSpecies(species.get(complexId)); species.put(complexId, c); } } private void buildComplexInfluences() { for (Promoter p : promoters.values()) { for (Influence r : p.getActivatingInfluences()) { String inputId = r.getInput(); if (complexMap.containsKey(inputId)) { p.addActivator(inputId, species.get(inputId)); species.get(inputId).setActivator(true); } } for (Influence r : p.getRepressingInfluences()) { String inputId = r.getInput(); if (complexMap.containsKey(inputId)) { p.addRepressor(inputId, species.get(inputId)); species.get(inputId).setRepressor(true); } } } } public void markAbstractable() { for (String complexId : complexMap.keySet()) { if (!partsMap.containsKey(complexId)) { HashSet<String> partsVisited = new HashSet<String>(); checkComplex(complexId, partsVisited); } } for (String partId : partsMap.keySet()) { SpeciesInterface part = species.get(partId); if ((partsMap.get(partId).size() > 1 || part.isActivator() || part.isRepressor()) && !part.isSequesterAbstractable() && !part.isConvergent()) checkSequester(partId, partId); } } //Marks complex as abstractable if it isn't genetic, diffusible, used in an event or rule, or used in a non-degradation reaction. //Otherwise unmarks all downstream complexes as abstractable. //Marks species as convergent if encountered on more than one downstream branch //Recursively checks all downstream complexes. private void checkComplex(String complexId, HashSet<String> partsVisited) { SpeciesInterface complex = species.get(complexId); if (!complex.isAbstractable()) { if (!isGenetic(complexId) && !complex.isDiffusible() && !SBMLutilities.variableInUse(document, complexId, false, false, true) && !SBMLutilities.usedInNonDegradationReaction(document, complexId)) { complex.setAbstractable(true); for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); if (partsVisited.contains(partId)) species.get(partId).setConvergent(true); else partsVisited.add(partId); if (complexMap.containsKey(partId)) { checkComplex(partId, partsVisited); } } } else unAbstractDown(complexId, ""); } } //Marks part as sequesterable after recursively checking that all upstream complexes are abstractable, have a binding stoichiometry of one, //are formed from two or more unique parts, and do not have potentially sequesterable parts on other downstream branches. //Otherwise unmarks all upstream complexes as abstractable. //Regardless unmarks all downstream complexes as abstractable. private boolean checkSequester(String partId, String sequesterRoot) { HashSet<SpeciesInterface> abstractableComplexes = new HashSet<SpeciesInterface>(); for (Influence infl : partsMap.get(partId)) { String complexId = infl.getOutput(); SpeciesInterface complex = species.get(complexId); if (complex.isAbstractable() && infl.getCoop() == 1 && complexMap.get(complexId).size() > 1 && checkSequesterComplex(complexId, partId) && (!partsMap.containsKey(complexId) || complex.isSequesterable() || checkSequester(complexId, sequesterRoot))) abstractableComplexes.add(complex); else { if (partId.equals(sequesterRoot)) { unAbstractUp(partId); if (complexMap.containsKey(partId)) unAbstractDown(partId, ""); } return false; } } if (partId.equals(sequesterRoot)) { species.get(partId).setSequesterable(true); if (complexMap.containsKey(partId)) unAbstractDown(partId, ""); } for (SpeciesInterface complex: abstractableComplexes) { complex.setSequesterable(false); complex.setSequesterAbstractable(true); } return true; } //Returns false if sequester complex has potentially sequesterable parts on downstream branches other than lastSequester. private boolean checkSequesterComplex(String complexId, String lastSequester) { for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); SpeciesInterface part = species.get(partId); if (!partId.equals(lastSequester)) { if (partsMap.get(partId).size() > 1 || part.isActivator() || part.isRepressor() || (complexMap.containsKey(partId) && !checkSequesterComplex(partId, ""))) return false; } } return true; } //Recursively unmarks complexes as abstractable on downstream branches other than payNoMind. public void unAbstractDown(String complexId, String payNoMind) { species.get(complexId).setAbstractable(false); for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); if (!partId.equals(payNoMind) && complexMap.containsKey(partId)) { unAbstractDown(partId, ""); } } } //Recursively unmarks all upstream complexes as abstractable. public void unAbstractUp(String partId) { for (Influence infl : partsMap.get(partId)) { String complexId = infl.getOutput(); unAbstractDown(complexId, partId); if (partsMap.containsKey(complexId)) unAbstractUp(complexId); } } //Unmarks complex species as abstractable (and their parts as sequesterable) if they are interesting public void unMarkInterestingSpecies(String[] interestingSpecies) { for (String interestingId : interestingSpecies) { if (species.containsKey(interestingId) && complexMap.containsKey(interestingId)) { species.get(interestingId).setAbstractable(false); species.get(interestingId).setSequesterAbstractable(false); for (Influence infl : complexMap.get(interestingId)) species.get(infl.getInput()).setSequesterable(false); } } } //Returns default interesting species, i.e. those that are outputs or genetically produced public ArrayList<String> getInterestingSpecies() { ArrayList<String> interestingSpecies = new ArrayList<String>(); for (String id : species.keySet()) { if (!complexMap.keySet().contains(id) || species.get(id).getType().equals(GlobalConstants.OUTPUT)) interestingSpecies.add(id); } return interestingSpecies; } public HashMap<String, SpeciesInterface> getSpecies() { return species; } public void setSpecies(HashMap<String, SpeciesInterface> species) { this.species = species; } public HashMap<String, Promoter> getPromoters() { return promoters; } public void setPromoters(HashMap<String, Promoter> promoters) { this.promoters = promoters; } public BioModel getProperties() { return properties; } public void setProperties(BioModel properties) { this.properties = properties; } public HashMap<String, ArrayList<Influence>> getComplexMap() { return complexMap; } private boolean isGenetic(String speciesId) { for (Promoter p : getPromoters().values()) if (p.getOutputs().toString().contains(speciesId)) return true; return false; } private String sbmlDocument = ""; private SBMLDocument document = null; private static SBMLDocument currentDocument = null; private static String currentRoot = ""; private boolean operatorAbstraction = false; private boolean complexAbstraction = false; private String[] interestingSpecies; private HashMap<String, SpeciesInterface> species = null; private HashMap<String, Promoter> promoters = null; private HashMap<String, ArrayList<Influence>> complexMap; private HashMap<String, ArrayList<Influence>> partsMap; private HashMap<String, Properties> compartments; private BioModel properties = null; // private String krnapString = GlobalConstants.RNAP_BINDING_STRING; private String kBasalString = GlobalConstants.KBASAL_STRING; private String kOcString = GlobalConstants.OCR_STRING; private String property; /** * Returns the curent SBML document being built * * @return the curent SBML document being built */ public static SBMLDocument getCurrentDocument() { return currentDocument; } /** * Sets the current root * @param root the root directory */ public static void setRoot(String root) { currentRoot = root; } public static String getUnitString(ArrayList<String> unitNames, ArrayList<Integer> exponents, ArrayList<Integer> multiplier, Model model) { // First build the name of the unit and see if it exists, start by // sorting the units to build a unique string for (int i = 0; i < unitNames.size(); i++) { for (int j = i; j > 0; j--) { if (unitNames.get(j - 1).compareTo(unitNames.get(i)) > 0) { Integer tempD = multiplier.get(j); Integer tempI = exponents.get(j); String tempS = unitNames.get(j); multiplier.set(j, multiplier.get(j - 1)); unitNames.set(j, unitNames.get(j - 1)); exponents.set(j, exponents.get(j - 1)); multiplier.set(j - 1, tempD); unitNames.set(j - 1, tempS); exponents.set(j - 1, tempI); } } } UnitDefinition t = new UnitDefinition(Gui.SBML_LEVEL, Gui.SBML_VERSION); String name = "u_"; for (int i = 0; i < unitNames.size(); i++) { String sign = ""; if (exponents.get(i).intValue() < 0) { sign = "n"; } name = name + multiplier.get(i) + "_" + unitNames.get(i) + "_" + sign + Math.abs(exponents.get(i)) + "_"; Unit u = t.createUnit(); u.setKind(libsbml.UnitKind_forName(unitNames.get(i))); u.setExponent(exponents.get(i).intValue()); u.setMultiplier(multiplier.get(i).intValue()); u.setScale(0); } name = name.substring(0, name.length() - 1); t.setId(name); if (model.getUnitDefinition(name) == null) { model.addUnitDefinition(t); } return name; } /** * Returns a unit name for a parameter based on the number of molecules * involved * * @param numMolecules * the number of molecules involved * @return a unit name */ public static String getMoleTimeParameter(int numMolecules) { ArrayList<String> unitS = new ArrayList<String>(); ArrayList<Integer> unitE = new ArrayList<Integer>(); ArrayList<Integer> unitM = new ArrayList<Integer>(); if (numMolecules > 1) { unitS.add("mole"); unitE.add(new Integer(-(numMolecules - 1))); unitM.add(new Integer(1)); } unitS.add("second"); unitE.add(new Integer(-1)); unitM.add(new Integer(1)); return GeneticNetwork.getUnitString(unitS, unitE, unitM, currentDocument.getModel()); } /** * Returns a unit name for a parameter based on the number of molecules * involved * * @param numMolecules * the number of molecules involved * @return a unit name */ public static String getMoleParameter(int numMolecules) { ArrayList<String> unitS = new ArrayList<String>(); ArrayList<Integer> unitE = new ArrayList<Integer>(); ArrayList<Integer> unitM = new ArrayList<Integer>(); unitS.add("mole"); unitE.add(new Integer(-(numMolecules - 1))); unitM.add(new Integer(1)); return GeneticNetwork.getUnitString(unitS, unitE, unitM, currentDocument.getModel()); } public static String getMoleParameter(String numMolecules) { return getMoleParameter(Integer.parseInt(numMolecules)); } }
gui/src/biomodel/network/GeneticNetwork.java
package biomodel.network; import java.awt.Dimension; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import lpn.parser.LhpnFile; import lpn.parser.Translator; import main.Gui; import main.util.MutableString; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.ModifierSpeciesReference; import org.sbml.libsbml.Event; import org.sbml.libsbml.EventAssignment; import org.sbml.libsbml.KineticLaw; import org.sbml.libsbml.LocalParameter; import org.sbml.libsbml.Model; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import org.sbml.libsbml.Submodel; import org.sbml.libsbml.Unit; import org.sbml.libsbml.UnitDefinition; import org.sbml.libsbml.XMLAttributes; import org.sbml.libsbml.XMLNode; import org.sbml.libsbml.XMLTriple; import org.sbml.libsbml.libsbml; import com.lowagie.text.Document; import biomodel.gui.Grid; import biomodel.gui.textualeditor.SBMLutilities; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.Utility; import biomodel.visitor.AbstractPrintVisitor; import biomodel.visitor.PrintActivatedBindingVisitor; import biomodel.visitor.PrintActivatedProductionVisitor; import biomodel.visitor.PrintComplexVisitor; import biomodel.visitor.PrintDecaySpeciesVisitor; import biomodel.visitor.PrintRepressionBindingVisitor; import biomodel.visitor.PrintSpeciesVisitor; /** * This class represents a genetic network * * @author Nam * */ public class GeneticNetwork { //private String separator; /** * Constructor * * @param species * a hashmap of species * @param stateMap * a hashmap of statename to species name * @param promoters * a hashmap of promoters */ public GeneticNetwork(HashMap<String, SpeciesInterface> species, HashMap<String, ArrayList<Influence>> complexMap, HashMap<String, ArrayList<Influence>> partsMap, HashMap<String, Promoter> promoters) { this(species, complexMap, partsMap, promoters, null); } /** * Constructor */ public GeneticNetwork() { /* if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } */ } /** * Constructor * * @param species * a hashmap of species * @param stateMap * a hashmap of statename to species name * @param promoters * a hashmap of promoters * @param gcm * a gcm file containing extra information */ public GeneticNetwork(HashMap<String, SpeciesInterface> species, HashMap<String, ArrayList<Influence>> complexMap, HashMap<String, ArrayList<Influence>> partsMap, HashMap<String, Promoter> promoters, BioModel gcm) { /* if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } */ this.species = species; interestingSpecies = new String[species.size()]; this.promoters = promoters; this.complexMap = complexMap; this.partsMap = partsMap; this.properties = gcm; // TODO: THIS IS BROKEN this.compartments = new HashMap<String,Properties>(); for (long i=0; i < gcm.getSBMLDocument().getModel().getNumCompartments(); i++) { compartments.put(gcm.getSBMLDocument().getModel().getCompartment(i).getId(), null); } AbstractPrintVisitor.setGCMFile(gcm); buildComplexes(); buildComplexInfluences(); } public void buildTemplate(HashMap<String, SpeciesInterface> species, HashMap<String, Promoter> promoters, String gcm, String filename) { BioModel file = new BioModel(currentRoot); file.load(currentRoot+gcm); AbstractPrintVisitor.setGCMFile(file); setSpecies(species); setPromoters(promoters); SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION); currentDocument = document; Model m = document.createModel(); document.setModel(m); Utility.addCompartments(document, "default"); document.getModel().getCompartment("default").setSize(1); document.getModel().getCompartment("default").setConstant(true); SBMLWriter writer = new SBMLWriter(); printSpecies(document); printOnlyPromoters(document); try { PrintStream p = new PrintStream(new FileOutputStream(filename)); m.setName("Created from " + gcm); m.setId(new File(filename).getName().replace(".xml", "")); m.setVolumeUnits("litre"); //m.setSubstanceUnits("mole"); p.print(writer.writeSBMLToString(document)); p.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Loads in a properties file * * @param filename * the file to load */ public void loadProperties(BioModel gcm) { properties = gcm; } public void loadProperties(BioModel gcm, ArrayList<String> gcmAbstractions, String[] interestingSpecies, String property) { properties = gcm; for (String abstractionOption : gcmAbstractions) { if (abstractionOption.equals("complex-formation-and-sequestering-abstraction")) complexAbstraction = true; else if (abstractionOption.equals("operator-site-reduction-abstraction")) operatorAbstraction = true; } this.interestingSpecies = interestingSpecies; this.property = property; } public void setSBMLFile(String file) { sbmlDocument = file; } public void setSBML(SBMLDocument doc) { document = doc; } public String getSBMLFile() { return sbmlDocument; } public SBMLDocument getSBML() { return document; } /** * Outputs the network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument outputSBML(String filename) { SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION); currentDocument = document; Model m = document.createModel(); document.setModel(m); Utility.addCompartments(document, "default"); document.getModel().getCompartment("default").setSize(1); return outputSBML(filename, document); } public SBMLDocument outputSBML(String filename, SBMLDocument document) { try { Model m = document.getModel(); SBMLWriter writer = new SBMLWriter(); printSpecies(document); if (!operatorAbstraction) { if (promoters.size()>0) { printPromoters(document); printRNAP(document); } } printDecay(document); printPromoterProduction(document); if (!operatorAbstraction) printPromoterBinding(document); printComplexBinding(document); reformatArrayContent(document, filename); PrintStream p = new PrintStream(new FileOutputStream(filename),true,"UTF-8"); m.setName("Created from " + new File(filename).getName().replace("xml", "gcm")); m.setId(new File(filename).getName().replace(".xml", "")); m.setVolumeUnits("litre"); //m.setSubstanceUnits("mole"); if (property != null && !property.equals("")) { ArrayList<String> species = new ArrayList<String>(); ArrayList<Object[]> levels = new ArrayList<Object[]>(); for (String spec : properties.getSpecies()) { species.add(spec); levels.add(new Object[0]); } MutableString prop = new MutableString(property); LhpnFile lpn = properties.convertToLHPN(species, levels, prop); property = prop.getString(); Translator.generateSBMLConstraints(document, property, lpn); } if (document != null) { document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, true); document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, true); document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false); document.setConsistencyChecks(libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, true); long numErrors = document.checkConsistency(); if (numErrors > 0) { String message = ""; for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // .replace(". ", // ".\n"); message += i + ":" + error + "\n"; } JTextArea messageArea = new JTextArea(message); messageArea.setLineWrap(true); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(Gui.frame, scroll, "Generated SBML Has Errors", JOptionPane.ERROR_MESSAGE); } } p.print(writer.writeSBMLToString(document)); p.close(); return document; } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Merges an SBML file network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument mergeSBML(String filename) { try { if (document == null) { if (sbmlDocument.equals("")) { return outputSBML(filename); } SBMLDocument document = Gui.readSBML(currentRoot + sbmlDocument); // checkConsistancy(document); currentDocument = document; return outputSBML(filename, document); } else { currentDocument = document; return outputSBML(filename, document); } } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Merges an SBML file network to an SBML file * * @param filename * @return the sbml document */ public SBMLDocument mergeSBML(String filename, SBMLDocument document) { try { currentDocument = document; return outputSBML(filename, document); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Unable to output to SBML"); } } /** * Prints each promoter binding * * @param document * the SBMLDocument to print to */ private void printPromoterBinding(SBMLDocument document) { for (Promoter p : promoters.values()) { // First setup RNAP binding if (p.getOutputs().size()==0) continue; String compartment = p.getCompartment(); String rnapName = "RNAP"; if (!compartment.equals(document.getModel().getCompartment(0).getId())) rnapName = compartment + "__RNAP"; org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(Gui.SBML_LEVEL, Gui.SBML_VERSION); r.setCompartment(compartment); r.setId("R_" + p.getId() + "_RNAP"); r.addReactant(Utility.SpeciesReference(rnapName, 1)); r.addReactant(Utility.SpeciesReference(p.getId(), 1)); r.addProduct(Utility.SpeciesReference(p.getId() + "_RNAP", 1)); r.setReversible(true); r.setFast(false); KineticLaw kl = r.createKineticLaw(); double[] Krnap = p.getKrnap(); if (Krnap[0] >= 0) { kl.addParameter(Utility.Parameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING, Krnap[0], GeneticNetwork.getMoleTimeParameter(2))); if (Krnap.length == 2) { kl.addParameter(Utility.Parameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING, Krnap[1], GeneticNetwork.getMoleTimeParameter(1))); } else { kl.addParameter(Utility.Parameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING, 1, GeneticNetwork.getMoleTimeParameter(1))); } } kl.setFormula(GlobalConstants.FORWARD_RNAP_BINDING_STRING + "*" + rnapName + "*" + p.getId() + "-"+ GlobalConstants.REVERSE_RNAP_BINDING_STRING + "*" + p.getId() + "_RNAP"); Utility.addReaction(document, r); // Next setup activated binding PrintActivatedBindingVisitor v = new PrintActivatedBindingVisitor( document, p, species, compartment, complexMap, partsMap); v.setComplexAbstraction(complexAbstraction); v.run(); // Next setup repression binding PrintRepressionBindingVisitor v2 = new PrintRepressionBindingVisitor( document, p, species, compartment, complexMap, partsMap); v2.setComplexAbstraction(complexAbstraction); v2.run(); } } /** * does lots of formatting -- mostly to bring the model into compliance with JSBML and to replace * the Type=Grid annotation with better information * * @param document */ private void reformatArrayContent(SBMLDocument document, String filename) { ArrayList<Reaction> membraneDiffusionReactions = new ArrayList<Reaction>(); //find all individual membrane diffusion reactions for (int i = 0; i < document.getModel().getNumReactions(); ++i) { if (document.getModel().getReaction(i).getId().contains("MembraneDiffusion")) membraneDiffusionReactions.add(document.getModel().getReaction(i)); } HashSet<String> reactionsToRemove = new HashSet<String>(); //turn the individual membrane diffusion reactions into arrays for each species for (Reaction membraneDiffusionReaction : membraneDiffusionReactions) { String reactionID = membraneDiffusionReaction.getId(); ArrayList<String> validSubmodels = new ArrayList<String>(); //loop through submodels to see if they have this same membrane diffusion reaction ID for (int submodelIndex = 0; submodelIndex < properties.getSBMLCompModel().getNumSubmodels(); ++submodelIndex) { SBMLReader sbmlReader = new SBMLReader(); Model submodel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getSBMLCompModel().getSubmodel(submodelIndex).getModelRef() + ".xml").getModel(); if (submodel.getReaction(reactionID) != null) validSubmodels.add(submodel.getId()); } membraneDiffusionReaction.setAnnotation(""); //now go through this list of valid submodels, find their locations, and add those to the reaction's annotation for (String validSubmodelID : validSubmodels) { if (properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations") != null) { validSubmodelID = validSubmodelID.replace("GRID__",""); if (membraneDiffusionReaction.getAnnotationString().length() > 0) membraneDiffusionReaction.appendAnnotation(", " + properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","")); else membraneDiffusionReaction.setAnnotation( properties.getSBMLDocument().getModel().getParameter(validSubmodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","")); } } //fix the array annotation that was just created String reactionAnnotation = membraneDiffusionReaction.getAnnotationString(); ArrayList<String> components = new ArrayList<String>(); String[] splitAnnotation = reactionAnnotation.replace("\"","").split("array:"); //find all components in the annotation for (int j = 2; j < splitAnnotation.length; ++j) { components.add(splitAnnotation[j].split("=")[0].trim()); } //handle/fix non-grid membrane diffusion reactions //if it doesn't have a product then it's a non-grid reaction //so we need to see if the appropriate product is available //if it isn't, the reaction needs to be deleted as it shouldn't exist //unless the species exists on both sides of the membrane if (membraneDiffusionReaction.getNumProducts() == 0) { //take off the immediate compartment ID String[] splitReactantID = membraneDiffusionReaction.getReactant(0).getSpecies().split("__"); String potentialProductID = ""; for (int i = 1; i < splitReactantID.length; ++i) potentialProductID += splitReactantID[i]; //if the potential product is there and is diffusible if (document.getModel().getSpecies(potentialProductID) != null && document.getModel().getReaction("MembraneDiffusion_" + potentialProductID) != null) { SpeciesReference newProduct = membraneDiffusionReaction.createProduct(); newProduct.setSpecies(potentialProductID); newProduct.setStoichiometry(1.0); newProduct.setConstant(true); //add the product into the kinetic law membraneDiffusionReaction.getKineticLaw().setFormula( membraneDiffusionReaction.getKineticLaw().getFormula() + " * " + potentialProductID); //take off the annotation so it's not mistaken as a grid-based memdiff reaction membraneDiffusionReaction.setAnnotation(""); } else reactionsToRemove.add(membraneDiffusionReaction.getId()); } } ArrayList<Event> dynamicEvents = new ArrayList<Event>(); //look through all submodels for dynamic events for (int submodelIndex = 0; submodelIndex < properties.getSBMLCompModel().getNumSubmodels(); ++submodelIndex) { SBMLReader sbmlReader = new SBMLReader(); Model submodel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getSBMLCompModel().getSubmodel(submodelIndex).getModelRef() + ".xml").getModel(); if (properties.getSBMLCompModel().getSubmodel(submodelIndex).getId().contains("GRID__") == false) submodel.setId(properties.getSBMLCompModel().getSubmodel(submodelIndex).getId()); //find all individual dynamic events (within submodels) for (int i = 0; i < submodel.getNumEvents(); ++i) { Event event = submodel.getEvent(i); if (event.getAnnotationString().length() > 0 && ( event.getAnnotationString().contains("Division") || event.getAnnotationString().contains("Death"))) { if (event.getAnnotationString().contains("Symmetric Division")) event.setId(submodel.getId() + "__SymmetricDivision__" + event.getId()); if (event.getAnnotationString().contains("Asymmetric Division")) event.setId(submodel.getId() + "__AsymmetricDivision__" + event.getId()); else if (event.getAnnotationString().contains("Death")) event.setId(submodel.getId() + "__Death__" + event.getId()); dynamicEvents.add(event); } } } //make arrays out of the dynamic events (for the top-level model) for (Event dynEvent : dynamicEvents) { Event e = dynEvent.cloneObject(); e.setNamespaces(document.getNamespaces()); document.getModel().addEvent(e); Event dynamicEvent = document.getModel().getEvent(dynEvent.getId()); String[] splitID = dynamicEvent.getId().split("__"); String submodelID = splitID[0]; //length of 3 indicates an array/grid boolean isGrid = (splitID.length == 3); if (isGrid) dynamicEvent.setId(dynamicEvent.getId().replace(submodelID + "__","")); if (properties.getSBMLDocument().getModel().getParameter(submodelID + "__locations") != null) { dynamicEvent.setAnnotation(", " + properties.getSBMLDocument().getModel().getParameter(submodelID + "__locations").getAnnotationString() .replace("<annotation>","").replace("</annotation>","").trim()); } // String reactionAnnotation = dynamicEvent.getAnnotationString(); // ArrayList<String> components = new ArrayList<String>(); // // String[] splitAnnotation = reactionAnnotation.replace("\"","").split("array:"); // // //find all components in the annotation // for (int j = 2; j < splitAnnotation.length; ++j) { // // components.add(splitAnnotation[j].split("=")[0].trim()); // } // // //replace the annotation with a better-formatted version (for jsbml) // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:array", "http://www.fakeuri.com"); // // for (String componentID : components) // attr.add("array:" + componentID, "(" + properties.getSubmodelRow(componentID) + "," + // properties.getSubmodelCol(componentID) + ")"); // // XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); // // if (isGrid) // dynamicEvent.setAnnotation(node); } //replace all Type=Grid occurences with more complete information for (int i = 0; i < document.getModel().getNumReactions(); ++i) { if (document.getModel().getReaction(i).getAnnotationString() != null && document.getModel().getReaction(i).getAnnotationString().contains("type=\"grid\"")) { document.getModel().getReaction(i).setAnnotation(""); } } //replace all Type=Grid occurences with more complete information for (int i = 0; i < document.getModel().getNumSpecies(); ++i) { if (document.getModel().getSpecies(i).getAnnotationString() != null && document.getModel().getSpecies(i).getAnnotationString().contains("type=\"grid\"")) { XMLAttributes attr = new XMLAttributes(); attr.add("xmlns:array", "http://www.fakeuri.com"); attr.add("array:rowsLowerLimit", "0"); attr.add("array:colsLowerLimit", "0"); attr.add("array:rowsUpperLimit", String.valueOf(properties.getGrid().getNumRows() - 1)); attr.add("array:colsUpperLimit", String.valueOf(properties.getGrid().getNumCols() - 1)); XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); document.getModel().getSpecies(i).setAnnotation(node); } } //get a list of all components //ArrayList<String> components = new ArrayList<String>(); ArrayList<String> allComponents = new ArrayList<String>(); //search through the parameter location arrays for (int i = 0; i < document.getModel().getNumParameters(); ++i) { Parameter parameter = document.getModel().getParameter(i); //if it's a location parameter if (parameter.getId().contains("__locations")) { String[] splitAnnotation = parameter.getAnnotationString().replace("\"","").split("array:"); for (int j = 2; j < splitAnnotation.length; ++j) { allComponents.add(splitAnnotation[j].split("=")[0].trim()); } // //replace the locations arrays with correctly-formated versions // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:array", "http://www.fakeuri.com"); // // for (String componentID : components) // attr.add("array:" + componentID, "(" + properties.getSubmodelRow(componentID) + "," + // properties.getSubmodelCol(componentID) + ")"); // // XMLNode node = new XMLNode(new XMLTriple("array","","array"), attr); // parameter.setAnnotation(node); } } // //convert the compartment annotations so that they can be preserved in jsbml // for (int i = 0; i < document.getModel().getNumCompartments(); ++i) { // // if (document.getModel().getCompartment(i).getAnnotationString() != null && // document.getModel().getCompartment(i).getAnnotationString().contains("EnclosingCompartment")) { // // XMLAttributes attr = new XMLAttributes(); // attr.add("xmlns:compartment", "http://www.fakeuri.com"); // attr.add("compartment:type", "enclosing"); // XMLNode node = new XMLNode(new XMLTriple("compartment","","compartment"), attr); // document.getModel().getCompartment(i).setAnnotation(node); // } // } for (String componentID : allComponents) { SBMLReader sbmlReader = new SBMLReader(); Model compModel = sbmlReader.readSBMLFromFile(properties.getPath() + properties.getModelFileName(componentID)).getModel(); //update the kmdiff values for membrane diffusion reactions //takes rates from the internal model for (int j = 0; j < compModel.getNumReactions(); ++j) { if (compModel.getReaction(j).getId().contains("MembraneDiffusion")) { Reaction reaction = compModel.getReaction(j); LocalParameter kmdiff_r = reaction.getKineticLaw().getLocalParameter("kmdiff_r"); LocalParameter kmdiff_f = reaction.getKineticLaw().getLocalParameter("kmdiff_f"); String speciesID = reaction.getReactant(0).getSpecies(); Parameter parameter_r = document.getModel().createParameter(); Parameter parameter_f = document.getModel().createParameter(); parameter_r.setId(componentID + "__" + speciesID + "__kmdiff_r"); parameter_f.setId(componentID + "__" + speciesID + "__kmdiff_f"); parameter_r.setName("Reverse membrane diffusion rate"); parameter_f.setName("Forward membrane diffusion rate"); parameter_r.setConstant(true); parameter_f.setConstant(true); if (kmdiff_r == null) { parameter_r.setValue(compModel.getParameter("kmdiff_r").getValue()); parameter_f.setValue(compModel.getParameter("kmdiff_f").getValue()); } else { parameter_r.setValue(kmdiff_r.getValue()); parameter_f.setValue(kmdiff_f.getValue()); } } } } for (String rtr : reactionsToRemove) document.getModel().removeReaction(rtr); SBMLWriter writer = new SBMLWriter(); PrintStream p; try { p = new PrintStream(new FileOutputStream(filename), true, "UTF-8"); p.print(writer.writeSBMLToString(document)); } catch (Exception e) { //e.printStackTrace(); } } /** * Prints each promoter production values * * @param document * the SBMLDocument to print to */ private void printPromoterProduction(SBMLDocument document) { for (Promoter p : promoters.values()) { if (p.getOutputs().size()==0) continue; String compartment = p.getCompartment(); org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(Gui.SBML_LEVEL, Gui.SBML_VERSION); r.setCompartment(compartment); for (SpeciesInterface species : p.getOutputs()) { r.addProduct(Utility.SpeciesReference(species.getId(), p.getStoich())); } r.setReversible(false); r.setFast(false); KineticLaw kl = r.createKineticLaw(); if (operatorAbstraction) { r.setId("R_abstracted_production_" + p.getId()); double rnap = 30; if (properties != null) rnap = Double.parseDouble(properties.getParameter(GlobalConstants.RNAP_STRING)); AbstractionEngine e = new AbstractionEngine(species, complexMap, partsMap, rnap, r, kl); kl.setFormula(e.abstractOperatorSite(p)); Utility.addReaction(document, r); } else { r.addModifier(Utility.ModifierSpeciesReference(p.getId() + "_RNAP")); if (p.getActivators().size() > 0) { r.setId("R_basal_production_" + p.getId()); kl.addParameter(Utility.Parameter(kBasalString, p.getKbasal(), getMoleTimeParameter(1))); kl.setFormula(kBasalString + "*" + p.getId() + "_RNAP"); } else { r.setId("R_constitutive_production_" + p.getId()); kl.addParameter(Utility.Parameter(kOcString, p.getKoc(), getMoleTimeParameter(1))); kl.setFormula(kOcString + "*" + p.getId() + "_RNAP"); } Utility.addReaction(document, r); if (p.getActivators().size() > 0) { PrintActivatedProductionVisitor v = new PrintActivatedProductionVisitor( document, p, compartment); v.run(); } } } } /** * Prints the decay reactions * * @param document * the SBML document */ private void printDecay(SBMLDocument document) { PrintDecaySpeciesVisitor visitor = new PrintDecaySpeciesVisitor(document, species, compartments, complexMap, partsMap); visitor.setComplexAbstraction(complexAbstraction); visitor.run(); } /** * Prints the species in the network * * @param document * the SBML document */ private void printSpecies(SBMLDocument document) { PrintSpeciesVisitor visitor = new PrintSpeciesVisitor(document, species, compartments); visitor.setComplexAbstraction(complexAbstraction); visitor.run(); } private void printComplexBinding(SBMLDocument document) { PrintComplexVisitor v = new PrintComplexVisitor(document, species, compartments, complexMap, partsMap); v.setComplexAbstraction(complexAbstraction); v.run(); } /** * Prints the promoters in the network * * @param document * the SBML document */ private void printPromoters(SBMLDocument document) { for (Promoter p : promoters.values()) { if (p.getOutputs().size()==0) continue; // First print out the promoter, and promoter bound to RNAP // But first check if promoter belongs to a compartment other than default String compartment = p.getCompartment(); Species s = Utility.makeSpecies(p.getId(), compartment, p.getInitialAmount(), -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); s = Utility.makeSpecies(p.getId() + "_RNAP", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); // Now cycle through all activators and repressors and add // those species bound to promoter for (SpeciesInterface specie : p.getActivators()) { String activator = specie.getId(); String[] splitted = activator.split("__"); if (splitted.length > 1) activator = splitted[1]; s = Utility.makeSpecies(p.getId() + "_" + activator + "_RNAP", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } for (SpeciesInterface specie : p.getRepressors()) { String repressor = specie.getId(); String[] splitted = repressor.split("__"); if (splitted.length > 1) repressor = splitted[1]; s = Utility.makeSpecies(p.getId() + "_" + repressor + "_bound", compartment, 0, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } } } /** * Prints the promoters in the network * * @param document * the SBML document */ private void printOnlyPromoters(SBMLDocument document) { for (Promoter p : promoters.values()) { Species s = Utility.makeSpecies(p.getId(), document.getModel().getCompartment(0).getId(), p.getInitialAmount(), -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); } } /** * Prints the RNAP molecule to the document * * @param document * the SBML document */ private void printRNAP(SBMLDocument document) { double rnap = 30; if (properties != null) { rnap = Double.parseDouble(properties.getParameter(GlobalConstants.RNAP_STRING)); } Species s = Utility.makeSpecies("RNAP", document.getModel().getCompartment(0).getId(), rnap, -1); s.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, s); //Adds RNA polymerase for compartments other than default for (String compartment : compartments.keySet()) { Properties prop = compartments.get(compartment); if (prop != null && prop.containsKey(GlobalConstants.RNAP_STRING)) { rnap = Double.parseDouble((String)prop.get(GlobalConstants.RNAP_STRING)); } Species sc = Utility.makeSpecies(compartment + "__RNAP", compartment, rnap, -1); sc.setHasOnlySubstanceUnits(true); Utility.addSpecies(document, sc); } } /** * Checks if species belongs in a compartment other than default */ private String checkCompartments(String species) { String compartment = document.getModel().getCompartment(0).getId(); //String[] splitted = species.split("__"); String component = species; while (component.contains("__")) { component = component.substring(0,component.lastIndexOf("__")); for (String compartmentName : compartments.keySet()) { if (compartmentName.equals(component)) return compartmentName; else if (compartmentName.contains("__") && compartmentName.substring(0, compartmentName.lastIndexOf("__")) .equals(component)) { return compartmentName; } } } /* if (compartments.contains(splitted[0])) compartment = splitted[0]; */ return compartment; } public AbstractionEngine createAbstractionEngine() { return new AbstractionEngine(species, complexMap, partsMap, Double.parseDouble(properties .getParameter(GlobalConstants.RNAP_STRING))); } /** * Builds the complex species * */ private void buildComplexes() { for (String complexId : complexMap.keySet()) { ComplexSpecies c = new ComplexSpecies(species.get(complexId)); species.put(complexId, c); } } private void buildComplexInfluences() { for (Promoter p : promoters.values()) { for (Influence r : p.getActivatingInfluences()) { String inputId = r.getInput(); if (complexMap.containsKey(inputId)) { p.addActivator(inputId, species.get(inputId)); species.get(inputId).setActivator(true); } } for (Influence r : p.getRepressingInfluences()) { String inputId = r.getInput(); if (complexMap.containsKey(inputId)) { p.addRepressor(inputId, species.get(inputId)); species.get(inputId).setRepressor(true); } } } } public void markAbstractable() { for (String complexId : complexMap.keySet()) { if (!partsMap.containsKey(complexId)) { HashSet<String> partsVisited = new HashSet<String>(); checkComplex(complexId, partsVisited); } } for (String partId : partsMap.keySet()) { SpeciesInterface part = species.get(partId); if ((partsMap.get(partId).size() > 1 || part.isActivator() || part.isRepressor()) && !part.isSequesterAbstractable() && !part.isConvergent()) checkSequester(partId, partId); } } //Marks complex as abstractable if it isn't genetic, diffusible, used in an event or rule, or used in a non-degradation reaction. //Otherwise unmarks all downstream complexes as abstractable. //Marks species as convergent if encountered on more than one downstream branch //Recursively checks all downstream complexes. private void checkComplex(String complexId, HashSet<String> partsVisited) { SpeciesInterface complex = species.get(complexId); if (!complex.isAbstractable()) { if (!isGenetic(complexId) && !complex.isDiffusible() && !SBMLutilities.variableInUse(document, complexId, false, false, true) && !SBMLutilities.usedInNonDegradationReaction(document, complexId)) { complex.setAbstractable(true); for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); if (partsVisited.contains(partId)) species.get(partId).setConvergent(true); else partsVisited.add(partId); if (complexMap.containsKey(partId)) { checkComplex(partId, partsVisited); } } } else unAbstractDown(complexId, ""); } } //Marks part as sequesterable after recursively checking that all upstream complexes are abstractable, have a binding stoichiometry of one, //are formed from two or more unique parts, and do not have potentially sequesterable parts on other downstream branches. //Otherwise unmarks all upstream complexes as abstractable. //Regardless unmarks all downstream complexes as abstractable. private boolean checkSequester(String partId, String sequesterRoot) { HashSet<SpeciesInterface> abstractableComplexes = new HashSet<SpeciesInterface>(); for (Influence infl : partsMap.get(partId)) { String complexId = infl.getOutput(); SpeciesInterface complex = species.get(complexId); if (complex.isAbstractable() && infl.getCoop() == 1 && complexMap.get(complexId).size() > 1 && checkSequesterComplex(complexId, partId) && (!partsMap.containsKey(complexId) || complex.isSequesterable() || checkSequester(complexId, sequesterRoot))) abstractableComplexes.add(complex); else { if (partId.equals(sequesterRoot)) { unAbstractUp(partId); if (complexMap.containsKey(partId)) unAbstractDown(partId, ""); } return false; } } if (partId.equals(sequesterRoot)) { species.get(partId).setSequesterable(true); if (complexMap.containsKey(partId)) unAbstractDown(partId, ""); } for (SpeciesInterface complex: abstractableComplexes) { complex.setSequesterable(false); complex.setSequesterAbstractable(true); } return true; } //Returns false if sequester complex has potentially sequesterable parts on downstream branches other than lastSequester. private boolean checkSequesterComplex(String complexId, String lastSequester) { for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); SpeciesInterface part = species.get(partId); if (!partId.equals(lastSequester)) { if (partsMap.get(partId).size() > 1 || part.isActivator() || part.isRepressor() || (complexMap.containsKey(partId) && !checkSequesterComplex(partId, ""))) return false; } } return true; } //Recursively unmarks complexes as abstractable on downstream branches other than payNoMind. public void unAbstractDown(String complexId, String payNoMind) { species.get(complexId).setAbstractable(false); for (Influence infl : complexMap.get(complexId)) { String partId = infl.getInput(); if (!partId.equals(payNoMind) && complexMap.containsKey(partId)) { unAbstractDown(partId, ""); } } } //Recursively unmarks all upstream complexes as abstractable. public void unAbstractUp(String partId) { for (Influence infl : partsMap.get(partId)) { String complexId = infl.getOutput(); unAbstractDown(complexId, partId); if (partsMap.containsKey(complexId)) unAbstractUp(complexId); } } //Unmarks complex species as abstractable (and their parts as sequesterable) if they are interesting public void unMarkInterestingSpecies(String[] interestingSpecies) { for (String interestingId : interestingSpecies) { if (species.containsKey(interestingId) && complexMap.containsKey(interestingId)) { species.get(interestingId).setAbstractable(false); species.get(interestingId).setSequesterAbstractable(false); for (Influence infl : complexMap.get(interestingId)) species.get(infl.getInput()).setSequesterable(false); } } } //Returns default interesting species, i.e. those that are outputs or genetically produced public ArrayList<String> getInterestingSpecies() { ArrayList<String> interestingSpecies = new ArrayList<String>(); for (String id : species.keySet()) { if (!complexMap.keySet().contains(id) || species.get(id).getType().equals(GlobalConstants.OUTPUT)) interestingSpecies.add(id); } return interestingSpecies; } public HashMap<String, SpeciesInterface> getSpecies() { return species; } public void setSpecies(HashMap<String, SpeciesInterface> species) { this.species = species; } public HashMap<String, Promoter> getPromoters() { return promoters; } public void setPromoters(HashMap<String, Promoter> promoters) { this.promoters = promoters; } public BioModel getProperties() { return properties; } public void setProperties(BioModel properties) { this.properties = properties; } public HashMap<String, ArrayList<Influence>> getComplexMap() { return complexMap; } private boolean isGenetic(String speciesId) { for (Promoter p : getPromoters().values()) if (p.getOutputs().toString().contains(speciesId)) return true; return false; } private String sbmlDocument = ""; private SBMLDocument document = null; private static SBMLDocument currentDocument = null; private static String currentRoot = ""; private boolean operatorAbstraction = false; private boolean complexAbstraction = false; private String[] interestingSpecies; private HashMap<String, SpeciesInterface> species = null; private HashMap<String, Promoter> promoters = null; private HashMap<String, ArrayList<Influence>> complexMap; private HashMap<String, ArrayList<Influence>> partsMap; private HashMap<String, Properties> compartments; private BioModel properties = null; // private String krnapString = GlobalConstants.RNAP_BINDING_STRING; private String kBasalString = GlobalConstants.KBASAL_STRING; private String kOcString = GlobalConstants.OCR_STRING; private String property; /** * Returns the curent SBML document being built * * @return the curent SBML document being built */ public static SBMLDocument getCurrentDocument() { return currentDocument; } /** * Sets the current root * @param root the root directory */ public static void setRoot(String root) { currentRoot = root; } public static String getUnitString(ArrayList<String> unitNames, ArrayList<Integer> exponents, ArrayList<Integer> multiplier, Model model) { // First build the name of the unit and see if it exists, start by // sorting the units to build a unique string for (int i = 0; i < unitNames.size(); i++) { for (int j = i; j > 0; j--) { if (unitNames.get(j - 1).compareTo(unitNames.get(i)) > 0) { Integer tempD = multiplier.get(j); Integer tempI = exponents.get(j); String tempS = unitNames.get(j); multiplier.set(j, multiplier.get(j - 1)); unitNames.set(j, unitNames.get(j - 1)); exponents.set(j, exponents.get(j - 1)); multiplier.set(j - 1, tempD); unitNames.set(j - 1, tempS); exponents.set(j - 1, tempI); } } } UnitDefinition t = new UnitDefinition(Gui.SBML_LEVEL, Gui.SBML_VERSION); String name = "u_"; for (int i = 0; i < unitNames.size(); i++) { String sign = ""; if (exponents.get(i).intValue() < 0) { sign = "n"; } name = name + multiplier.get(i) + "_" + unitNames.get(i) + "_" + sign + Math.abs(exponents.get(i)) + "_"; Unit u = t.createUnit(); u.setKind(libsbml.UnitKind_forName(unitNames.get(i))); u.setExponent(exponents.get(i).intValue()); u.setMultiplier(multiplier.get(i).intValue()); u.setScale(0); } name = name.substring(0, name.length() - 1); t.setId(name); if (model.getUnitDefinition(name) == null) { model.addUnitDefinition(t); } return name; } /** * Returns a unit name for a parameter based on the number of molecules * involved * * @param numMolecules * the number of molecules involved * @return a unit name */ public static String getMoleTimeParameter(int numMolecules) { ArrayList<String> unitS = new ArrayList<String>(); ArrayList<Integer> unitE = new ArrayList<Integer>(); ArrayList<Integer> unitM = new ArrayList<Integer>(); if (numMolecules > 1) { unitS.add("mole"); unitE.add(new Integer(-(numMolecules - 1))); unitM.add(new Integer(1)); } unitS.add("second"); unitE.add(new Integer(-1)); unitM.add(new Integer(1)); return GeneticNetwork.getUnitString(unitS, unitE, unitM, currentDocument.getModel()); } /** * Returns a unit name for a parameter based on the number of molecules * involved * * @param numMolecules * the number of molecules involved * @return a unit name */ public static String getMoleParameter(int numMolecules) { ArrayList<String> unitS = new ArrayList<String>(); ArrayList<Integer> unitE = new ArrayList<Integer>(); ArrayList<Integer> unitM = new ArrayList<Integer>(); unitS.add("mole"); unitE.add(new Integer(-(numMolecules - 1))); unitM.add(new Integer(1)); return GeneticNetwork.getUnitString(unitS, unitE, unitM, currentDocument.getModel()); } public static String getMoleParameter(String numMolecules) { return getMoleParameter(Integer.parseInt(numMolecules)); } }
Restore the setSubstanceUnits in ModelPanel.java
gui/src/biomodel/network/GeneticNetwork.java
Restore the setSubstanceUnits in ModelPanel.java
Java
apache-2.0
f33925a1c6972588f0c3a8bc3e1fb460c68c08dc
0
javamelody/javamelody,javamelody/javamelody,javamelody/javamelody
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Scanner; import java.util.regex.Pattern; /** * Liste et informations sur les process linux ou unix. * @author Emeric Vernat */ final class ProcessInformations implements Serializable { static final boolean WINDOWS = System.getProperty("os.name").toLowerCase(Locale.getDefault()) .contains("windows"); private static final long serialVersionUID = 2163916067335213382L; private static final Pattern WINDOWS_STATE_PATTERN = Pattern.compile("................"); private static final Pattern WINDOWS_CPU_TIME_PATTERN = Pattern.compile("[0-9:]*"); private final String user; private final int pid; // rapport Temps CPU / Temps utilisateur. // Il s'agit d'un rapport entre le temps d'exécution effectif et le temps depuis lequel le processus a été lancé private final float cpuPercentage; private final float memPercentage; // taille virtuelle de l'image du processus (code + données + pile). private final int vsz; // taille résidente de l'image du processus. Nombre de kilo-octets se trouvant en mémoire private final int rss; // numéro mineur de périphérique tty (terminal de contrôle) private final String tty; // état du processus. Le premier champ correspond à // R (runnable) prêt à  être exécuté, // S (sleeping) endormi, // D sommeil ininterruptible, // T (traced) arrêté ou suivi, // Z (zombie). // Le second champ contient W si le processus n'a pas de pages résidentes. // Le troisième champ contient N si le processus a une valeur de gentillesse positive (nice, champ NI). private final String stat; private final String start; private final String cpuTime; private final String command; private ProcessInformations(Scanner sc, boolean windows) { super(); if (windows) { final StringBuilder imageNameBuilder = new StringBuilder(sc.next()); while (!sc.hasNextInt()) { imageNameBuilder.append(' ').append(sc.next()); } pid = sc.nextInt(); if ("Console".equals(sc.next())) { // ce if est nécessaire si windows server 2003 mais sans connexion à distance ouverte // (comme tasklist.txt dans resources de test, // car parfois "Console" est présent mais parfois non) sc.next(); } final String memory = sc.next(); cpuPercentage = -1; memPercentage = -1; vsz = Integer.parseInt(memory.replace("ÿ", "")); rss = -1; tty = null; sc.next(); sc.skip(WINDOWS_STATE_PATTERN); stat = null; final StringBuilder userBuilder = new StringBuilder(sc.next()); while (!sc.hasNext(WINDOWS_CPU_TIME_PATTERN)) { userBuilder.append(' ').append(sc.next()); } this.user = userBuilder.toString(); start = null; cpuTime = sc.next(); command = imageNameBuilder.append(" (").append(sc.nextLine().trim()).append(')') .toString(); } else { user = sc.next(); pid = sc.nextInt(); cpuPercentage = sc.nextFloat(); memPercentage = sc.nextFloat(); vsz = sc.nextInt(); rss = sc.nextInt(); tty = sc.next(); stat = sc.next(); start = sc.next(); cpuTime = sc.next(); command = sc.nextLine(); } } static List<ProcessInformations> buildProcessInformations(InputStream in, boolean windows) { final String charset; if (windows) { charset = "Cp1252"; } else { charset = "UTF-8"; } final Scanner sc = new Scanner(in, charset); sc.useRadix(10); sc.useLocale(Locale.US); sc.nextLine(); if (windows) { sc.nextLine(); sc.nextLine(); } final List<ProcessInformations> processInfos = new ArrayList<ProcessInformations>(); while (sc.hasNext()) { final ProcessInformations processInfo = new ProcessInformations(sc, windows); processInfos.add(processInfo); } return Collections.unmodifiableList(processInfos); } static List<ProcessInformations> buildProcessInformations() throws IOException { Process process = null; try { if (WINDOWS) { process = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "tasklist /V" }); } else { // tous les systèmes (ou presque) non Windows sont une variante de linux ou unix // (http://mindprod.com/jgloss/properties.html) qui acceptent la commande ps process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "ps wauxf" }); } return buildProcessInformations(process.getInputStream(), WINDOWS); } finally { if (process != null) { // évitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165 process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } } } String getUser() { return user; } int getPid() { return pid; } float getCpuPercentage() { return cpuPercentage; } float getMemPercentage() { return memPercentage; } int getVsz() { return vsz; } int getRss() { return rss; } String getTty() { return tty; } String getStat() { return stat; } String getStart() { return start; } String getCpuTime() { return cpuTime; } String getCommand() { return command; } }
javamelody-core/src/main/java/net/bull/javamelody/ProcessInformations.java
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Scanner; import java.util.regex.Pattern; /** * Liste et informations sur les process linux ou unix. * @author Emeric Vernat */ final class ProcessInformations implements Serializable { static final boolean WINDOWS = System.getProperty("os.name").toLowerCase(Locale.getDefault()) .contains("windows"); private static final long serialVersionUID = 2163916067335213382L; private static final Pattern WINDOWS_STATE_PATTERN = Pattern.compile("................"); private static final Pattern WINDOWS_CPU_TIME_PATTERN = Pattern.compile("[0-9:]*"); private final String user; private final int pid; // rapport Temps CPU / Temps utilisateur. // Il s'agit d'un rapport entre le temps d'exécution effectif et le temps depuis lequel le processus a été lancé private final float cpuPercentage; private final float memPercentage; // taille virtuelle de l'image du processus (code + données + pile). private final int vsz; // taille résidente de l'image du processus. Nombre de kilo-octets se trouvant en mémoire private final int rss; // numéro mineur de périphérique tty (terminal de contrôle) private final String tty; // état du processus. Le premier champ correspond à // R (runnable) prêt à  être exécuté, // S (sleeping) endormi, // D sommeil ininterruptible, // T (traced) arrêté ou suivi, // Z (zombie). // Le second champ contient W si le processus n'a pas de pages résidentes. // Le troisième champ contient N si le processus a une valeur de gentillesse positive (nice, champ NI). private final String stat; private final String start; private final String cpuTime; private final String command; private ProcessInformations(Scanner sc, boolean windows) { super(); if (windows) { final StringBuilder imageNameBuilder = new StringBuilder(sc.next()); while (!sc.hasNextInt()) { imageNameBuilder.append(' ').append(sc.next()); } pid = sc.nextInt(); sc.next(); String memory = sc.next(); if (memory.length() == 0 || !Character.isDigit(memory.charAt(0))) { // ce if est nécessaire si windows server 2003 mais sans connexion à distance ouverte // (comme tasklist.txt dans resources de test, // car parfois "Console" est présent mais parfois non) memory = sc.next(); } cpuPercentage = -1; memPercentage = -1; vsz = Integer.parseInt(memory.replace("ÿ", "")); rss = -1; tty = null; sc.next(); sc.skip(WINDOWS_STATE_PATTERN); stat = null; final StringBuilder userBuilder = new StringBuilder(sc.next()); while (!sc.hasNext(WINDOWS_CPU_TIME_PATTERN)) { userBuilder.append(' ').append(sc.next()); } this.user = userBuilder.toString(); start = null; cpuTime = sc.next(); command = imageNameBuilder.append(" (").append(sc.nextLine().trim()).append(')') .toString(); } else { user = sc.next(); pid = sc.nextInt(); cpuPercentage = sc.nextFloat(); memPercentage = sc.nextFloat(); vsz = sc.nextInt(); rss = sc.nextInt(); tty = sc.next(); stat = sc.next(); start = sc.next(); cpuTime = sc.next(); command = sc.nextLine(); } } static List<ProcessInformations> buildProcessInformations(InputStream in, boolean windows) { final String charset; if (windows) { charset = "Cp1252"; } else { charset = "UTF-8"; } final Scanner sc = new Scanner(in, charset); sc.useRadix(10); sc.useLocale(Locale.US); sc.nextLine(); if (windows) { sc.nextLine(); sc.nextLine(); } final List<ProcessInformations> processInfos = new ArrayList<ProcessInformations>(); while (sc.hasNext()) { final ProcessInformations processInfo = new ProcessInformations(sc, windows); processInfos.add(processInfo); } return Collections.unmodifiableList(processInfos); } static List<ProcessInformations> buildProcessInformations() throws IOException { Process process = null; try { if (WINDOWS) { process = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "tasklist /V" }); } else { // tous les systèmes (ou presque) non Windows sont une variante de linux ou unix // (http://mindprod.com/jgloss/properties.html) qui acceptent la commande ps process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "ps wauxf" }); } return buildProcessInformations(process.getInputStream(), WINDOWS); } finally { if (process != null) { // évitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165 process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } } } String getUser() { return user; } int getPid() { return pid; } float getCpuPercentage() { return cpuPercentage; } float getMemPercentage() { return memPercentage; } int getVsz() { return vsz; } int getRss() { return rss; } String getTty() { return tty; } String getStat() { return stat; } String getStart() { return start; } String getCpuTime() { return cpuTime; } String getCommand() { return command; } }
correction valeur de "Taille mémoire virtuelle (vsz, Ko)" dans les processus si windows
javamelody-core/src/main/java/net/bull/javamelody/ProcessInformations.java
correction valeur de "Taille mémoire virtuelle (vsz, Ko)" dans les processus si windows
Java
apache-2.0
4525b92ba410ddb6af903f45038f6aaba75234d4
0
MediaMath/t1-java,MediaMath/t1-java
/******************************************************************************* * Copyright 2016 MediaMath * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.mediamath.terminalone.utils; import com.google.gson.reflect.TypeToken; import com.mediamath.terminalone.models.AdServer; import com.mediamath.terminalone.models.Advertiser; import com.mediamath.terminalone.models.Agency; import com.mediamath.terminalone.models.AtomicCreative; import com.mediamath.terminalone.models.AudienceSegment; import com.mediamath.terminalone.models.Campaign; import com.mediamath.terminalone.models.ChildPixel; import com.mediamath.terminalone.models.Concept; import com.mediamath.terminalone.models.Contact; import com.mediamath.terminalone.models.Creative; import com.mediamath.terminalone.models.CreativeApproval; import com.mediamath.terminalone.models.Deal; import com.mediamath.terminalone.models.JsonResponse; import com.mediamath.terminalone.models.Organization; import com.mediamath.terminalone.models.Pixel; import com.mediamath.terminalone.models.PixelProvider; import com.mediamath.terminalone.models.PlacementSlot; import com.mediamath.terminalone.models.Publisher; import com.mediamath.terminalone.models.PublisherSite; import com.mediamath.terminalone.models.SiteList; import com.mediamath.terminalone.models.SitePlacement; import com.mediamath.terminalone.models.Strategy; import com.mediamath.terminalone.models.StrategyAudienceSegment; import com.mediamath.terminalone.models.StrategyConcept; import com.mediamath.terminalone.models.StrategyDayPart; import com.mediamath.terminalone.models.StrategyDomain; import com.mediamath.terminalone.models.StrategySupplySource; import com.mediamath.terminalone.models.SupplySource; import com.mediamath.terminalone.models.TargetDimension; import com.mediamath.terminalone.models.TargetValues; import com.mediamath.terminalone.models.User; import com.mediamath.terminalone.models.Vendor; import com.mediamath.terminalone.models.VendorContract; import com.mediamath.terminalone.models.VendorDomain; import com.mediamath.terminalone.models.VendorPixel; import com.mediamath.terminalone.models.VendorPixelDomain; import com.mediamath.terminalone.models.Vertical; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; public final class Constants { private static final String CREATIVE_APPROVAL = "creative_approval"; private static final String STRATEGY_AUDIENCE_SEGMENT = "strategy_audience_segment"; private static final String STRATEGY_AUDIENCE_SEGMENTS = "strategy_audience_segments"; private static final String SITE_PLACEMENT = "site_placement"; private static final String SITE_LIST = "site_list"; private static final String PLACEMENT_SLOT = "placement_slot"; private static final String PIXEL_PROVIDER = "pixel_provider"; private static final String DEAL = "deal"; private static final String AD_SERVER = "ad_server"; private static final String AUDIENCE_SEGMENT = "audience_segment"; private static final String VERTICAL = "vertical"; private static final String VERTICALS = "verticals"; private static final String VENDOR_PIXEL_DOMAIN = "vendor_pixel_domain"; private static final String VENDOR_PIXEL = "vendor_pixel"; private static final String VENDOR_DOMAIN = "vendor_domain"; private static final String VENDOR_CONTRACT = "vendor_contract"; private static final String VENDOR = "vendor"; private static final String VENDOR_PIXEL_DOMAINS = "vendor_pixel_domains"; private static final String VENDOR_PIXELS = "vendor_pixels"; private static final String VENDOR_DOMAINS = "vendor_domains"; private static final String VENDOR_CONTRACTS = "vendor_contracts"; private static final String VENDORS = "vendors"; private static final String TRAFFIC_CONTACT = "traffic_contact"; private static final String BILLING_CONTACT = "billing_contact"; private static final String SALES_CONTACT = "sales_contact"; private static final String TARGET_VALUE = "target_value"; private static final String TARGET_DIMENSION = "target_dimension"; private static final String TARGET_VALUES = "target_values"; private static final String TARGET_DIMENSIONS = "target_dimensions"; private static final String USER = "user"; private static final String USERS = "users"; private static final String SUPPLY_SOURCE = "supply_source"; private static final String STRATEGY_SUPPLY_SOURCE = "strategy_supply_source"; private static final String STRATEGY_DOMAIN_RESTRICTION = "strategy_domain_restriction"; private static final String STRATEGY_DAY_PART = "strategy_day_part"; private static final String STRATEGY_CONCEPT = "strategy_concept"; private static final String SUPPLY_SOURCES = "supply_sources"; private static final String STRATEGY_SUPPLY_SOURCES = "strategy_supply_sources"; private static final String STRATEGY_DOMAIN_RESTRICTIONS = "strategy_domain_restrictions"; private static final String STRATEGY_DAY_PARTS = "strategy_day_parts"; private static final String STRATEGY_CONCEPTS = "strategy_concepts"; private static final String STRATEGY = "strategy"; private static final String STRATEGIES = "strategies"; private static final String SITE_PLACEMENTS = "site_placements"; private static final String SITE_LISTS = "site_lists"; private static final String PUBLISHER_SITE = "publisher_site"; private static final String PUBLISHER_SITES = "publisher_sites"; private static final String PUBLISHER = "publisher"; private static final String PUBLISHERS = "publishers"; private static final String PLACEMENT_SLOTS = "placement_slots"; private static final String PIXEL_PROVIDERS = "pixel_providers"; private static final String PIXEL_BUNDLES = "pixel_bundles"; private static final String PIXEL_BUNDLE = "pixel_bundle"; private static final String PIXEL = "pixel"; private static final String PIXELS = "pixels"; private static final String ORGANIZATION = "organization"; private static final String ORGANIZATIONS = "organizations"; private static final String DEALS = "deals"; private static final String CREATIVE_APPROVALS = "creative_approvals"; private static final String CREATIVE = "creative"; private static final String CONCEPT = "concept"; private static final String CREATIVES = "creatives"; private static final String CONCEPTS = "concepts"; private static final String CAMPAIGN = "campaign"; private static final String CAMPAIGNS = "campaigns"; private static final String AUDIENCE_SEGMENTS = "audience_segments"; private static final String ATOMIC_CREATIVE = "atomic_creative"; private static final String ATOMIC_CREATIVES = "atomic_creatives"; private static final String AGENCY = "agency"; private static final String AGENCIES = "agencies"; private static final String ADVERTISER = "advertiser"; private static final String ADVERTISERS = "advertisers"; private static final String AD_SERVERS = "ad_servers"; // required for converting requested string path names to entity names when // collection demended public static HashMap<String, String> pathToCollectionEntity = new HashMap<String, String>(); // Required for converting entity names to path names [to form paths.] public static HashMap<String, String> entityPaths = new HashMap<String, String>(); // Required for Identifying entity based on requiested path/entity string public static HashMap<String, String> pathToEntity = new HashMap<String, String>(); public static HashMap<String, Integer> childPathSub = new HashMap<String, Integer>(); public static HashMap<String, HashMap<String, Integer>> childPaths = new HashMap<String, HashMap<String, Integer>>(); // TODO: clean up // get the type of entity.. required for parsing. public static HashMap<String, Type> getEntityType = new HashMap<String, Type>(); // TODO: clean up // get the type of list of entity.. required for parsing. public static HashMap<String, Type> getListoFEntityType = new HashMap<String, Type>(); static { getEntityType.put(AD_SERVERS, new TypeToken<JsonResponse<AdServer>>() { }.getType()); getEntityType.put(ADVERTISERS, new TypeToken<JsonResponse<Advertiser>>() { }.getType()); getEntityType.put(ADVERTISER, new TypeToken<JsonResponse<Advertiser>>() { }.getType()); getEntityType.put(AGENCIES, new TypeToken<JsonResponse<Agency>>() { }.getType()); getEntityType.put(AGENCY, new TypeToken<JsonResponse<Agency>>() { }.getType()); getEntityType.put(ATOMIC_CREATIVES, new TypeToken<JsonResponse<AtomicCreative>>() { }.getType()); getEntityType.put(ATOMIC_CREATIVE, new TypeToken<JsonResponse<AtomicCreative>>() { }.getType()); getEntityType.put(AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<AudienceSegment>>() { }.getType()); getEntityType.put(CAMPAIGNS, new TypeToken<JsonResponse<Campaign>>() { }.getType()); getEntityType.put(CAMPAIGN, new TypeToken<JsonResponse<Campaign>>() { }.getType()); getEntityType.put(CONCEPTS, new TypeToken<JsonResponse<Concept>>() { }.getType()); getEntityType.put(CONCEPT, new TypeToken<JsonResponse<Concept>>() { }.getType()); getEntityType.put(CREATIVES, new TypeToken<JsonResponse<Creative>>() { }.getType()); getEntityType.put(CREATIVE, new TypeToken<JsonResponse<Creative>>() { }.getType()); getEntityType.put(CREATIVE_APPROVALS, new TypeToken<JsonResponse<CreativeApproval>>() { }.getType()); getEntityType.put(DEALS, new TypeToken<JsonResponse<Deal>>() { }.getType()); getEntityType.put(ORGANIZATIONS, new TypeToken<JsonResponse<Organization>>() { }.getType()); getEntityType.put(ORGANIZATION, new TypeToken<JsonResponse<Organization>>() { }.getType()); getEntityType.put(PIXELS, new TypeToken<JsonResponse<ChildPixel>>() { }.getType()); getEntityType.put(PIXEL, new TypeToken<JsonResponse<ChildPixel>>() { }.getType()); getEntityType.put(PIXEL_BUNDLE, new TypeToken<JsonResponse<Pixel>>() { }.getType()); getEntityType.put(PIXEL_BUNDLES, new TypeToken<JsonResponse<Pixel>>() { }.getType()); getEntityType.put(PIXEL_PROVIDERS, new TypeToken<JsonResponse<PixelProvider>>() { }.getType()); getEntityType.put(PLACEMENT_SLOTS, new TypeToken<JsonResponse<PlacementSlot>>() { }.getType()); getEntityType.put(PUBLISHERS, new TypeToken<JsonResponse<Publisher>>() { }.getType()); getEntityType.put(PUBLISHER, new TypeToken<JsonResponse<Publisher>>() { }.getType()); getEntityType.put(PUBLISHER_SITES, new TypeToken<JsonResponse<PublisherSite>>() { }.getType()); getEntityType.put(PUBLISHER_SITE, new TypeToken<JsonResponse<PublisherSite>>() { }.getType()); getEntityType.put(SITE_LISTS, new TypeToken<JsonResponse<SiteList>>() { }.getType()); getEntityType.put(SITE_PLACEMENTS, new TypeToken<JsonResponse<SitePlacement>>() { }.getType()); getEntityType.put(STRATEGIES, new TypeToken<JsonResponse<Strategy>>() { }.getType()); getEntityType.put(STRATEGY, new TypeToken<JsonResponse<Strategy>>() { }.getType()); getEntityType.put(STRATEGY_CONCEPTS, new TypeToken<JsonResponse<StrategyConcept>>() { }.getType()); getEntityType.put(STRATEGY_CONCEPT, new TypeToken<JsonResponse<StrategyConcept>>() { }.getType()); getEntityType.put(STRATEGY_DAY_PARTS, new TypeToken<JsonResponse<StrategyDayPart>>() { }.getType()); getEntityType.put(STRATEGY_DAY_PART, new TypeToken<JsonResponse<StrategyDayPart>>() { }.getType()); getEntityType.put(STRATEGY_DOMAIN_RESTRICTIONS, new TypeToken<JsonResponse<StrategyDomain>>() { }.getType()); getEntityType.put(STRATEGY_DOMAIN_RESTRICTION, new TypeToken<JsonResponse<StrategyDomain>>() { }.getType()); getEntityType.put(STRATEGY_SUPPLY_SOURCES, new TypeToken<JsonResponse<StrategySupplySource>>() { }.getType()); getEntityType.put(STRATEGY_SUPPLY_SOURCE, new TypeToken<JsonResponse<StrategySupplySource>>() { }.getType()); getEntityType.put(SUPPLY_SOURCES, new TypeToken<JsonResponse<SupplySource>>() { }.getType()); getEntityType.put(SUPPLY_SOURCE, new TypeToken<JsonResponse<SupplySource>>() { }.getType()); getEntityType.put(USERS, new TypeToken<JsonResponse<User>>() { }.getType()); getEntityType.put(USER, new TypeToken<JsonResponse<User>>() { }.getType()); getEntityType.put(TARGET_DIMENSIONS, new TypeToken<JsonResponse<TargetDimension>>() { }.getType()); getEntityType.put(TARGET_DIMENSION, new TypeToken<JsonResponse<TargetDimension>>() { }.getType()); getEntityType.put(TARGET_VALUES, new TypeToken<JsonResponse<TargetValues>>() { }.getType()); getEntityType.put(TARGET_VALUE, new TypeToken<JsonResponse<TargetValues>>() { }.getType()); getEntityType.put(SALES_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(BILLING_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(TRAFFIC_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(VENDORS, new TypeToken<JsonResponse<Vendor>>() { }.getType()); getEntityType.put(VENDOR, new TypeToken<JsonResponse<Vendor>>() { }.getType()); getEntityType.put(VENDOR_CONTRACTS, new TypeToken<JsonResponse<VendorContract>>() { }.getType()); getEntityType.put(VENDOR_CONTRACT, new TypeToken<JsonResponse<VendorContract>>() { }.getType()); getEntityType.put(VENDOR_DOMAINS, new TypeToken<JsonResponse<VendorDomain>>() { }.getType()); getEntityType.put(VENDOR_DOMAIN, new TypeToken<JsonResponse<VendorDomain>>() { }.getType()); getEntityType.put(VENDOR_PIXELS, new TypeToken<JsonResponse<VendorPixel>>() { }.getType()); getEntityType.put(VENDOR_PIXEL, new TypeToken<JsonResponse<VendorPixel>>() { }.getType()); getEntityType.put(VENDOR_PIXEL_DOMAINS, new TypeToken<JsonResponse<VendorPixelDomain>>() { }.getType()); getEntityType.put(VENDOR_PIXEL_DOMAIN, new TypeToken<JsonResponse<VendorPixelDomain>>() { }.getType()); getEntityType.put(VERTICALS, new TypeToken<JsonResponse<Vertical>>() { }.getType()); getEntityType.put(VERTICAL, new TypeToken<JsonResponse<Vertical>>() { }.getType()); /* LIST RETURN TYPE */ getListoFEntityType.put(AD_SERVERS, new TypeToken<JsonResponse<ArrayList<AdServer>>>() { }.getType()); getListoFEntityType.put(AD_SERVER, new TypeToken<JsonResponse<ArrayList<AdServer>>>() { }.getType()); getListoFEntityType.put(ADVERTISERS, new TypeToken<JsonResponse<ArrayList<Advertiser>>>() { }.getType()); getListoFEntityType.put(ADVERTISER, new TypeToken<JsonResponse<ArrayList<Advertiser>>>() { }.getType()); getListoFEntityType.put(AGENCIES, new TypeToken<JsonResponse<ArrayList<Agency>>>() { }.getType()); getListoFEntityType.put(AGENCY, new TypeToken<JsonResponse<ArrayList<Agency>>>() { }.getType()); getListoFEntityType.put(ATOMIC_CREATIVES, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(ATOMIC_CREATIVE, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENT, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(CAMPAIGNS, new TypeToken<JsonResponse<ArrayList<Campaign>>>() { }.getType()); getListoFEntityType.put(CAMPAIGN, new TypeToken<JsonResponse<ArrayList<Campaign>>>() { }.getType()); getListoFEntityType.put(CONCEPTS, new TypeToken<JsonResponse<ArrayList<Concept>>>() { }.getType()); getListoFEntityType.put(CONCEPT, new TypeToken<JsonResponse<ArrayList<Concept>>>() { }.getType()); getListoFEntityType.put(CREATIVES, new TypeToken<JsonResponse<ArrayList<Creative>>>() { }.getType()); getListoFEntityType.put(CREATIVE, new TypeToken<JsonResponse<ArrayList<Creative>>>() { }.getType()); getListoFEntityType.put(CREATIVE_APPROVALS, new TypeToken<JsonResponse<ArrayList<CreativeApproval>>>() { }.getType()); getListoFEntityType.put(CREATIVE_APPROVAL, new TypeToken<JsonResponse<ArrayList<CreativeApproval>>>() { }.getType()); getListoFEntityType.put(DEALS, new TypeToken<JsonResponse<ArrayList<Deal>>>() { }.getType()); getListoFEntityType.put(DEAL, new TypeToken<JsonResponse<ArrayList<Deal>>>() { }.getType()); getListoFEntityType.put(ORGANIZATIONS, new TypeToken<JsonResponse<ArrayList<Organization>>>() { }.getType()); getListoFEntityType.put(ORGANIZATION, new TypeToken<JsonResponse<ArrayList<Organization>>>() { }.getType()); getListoFEntityType.put(PIXELS, new TypeToken<JsonResponse<ArrayList<ChildPixel>>>() { }.getType()); getListoFEntityType.put(PIXEL, new TypeToken<JsonResponse<ArrayList<ChildPixel>>>() { }.getType()); getListoFEntityType.put(PIXEL_BUNDLES, new TypeToken<JsonResponse<ArrayList<Pixel>>>() { }.getType()); getListoFEntityType.put(PIXEL_BUNDLE, new TypeToken<JsonResponse<ArrayList<Pixel>>>() { }.getType()); getListoFEntityType.put(PIXEL_PROVIDERS, new TypeToken<JsonResponse<ArrayList<PixelProvider>>>() { }.getType()); getListoFEntityType.put(PIXEL_PROVIDER, new TypeToken<JsonResponse<ArrayList<PixelProvider>>>() { }.getType()); getListoFEntityType.put(PLACEMENT_SLOTS, new TypeToken<JsonResponse<ArrayList<PlacementSlot>>>() { }.getType()); getListoFEntityType.put(PLACEMENT_SLOT, new TypeToken<JsonResponse<ArrayList<PlacementSlot>>>() { }.getType()); getListoFEntityType.put(PUBLISHERS, new TypeToken<JsonResponse<ArrayList<Publisher>>>() { }.getType()); getListoFEntityType.put(PUBLISHER, new TypeToken<JsonResponse<ArrayList<Publisher>>>() { }.getType()); getListoFEntityType.put(PUBLISHER_SITES, new TypeToken<JsonResponse<ArrayList<PublisherSite>>>() { }.getType()); getListoFEntityType.put(PUBLISHER_SITE, new TypeToken<JsonResponse<ArrayList<PublisherSite>>>() { }.getType()); getListoFEntityType.put(SITE_LISTS, new TypeToken<JsonResponse<ArrayList<SiteList>>>() { }.getType()); getListoFEntityType.put(SITE_LIST, new TypeToken<JsonResponse<ArrayList<SiteList>>>() { }.getType()); getListoFEntityType.put(SITE_PLACEMENTS, new TypeToken<JsonResponse<ArrayList<SitePlacement>>>() { }.getType()); getListoFEntityType.put(SITE_PLACEMENT, new TypeToken<JsonResponse<ArrayList<SitePlacement>>>() { }.getType()); getListoFEntityType.put(STRATEGIES, new TypeToken<JsonResponse<ArrayList<Strategy>>>() { }.getType()); getListoFEntityType.put(STRATEGY, new TypeToken<JsonResponse<ArrayList<Strategy>>>() { }.getType()); getListoFEntityType.put(STRATEGY_CONCEPT, new TypeToken<JsonResponse<ArrayList<StrategyConcept>>>() { }.getType()); getListoFEntityType.put(STRATEGY_CONCEPTS, new TypeToken<JsonResponse<ArrayList<StrategyConcept>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DAY_PARTS, new TypeToken<JsonResponse<ArrayList<StrategyDayPart>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DAY_PART, new TypeToken<JsonResponse<ArrayList<StrategyDayPart>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DOMAIN_RESTRICTION, new TypeToken<JsonResponse<ArrayList<StrategyDomain>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DOMAIN_RESTRICTIONS, new TypeToken<JsonResponse<ArrayList<StrategyDomain>>>() { }.getType()); getListoFEntityType.put(STRATEGY_SUPPLY_SOURCES, new TypeToken<JsonResponse<ArrayList<StrategySupplySource>>>() { }.getType()); getListoFEntityType.put(STRATEGY_SUPPLY_SOURCE, new TypeToken<JsonResponse<ArrayList<StrategySupplySource>>>() { }.getType()); getListoFEntityType.put(SUPPLY_SOURCES, new TypeToken<JsonResponse<ArrayList<SupplySource>>>() { }.getType()); getListoFEntityType.put(SUPPLY_SOURCE, new TypeToken<JsonResponse<ArrayList<SupplySource>>>() { }.getType()); getListoFEntityType.put(STRATEGY_AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<ArrayList<StrategyAudienceSegment>>>() { }.getType()); getListoFEntityType.put(STRATEGY_AUDIENCE_SEGMENT, new TypeToken<JsonResponse<ArrayList<StrategyAudienceSegment>>>() { }.getType()); getListoFEntityType.put(USERS, new TypeToken<JsonResponse<ArrayList<User>>>() { }.getType()); getListoFEntityType.put(USER, new TypeToken<JsonResponse<ArrayList<User>>>() { }.getType()); getListoFEntityType.put(TARGET_DIMENSIONS, new TypeToken<JsonResponse<ArrayList<TargetDimension>>>() { }.getType()); getListoFEntityType.put(TARGET_DIMENSION, new TypeToken<JsonResponse<ArrayList<TargetDimension>>>() { }.getType()); getListoFEntityType.put(TARGET_VALUES, new TypeToken<JsonResponse<ArrayList<TargetValues>>>() { }.getType()); getListoFEntityType.put(TARGET_VALUE, new TypeToken<JsonResponse<ArrayList<TargetValues>>>() { }.getType()); getListoFEntityType.put(VENDORS, new TypeToken<JsonResponse<ArrayList<Vendor>>>() { }.getType()); getListoFEntityType.put(VENDOR, new TypeToken<JsonResponse<ArrayList<Vendor>>>() { }.getType()); getListoFEntityType.put(VENDOR_CONTRACTS, new TypeToken<JsonResponse<ArrayList<VendorContract>>>() { }.getType()); getListoFEntityType.put(VENDOR_CONTRACT, new TypeToken<JsonResponse<ArrayList<VendorContract>>>() { }.getType()); getListoFEntityType.put(VENDOR_DOMAINS, new TypeToken<JsonResponse<ArrayList<VendorDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_DOMAIN, new TypeToken<JsonResponse<ArrayList<VendorDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXELS, new TypeToken<JsonResponse<ArrayList<VendorPixel>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL, new TypeToken<JsonResponse<ArrayList<VendorPixel>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL_DOMAINS, new TypeToken<JsonResponse<ArrayList<VendorPixelDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL_DOMAIN, new TypeToken<JsonResponse<ArrayList<VendorPixelDomain>>>() { }.getType()); getListoFEntityType.put(VERTICALS, new TypeToken<JsonResponse<ArrayList<Vertical>>>() { }.getType()); getListoFEntityType.put(VERTICAL, new TypeToken<JsonResponse<ArrayList<Vertical>>>() { }.getType()); // required for converting requested string path names to entity names // when collection demended pathToCollectionEntity.put(AD_SERVERS, "AdServer"); pathToCollectionEntity.put(ADVERTISERS, "Advertiser"); pathToCollectionEntity.put(AGENCIES, "Agency"); pathToCollectionEntity.put(ATOMIC_CREATIVES, "AtomicCreative"); pathToCollectionEntity.put(AUDIENCE_SEGMENTS, "AudienceSegment"); pathToCollectionEntity.put(CAMPAIGNS, "Campaign"); pathToCollectionEntity.put(CONCEPTS, "Concept"); pathToCollectionEntity.put(CREATIVES, "Creative"); pathToCollectionEntity.put(CREATIVE_APPROVALS, "CreativeApproval"); pathToCollectionEntity.put(DEALS, "Deal"); pathToCollectionEntity.put(ORGANIZATIONS, "Organization"); pathToCollectionEntity.put(PIXELS, "ChildPixel"); pathToCollectionEntity.put(PIXEL_BUNDLES, "PixelBundle"); pathToCollectionEntity.put(PIXEL_PROVIDERS, "PixelProvider"); pathToCollectionEntity.put(PLACEMENT_SLOTS, "PlacementSlot"); pathToCollectionEntity.put(PUBLISHERS, "Publisher"); pathToCollectionEntity.put(PUBLISHER_SITES, "PublisherSite"); pathToCollectionEntity.put(SITE_LISTS, "SiteList"); pathToCollectionEntity.put(SITE_PLACEMENTS, "SitePlacement"); pathToCollectionEntity.put(STRATEGIES, "Strategy"); pathToCollectionEntity.put(STRATEGY_CONCEPTS, "StrategyConcept"); pathToCollectionEntity.put(STRATEGY_DAY_PARTS, "StrategyDayPart"); pathToCollectionEntity.put(STRATEGY_DOMAIN_RESTRICTIONS, "StrategyDomain"); pathToCollectionEntity.put(STRATEGY_SUPPLY_SOURCES, "StrategySupplySource"); pathToCollectionEntity.put(SUPPLY_SOURCES, "SupplySource"); pathToCollectionEntity.put(USERS, "User"); pathToCollectionEntity.put(TARGET_DIMENSIONS, "TargetDimension"); pathToCollectionEntity.put(TARGET_VALUES, "TargetValue"); pathToCollectionEntity.put("permissions", "Permission"); pathToCollectionEntity.put("reports", "Report"); pathToCollectionEntity.put(VENDORS, "Vendor"); pathToCollectionEntity.put(VENDOR_CONTRACTS, "VendorContract"); pathToCollectionEntity.put(VENDOR_DOMAINS, "VendorDomain"); pathToCollectionEntity.put(VENDOR_PIXELS, "VendorPixel"); pathToCollectionEntity.put(VENDOR_PIXEL_DOMAINS, "VendorPixelDomain"); pathToCollectionEntity.put(VERTICALS, "Vertical"); // Required for converting entity names to path names [to form paths.] entityPaths.put("AdServer", AD_SERVERS); entityPaths.put("Advertiser", ADVERTISERS); entityPaths.put("Agency", AGENCIES); entityPaths.put("AtomicCreative", ATOMIC_CREATIVES); entityPaths.put("AudienceSegment", AUDIENCE_SEGMENTS); entityPaths.put("Campaign", CAMPAIGNS); entityPaths.put("Concept", CONCEPTS); entityPaths.put("Creative", CREATIVES); entityPaths.put("CreativeApproval", ATOMIC_CREATIVES); entityPaths.put("Deal", DEALS); entityPaths.put("Organization", ORGANIZATIONS); entityPaths.put("ChildPixel", PIXELS); entityPaths.put("PixelBundle", PIXEL_BUNDLES); entityPaths.put("PixelProvider", PIXEL_PROVIDERS); entityPaths.put("PlacementSlot", PLACEMENT_SLOTS); entityPaths.put("Publisher", PUBLISHERS); entityPaths.put("PublisherSite", PUBLISHER_SITES); entityPaths.put("SiteList", SITE_LISTS); entityPaths.put("SitePlacement", SITE_PLACEMENTS); entityPaths.put("Strategy", STRATEGIES); entityPaths.put("StrategyConcept", STRATEGY_CONCEPTS); entityPaths.put("StrategyDayPart", STRATEGY_DAY_PARTS); entityPaths.put("StrategyDomain", STRATEGY_DOMAIN_RESTRICTIONS); entityPaths.put("StrategySupplySource", STRATEGY_SUPPLY_SOURCES); entityPaths.put("SupplySource", SUPPLY_SOURCES); entityPaths.put("User", USERS); entityPaths.put("TargetDimension", TARGET_DIMENSIONS); entityPaths.put("TargetValue", TARGET_VALUES); entityPaths.put("Permission", "permissions"); entityPaths.put("Report", "reports"); entityPaths.put("Vendor", VENDORS); entityPaths.put("VendorContract", VENDOR_CONTRACTS); entityPaths.put("VendorDomain", VENDOR_DOMAINS); entityPaths.put("VendorPixel", VENDOR_PIXELS); entityPaths.put("VendorPixelDomain", VENDOR_PIXEL_DOMAINS); entityPaths.put("Vertical", VERTICALS); // Required for Identifying entity based on requested path/entity string pathToEntity.put(AD_SERVER, "AdServer"); pathToEntity.put(ADVERTISER, "Advertiser"); pathToEntity.put(AGENCY, "Agency"); pathToEntity.put(ATOMIC_CREATIVE, "AtomicCreative"); pathToEntity.put(AUDIENCE_SEGMENT, "AudienceSegment"); pathToEntity.put(CAMPAIGN, "Campaign"); pathToEntity.put(CONCEPT, "Concept"); pathToEntity.put(CREATIVE, "Creative"); pathToEntity.put(CREATIVE_APPROVAL, "CreativeApproval"); pathToEntity.put(DEAL, "Deal"); pathToEntity.put(ORGANIZATION, "Organization"); pathToEntity.put(PIXEL, "ChildPixel"); pathToEntity.put(PIXEL_BUNDLE, "PixelBundle"); pathToEntity.put(PIXEL_PROVIDER, "PixelProvider"); pathToEntity.put(PLACEMENT_SLOT, "PlacementSlot"); pathToEntity.put(PUBLISHER, "Publisher"); pathToEntity.put(PUBLISHER_SITE, "PublisherSite"); pathToEntity.put(SITE_LIST, "SiteList"); pathToEntity.put(SITE_PLACEMENT, "SitePlacement"); pathToEntity.put(STRATEGY, "Strategy"); pathToEntity.put(STRATEGY_CONCEPT, "StrategyConcept"); pathToEntity.put(STRATEGY_DAY_PART, "StrategyDayPart"); pathToEntity.put(STRATEGY_DOMAIN_RESTRICTION, "StrategyDomain"); pathToEntity.put(STRATEGY_SUPPLY_SOURCE, "StrategySupplySource"); pathToEntity.put(SUPPLY_SOURCE, "SupplySource"); pathToEntity.put(USER, "User"); pathToEntity.put(TARGET_DIMENSION, "TargetDimension"); pathToEntity.put(TARGET_VALUE, "TargetValue"); pathToEntity.put("permission", "Permission"); pathToEntity.put("report", "Report"); pathToEntity.put(VENDOR, "Vendor"); pathToEntity.put(VENDOR_CONTRACT, "VendorContract"); pathToEntity.put(VENDOR_DOMAIN, "VendorDomain"); pathToEntity.put(VENDOR_PIXEL, "VendorPixel"); pathToEntity.put(VENDOR_PIXEL_DOMAIN, "VendorPixelDomain"); pathToEntity.put(VERTICAL, "Vertical"); // CHILD PATHS HashMap<String, Integer> subMap1 = new HashMap<String, Integer>(); subMap1.put("acl", 0); childPaths.put("acl", (new HashMap<String, Integer>())); HashMap<String, Integer> subMap2 = new HashMap<String, Integer>(); subMap2.put(TARGET_DIMENSIONS, 22); childPaths.put("audio", subMap2); HashMap<String, Integer> subMap3 = new HashMap<String, Integer>(); subMap3.put(TARGET_DIMENSIONS, 4); childPaths.put("browser", subMap3); HashMap<String, Integer> subMap4 = new HashMap<String, Integer>(); subMap4.put(TARGET_DIMENSIONS, 16); childPaths.put("channels", subMap4); HashMap<String, Integer> subMap5 = new HashMap<String, Integer>(); subMap5.put(CONCEPTS, 0); childPaths.put(CONCEPTS, subMap5); HashMap<String, Integer> subMap6 = new HashMap<String, Integer>(); subMap6.put(TARGET_DIMENSIONS, 2); childPaths.put("connection speed", subMap6); HashMap<String, Integer> subMap7 = new HashMap<String, Integer>(); subMap7.put(TARGET_DIMENSIONS, 21); childPaths.put("content initiation", subMap7); HashMap<String, Integer> subMap8 = new HashMap<String, Integer>(); subMap8.put(TARGET_DIMENSIONS, 14); childPaths.put("country", subMap8); HashMap<String, Integer> subMap9 = new HashMap<String, Integer>(); subMap9.put("day_parts", 0); childPaths.put("day_parts", subMap9); HashMap<String, Integer> subMap10 = new HashMap<String, Integer>(); subMap10.put(TARGET_DIMENSIONS, 24); childPaths.put("device", subMap10); HashMap<String, Integer> subMap11 = new HashMap<String, Integer>(); subMap11.put(TARGET_DIMENSIONS, 1); childPaths.put("dma", subMap11); HashMap<String, Integer> subMap12 = new HashMap<String, Integer>(); subMap12.put(TARGET_DIMENSIONS, 19); childPaths.put("fold position", subMap12); HashMap<String, Integer> subMap13 = new HashMap<String, Integer>(); subMap13.put(TARGET_DIMENSIONS, 3); childPaths.put("isp", subMap13); HashMap<String, Integer> subMap14 = new HashMap<String, Integer>(); subMap14.put(TARGET_DIMENSIONS, 20); childPaths.put("linear format", subMap14); HashMap<String, Integer> subMap15 = new HashMap<String, Integer>(); subMap15.put(TARGET_DIMENSIONS, 8); childPaths.put("mathselect250", subMap15); HashMap<String, Integer> subMap16 = new HashMap<String, Integer>(); subMap16.put(TARGET_DIMENSIONS, 5); childPaths.put("os", subMap16); HashMap<String, Integer> subMap17 = new HashMap<String, Integer>(); subMap17.put("permissions", 0); childPaths.put("permission", subMap17); HashMap<String, Integer> subMap18 = new HashMap<String, Integer>(); subMap18.put("permissions", 0); childPaths.put("permissions", subMap18); HashMap<String, Integer> subMap19 = new HashMap<String, Integer>(); subMap19.put(TARGET_DIMENSIONS, 23); childPaths.put("player size", subMap19); HashMap<String, Integer> subMap20 = new HashMap<String, Integer>(); subMap20.put(TARGET_DIMENSIONS, 7); childPaths.put("region", subMap20); HashMap<String, Integer> subMap21 = new HashMap<String, Integer>(); subMap21.put(TARGET_DIMENSIONS, 15); childPaths.put("safety", subMap21); HashMap<String, Integer> subMap22 = new HashMap<String, Integer>(); subMap22.put("supplies", 0); childPaths.put("supplies", subMap22); HashMap<String, Integer> subMap23 = new HashMap<String, Integer>(); subMap23.put("targeting_segments", 0); childPaths.put("targeting_segments", subMap23); HashMap<String, Integer> subMap24 = new HashMap<String, Integer>(); subMap24.put(AUDIENCE_SEGMENTS, 0); childPaths.put(AUDIENCE_SEGMENTS, subMap24); } }
src/main/java/com/mediamath/terminalone/utils/Constants.java
/******************************************************************************* * Copyright 2016 MediaMath * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.mediamath.terminalone.utils; import com.google.gson.reflect.TypeToken; import com.mediamath.terminalone.models.AdServer; import com.mediamath.terminalone.models.Advertiser; import com.mediamath.terminalone.models.Agency; import com.mediamath.terminalone.models.AtomicCreative; import com.mediamath.terminalone.models.AudienceSegment; import com.mediamath.terminalone.models.Campaign; import com.mediamath.terminalone.models.ChildPixel; import com.mediamath.terminalone.models.Concept; import com.mediamath.terminalone.models.Contact; import com.mediamath.terminalone.models.Creative; import com.mediamath.terminalone.models.CreativeApproval; import com.mediamath.terminalone.models.Deal; import com.mediamath.terminalone.models.JsonResponse; import com.mediamath.terminalone.models.Organization; import com.mediamath.terminalone.models.Pixel; import com.mediamath.terminalone.models.PixelProvider; import com.mediamath.terminalone.models.PlacementSlot; import com.mediamath.terminalone.models.Publisher; import com.mediamath.terminalone.models.PublisherSite; import com.mediamath.terminalone.models.SiteList; import com.mediamath.terminalone.models.SitePlacement; import com.mediamath.terminalone.models.Strategy; import com.mediamath.terminalone.models.StrategyAudienceSegment; import com.mediamath.terminalone.models.StrategyConcept; import com.mediamath.terminalone.models.StrategyDayPart; import com.mediamath.terminalone.models.StrategyDomain; import com.mediamath.terminalone.models.StrategySupplySource; import com.mediamath.terminalone.models.SupplySource; import com.mediamath.terminalone.models.TargetDimension; import com.mediamath.terminalone.models.TargetValues; import com.mediamath.terminalone.models.User; import com.mediamath.terminalone.models.Vendor; import com.mediamath.terminalone.models.VendorContract; import com.mediamath.terminalone.models.VendorDomain; import com.mediamath.terminalone.models.VendorPixel; import com.mediamath.terminalone.models.VendorPixelDomain; import com.mediamath.terminalone.models.Vertical; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; public final class Constants { private static final String STRATEGY_AUDIENCE_SEGMENT = "strategy_audience_segment"; private static final String STRATEGY_AUDIENCE_SEGMENTS = "strategy_audience_segments"; private static final String SITE_PLACEMENT = "site_placement"; private static final String SITE_LIST = "site_list"; private static final String PLACEMENT_SLOT = "placement_slot"; private static final String PIXEL_PROVIDER = "pixel_provider"; private static final String DEAL = "deal"; private static final String AD_SERVER = "ad_server"; private static final String AUDIENCE_SEGMENT = "audience_segment"; private static final String VERTICAL = "vertical"; private static final String VERTICALS = "verticals"; private static final String VENDOR_PIXEL_DOMAIN = "vendor_pixel_domain"; private static final String VENDOR_PIXEL = "vendor_pixel"; private static final String VENDOR_DOMAIN = "vendor_domain"; private static final String VENDOR_CONTRACT = "vendor_contract"; private static final String VENDOR = "vendor"; private static final String VENDOR_PIXEL_DOMAINS = "vendor_pixel_domains"; private static final String VENDOR_PIXELS = "vendor_pixels"; private static final String VENDOR_DOMAINS = "vendor_domains"; private static final String VENDOR_CONTRACTS = "vendor_contracts"; private static final String VENDORS = "vendors"; private static final String TRAFFIC_CONTACT = "traffic_contact"; private static final String BILLING_CONTACT = "billing_contact"; private static final String SALES_CONTACT = "sales_contact"; private static final String TARGET_VALUE = "target_value"; private static final String TARGET_DIMENSION = "target_dimension"; private static final String TARGET_VALUES = "target_values"; private static final String TARGET_DIMENSIONS = "target_dimensions"; private static final String USER = "user"; private static final String USERS = "users"; private static final String SUPPLY_SOURCE = "supply_source"; private static final String STRATEGY_SUPPLY_SOURCE = "strategy_supply_source"; private static final String STRATEGY_DOMAIN_RESTRICTION = "strategy_domain_restriction"; private static final String STRATEGY_DAY_PART = "strategy_day_part"; private static final String STRATEGY_CONCEPT = "strategy_concept"; private static final String SUPPLY_SOURCES = "supply_sources"; private static final String STRATEGY_SUPPLY_SOURCES = "strategy_supply_sources"; private static final String STRATEGY_DOMAIN_RESTRICTIONS = "strategy_domain_restrictions"; private static final String STRATEGY_DAY_PARTS = "strategy_day_parts"; private static final String STRATEGY_CONCEPTS = "strategy_concepts"; private static final String STRATEGY = "strategy"; private static final String STRATEGIES = "strategies"; private static final String SITE_PLACEMENTS = "site_placements"; private static final String SITE_LISTS = "site_lists"; private static final String PUBLISHER_SITE = "publisher_site"; private static final String PUBLISHER_SITES = "publisher_sites"; private static final String PUBLISHER = "publisher"; private static final String PUBLISHERS = "publishers"; private static final String PLACEMENT_SLOTS = "placement_slots"; private static final String PIXEL_PROVIDERS = "pixel_providers"; private static final String PIXEL_BUNDLES = "pixel_bundles"; private static final String PIXEL_BUNDLE = "pixel_bundle"; private static final String PIXEL = "pixel"; private static final String PIXELS = "pixels"; private static final String ORGANIZATION = "organization"; private static final String ORGANIZATIONS = "organizations"; private static final String DEALS = "deals"; private static final String CREATIVE_APPROVALS = "creative_approvals"; private static final String CREATIVE = "creative"; private static final String CONCEPT = "concept"; private static final String CREATIVES = "creatives"; private static final String CONCEPTS = "concepts"; private static final String CAMPAIGN = "campaign"; private static final String CAMPAIGNS = "campaigns"; private static final String AUDIENCE_SEGMENTS = "audience_segments"; private static final String ATOMIC_CREATIVE = "atomic_creative"; private static final String ATOMIC_CREATIVES = "atomic_creatives"; private static final String AGENCY = "agency"; private static final String AGENCIES = "agencies"; private static final String ADVERTISER = "advertiser"; private static final String ADVERTISERS = "advertisers"; private static final String AD_SERVERS = "ad_servers"; // required for converting requested string path names to entity names when collection demended public static HashMap<String, String> pathToCollectionEntity = new HashMap<String, String>(); // Required for converting entity names to path names [to form paths.] public static HashMap<String, String> entityPaths = new HashMap<String, String>(); // Required for Identifying entity based on requiested path/entity string public static HashMap<String, String> pathToEntity = new HashMap<String, String>(); public static HashMap<String, Integer> childPathSub = new HashMap<String, Integer>(); public static HashMap<String, HashMap<String, Integer>> childPaths = new HashMap<String, HashMap<String, Integer>>(); // TODO: clean up // get the type of entity.. required for parsing. public static HashMap<String, Type> getEntityType = new HashMap<String, Type>(); // TODO: clean up // get the type of list of entity.. required for parsing. public static HashMap<String, Type> getListoFEntityType = new HashMap<String, Type>(); static { getEntityType.put(AD_SERVERS, new TypeToken<JsonResponse<AdServer>>() { }.getType()); getEntityType.put(ADVERTISERS, new TypeToken<JsonResponse<Advertiser>>() { }.getType()); getEntityType.put(ADVERTISER, new TypeToken<JsonResponse<Advertiser>>() { }.getType()); getEntityType.put(AGENCIES, new TypeToken<JsonResponse<Agency>>() { }.getType()); getEntityType.put(AGENCY, new TypeToken<JsonResponse<Agency>>() { }.getType()); getEntityType.put(ATOMIC_CREATIVES, new TypeToken<JsonResponse<AtomicCreative>>() { }.getType()); getEntityType.put(ATOMIC_CREATIVE, new TypeToken<JsonResponse<AtomicCreative>>() { }.getType()); getEntityType.put(AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<AudienceSegment>>() { }.getType()); getEntityType.put(CAMPAIGNS, new TypeToken<JsonResponse<Campaign>>() { }.getType()); getEntityType.put(CAMPAIGN, new TypeToken<JsonResponse<Campaign>>() { }.getType()); getEntityType.put(CONCEPTS, new TypeToken<JsonResponse<Concept>>() { }.getType()); getEntityType.put(CONCEPT, new TypeToken<JsonResponse<Concept>>() { }.getType()); getEntityType.put(CREATIVES, new TypeToken<JsonResponse<Creative>>() { }.getType()); getEntityType.put(CREATIVE, new TypeToken<JsonResponse<Creative>>() { }.getType()); getEntityType.put(CREATIVE_APPROVALS, new TypeToken<JsonResponse<CreativeApproval>>() { }.getType()); getEntityType.put(DEALS, new TypeToken<JsonResponse<Deal>>() { }.getType()); getEntityType.put(ORGANIZATIONS, new TypeToken<JsonResponse<Organization>>() { }.getType()); getEntityType.put(ORGANIZATION, new TypeToken<JsonResponse<Organization>>() { }.getType()); getEntityType.put(PIXELS, new TypeToken<JsonResponse<ChildPixel>>() { }.getType()); getEntityType.put(PIXEL, new TypeToken<JsonResponse<ChildPixel>>() { }.getType()); getEntityType.put(PIXEL_BUNDLE, new TypeToken<JsonResponse<Pixel>>() { }.getType()); getEntityType.put(PIXEL_BUNDLES, new TypeToken<JsonResponse<Pixel>>() { }.getType()); getEntityType.put(PIXEL_PROVIDERS, new TypeToken<JsonResponse<PixelProvider>>() { }.getType()); getEntityType.put(PLACEMENT_SLOTS, new TypeToken<JsonResponse<PlacementSlot>>() { }.getType()); getEntityType.put(PUBLISHERS, new TypeToken<JsonResponse<Publisher>>() { }.getType()); getEntityType.put(PUBLISHER, new TypeToken<JsonResponse<Publisher>>() { }.getType()); getEntityType.put(PUBLISHER_SITES, new TypeToken<JsonResponse<PublisherSite>>() { }.getType()); getEntityType.put(PUBLISHER_SITE, new TypeToken<JsonResponse<PublisherSite>>() { }.getType()); getEntityType.put(SITE_LISTS, new TypeToken<JsonResponse<SiteList>>(){}.getType()); getEntityType.put(SITE_PLACEMENTS, new TypeToken<JsonResponse<SitePlacement>>(){}.getType()); getEntityType.put(STRATEGIES, new TypeToken<JsonResponse<Strategy>>() { }.getType()); getEntityType.put(STRATEGY, new TypeToken<JsonResponse<Strategy>>() { }.getType()); getEntityType.put(STRATEGY_CONCEPTS, new TypeToken<JsonResponse<StrategyConcept>>() { }.getType()); getEntityType.put(STRATEGY_CONCEPT, new TypeToken<JsonResponse<StrategyConcept>>() {}.getType()); getEntityType.put(STRATEGY_DAY_PARTS, new TypeToken<JsonResponse<StrategyDayPart>>() { }.getType()); getEntityType.put(STRATEGY_DAY_PART, new TypeToken<JsonResponse<StrategyDayPart>>() {}.getType()); getEntityType.put(STRATEGY_DOMAIN_RESTRICTIONS, new TypeToken<JsonResponse<StrategyDomain>>() {}.getType()); getEntityType.put(STRATEGY_DOMAIN_RESTRICTION, new TypeToken<JsonResponse<StrategyDomain>>() {}.getType()); getEntityType.put(STRATEGY_SUPPLY_SOURCES, new TypeToken<JsonResponse<StrategySupplySource>>() {}.getType()); getEntityType.put(STRATEGY_SUPPLY_SOURCE,new TypeToken<JsonResponse<StrategySupplySource>>() {}.getType()); getEntityType.put(SUPPLY_SOURCES, new TypeToken<JsonResponse<SupplySource>>() {}.getType()); getEntityType.put(SUPPLY_SOURCE, new TypeToken<JsonResponse<SupplySource>>() {}.getType()); getEntityType.put(USERS, new TypeToken<JsonResponse<User>>() { }.getType()); getEntityType.put(USER, new TypeToken<JsonResponse<User>>() { }.getType()); getEntityType.put(TARGET_DIMENSIONS, new TypeToken<JsonResponse<TargetDimension>>() { }.getType()); getEntityType.put(TARGET_DIMENSION, new TypeToken<JsonResponse<TargetDimension>>() { }.getType()); getEntityType.put(TARGET_VALUES, new TypeToken<JsonResponse<TargetValues>>() { }.getType()); getEntityType.put(TARGET_VALUE, new TypeToken<JsonResponse<TargetValues>>() { }.getType()); getEntityType.put(SALES_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(BILLING_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(TRAFFIC_CONTACT, new TypeToken<JsonResponse<Contact>>() { }.getType()); getEntityType.put(VENDORS, new TypeToken<JsonResponse<Vendor>>() { }.getType()); getEntityType.put(VENDOR, new TypeToken<JsonResponse<Vendor>>() { }.getType()); getEntityType.put(VENDOR_CONTRACTS, new TypeToken<JsonResponse<VendorContract>>() { }.getType()); getEntityType.put(VENDOR_CONTRACT, new TypeToken<JsonResponse<VendorContract>>() { }.getType()); getEntityType.put(VENDOR_DOMAINS, new TypeToken<JsonResponse<VendorDomain>>() { }.getType()); getEntityType.put(VENDOR_DOMAIN, new TypeToken<JsonResponse<VendorDomain>>() { }.getType()); getEntityType.put(VENDOR_PIXELS, new TypeToken<JsonResponse<VendorPixel>>() { }.getType()); getEntityType.put(VENDOR_PIXEL, new TypeToken<JsonResponse<VendorPixel>>() { }.getType()); getEntityType.put(VENDOR_PIXEL_DOMAINS, new TypeToken<JsonResponse<VendorPixelDomain>>() { }.getType()); getEntityType.put(VENDOR_PIXEL_DOMAIN, new TypeToken<JsonResponse<VendorPixelDomain>>() { }.getType()); getEntityType.put(VERTICALS, new TypeToken<JsonResponse<Vertical>>() { }.getType()); getEntityType.put(VERTICAL, new TypeToken<JsonResponse<Vertical>>() { }.getType()); /* LIST RETURN TYPE */ getListoFEntityType.put(ATOMIC_CREATIVES, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(ATOMIC_CREATIVE, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENT, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(CAMPAIGNS, new TypeToken<JsonResponse<ArrayList<Campaign>>>() { }.getType()); getListoFEntityType.put(CAMPAIGN, new TypeToken<JsonResponse<ArrayList<Campaign>>>() { }.getType()); getListoFEntityType.put(AD_SERVERS, new TypeToken<JsonResponse<ArrayList<AdServer>>>() { }.getType()); getListoFEntityType.put(AD_SERVER, new TypeToken<JsonResponse<ArrayList<AdServer>>>() { }.getType()); getListoFEntityType.put(ADVERTISERS, new TypeToken<JsonResponse<ArrayList<Advertiser>>>() { }.getType()); getListoFEntityType.put(ADVERTISER, new TypeToken<JsonResponse<ArrayList<Advertiser>>>() { }.getType()); getListoFEntityType.put(AGENCIES, new TypeToken<JsonResponse<ArrayList<Agency>>>() { }.getType()); getListoFEntityType.put(AGENCY, new TypeToken<JsonResponse<ArrayList<Agency>>>() { }.getType()); getListoFEntityType.put(CONCEPTS, new TypeToken<JsonResponse<ArrayList<Concept>>>() { }.getType()); getListoFEntityType.put(CONCEPT, new TypeToken<JsonResponse<ArrayList<Concept>>>() { }.getType()); getListoFEntityType.put(DEALS, new TypeToken<JsonResponse<ArrayList<Deal>>>() { }.getType()); getListoFEntityType.put(DEAL, new TypeToken<JsonResponse<ArrayList<Deal>>>() { }.getType()); getListoFEntityType.put(ORGANIZATIONS, new TypeToken<JsonResponse<ArrayList<Organization>>>() { }.getType()); getListoFEntityType.put(ORGANIZATION, new TypeToken<JsonResponse<ArrayList<Organization>>>() { }.getType()); getListoFEntityType.put(PIXELS, new TypeToken<JsonResponse<ArrayList<ChildPixel>>>() { }.getType()); getListoFEntityType.put(PIXEL, new TypeToken<JsonResponse<ArrayList<ChildPixel>>>() { }.getType()); getListoFEntityType.put(CREATIVES, new TypeToken<JsonResponse<ArrayList<Creative>>>() { }.getType()); getListoFEntityType.put(CREATIVE, new TypeToken<JsonResponse<ArrayList<Creative>>>() { }.getType()); getListoFEntityType.put(ATOMIC_CREATIVES, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(ATOMIC_CREATIVE, new TypeToken<JsonResponse<ArrayList<AtomicCreative>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(AUDIENCE_SEGMENT, new TypeToken<JsonResponse<ArrayList<AudienceSegment>>>() { }.getType()); getListoFEntityType.put(CREATIVE_APPROVALS, new TypeToken<JsonResponse<ArrayList<CreativeApproval>>>() { }.getType()); getListoFEntityType.put("creative_approval", new TypeToken<JsonResponse<ArrayList<CreativeApproval>>>() { }.getType()); getListoFEntityType.put(PIXEL_BUNDLES, new TypeToken<JsonResponse<ArrayList<Pixel>>>() { }.getType()); getListoFEntityType.put(PIXEL_BUNDLE, new TypeToken<JsonResponse<ArrayList<Pixel>>>() { }.getType()); getListoFEntityType.put(PIXEL_PROVIDERS, new TypeToken<JsonResponse<ArrayList<PixelProvider>>>() { }.getType()); getListoFEntityType.put(PIXEL_PROVIDER, new TypeToken<JsonResponse<ArrayList<PixelProvider>>>() { }.getType()); getListoFEntityType.put(PLACEMENT_SLOTS, new TypeToken<JsonResponse<ArrayList<PlacementSlot>>>() { }.getType()); getListoFEntityType.put(PLACEMENT_SLOT, new TypeToken<JsonResponse<ArrayList<PlacementSlot>>>() { }.getType()); getListoFEntityType.put(PUBLISHERS, new TypeToken<JsonResponse<ArrayList<Publisher>>>() { }.getType()); getListoFEntityType.put(PUBLISHER, new TypeToken<JsonResponse<ArrayList<Publisher>>>() { }.getType()); getListoFEntityType.put(PUBLISHER_SITES, new TypeToken<JsonResponse<ArrayList<PublisherSite>>>() { }.getType()); getListoFEntityType.put(PUBLISHER_SITE, new TypeToken<JsonResponse<ArrayList<PublisherSite>>>() { }.getType()); getListoFEntityType.put(SITE_LISTS, new TypeToken<JsonResponse<ArrayList<SiteList>>>() { }.getType()); getListoFEntityType.put(SITE_LIST, new TypeToken<JsonResponse<ArrayList<SiteList>>>() { }.getType()); getListoFEntityType.put(SITE_PLACEMENTS, new TypeToken<JsonResponse<ArrayList<SitePlacement>>>() { }.getType()); getListoFEntityType.put(SITE_PLACEMENT, new TypeToken<JsonResponse<ArrayList<SitePlacement>>>() { }.getType()); getListoFEntityType.put(STRATEGIES, new TypeToken<JsonResponse<ArrayList<Strategy>>>() { }.getType()); getListoFEntityType.put(STRATEGY, new TypeToken<JsonResponse<ArrayList<Strategy>>>() { }.getType()); getListoFEntityType.put(STRATEGY_CONCEPTS, new TypeToken<JsonResponse<ArrayList<StrategyConcept>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DAY_PARTS, new TypeToken<JsonResponse<ArrayList<StrategyDayPart>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DOMAIN_RESTRICTIONS, new TypeToken<JsonResponse<ArrayList<StrategyDomain>>>() { }.getType()); getListoFEntityType.put(STRATEGY_SUPPLY_SOURCES, new TypeToken<JsonResponse<ArrayList<StrategySupplySource>>>() { }.getType()); getListoFEntityType.put(SUPPLY_SOURCES, new TypeToken<JsonResponse<ArrayList<SupplySource>>>() { }.getType()); getListoFEntityType.put(STRATEGY_CONCEPT, new TypeToken<JsonResponse<ArrayList<StrategyConcept>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DAY_PART, new TypeToken<JsonResponse<ArrayList<StrategyDayPart>>>() { }.getType()); getListoFEntityType.put(STRATEGY_DOMAIN_RESTRICTION, new TypeToken<JsonResponse<ArrayList<StrategyDomain>>>() { }.getType()); getListoFEntityType.put(STRATEGY_SUPPLY_SOURCE, new TypeToken<JsonResponse<ArrayList<StrategySupplySource>>>() { }.getType()); getListoFEntityType.put(SUPPLY_SOURCE, new TypeToken<JsonResponse<ArrayList<SupplySource>>>() { }.getType()); getListoFEntityType.put(STRATEGY_AUDIENCE_SEGMENTS, new TypeToken<JsonResponse<ArrayList<StrategyAudienceSegment>>>() { }.getType()); getListoFEntityType.put(STRATEGY_AUDIENCE_SEGMENT, new TypeToken<JsonResponse<ArrayList<StrategyAudienceSegment>>>() { }.getType()); getListoFEntityType.put(USERS, new TypeToken<JsonResponse<ArrayList<User>>>() { }.getType()); getListoFEntityType.put(USER, new TypeToken<JsonResponse<ArrayList<User>>>() { }.getType()); getListoFEntityType.put(TARGET_DIMENSIONS, new TypeToken<JsonResponse<ArrayList<TargetDimension>>>() { }.getType()); getListoFEntityType.put(TARGET_DIMENSION, new TypeToken<JsonResponse<ArrayList<TargetDimension>>>() { }.getType()); getListoFEntityType.put(TARGET_VALUES, new TypeToken<JsonResponse<ArrayList<TargetValues>>>() { }.getType()); getListoFEntityType.put(TARGET_VALUE, new TypeToken<JsonResponse<ArrayList<TargetValues>>>() { }.getType()); getListoFEntityType.put(VENDORS, new TypeToken<JsonResponse<ArrayList<Vendor>>>() { }.getType()); getListoFEntityType.put(VENDOR, new TypeToken<JsonResponse<ArrayList<Vendor>>>() { }.getType()); getListoFEntityType.put(VENDOR_CONTRACTS, new TypeToken<JsonResponse<ArrayList<VendorContract>>>() { }.getType()); getListoFEntityType.put(VENDOR_CONTRACT, new TypeToken<JsonResponse<ArrayList<VendorContract>>>() { }.getType()); getListoFEntityType.put(VENDOR_DOMAINS, new TypeToken<JsonResponse<ArrayList<VendorDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_DOMAIN, new TypeToken<JsonResponse<ArrayList<VendorDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXELS, new TypeToken<JsonResponse<ArrayList<VendorPixel>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL, new TypeToken<JsonResponse<ArrayList<VendorPixel>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL_DOMAINS, new TypeToken<JsonResponse<ArrayList<VendorPixelDomain>>>() { }.getType()); getListoFEntityType.put(VENDOR_PIXEL_DOMAIN, new TypeToken<JsonResponse<ArrayList<VendorPixelDomain>>>() { }.getType()); getListoFEntityType.put(VERTICALS, new TypeToken<JsonResponse<ArrayList<Vertical>>>() { }.getType()); getListoFEntityType.put(VERTICAL, new TypeToken<JsonResponse<ArrayList<Vertical>>>() { }.getType()); // required for converting requested string path names to entity names when collection demended pathToCollectionEntity.put(AD_SERVERS, "AdServer"); pathToCollectionEntity.put(ADVERTISERS, "Advertiser"); pathToCollectionEntity.put(AGENCIES, "Agency"); pathToCollectionEntity.put(ATOMIC_CREATIVES, "AtomicCreative"); pathToCollectionEntity.put(AUDIENCE_SEGMENTS, "AudienceSegment"); pathToCollectionEntity.put(CAMPAIGNS, "Campaign"); pathToCollectionEntity.put(CONCEPTS, "Concept"); pathToCollectionEntity.put(CREATIVES, "Creative"); pathToCollectionEntity.put(CREATIVE_APPROVALS, "CreativeApproval"); pathToCollectionEntity.put(DEALS, "Deal"); pathToCollectionEntity.put(ORGANIZATIONS, "Organization"); pathToCollectionEntity.put(PIXELS, "ChildPixel"); pathToCollectionEntity.put(PIXEL_BUNDLES, "PixelBundle"); pathToCollectionEntity.put(PIXEL_PROVIDERS, "PixelProvider"); pathToCollectionEntity.put(PLACEMENT_SLOTS, "PlacementSlot"); pathToCollectionEntity.put(PUBLISHERS, "Publisher"); pathToCollectionEntity.put(PUBLISHER_SITES, "PublisherSite"); pathToCollectionEntity.put(SITE_LISTS, "SiteList"); pathToCollectionEntity.put(SITE_PLACEMENTS, "SitePlacement"); pathToCollectionEntity.put(STRATEGIES, "Strategy"); pathToCollectionEntity.put(STRATEGY_CONCEPTS, "StrategyConcept"); pathToCollectionEntity.put(STRATEGY_DAY_PARTS, "StrategyDayPart"); pathToCollectionEntity.put(STRATEGY_DOMAIN_RESTRICTIONS, "StrategyDomain"); pathToCollectionEntity.put(STRATEGY_SUPPLY_SOURCES, "StrategySupplySource"); pathToCollectionEntity.put(SUPPLY_SOURCES, "SupplySource"); pathToCollectionEntity.put(USERS, "User"); pathToCollectionEntity.put(TARGET_DIMENSIONS, "TargetDimension"); pathToCollectionEntity.put(TARGET_VALUES, "TargetValue"); pathToCollectionEntity.put("permissions", "Permission"); pathToCollectionEntity.put("reports", "Report"); pathToCollectionEntity.put(VENDORS, "Vendor"); pathToCollectionEntity.put(VENDOR_CONTRACTS, "VendorContract"); pathToCollectionEntity.put(VENDOR_DOMAINS, "VendorDomain"); pathToCollectionEntity.put(VENDOR_PIXELS, "VendorPixel"); pathToCollectionEntity.put(VENDOR_PIXEL_DOMAINS, "VendorPixelDomain"); pathToCollectionEntity.put(VERTICALS, "Vertical"); // Required for converting entity names to path names [to form paths.] entityPaths.put("AdServer", AD_SERVERS); entityPaths.put("Advertiser", ADVERTISERS); entityPaths.put("Agency", AGENCIES); entityPaths.put("AtomicCreative", ATOMIC_CREATIVES); entityPaths.put("AudienceSegment", AUDIENCE_SEGMENTS); entityPaths.put("Campaign", CAMPAIGNS); entityPaths.put("Concept", CONCEPTS); entityPaths.put("Creative", CREATIVES); entityPaths.put("CreativeApproval", ATOMIC_CREATIVES); entityPaths.put("Deal", DEALS); entityPaths.put("Organization", ORGANIZATIONS); entityPaths.put("ChildPixel", PIXELS); entityPaths.put("PixelBundle", PIXEL_BUNDLES); entityPaths.put("PixelProvider", PIXEL_PROVIDERS); entityPaths.put("PlacementSlot", PLACEMENT_SLOTS); entityPaths.put("Publisher", PUBLISHERS); entityPaths.put("PublisherSite", PUBLISHER_SITES); entityPaths.put("SiteList", SITE_LISTS); entityPaths.put("SitePlacement", SITE_PLACEMENTS); entityPaths.put("Strategy", STRATEGIES); entityPaths.put("StrategyConcept", STRATEGY_CONCEPTS); entityPaths.put("StrategyDayPart", STRATEGY_DAY_PARTS); entityPaths.put("StrategyDomain", STRATEGY_DOMAIN_RESTRICTIONS); entityPaths.put("StrategySupplySource", STRATEGY_SUPPLY_SOURCES); entityPaths.put("SupplySource", SUPPLY_SOURCES); entityPaths.put("User", USERS); entityPaths.put("TargetDimension", TARGET_DIMENSIONS); entityPaths.put("TargetValue", TARGET_VALUES); entityPaths.put("Permission", "permissions"); entityPaths.put("Report", "reports"); entityPaths.put("Vendor", VENDORS); entityPaths.put("VendorContract", VENDOR_CONTRACTS); entityPaths.put("VendorDomain", VENDOR_DOMAINS); entityPaths.put("VendorPixel", VENDOR_PIXELS); entityPaths.put("VendorPixelDomain", VENDOR_PIXEL_DOMAINS); entityPaths.put("Vertical", VERTICALS); // Required for Identifying entity based on requested path/entity string pathToEntity.put(AD_SERVER, "AdServer"); pathToEntity.put(ADVERTISER, "Advertiser"); pathToEntity.put(AGENCY, "Agency"); pathToEntity.put(ATOMIC_CREATIVE, "AtomicCreative"); pathToEntity.put(AUDIENCE_SEGMENT, "AudienceSegment"); pathToEntity.put(CAMPAIGN, "Campaign"); pathToEntity.put(CONCEPT, "Concept"); pathToEntity.put(CREATIVE, "Creative"); pathToEntity.put("creative_approval", "CreativeApproval"); pathToEntity.put(DEAL, "Deal"); pathToEntity.put(ORGANIZATION, "Organization"); pathToEntity.put(PIXEL, "ChildPixel"); pathToEntity.put(PIXEL_BUNDLE, "PixelBundle"); pathToEntity.put(PIXEL_PROVIDER, "PixelProvider"); pathToEntity.put(PLACEMENT_SLOT, "PlacementSlot"); pathToEntity.put(PUBLISHER, "Publisher"); pathToEntity.put(PUBLISHER_SITE, "PublisherSite"); pathToEntity.put(SITE_LIST, "SiteList"); pathToEntity.put(SITE_PLACEMENT, "SitePlacement"); pathToEntity.put(STRATEGY, "Strategy"); pathToEntity.put(STRATEGY_CONCEPT, "StrategyConcept"); pathToEntity.put(STRATEGY_DAY_PART, "StrategyDayPart"); pathToEntity.put(STRATEGY_DOMAIN_RESTRICTION, "StrategyDomain"); pathToEntity.put(STRATEGY_SUPPLY_SOURCE, "StrategySupplySource"); pathToEntity.put(SUPPLY_SOURCE, "SupplySource"); pathToEntity.put(USER, "User"); pathToEntity.put(TARGET_DIMENSION, "TargetDimension"); pathToEntity.put(TARGET_VALUE, "TargetValue"); pathToEntity.put("permission", "Permission"); pathToEntity.put("report", "Report"); pathToEntity.put(VENDOR, "Vendor"); pathToEntity.put(VENDOR_CONTRACT, "VendorContract"); pathToEntity.put(VENDOR_DOMAIN, "VendorDomain"); pathToEntity.put(VENDOR_PIXEL, "VendorPixel"); pathToEntity.put(VENDOR_PIXEL_DOMAIN, "VendorPixelDomain"); pathToEntity.put(VERTICAL, "Vertical"); // CHILD PATHS HashMap<String, Integer> subMap1 = new HashMap<String, Integer>(); subMap1.put("acl", 0); childPaths.put("acl", (new HashMap<String, Integer>())); HashMap<String, Integer> subMap2 = new HashMap<String, Integer>(); subMap2.put(TARGET_DIMENSIONS, 22); childPaths.put("audio", subMap2); HashMap<String, Integer> subMap3 = new HashMap<String, Integer>(); subMap3.put(TARGET_DIMENSIONS, 4); childPaths.put("browser", subMap3); HashMap<String, Integer> subMap4 = new HashMap<String, Integer>(); subMap4.put(TARGET_DIMENSIONS, 16); childPaths.put("channels", subMap4); HashMap<String, Integer> subMap5 = new HashMap<String, Integer>(); subMap5.put(CONCEPTS, 0); childPaths.put(CONCEPTS, subMap5); HashMap<String, Integer> subMap6 = new HashMap<String, Integer>(); subMap6.put(TARGET_DIMENSIONS, 2); childPaths.put("connection speed", subMap6); HashMap<String, Integer> subMap7 = new HashMap<String, Integer>(); subMap7.put(TARGET_DIMENSIONS, 21); childPaths.put("content initiation", subMap7); HashMap<String, Integer> subMap8 = new HashMap<String, Integer>(); subMap8.put(TARGET_DIMENSIONS, 14); childPaths.put("country", subMap8); HashMap<String, Integer> subMap9 = new HashMap<String, Integer>(); subMap9.put("day_parts", 0); childPaths.put("day_parts", subMap9); HashMap<String, Integer> subMap10 = new HashMap<String, Integer>(); subMap10.put(TARGET_DIMENSIONS, 24); childPaths.put("device", subMap10); HashMap<String, Integer> subMap11 = new HashMap<String, Integer>(); subMap11.put(TARGET_DIMENSIONS, 1); childPaths.put("dma", subMap11); HashMap<String, Integer> subMap12 = new HashMap<String, Integer>(); subMap12.put(TARGET_DIMENSIONS, 19); childPaths.put("fold position", subMap12); HashMap<String, Integer> subMap13 = new HashMap<String, Integer>(); subMap13.put(TARGET_DIMENSIONS, 3); childPaths.put("isp", subMap13); HashMap<String, Integer> subMap14 = new HashMap<String, Integer>(); subMap14.put(TARGET_DIMENSIONS, 20); childPaths.put("linear format", subMap14); HashMap<String, Integer> subMap15 = new HashMap<String, Integer>(); subMap15.put(TARGET_DIMENSIONS, 8); childPaths.put("mathselect250", subMap15); HashMap<String, Integer> subMap16 = new HashMap<String, Integer>(); subMap16.put(TARGET_DIMENSIONS, 5); childPaths.put("os", subMap16); HashMap<String, Integer> subMap17 = new HashMap<String, Integer>(); subMap17.put("permissions", 0); childPaths.put("permission", subMap17); HashMap<String, Integer> subMap18 = new HashMap<String, Integer>(); subMap18.put("permissions", 0); childPaths.put("permissions", subMap18); HashMap<String, Integer> subMap19 = new HashMap<String, Integer>(); subMap19.put(TARGET_DIMENSIONS, 23); childPaths.put("player size", subMap19); HashMap<String, Integer> subMap20 = new HashMap<String, Integer>(); subMap20.put(TARGET_DIMENSIONS, 7); childPaths.put("region", subMap20); HashMap<String, Integer> subMap21 = new HashMap<String, Integer>(); subMap21.put(TARGET_DIMENSIONS, 15); childPaths.put("safety", subMap21); HashMap<String, Integer> subMap22 = new HashMap<String, Integer>(); subMap22.put("supplies", 0); childPaths.put("supplies", subMap22); HashMap<String, Integer> subMap23 = new HashMap<String, Integer>(); subMap23.put("targeting_segments", 0); childPaths.put("targeting_segments", subMap23); HashMap<String, Integer> subMap24 = new HashMap<String, Integer>(); subMap24.put(AUDIENCE_SEGMENTS, 0); childPaths.put(AUDIENCE_SEGMENTS, subMap24); } }
Sonar Fixes - Constants Class
src/main/java/com/mediamath/terminalone/utils/Constants.java
Sonar Fixes - Constants Class
Java
apache-2.0
d5e2e3fe68f422fe8f6cf7bdcfcfd4ffa395787b
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package learn; //import gcm2sbml.parser.GCMFile; import lhpn2sbml.parser.LhpnFile; import lhpn2sbml.parser.Lpn2verilog; import parser.*; import java.io.*; import java.util.*; import javax.swing.*; //import org.sbml.libsbml.*; import biomodelsim.*; /** * This class generates an LHPN model from the simulation traces provided * in the learn view. The generated LHPN is stored in an object of type * lhpn2sbml.parser.LHPNfile . It is then saved in *.lpn file using the * save() method of the above class. * * Rev. 1 - Kevin Jones * Rev. 2 - Scott Little (data2lhpn.py) * Rev. 3 - Satish Batchu ( dataToLHPN() ) */ public class LearnModel { // added ItemListener SB private static final long serialVersionUID = -5806315070287184299L; private String directory, lrnFile; private Log log; private String separator; private String learnFile, lhpnFile; private ArrayList<Variable> reqdVarsL; //private ArrayList<String> careVars; private ArrayList<Integer> reqdVarIndices; private ArrayList<ArrayList<Double>> data; private ArrayList<String> varNames; //private HashMap<String, int[]> careBins; private int[][] bins; private ArrayList<ArrayList<Double>> divisionsL; private HashMap<String, ArrayList<Double>> thresholds; private Double[][] rates; private double[][] values; private Double[] duration; private int pathLengthBin ; //= 7 ;// intFixed 25 pd 7 integrator 15; private int rateSampling ; //= -1 ; //intFixed 250; 20; //-1; private LhpnFile g; private Integer numPlaces = 0; private Integer numTransitions = 0; private HashMap<String, Properties> placeInfo; private HashMap<String, Properties> transitionInfo; private HashMap<String, Properties> cvgInfo; private Double minDelayVal = 10.0; private Double minRateVal = 10.0; private Double minDivisionVal = 10.0; private Double delayScaleFactor = 1.0; private Double valScaleFactor = 1.0; BufferedWriter out; File logFile; // Threshold parameters // private double epsilon ;//= 0.1; // What is the +/- epsilon where signals are considered to be equivalent private Integer runLength ; //= 15; // the number of time points that a value must persist to be considered constant private Double runTime ; // = 5e-12; // 10e-6 for intFixed; 5e-6 for integrator. 5e-12 for pd;// the amount of time that must pass to be considered constant when using absoluteTime private boolean absoluteTime ; // = true; // true for intfixed //false; true for pd; false for integrator// when False time points are used to determine DMVC and when true absolutime time is used to determine DMVC private double percent ; // = 0.8; // a decimal value representing the percent of the total trace that must be constant to qualify to become a DMVC var private Double[] lowerLimit; private Double[] upperLimit; private String[] transEnablingsVHDL; private String[][] transIntAssignVHDL; private String[] transDelayAssignVHDL; private String[] transEnablingsVAMS; private String[] transConditionalsVAMS; private String[][] transIntAssignVAMS; private String[] transDelayAssignVAMS; private String failPropVHDL; private HashMap<String, Properties> transientNetPlaces; private HashMap<String, Properties> transientNetTransitions; private ArrayList<String> propPlaces; private boolean vamsRandom = false; private HashMap<String,Properties> dmvcValuesUnique; private Double dsFactor, vsFactor; private String currentPlace; private String[] currPlaceBin; private LhpnFile lpnWithPseudo; private int pseudoTransNum = 0; private HashMap<String,Boolean> pseudoVars; private ArrayList<HashMap<String, String>> constVal; private boolean dmvDetectDone = false; private boolean dmvStatusLoaded = false; private int pathLengthVar = 40; private double unstableTime; private boolean binError; private HashMap<String, ArrayList<String>> destabMap; // Pattern lParenR = Pattern.compile("\\(+"); //Pattern floatingPointNum = Pattern.compile(">=(-*[0-9]+\\.*[0-9]*)"); // Pattern falseR = Pattern.compile("false",Pattern.CASE_INSENSITIVE); //pass the I flag to be case insensitive /** * This is a constructor for learning LPN models from simulation data. This could * have been just a method in LearnLHPN class but because it started with * a lot of global variables/fields, it ended up being a constructor in a * separate class. * * Version 1 : Kevin Jones (Perl) * Version 2 : Scott Little (data2lhpn.py) * Version 3 : Satish Batchu (LearnModel.java) */ public LhpnFile learnModel(String directory, Log log, BioSim biosim, int moduleNumber, HashMap<String, ArrayList<Double>> thresh, HashMap<String,Double> tPar, ArrayList<Variable> rVarsL, HashMap<String, ArrayList<String>> dstab, Boolean netForStable, Double vScaleFactor, Double dScaleFactor, String failProp) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Assign the parameters received from the call to the fields of this class this.log = log; this.directory = directory; this.reqdVarsL = rVarsL; this.thresholds = thresh; this.valScaleFactor = vScaleFactor; this.delayScaleFactor = dScaleFactor; this.destabMap = dstab; String[] getFilename = directory.split(separator); if (moduleNumber == 0) lhpnFile = getFilename[getFilename.length - 1] + ".lpn"; else lhpnFile = getFilename[getFilename.length - 1] + moduleNumber + ".lpn"; // epsilon = tPar.get("epsilon"); pathLengthBin = (int) tPar.get("pathLengthBin").doubleValue(); pathLengthVar = (int) tPar.get("pathLengthVar").doubleValue(); rateSampling = (int) tPar.get("rateSampling").doubleValue(); percent = tPar.get("percent"); if (tPar.containsKey("runTime")){ //only runTime or runLength is required based on gui selection runTime = tPar.get("runTime"); runLength = null; } else{ runLength = (int) tPar.get("runLength").doubleValue(); runTime = null; } unstableTime = tPar.get("unstableTime").doubleValue(); new File(directory + separator + lhpnFile).delete(); try { logFile = new File(directory + separator + "run.log"); if (moduleNumber == 0) logFile.createNewFile(); //create new file first time out = new BufferedWriter(new FileWriter(logFile,true)); //appending // resetAll(); numPlaces = 0; numTransitions = 0; out.write("Running: dataToLHPN for module " + moduleNumber + "\n"); TSDParser tsd = new TSDParser(directory + separator + "run-1.tsd", false); varNames = tsd.getSpecies(); //String[] learnDir = lrnFile.split("\\."); //File cvgFile = new File(directory + separator + learnDir[0] + ".cvg"); File cvgFile = new File(directory + separator + "run.cvg"); //cvgFile.createNewFile(); BufferedWriter coverage = new BufferedWriter(new FileWriter(cvgFile)); g = new LhpnFile(); // The generated lhpn is stored in this object placeInfo = new HashMap<String, Properties>(); transitionInfo = new HashMap<String, Properties>(); cvgInfo = new HashMap<String, Properties>(); transientNetPlaces = new HashMap<String, Properties>(); transientNetTransitions = new HashMap<String, Properties>(); if ((failProp != null)){ //Construct a property net with single place and a fail trans propPlaces = new ArrayList<String>(); Properties p0 = new Properties(); placeInfo.put("failProp", p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "PROP"); p0.setProperty("initiallyMarked", "true"); g.addPlace("p" + numPlaces, true); propPlaces.add("p" + numPlaces); numPlaces++; Properties p1 = new Properties(); transitionInfo.put("failProp", p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get("failProp").getProperty("placeNum"), "t" + transitionInfo.get("failProp").getProperty("transitionNum")); g.getTransition("t" + numTransitions).setFail(true); numTransitions++; } out.write("epsilon = " + "; ratesampling = " + rateSampling + "; pathLengthBin = " + pathLengthBin + "; percent = " + percent + "; runlength = " + runLength + "; runtime = " + runTime + "; absoluteTime = " + absoluteTime + "; delayscalefactor = " + delayScaleFactor + "; valuescalefactor = " + valScaleFactor + "\n"); dsFactor = this.delayScaleFactor; vsFactor = this.valScaleFactor; dmvcValuesUnique = new HashMap<String, Properties>(); constVal = new ArrayList<HashMap<String, String>>(); int tsdFileNum = 1; while (new File(directory + separator + "run-" + tsdFileNum + ".tsd").exists()) { Properties cProp = new Properties(); cvgInfo.put(String.valueOf(tsdFileNum), cProp); cProp.setProperty("places", String.valueOf(0)); cProp.setProperty("transitions", String.valueOf(0)); cProp.setProperty("rates", String.valueOf(0)); cProp.setProperty("delays", String.valueOf(0)); if (!netForStable) tsd = new TSDParser(directory + separator + "run-" + tsdFileNum + ".tsd", false); else tsd = new TSDParser(directory + separator + "runWithStables-" + tsdFileNum + ".tsd", false); data = tsd.getData(); varNames = tsd.getSpecies(); if (((destabMap != null) && (destabMap.size() != 0)) ){ //remove stable if it was added for (int l = 0; l < varNames.size(); l++) if (varNames.get(l).equals("stable")) varNames.remove(l); // should remove stable from this list for (int l = 0; l < reqdVarsL.size(); l++) if (reqdVarsL.get(l).getName().equals("stable")) reqdVarsL.remove(l); // should remove stable from this list if (thresholds.containsKey("stable")) thresholds.remove("stable"); // remove for stable. } findReqdVarIndices(); genBinsRates(thresholds); if ((destabMap != null) && (destabMap.size() != 0)){ out.write("Generating data for stables \n"); //addStablesToData(thresholds, destabMap); addStablesToData2(bins,duration,thresholds,destabMap, reqdVarsL); for (String s : varNames) out.write(s + " "); out.write("\n"); tsd.setData(data); tsd.setSpecies(varNames); tsd.outputTSD(directory + separator + "runWithStables-" + tsdFileNum + ".tsd"); } findReqdVarIndices(); genBinsRates(thresholds); detectDMV(data,false); updateGraph(bins, rates, tsdFileNum, cProp); //cProp.store(coverage, "run-" + String.valueOf(i) + ".tsd"); coverage.write("run-" + String.valueOf(tsdFileNum) + ".tsd\t"); coverage.write("places : " + cProp.getProperty("places")); coverage.write("\ttransitions : " + cProp.getProperty("transitions") + "\n"); tsdFileNum++; } coverage.close(); for (String st1 : g.getTransitionList()) { out.write("\nTransition is " + st1); if (isTransientTransition(st1)){ out.write(" Incoming place " + g.getPreset(st1)[0]); if (g.getPostset(st1).length != 0){ out.write(" Outgoing place " + g.getPostset(st1)[0]); } continue; } String binEncoding = getPlaceInfoIndex(g.getPreset(st1)[0]); out.write(" Incoming place " + g.getPreset(st1)[0] + " Bin encoding is " + binEncoding); if (g.getPostset(st1).length != 0){ binEncoding = getPlaceInfoIndex(g.getPostset(st1)[0]); out.write(" Outgoing place " + g.getPostset(st1)[0] + " Bin encoding is " + binEncoding); } } out.write("\nTotal no of transitions : " + numTransitions); out.write("\nTotal no of places : " + numPlaces); Properties initCond = new Properties(); for (Variable v : reqdVarsL) { if (v.isDmvc()) { g.addInteger(v.getName(), v.getInitValue()); } else { initCond.put("value", v.getInitValue()); initCond.put("rate", v.getInitRate()); g.addContinuous(v.getName(), initCond); } } HashMap<String, ArrayList<Double>> scaledThresholds; scaledThresholds = normalize(); // globalValueScaling.setText(Double.toString(valScaleFactor)); // globalDelayScaling.setText(Double.toString(delayScaleFactor)); initCond = new Properties(); for (Variable v : reqdVarsL) { // Updating with scaled initial values & rates if (v.isDmvc()) { g.changeIntegerInitCond(v.getName(), v.getInitValue()); } else { initCond.put("value", v.getInitValue()); initCond.put("rate", v.getInitRate()); g.changeContInitCond(v.getName(), initCond); } } String[] transitionList = g.getTransitionList(); /* transEnablingsVAMS = new String[transitionList.length]; transConditionalsVAMS = new String[transitionList.length]; transIntAssignVAMS = new String[transitionList.length][reqdVarsL.size()]; transDelayAssignVAMS = new String[transitionList.length]; */ int transNum; for (String t : transitionList) { transNum = Integer.parseInt(t.split("t")[1]); if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { // g.getPreset(t).length != 0 && g.getPostset(t).length != 0 ?? String tKey = getTransitionInfoIndex(t); String prevPlaceFullKey = getPresetPlaceFullKey(tKey); String nextPlaceFullKey = getPostsetPlaceFullKey(tKey); //ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); ArrayList<Integer> diffL = diff(prevPlaceFullKey, nextPlaceFullKey); String condStr = ""; // transEnablingsVAMS[transNum] = ""; //String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(","); //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(","); String[] binIncoming = prevPlaceFullKey.split(","); String[] binOutgoing = nextPlaceFullKey.split(","); Boolean firstInputBinChg = true; Boolean firstOutputBinChg = true; Boolean careOpChange = false, careIpChange = false; for (int k : diffL) { if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) { // the above condition means that if the bin change is not on a non-input dmv variable, there won't be any enabling condition if (reqdVarsL.get(k).isCare()) careIpChange = true; if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) { //double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue(); double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])-1).doubleValue(); // changed on July 20, 2010 if (firstInputBinChg){ condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/valScaleFactor +"))"; } else{ condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/valScaleFactor +"))"; } } else { double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue(); if (firstInputBinChg){ condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; //changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/valScaleFactor +"))"; } else{ condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; //changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/valScaleFactor +"))"; } } //if (diffL.get(diffL.size() - 1) != k) { // condStr += "&"; ////COME BACK??? temporary transEnablingsVAMS[transNum] += //} firstInputBinChg = false; } // Enablings Till above.. Below one is dmvc delay,assignment. Whenever a transition's preset and postset places differ in dmvc vars, then this transition gets the assignment of the dmvc value in the postset place and delay assignment of the preset place's duration range. This has to be changed after taking the causal relation input if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis if (reqdVarsL.get(k).isCare()) careOpChange = true; // String pPrev = g.getPreset(t)[0]; // String nextPlace = g.getPostset(t)[0]; String nextPlaceKey = getPlaceInfoIndex(g.getPostset(t)[0]); //if (!isTransientTransition(t)){ // int mind = (int) Math.floor(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + "," + getPlaceInfoIndex(nextPlace)).getProperty("dMin"))); // int maxd = (int) Math.ceil(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + "," + getPlaceInfoIndex(nextPlace)).getProperty("dMax"))); int mind = (int) Math.floor(Double.parseDouble(transitionInfo.get(tKey).getProperty("dMin"))); int maxd = (int) Math.ceil(Double.parseDouble(transitionInfo.get(tKey).getProperty("dMax"))); if (mind != maxd) g.changeDelay(t, "uniform(" + mind + "," + maxd + ")"); else g.changeDelay(t, String.valueOf(mind)); //int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); //int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); if (minv != maxv) g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign(t,reqdVarsL.get(k).getName(), String.valueOf(minv)); int dmvTnum = Integer.parseInt(t.split("t")[1]); if (!vamsRandom){ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor)+";\n"; // transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) } else{ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf((int)Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/valScaleFactor)) + "," + String.valueOf((int)Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/valScaleFactor))+");\n"; // transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," +(int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9) } /*} else{ g.changeDelay(t, "[" + (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + "," + (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))) + "]"); g.addIntAssign(t,reqdVarsL.get(k).getName(),"[" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ","+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + "]"); int dmvTnum = Integer.parseInt(t.split("t")[1]); transIntAssignVAMS[dmvTnum][k] = ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor); transDelayAssignVAMS[dmvTnum] = (int)(((Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))))*Math.pow(10, 12))/(2.0*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) }*/ } } if (careIpChange & careOpChange){ // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration. if ((getPlaceInfoIndex(g.getPreset(t)[0]) != null) && (getPlaceInfoIndex(g.getPostset(t)[0]) != null)) //if (!(transitionInfo.get(getPlaceInfoIndex(g.getPreset(t)[0]) + "," + getPlaceInfoIndex(g.getPostset(t)[0])).containsKey("ioChangeDelay"))) if (!(transitionInfo.get(tKey).containsKey("ioChangeDelay"))){ g.changeDelay(t, "0"); } } // if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){ // transEnablingsVAMS[transNum] += ")"; // } if (!condStr.equalsIgnoreCase("")){ //condStr += enFailAnd; g.addEnabling(t, condStr); } else{ //Nothing added to Enabling condition. //condStr = enFail; //g.addEnabling(t, condStr); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); String prevPlaceFullKey = getPresetPlaceFullKey(tKey); String nextPlaceFullKey = getPostsetPlaceFullKey(tKey); //ArrayList<Integer> diffL = diff(getTransientNetPlaceIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); ArrayList<Integer> diffL = diff(prevPlaceFullKey, nextPlaceFullKey); String condStr = ""; // transEnablingsVAMS[transNum] = ""; //String[] binIncoming = getTransientNetPlaceIndex(g.getPreset(t)[0]).split(","); //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(","); String[] binIncoming = prevPlaceFullKey.split(","); String[] binOutgoing = nextPlaceFullKey.split(","); Boolean firstInputBinChg = true; Boolean careOpChange = false, careIpChange = false; for (int k : diffL) { if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) { if (reqdVarsL.get(k).isCare()) careIpChange = true; if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) { //double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue(); double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])-1).doubleValue(); // changed on July 20, 2010 if (firstInputBinChg){ condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary } else{ condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary } } else { double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue(); if (firstInputBinChg){ condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";//changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary } else { condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";//changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary } } //if (diffL.get(diffL.size() - 1) != k) { // condStr += "&"; // //COME BACK??? temporary transEnablingsVAMS[transNum] += //} firstInputBinChg = false; } if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis if (reqdVarsL.get(k).isCare()) careOpChange = true; //String pPrev = g.getPreset(t)[0]; //String nextPlace = g.getPostset(t)[0]; String nextPlaceKey = getPlaceInfoIndex(g.getPostset(t)[0]); //int mind = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+ "," +getPlaceInfoIndex(nextPlace)).getProperty("dMin"))); //int maxd = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+ "," +getPlaceInfoIndex(nextPlace)).getProperty("dMax"))); int mind = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(tKey).getProperty("dMin"))); int maxd = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(tKey).getProperty("dMax"))); if (mind != maxd) g.changeDelay(t, "uniform(" + mind + "," + maxd + ")"); else g.changeDelay(t, String.valueOf(mind)); //int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); //int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); if (minv != maxv) g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign(t,reqdVarsL.get(k).getName(),String.valueOf(minv)); int dmvTnum = Integer.parseInt(t.split("t")[1]); if (!vamsRandom){ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor)+";\n";; // transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) } else{ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf(Math.floor((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/valScaleFactor))) + "," + String.valueOf(Math.ceil((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/valScaleFactor)))+");\n"; // transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," + (int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9) } } } if (careIpChange & careOpChange){ // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration. if ((getTransientNetPlaceIndex(g.getPreset(t)[0]) != null) && (getPlaceInfoIndex(g.getPostset(t)[0]) != null)) //if (!(transientNetTransitions.get(getTransientNetPlaceIndex(g.getPreset(t)[0]) + "," + getPlaceInfoIndex(g.getPostset(t)[0])).containsKey("ioChangeDelay"))) if (!(transientNetTransitions.get(tKey).containsKey("ioChangeDelay"))) g.changeDelay(t, "0"); } if (diffL.size() > 1){ // transEnablingsVHDL[transNum] = "(" + transEnablingsVHDL[transNum] + ")"; } // if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){ // transEnablingsVAMS[transNum] += ")"; // } if (!condStr.equalsIgnoreCase("")){ g.addEnabling(t, condStr); } else{ //g.addEnabling(t, condStr); } } } } if (failProp != null){ if ((g.getPreset(t) != null) && (!isTransientTransition(t)) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("PROP"))){ g.addEnabling(t, failProp); } } } ArrayList<String> placesWithoutPostsetTrans = new ArrayList<String>(); ArrayList<String> dcVars = new ArrayList<String>(); for (Variable v : reqdVarsL){ if (!v.isCare()) dcVars.add(v.getName()); } for (String st1 : g.getPlaceList()) { if (g.getPostset(st1).length == 0){ // a place without a postset transition placesWithoutPostsetTrans.add(st1); } else if (g.getPostset(st1).length > 1){ HashMap<String,Boolean> varsInEnabling = new HashMap<String,Boolean>(); for (String st2 : g.getPostset(st1)){ if (g.getEnablingTree(st2) != null){ for (String st3 : g.getEnablingTree(st2).getVars()){ varsInEnabling.put(st3, true); } } } for (String st2 : g.getPostset(st1)){ if ((varsInEnabling.keySet().size() >= 1) || (dcVars.size() > 0)){ // && (g.getEnablingTree(st2) != null)) //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(st2)[0]).split(","); String transKey; if (!isTransientTransition(st2)) transKey = getTransitionInfoIndex(st2); else transKey = getTransientNetTransitionIndex(st2); String[] binOutgoing = getPostsetPlaceFullKey(transKey).split(","); String condStr = ""; for (String st : varsInEnabling.keySet()){ int bin = Integer.valueOf(binOutgoing[findReqdVarslIndex(st)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on Aug7,2010 } } for (String st : dcVars){ if(!varsInEnabling.containsKey(st)){ int bin = Integer.valueOf(binOutgoing[findReqdVarslIndex(st)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } } out.write("Changed enabling of " + st2 + " to " + condStr + "\n"); g.addEnabling(st2, condStr); } } /*for (String st2 : g.getPostset(st1)){ ExprTree enableTree = g.getEnablingTree(st2); if (enableTree != null){ // If enabling of a transition is null then it's obviously not mutually exclusive of any other parallel transitions from that place for (String st3 : varsInEnabling.keySet()){ // TODO: CHECK THE BIN CHANGES HERE AND ADD ENABLING CONDITIONS if (!enableTree.containsVar(st3)){ // System.out.println("At place " + st1 + " for transition " + st2 + ",Get threshold of " + st3); visitedPlaces = new HashMap<String,Boolean>(); String completeEn =traceBack(st1,st3); System.out.println("At place " + st1 + " for transition " + st2 + ",Get threshold of " + st3+ " from " + completeEn); Pattern enPatternParan = Pattern.compile(".*?(~?\\(" + st3+ ".*?\\)*)[a-zA-Z]*.*"); Pattern enPattern; Matcher enMatcher; //Pattern enPatternNoParan = Pattern.compile(".*?(~?\\(?" + st3+ ".*?\\)*)[a-zA-Z]*.*"); Matcher enMatcherParan = enPatternParan.matcher(completeEn); if (enMatcherParan.find()) { enPattern = Pattern.compile(".*?(~?\\(" + st3+ ".*?\\)).*?"); System.out.println("Matching for pattern " + enPattern.toString()); enMatcher = enPattern.matcher(completeEn); String enCond = enMatcher.group(1); System.out.println("Extracted " +enCond); } else { enPattern = Pattern.compile(".*?(" + st3+ ".*?)[a-zA-Z]*.*?"); System.out.println("Matching for pattern " + enPattern.toString()); enMatcher = enPattern.matcher(completeEn); String enCond = enMatcher.group(1); System.out.println("Extracted " +enCond); } } } } }*/ } if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { if (g.getPreset(st1).length != 0){ for (String t : g.getPreset(st1)) { for (int k = 0; k < reqdVarsL.size(); k++) { if (!reqdVarsL.get(k).isDmvc()) { int minr = getMinRate(p, reqdVarsL.get(k).getName()); int maxr = getMaxRate(p, reqdVarsL.get(k).getName()); if (minr != maxr) g.addRateAssign(t, reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign(t, reqdVarsL.get(k).getName(), String.valueOf(minr)); } } } } } } } for (String st1 : transientNetTransitions.keySet()){ String s = g.getPostset("t" + transientNetTransitions.get(st1).getProperty("transitionNum"))[0]; // check TYPE of preset ???? String p = getPlaceInfoIndex(s); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { for (int k = 0; k < reqdVarsL.size(); k++) { if (!reqdVarsL.get(k).isDmvc()) { // out.write("<" + t + "=[" + reqdVarsL.get(k).getName() + ":=[" + getMinRate(p, reqdVarsL.get(k).getName()) + "," + getMaxRate(p, reqdVarsL.get(k).getName()) + "]]>"); int minr = getMinRate(p, reqdVarsL.get(k).getName()); int maxr = getMaxRate(p, reqdVarsL.get(k).getName()); if (minr != maxr) g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), String.valueOf(minr)); } } } } //Reversed the order of adding initPlace and removing placeswithout postset transitions. //This makes sure that signals which are constant throughout a trace are not completely lost. addInitPlace(scaledThresholds); for (String st1 : placesWithoutPostsetTrans){ placeInfo.remove(getPlaceInfoIndex(st1)); g.removePlace(st1); } if (moduleNumber == 0){ out.write("Adding pseudo transitions now. It'll be saved in " + directory + separator + "pseudo" + lhpnFile + "\n"); addPseudo(scaledThresholds); lpnWithPseudo.save(directory + separator + "pseudo" + lhpnFile); } // addMetaBins(); // addMetaBinTransitions(); if ((destabMap != null) || (destabMap.size() != 0)){ HashMap<String, ArrayList<String>> dMap = new HashMap<String, ArrayList<String>>(); int mNum = 1000; for (String destabOp : destabMap.keySet()){ out.write("Generating stable signals with reqdVarsL as "); ArrayList <Variable> varsT = new ArrayList <Variable>(); for (String d : destabMap.get(destabOp)){ Variable input = new Variable(""); input.copy(reqdVarsL.get(findReqdVarslIndex(d))); //input.setCare(true); varsT.add(input); out.write(input.getName() + " "); } Variable output = new Variable(""); output.copy(reqdVarsL.get(findReqdVarslIndex("stable"))); output.setInput(false); output.setOutput(true); output.setCare(true); varsT.add(output); out.write(output.getName() + "\n"); LearnModel l = new LearnModel(); LhpnFile moduleLPN = l.learnModel(directory, log, biosim, mNum, thresholds, tPar, varsT, dMap, true, valScaleFactor, delayScaleFactor, null); //true parameter above indicates that the net being generated is for assigning stable // new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile); g = mergeLhpns(moduleLPN,g); mNum++; } } out.write("learning module done. Saving stuff and learning other modules.\n"); g.save(directory + separator + lhpnFile); new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile); out.write("Returning " + directory + separator + lhpnFile + "\n"); out.close(); //writeVerilogAMSFile(lhpnFile.replace(".lpn",".vams")); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "LPN file couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (NullPointerException e4) { e4.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "LPN file couldn't be created/written. Null exception", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (ArrayIndexOutOfBoundsException e1) { // comes from initMark = -1 of updateGraph() e1.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Unable to calculate rates.\nWindow size or pathLengthBin must be reduced.\nLearning unsuccessful.", "ERROR!", JOptionPane.ERROR_MESSAGE); try { out.write("ERROR! Unable to calculate rates.\nIf Window size = -1, pathLengthBin must be reduced;\nElse, reduce windowsize\nLearning unsuccessful."); out.close(); } catch (IOException e2) { e2.printStackTrace(); } } catch (java.lang.IllegalStateException e3){ e3.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "LPN File not found for merging.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return (g); } public ArrayList modeBinsCalculate(HashMap<String, ArrayList<String>> useMap, int i) { ArrayList currentBinArray = new ArrayList(); ArrayList<ArrayList> modeBinArray = new ArrayList<ArrayList>(); Set<String> useMapKeySet = useMap.keySet(); int index =0; int bin=0; for (int j=0; j<reqdVarsL.size(); j++){ Variable v = reqdVarsL.get(j); String vName = v.getName(); //****System.out.println("in mode bin calculate v : "+vName); for(int k=0; k<useMapKeySet.size(); k++){ int length =0; if(useMapKeySet.contains(vName)){ //System.out.println("no key : "); } else{ ///***System.out.println("print it ///////////// : "+v.getName()); //System.out.println("couterInMethod : "+cim); //cim++; ///***System.out.println("bin in mode : "+bins[j][i]); bin =bins[j][i]; currentBinArray.add(index, bin); //System.out.println("bin final ^^^^^^^^ : "+bin); index++; } } } return currentBinArray; } public ArrayList varsBinsCalculate(HashMap<String, ArrayList<String>> useMap, int i) { ArrayList currentBinArray = new ArrayList(); ArrayList<ArrayList> varsBinArray = new ArrayList<ArrayList>(); Set<String> useMapKeySet = useMap.keySet(); int index =0; int bin=0; for (int j=0; j<reqdVarsL.size(); j++){ Variable v = reqdVarsL.get(j); String vName = v.getName(); //System.out.println("in vars bin calculate v : "+vName); //for(int k=0; k<useMapKeySet.size(); k++){ ///int length =0; if(!useMapKeySet.contains(vName)){ //System.out.println("no key : "); } else{ //System.out.println("bin in method vars bin : "+bins[j][i]+" at time : "+i); bin =bins[j][i]; currentBinArray.add(index, bin); //System.out.println("bin final vars^^^^^^^^ : "+bin); index++; } //} } return currentBinArray; } public ArrayList returnBin(ArrayList<Object> allInfo, int i ){ ArrayList binInfo2 = (ArrayList) allInfo.get(i); ArrayList varsBinAtEnd2 = (ArrayList)binInfo2.get(1); return varsBinAtEnd2; } public int returnTime(ArrayList allInfo, int i ){ ArrayList binInfo2 = (ArrayList) allInfo.get(i); int time = (Integer) binInfo2.get(0); return time; } public double returnDuration(ArrayList allInfo, int i ){ ArrayList binInfo2 = (ArrayList) allInfo.get(i); double duration = (Double) binInfo2.get(2); return duration; } public void addStablesToData2(int[][]bins, Double[] duration, HashMap<String, ArrayList<Double>> localThresholds, HashMap<String, ArrayList<String>> useMap, ArrayList<Variable> reqdVarsL){ //System.out.println("This is useMap size : " +useMap.keySet()); //Set<String> hello = useMap.keySet(); //int hi =hello.contains(v) //System.out.println("This is hi size : " +hi); //Set<String> hello = useMap.keySet(); //System.out.println("This is hi size : " +data.get(0).size()); //for(int s=0; s<data.get(0).size(); s++){ //System.out.println("bin of ctl : "+bins[0][s]+" at time : "+s); //} //System.out.println("Bin size : " +bins.length); //for(int m=0; m<varNames.size(); m++) ////{ //System.out.println("This is varNames size : " +varNames.get(m)); //} ArrayList<Integer> modeBinAtStart; ArrayList<Integer> modeBinAtEnd; ArrayList<Integer> varsBinCurrent; ArrayList<Integer> varsBinAtEnd; int start=0; int end =0; int startMode=0; int endMode =0; //Hashtable<String, Object> binInfo = new Hashtable<String, Object>(); //Interface Set<Object> allVarsBins = new Set<Object>(); //Set wrappedSet = new HashSet<E>(); Set allVarsBins = new HashSet(); //ArrayList<Object> binInfo = new ArrayList<Object>(); ArrayList<Object> allInfo = new ArrayList<Object>(); ArrayList<Double> dataForStable = new ArrayList<Double>(); //int index=0; int count1=0; ArrayList compareBin = new ArrayList(); //System.out.println("size : "+data.get(0).size()); while (end<(data.get(0).size()-2) && endMode<(data.get(0).size()-2)) {// System.out.println("end Mode is : "+endMode); modeBinAtStart = modeBinsCalculate(useMap,startMode); //System.out.println("modeBinAtStart%%%%%%% : "+modeBinAtStart+" at time : "+startMode); modeBinAtEnd = modeBinsCalculate(useMap, endMode+1); //System.out.println("end Mode is 2: "+endMode); //System.out.println("modeBinAtEnd%%%%%%%%%%%%% : "+modeBinAtEnd+" at time "+(endMode+1)); //int whileCounter = 0; //while(modeBinAtStart==modeBinAtEnd){ while((modeBinAtStart.equals(modeBinAtEnd))&& endMode<(data.get(0).size()-2)){ //if(modeBinAtStart.equals(modeBinAtEnd)){ //****System.out.println("modeBinAtStart : "+modeBinAtStart); //System.out.println("modeBinAtEnd : "+endMode); endMode++; end++; //****System.out.println("end in while loop : "+end); //****System.out.println("time Start : "+start); //****//****System.out.println("time end : "+end); varsBinCurrent=varsBinsCalculate(useMap,start); varsBinAtEnd=varsBinsCalculate(useMap,end); if((!varsBinCurrent.equals(varsBinAtEnd)) && (duration[end]!=null)){ //if(varsBinCurrent.!=varsBinAtEnd){ //****System.out.println("varsBinCurrent : "+varsBinCurrent); //****//****System.out.println("varsBinAtEnd : "+varsBinAtEnd); //****System.out.println("*********************************************end time : "+end); ArrayList<Object> binInfo = new ArrayList<Object>(); binInfo.add(new Integer(end)); binInfo.add(varsBinAtEnd); binInfo.add(new Double(duration[end])); //if(!allVarsBins.contains(varsBinCurrent)){ //allVarsBins.add(index, new Integer(varsBinCurrent)); allVarsBins.add(varsBinAtEnd); //System.out.println("binInfo : "+binInfo); //***System.out.println("allVarsBin : "+allVarsBins); allInfo.add(count1, binInfo); //allInfo.add(binInfo); count1++; //System.out.println("allInfo : "+allInfo); start=end; } //startMode=endMode; modeBinAtStart = modeBinsCalculate(useMap,startMode); //System.out.println("modeBinAtStart%%%%%%% : "+modeBinAtStart+" at time : "+startMode); //System.out.println("end Mode+1 is : "+endMode+1); modeBinAtEnd = modeBinsCalculate(useMap, endMode+1); //System.out.println("modeBinAtEnd%%%%%%%%%%%%% : "+modeBinAtEnd+" at time "+(endMode+1)); } //} int stable = startMode; //System.out.println("STABLE ASSIGNED : "+stable); //System.out.println("allVarsBin : "+allVarsBins); //ArrayList compareBin2; Iterator itr = allVarsBins.iterator(); while (itr.hasNext()){//System.out.println("compareBin : "+itr.next()); compareBin=(ArrayList)itr.next(); //System.out.println("compareBin : "+compareBin); //System.out.println("all info size is : "+allInfo.size()); for(int i=(allInfo.size()-1);i>=0; --i){ //System.out.println("compareBin : "+compareBin); ArrayList varsBinAtEnd2 = returnBin(allInfo, i); //System.out.println("varsBinAtEnd2 : "+varsBinAtEnd2); //if(compareBin==varsBinAtEnd2){ if(compareBin.equals(varsBinAtEnd2)){ for(int m=i-1; m>=0;m--){ //int time; int time= returnTime(allInfo,m+1); //System.out.println("time : "+time); if (time<stable) break; ArrayList bin2 = returnBin(allInfo, m); //System.out.println("bin2 : "+bin2); //if (bin2==varsBinAtEnd2){ if (bin2.equals(varsBinAtEnd2)){ double duration1= returnDuration(allInfo,i); //System.out.println("duration1 : "+duration1); double duration2= returnDuration(allInfo,m); //System.out.println("duration2 : "+duration2); if(Math.abs(duration1-duration2)/duration1>0.02){ stable = time; //System.out.println("stable changed here to : "+stable); } } } break; // need to chk } } } for(int i=startMode; i<=endMode; i++){ if(i<stable){ dataForStable.add(0.0); } else { dataForStable.add(1.0); } //dataForStable.add((data.get(0).size()-1), 1.0); } //System.out.println("startMode = " + startMode + " end = " + end + " endMode = " + endMode); //System.out.println("data for stables: "+dataForStable.size()); startMode=endMode+1; endMode=startMode; } dataForStable.add((data.get(0).size()-1), 1.0); //System.out.println("data for stables: "+dataForStable.size()); int dataSize= data.size(); data.add(dataSize, dataForStable); //System.out.println("size of stable array is " + dataForStable.size()); String s= "stable"; varNames.add(s); //System.out.println("VarNames: "+varNames); //variablesList.add(s); /*reqdVarsL.add(new Variable(s)); for(int m=0; m<reqdVarsL.size(); m++) { System.out.println("This is varNames size : " +reqdVarsL.get(m).getName()); }*/ Variable vStable = new Variable("stable"); vStable.setCare(true); vStable.setDmvc(true); vStable.forceDmvc(true); vStable.setEpsilon(0.1); // since stable is always 0 or 1 and threshold is 0.5. even epsilon of 0.3 is fine vStable.setInput(true); vStable.setOutput(false); // varsWithStables.add(vStable); reqdVarsL.add(vStable); // findReqdVarIndices(); ArrayList<Double> tStable = new ArrayList<Double>(); tStable.add(0.5); thresholds.put(s, tStable); /*for(int m=0; m<reqdVarsL.size(); m++) { System.out.println("This is reqdVarsL : " +reqdVarsL.get(m).getName()); }*/ //System.out.println("This is threshold : " +thresholds); } public void addStablesToData(HashMap<String, ArrayList<Double>> localThresholds, HashMap<String, ArrayList<String>> useMap){ boolean sameBin = true; ArrayList<String> destabIps; HashMap<String, Integer> dataIndices; int point; for (String s : useMap.keySet()){ // destabIps = new ArrayList<String>(); // destabIps.add("ctl"); destabIps = useMap.get(s); dataIndices = new HashMap<String, Integer>(); for (int i = 0; i < destabIps.size(); i++) { String currentVar = destabIps.get(i);//reqdVarsL.get(i).getName(); for (int j = 1; j < varNames.size(); j++) { if (currentVar.equalsIgnoreCase(varNames.get(j))) { dataIndices.put(currentVar,Integer.valueOf(j)); } } } //int[] oldBin = new int[destabIps.size()]; //int[] newBin = new int[destabIps.size()]; int[] oldBin = new int[dataIndices.size()]; int[] newBin = new int[dataIndices.size()]; //double unstableTime = 5960.0; ArrayList<Double> dataForStable = new ArrayList<Double>(); point = 0; dataForStable.add(0.0); //Assume that always it starts unstable for (int j = 0; j < destabIps.size(); j++){ String d = destabIps.get(j); if (dataIndices.containsKey(d)) oldBin[j] = getRegion(data.get(dataIndices.get(d)).get(point),localThresholds.get(d)); } for (int i = point+1; i < data.get(0).size(); i++){ sameBin = true; for (int j = 0; j < destabIps.size(); j++){// check if all the responsible destabilizing variables are in the same bin at i as they were at point String d = destabIps.get(j); if (dataIndices.containsKey(d)){ newBin[j] = getRegion(data.get(dataIndices.get(d)).get(i),localThresholds.get(d)); if (oldBin[j] != newBin[j]){ sameBin = false; break; } } } if ((sameBin) && (dataIndices.size() != 0)){ if ((data.get(0).get(i) - data.get(0).get(point)) >= unstableTime){ //dataForStable.set(i, 1.0); dataForStable.add(1.0); } else { //dataForStable.set(i, 0.0); dataForStable.add(0.0); } } else { //dataForStable.set(i, 0.0); dataForStable.add(0.0); for (int j = 0; j < destabIps.size(); j++){ String d = destabIps.get(j); if (dataIndices.containsKey(d)) oldBin[j] = getRegion(data.get(dataIndices.get(d)).get(point),localThresholds.get(d)); } point = i; } } if (dataIndices.size() != 0){ data.add(dataForStable); varNames.add("stable_" + s); } } } public Double getDelayScaleFactor(){ return delayScaleFactor; } public Double getValueScaleFactor(){ return valScaleFactor; } private int findReqdVarslIndex(String s) { for (int i = 0; i < reqdVarsL.size() ; i++){ if (s.equalsIgnoreCase(reqdVarsL.get(i).getName())){ return i; } } return -1; } private boolean isTransientPlace(String st1) { for (String s : transientNetPlaces.keySet()){ if (st1.equalsIgnoreCase("p" + transientNetPlaces.get(s).getProperty("placeNum"))){ return true; } } return false; } private boolean isTransientTransition(String st1) { for (String s : transientNetTransitions.keySet()){ if (st1.equalsIgnoreCase("t" + transientNetTransitions.get(s).getProperty("transitionNum"))){ return true; } } return false; } public void resetAll(){ // dmvcCnt = 0; numPlaces = 0; numTransitions = 0; delayScaleFactor = 1.0; valScaleFactor = 1.0; for (Variable v: reqdVarsL){ v.reset(); } } public void findReqdVarIndices(){ reqdVarIndices = new ArrayList<Integer>(); for (int i = 0; i < reqdVarsL.size(); i++) { for (int j = 1; j < varNames.size(); j++) { if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) { reqdVarIndices.add(j); } } } } public int getCareIndex(int reqdVarsIndex){ int count = -1; for (int j = 0; j < reqdVarsL.size(); j++){ if (reqdVarsL.get(j).isCare()){ count++; } if (j == reqdVarsIndex) return count; } return -1; } public void addInitPlace(HashMap<String,ArrayList<Double>> scaledThresholds){ //Properties initPlace = new Properties(); //placeInfo.put("initMarked", p0); //initPlace.setProperty("placeNum", numPlaces.toString()); //initPlace.setProperty("type", "INIT"); //initPlace.setProperty("initiallyMarked", "true"); int initPlaceNum = numPlaces; g.addPlace("p" + numPlaces, true); //propPlaces.add("p" + numPlaces); numPlaces++; try{ try{ out.write("Transient places are : "); for (String st : transientNetPlaces.keySet()){ out.write(st + ";"); } out.write("\n"); for (String st : transientNetPlaces.keySet()){ //Properties p1 = new Properties(); //p1.setProperty("transitionNum", numTransitions.toString()); //initTransitions.put(key, p1); //from initPlaceNum to key g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + initPlaceNum, "t" + numTransitions); g.addMovement("t" + numTransitions, "p" + transientNetPlaces.get(st).getProperty("placeNum")); g.changeInitialMarking("p" + transientNetPlaces.get(st).getProperty("placeNum"), false); out.write("Added transition t" + numTransitions + " b/w initPlace and transient place p" + transientNetPlaces.get(st).getProperty("placeNum") + "\n"); String[] binOutgoing = st.split(","); String condStr = ""; for (int j = 0; j < reqdVarsL.size(); j++){ // preserving the order by having reqdVarsL as outer loop rather than care String st2 = reqdVarsL.get(j).getName(); if (reqdVarsL.get(j).isCare()){ if (reqdVarsL.get(j).isInput()){ int bin = Integer.valueOf(binOutgoing[getCareIndex(j)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st2).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")&~(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } else { if (reqdVarsL.get(j).isDmvc()){ int minv = (int) Math.floor(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMax"))); if (minv != maxv) g.addIntAssign("t" + numTransitions,st2,"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign("t" + numTransitions,st2,String.valueOf(minv)); out.write("Added assignment to " + st2 + " at transition t" + numTransitions + "\n"); } // deal with rates for continuous here } } else { out.write(st2 + " was don't care " + "\n"); } } out.write("Changed enabling of t" + numTransitions + " to " + condStr + "\n"); g.addEnabling("t" + numTransitions, condStr); numTransitions++; } for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace. if (st1.size() != 0){ g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + initPlaceNum, "t" + numTransitions); for (String st2: st1.keySet()){ g.addIntAssign("t" + numTransitions,st2,st1.get(st2)); } numTransitions++; } } } catch (NullPointerException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Null exception in addInitPlace.", "ERROR!", JOptionPane.ERROR_MESSAGE); out.close(); } }catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened in addInitPlace.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void genBinsRates(HashMap<String, ArrayList<Double>> localThresholds) { // TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false); // genBins data = tsd.getData(); try{ reqdVarIndices = new ArrayList<Integer>(); //careBins = new HashMap<String, int[]>();//new int[reqdVarsL.size()][data.get(0).size()]; bins = new int[reqdVarsL.size()][data.get(0).size()]; for (int i = 0; i < reqdVarsL.size(); i++) { // System.out.println("Divisions " + divisionsL.get(i)); for (int j = 1; j < varNames.size(); j++) { String currentVar = reqdVarsL.get(i).getName(); if (currentVar.equalsIgnoreCase(varNames.get(j))) { // System.out.println(reqdVarsL.get(i) + " matched "+ // varNames.get(j) + " i = " + i + " j = " + j); reqdVarIndices.add(j); for (int k = 0; k < data.get(j).size(); k++) { // System.out.print(data.get(j).get(k) + " "); ArrayList<Double> thresh = localThresholds.get(currentVar); bins[i][k] = getRegion(data.get(j).get(k),thresh); if ((k != 0) && (bins[i][k] != bins[i][k-1])){ int length = 0; for (int m = k; m < data.get(j).size(); m++) { if (getRegion(data.get(j).get(m),thresh) == bins[i][k]) length++; else break; } if (length < pathLengthVar){ out.write("Short bin for variable " + currentVar + " at " + data.get(0).get(k) + " until " + data.get(0).get(k+length-1) + " due to min pathLengthVar. Using " + bins[i][k-1] + " instead of " + bins[i][k] + " \n"); for (int m = k; m < k+length; m++) { bins[i][m] = bins[i][k-1]; } } else { for (int m = k; m < k+length; m++) { bins[i][m] = bins[i][k]; } } k = k+length-1; } } if (binError) JOptionPane.showMessageDialog(BioSim.frame, "Bin couldn't be retrieved for a point. Please check thresholds.", "ERROR!", JOptionPane.ERROR_MESSAGE); // System.out.print(" "); break; } else { out.write("WARNING: A variable in reqdVarsL wasn't found in the complete list of names.\n"); } } } /* * System.out.println("array bins is :"); for (int i = 0; i < * reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + " * "); for (int k = 0; k < data.get(0).size(); k++) { * System.out.print(bins[i][k] + " "); } System.out.print("\n"); } */ // genRates rates = new Double[reqdVarsL.size()][data.get(0).size()]; values = new double[reqdVarsL.size()][data.get(0).size()]; duration = new Double[data.get(0).size()]; int mark, k, previous = 0, markFullPrev; // indices of rates not same as that of the variable. if // wanted, then size of rates array should be varNames // not reqdVars if (rateSampling == -1) { // replacing inf with -1 since int mark = 0; markFullPrev = 0; for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } markFullPrev = mark; //while ((mark < data.get(0).size()) && (compareBins(i, mark))) { while (mark < data.get(0).size()){ if (compareBins(i, mark)){ for (int j = 0; j < reqdVarsL.size(); j++){ k = reqdVarIndices.get(j); values[j][i] = (values[j][i]*(mark-i) + data.get(k).get(mark))/(mark-i+1); } mark++; } else break; //Assume that only inputs can be don't care if (!compareFullBinInputs(markFullPrev, mark-1)){ //mark-1 because of mark++ above markFullPrev = mark-1; } } if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLengthBin) && (mark != data.get(0).size())) { // && (mark != (data.get(0).size() - 1 condition added on nov 23.. to avoid the last region bcoz it's not complete. rechk if (!compareBins(previous,i)){ for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } //duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 duration[i] = data.get(0).get(mark) - data.get(0).get(markFullPrev); previous = i; if (markFullPrev != i) out.write("Some don't care input change in b/w a bin. So referencing off " + markFullPrev + " instead of " + i + "\n"); } else{ // There was a glitch and you returned to the same region for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous))); } if (mark < data.get(0).size()) //This if condition added to fix bug on sept 25 2010 duration[previous] = data.get(0).get(mark) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010 } } else if ((mark - i) < pathLengthBin) { // account for the glitch duration // out.write("Short bin at " + data.get(0).get(i) + " until " + data.get(0).get(mark) + " due to min pathLengthBin. This delay being added to " + previous + " \n"); duration[previous] += data.get(0).get(mark) - data.get(0).get(i); } else if (data.get(0).get(mark - 1) == data.get(0).get(i)){ // bin with only one point. Added this condition on June 9,2010 //Rates are meaningless here since the bin has just one point. //But calculating the rate because if it is null, then places won't be created in genBinsRates for one point bins. //Calculating rate b/w start point of next bin and start point of this bin out.write("Bin with one point at time " + data.get(0).get(i) + "\n"); for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark) - data.get(k).get(i)) / (data.get(0).get(mark) - data.get(0).get(i))); } duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 previous = i; } else if (mark == data.get(0).size()){ // long enough bin towards the end of trace. if (!compareBins(previous,i)){ for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } //duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 previous = i; } else{ // There was a glitch and you returned to the same region //Or signal is constant through out the trace for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous))); } //This duration shouldn't make any sense because there's no following transition duration[previous] = data.get(0).get(mark - 1) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010 } out.write("Bin at end of trace starts at " + previous + "\n"); } } } else { //TODO: This may have bugs in duration calculation etc. boolean calcRate; boolean prevFail = true; int binStartPoint = 0, binEndPoint = 0; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { calcRate = true; for (int l = 0; l < rateSampling; l++) { if (!compareBins(i, i + l)) { if (!prevFail){ binEndPoint = i -2 + rateSampling; duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint); } calcRate = false; prevFail = true; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } if (prevFail){ binStartPoint = i; } prevFail = false; } } // commented on nov 23. don't need this. should avoid rate calculation too for this region. but not avoiding now. /* if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint); }*/ } } catch (NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Bins/Rates could not be generated. Please check thresholds.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing genBinsRates messages.", "ERROR!", JOptionPane.ERROR_MESSAGE); } /*try { for (int i = 0; i < (data.get(0).size()); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); out.write(data.get(k).get(i) + " ");// + bins[j][i] + " " + // rates[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(bins[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(rates[j][i] + " "); } out.write(duration[i] + " "); out.write("\n"); } } catch (IOException e) { System.out .println("Log file couldn't be opened for writing rates and bins "); }*/ } public int getRegion(double value, ArrayList<Double> varThresholds){ int bin = 0; try{ for (int l = 0; l < varThresholds.size(); l++) { if (value <= varThresholds.get(l)) { bin = l; break; } else { bin = l + 1; } } } catch (NullPointerException e){ e.printStackTrace(); binError = true; } return bin; } public boolean compareBins(int j, int mark) { /*for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true;*/ /*for (String st : careVars) { // this way only when order of cares not important. since this is a hashmap if (bins[findReqdVarslIndex(st)][j]!= bins[findReqdVarslIndex(st)][mark]) { return false; } else { continue; } } return true;*/ for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isCare()){ if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } } return true; } public boolean compareFullBinInputs(int j, int mark) { for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isInput() && (bins[i][j] != bins[i][mark])) { return false; } else { continue; } } return true; } public void updateRateInfo(int[][] bins, Double[][] rates, int traceNum, Properties cvgProp) { String prevPlaceKey = "", prevPlaceFullKey = ""; // "" or " " ; rechk String key = "", fullKey = ""; Double prevPlaceDuration = null; String transId = null; Boolean prevIpChange = false, prevOpChange = false, ipChange = false, opChange = false, careIpChange = false; // boolean addNewPlace; ArrayList<String> ratePlaces = new ArrayList<String>(); // ratePlaces can include non-input dmv places. // boolean newRate = false; try{ Properties p0, p1 = null; out.write("In UpdateRateInfo\n"); for (int i = 0; i < (data.get(0).size() - 1); i++) { if (rates[0][i] != null) { // check if indices are ok. 0???? or 1??? prevPlaceKey = key; prevPlaceFullKey = fullKey; key = ""; fullKey = ""; //Full keys are for transitions; Just Keys are for Places for (int j = 0; j < reqdVarsL.size(); j++) { if (reqdVarsL.get(j).isCare()){ if (key.equalsIgnoreCase("")) key += bins[j][i]; else key += "," + bins[j][i]; } if (fullKey.equalsIgnoreCase("")) fullKey += bins[j][i]; else fullKey += "," + bins[j][i]; } out.write("Rates not null at " + i + "; key is " + key + "; full key is " + fullKey + ";\n"); if (placeInfo.containsKey(key) && (ratePlaces.size() != 0)) { p0 = placeInfo.get(key); out.write("Came back to existing place p" + p0.getProperty("placeNum") + " at time " + data.get(0).get(i) + " bins " + key + "\n"); if (traceNum > 1) ratePlaces.add("p" + p0.getProperty("placeNum")); } else if ((transientNetPlaces.containsKey(key)) && (((ratePlaces.size() == 1) && (traceNum == 1)) || ((ratePlaces.size() == 0) && (traceNum != 1)))){ // same transient in new trace => ratePlaces.size() < 1; same transient in same trace => ratePlaces.size() = 1 p0 = transientNetPlaces.get(key); out.write("Came back to existing transient place p" + p0.getProperty("placeNum") + " at time " + data.get(0).get(i) + " bins " + key + "\n"); if (ratePlaces.size() == 0){ // new trace ratePlaces.add("p" + p0.getProperty("placeNum")); } } else { p0 = new Properties(); if (ratePlaces.size() == 0){ transientNetPlaces.put(key, p0); g.addPlace("p" + numPlaces, true); } else{ placeInfo.put(key, p0); g.addPlace("p" + numPlaces, false); } p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","false"); // REMOVE LATER????? ratePlaces.add("p" + numPlaces); out.write("New place p" + numPlaces + " at time " + data.get(0).get(i) + " bins " + key + "\n"); numPlaces++; cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } for (int j = 0; j < reqdVarsL.size(); j++) { // rechk if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { // continue; // } if (reqdVarsL.get(j).isDmvc()) { // && !reqdVarsL.get(j).isInput()){ //System.out.println(reqdVarsL.get(j).getName() + " " + bins[j][i] + " " + dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i]))"\n"); out.write("Add value : " + reqdVarsL.get(j).getName() + " -> corresponding to bin " + bins[j][i] + " at place p" + p0.getProperty("placeNum") + "\n"); out.write("Add value : " + reqdVarsL.get(j).getName() + " -> " + Double.valueOf(dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i]))) + " at place p" + p0.getProperty("placeNum") + "\n"); addValue(p0,reqdVarsL.get(j).getName(),Double.valueOf(dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i])))); //out.write("Add value : " + reqdVarsL.get(j).getName() + " -> " + dmvcValuesUnique.get(reqdVarsL.get(j).getName()).get(bins[j][i]) + " at place p" + p0.getProperty("placeNum") + "\n"); continue; } addRate(p0, reqdVarsL.get(j).getName(), rates[j][i]); } boolean transientNet = false; if (!prevPlaceFullKey.equalsIgnoreCase(fullKey)) { if (!prevPlaceFullKey.equals("")){ ArrayList<Integer> diffL = diff(prevPlaceFullKey,fullKey); opChange = false; ipChange = false; careIpChange = false; for (int k : diffL) { if (reqdVarsL.get(k).isInput()) { ipChange = true; if (reqdVarsL.get(k).isCare()) careIpChange = true; } else { opChange = true; } } } else { ipChange = false; opChange = false; careIpChange = false; } if ((traceNum > 1) && transientNetTransitions.containsKey(prevPlaceFullKey + "," + fullKey) && (ratePlaces.size() == 2)) { // same transient transition as that from some previous trace p1 = transientNetTransitions.get(prevPlaceFullKey + "," + fullKey); transId = prevPlaceFullKey + "," + fullKey; out.write("Came back to existing transient transition t" + p1.getProperty("transitionNum") + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); } else if (transitionInfo.containsKey(prevPlaceFullKey + "," + fullKey) && (ratePlaces.size() > 2)) { // instead of tuple p1 = transitionInfo.get(prevPlaceFullKey + "," + fullKey); transId = prevPlaceFullKey + "," + fullKey; out.write("Came back to existing transition t" + p1.getProperty("transitionNum") + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); } else if (!prevPlaceFullKey.equalsIgnoreCase("")) { // transition = new Transition(reqdVarsL.size(),place,prevPlace); p1 = new Properties(); p1.setProperty("transitionNum", numTransitions.toString()); if (ratePlaces.size() == 2){ transientNetTransitions.put(prevPlaceFullKey + "," + fullKey, p1); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + transientNetPlaces.get(prevPlaceKey).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); transientNet = true; transId = prevPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } else { if (prevIpChange & !prevOpChange & opChange & !ipChange){ out.write("Should delete the transition" + transId+ " from "); if (transitionInfo.containsKey(transId)){ out.write("transitionInfo\n"); int removeTrans = Integer.valueOf(transitionInfo.get(transId).getProperty("transitionNum")); String lastLastPlace = g.getTransition("t" + removeTrans).getPreset()[0].getName(); //String lastLastPlaceKey = getPlaceInfoIndex(lastLastPlace); String lastLastPlaceFullKey = getPresetPlaceFullKey(transId); if (transitionInfo.containsKey(lastLastPlaceFullKey + "," + fullKey)){ p1 = transitionInfo.get(lastLastPlaceFullKey + "," + fullKey); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transitionInfo.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nFound an output change follwing a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and p" + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; merged transition already exists in the form of t" + p1.getProperty("transitionNum") + " b/w " + lastLastPlace + " and p" + placeInfo.get(key).getProperty("placeNum") + "\n"); transitionInfo.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; } else { transitionInfo.put(lastLastPlaceFullKey + "," + fullKey, p1); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transitionInfo.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement(lastLastPlace, "t" + transitionInfo.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nFound an output change follwing a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; add transition t" + numTransitions + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transitionInfo.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } else if (transientNetTransitions.containsKey(transId)){ out.write("transientNetTransitions\n"); int removeTrans = Integer.valueOf(transientNetTransitions.get(transId).getProperty("transitionNum")); String lastLastPlace = g.getTransition("t" + removeTrans).getPreset()[0].getName(); //String lastLastPlaceKey = getTransientNetPlaceIndex(lastLastPlace); String lastLastPlaceFullKey = getPresetPlaceFullKey(transId); if (transientNetTransitions.containsKey(lastLastPlaceFullKey + "," + fullKey)){ p1 = transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transientNetTransitions.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nTRANSIENT:Found an output change followed by a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; merged transition already exists in the form of t" + p1.getProperty("transitionNum") + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transientNetTransitions.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; } else { transientNetTransitions.put(lastLastPlaceFullKey + "," + fullKey, p1); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transientNetTransitions.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement(lastLastPlace, "t" + transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nTRANSIENT:Found an output change followed by a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; add transition t" + numTransitions + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transientNetTransitions.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; out.write("TRANSIENT:New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } else { out.write("transition " + transId+ " not present to delete\n"); System.out.println("transition " + transId+ " not present to delete\n"); } } else { transitionInfo.put(prevPlaceFullKey + "," + fullKey, p1); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(prevPlaceKey).getProperty("placeNum"), "t" + transitionInfo.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); transId = prevPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } // transition.setCore(true); } prevIpChange = ipChange; prevOpChange = opChange; //else if (prevPlaceKey == "") { // p1 = new Properties(); // p1.setProperty("transitionNum", numTransitions.toString()); // initTransitions.put(key, p1); //from initPlaceNum to key // g.addTransition("t" + numTransitions); // prevTranKey+key); // g.addMovement("p" + transientNetPlaces.get(prevPlaceKey).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum")); // g.addMovement("t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // numTransitions++; //} if (prevPlaceDuration != null){ //Delay on a transition is the duration spent at its preceding place /*if (!(ipChange & opChange)){ addDuration(p1, prevPlaceDuration); out.write(" Added duration " + prevPlaceDuration + " to transition t" + p1.getProperty("transitionNum") + "\n"); } else{ addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); }*/ if (!opChange){ //Commented above and changed to this on Aug 5,2010. When there's no o/p bin change, then thrs no need for delay. addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); } else if (careIpChange){ // Both o/p and a care i/p changed on the same transition. So, they changed at the same time. addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); } else { //o/p change alone or (o/p change and don't care i/p change) addDuration(p1, prevPlaceDuration); out.write(" Added duration " + prevPlaceDuration + " to transition t" + p1.getProperty("transitionNum") + "\n"); } } else { out.write(" Not adding duration here. CHECK\n"); } } prevPlaceDuration = duration[i]; /*if (duration[i] != null){ //STORING DELAYS AT TRANSITIONS NOW addDuration(p0, duration[i]); }*/ //else if (duration[i] != null && transientNet){ // addTransientDuration(p0, duration[i]); //} if (p1 != null) { for (int j = 0; j < reqdVarsL.size(); j++) { if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { continue; } if (reqdVarsL.get(j).isDmvc()) { continue; } addRate(p1, reqdVarsL.get(j).getName(), rates[j][i]); } } } } }catch (IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing UpdateRateInfo messages.", "ERROR!", JOptionPane.ERROR_MESSAGE); }catch (NullPointerException e4) { e4.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Null exception during model generation in updateRate", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public String getPresetPlaceFullKey(String transition){ //out.write("preset key for " + transition + " is "); String fullKey = ""; if (transition != null){ String[] b = transition.split(","); for (int j = 0; j < reqdVarsL.size(); j++) { if (fullKey.equalsIgnoreCase("")) fullKey += b[j]; else fullKey += "," + b[j]; } //out.write(fullKey + "\n"); return(fullKey); } else return null; } public String getPostsetPlaceFullKey(String transition){ String fullKey = ""; if (transition != null){ String[] b = transition.split(","); for (int j = 0; j < reqdVarsL.size(); j++) { if (fullKey.equalsIgnoreCase("")) fullKey += b[j + reqdVarsL.size()]; else fullKey += "," + b[j + reqdVarsL.size()]; } return(fullKey); } else return null; } public void updateGraph(int[][] bins, Double[][] rates, int traceNum, Properties cvgProp) { updateRateInfo(bins, rates, traceNum, cvgProp); //updateTimeInfo(bins,cvgProp); int initMark = -1; int k; String key; constVal.add(new HashMap<String, String>()); for (int i = 0; i < reqdVarsL.size(); i++) { for (int j = 0; j < data.get(0).size(); j++) { if (rates[i][j] != null) { k = reqdVarIndices.get(i); // addInitValues(data.get(k).get(j), i); // k or i think ?? // addInitRates(rates[i][j], i);// k or i think?? reqdVarsL.get(i).addInitValues(data.get(k).get(j)); // Do the same for initvals too?? //reqdVarsL.get(i).addInitRates(rates[i][j]); // this just adds the first rate; not the rates of entire 1st region. initMark = j; break; } } if (initMark == -1){//constant throughout the trace? initMark = 0; k = reqdVarIndices.get(i); constVal.get(constVal.size() - 1).put(reqdVarsL.get(i).getName(),data.get(k).get(0).toString()); reqdVarsL.get(i).addInitValues(data.get(k).get(0)); } key = "" + bins[0][initMark]; for (int l = 1; l < reqdVarsL.size(); l++) { // key = key + "" + bins[l][initMark]; key = key + "," + bins[l][initMark]; } if (!reqdVarsL.get(i).isDmvc()){ reqdVarsL.get(i).addInitRates((double)getMinRate(key, reqdVarsL.get(i).getName())); reqdVarsL.get(i).addInitRates((double)getMaxRate(key, reqdVarsL.get(i).getName())); } /* if (placeInfo.get(key).getProperty("initiallyMarked").equalsIgnoreCase("false")) { placeInfo.get(key).setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + placeInfo.get(key).getProperty("placeNum"), true); } */ } } public HashMap<String, ArrayList<Double>> detectDMV(ArrayList<ArrayList<Double>> data, Boolean callFromAutogen) { int startPoint, endPoint, mark, numPoints; HashMap<String, ArrayList<Double>> dmvDivisions = new HashMap<String, ArrayList<Double>>(); double absTime; //dmvcValuesUnique = new HashMap<String, ArrayList<Double>>(); try{ for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isForcedCont()){ reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is forced to be continuous \n"); } else { absTime = 0; mark = 0; DMVCrun runs = reqdVarsL.get(i).getRuns(); runs.clearAll(); // flush all the runs from previous dat file. int lastRunPointsWithoutTransition = 0; Double lastRunTimeWithoutTransition = 0.0; Double lastRunValueWithoutTransition = null; out.write("Epsilon for " + reqdVarsL.get(i).getName() + " is " + reqdVarsL.get(i).getEpsilon()); if (!callFromAutogen) { // This flag is required because if the call is from autogenT, then data has just the reqdVarsL but otherwise, it has all other vars too. So reqdVarIndices not reqd when called from autogen for (int j = 0; j <= data.get(reqdVarIndices.get(i)).size(); j++) { // changed from data.get(0).size() to data.get(reqdVarIndices.get(i)).size() on july 31,2010. if (j < mark) // not reqd?? continue; if (((j+1) < data.get(reqdVarIndices.get(i)).size()) && Math.abs(data.get(reqdVarIndices.get(i)).get(j) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon()) { startPoint = j; runs.addValue(data.get(reqdVarIndices.get(i)).get(j)); // chk carefully reqdVarIndices.get(i) while (((j + 1) < data.get(0).size()) && (bins[i][startPoint] == bins[i][j+1]) && (Math.abs(data.get(reqdVarIndices.get(i)).get(startPoint) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon())) { //checking of same bins[] condition added on May 11,2010. runs.addValue(data.get(reqdVarIndices.get(i)).get(j + 1)); // chk carefully // reqdVarIndices.get(i) j++; } endPoint = j; if (!absoluteTime) { if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); } else if (((endPoint - startPoint) + 1) >= runLength) { lastRunPointsWithoutTransition = endPoint - startPoint + 1; lastRunValueWithoutTransition = runs.getLastValue(); } else { runs.removeValue(); } } else { if ((endPoint < (data.get(0).size() - 1)) && (calcDelay(startPoint, endPoint) >= runTime)) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); absTime += calcDelay(startPoint, endPoint); } else if (calcDelay(startPoint, endPoint) >= runTime) { lastRunTimeWithoutTransition = calcDelay(startPoint, endPoint); lastRunValueWithoutTransition = runs.getLastValue(); } else { runs.removeValue(); } } mark = endPoint; } } numPoints = runs.getNumPoints(); if (!reqdVarsL.get(i).isForcedDmv() && ((absoluteTime && (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data .get(0).get(0))) < percent)) || (!absoluteTime && (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent)))){ // isForced condition added on may 28 runs.clearAll(); reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n"); } else { reqdVarsL.get(i).setDmvc(true); Double[] dmvcValues; if (lastRunValueWithoutTransition != null ){ Double[] dVals = reqdVarsL.get(i).getRuns().getAvgVals(); dmvcValues = new Double[dVals.length + 1]; for (int j = 0; j < dVals.length; j++){ dmvcValues[j] = dVals[j]; } dmvcValues[dVals.length] = lastRunValueWithoutTransition; } else dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals(); Arrays.sort(dmvcValues); //System.out.println("Sorted DMV values of " + reqdVarsL.get(i).getName() + " are "); //for (Double l : dmvcValues){ // System.out.print(l + " "); //} //System.out.println(); if (!dmvcValuesUnique.containsKey(reqdVarsL.get(i).getName())) dmvcValuesUnique.put(reqdVarsL.get(i).getName(),new Properties()); out.write("DMV values of " + reqdVarsL.get(i).getName() + " are : "); if (dmvcValues.length == 0){// constant value throughout the trace dmvcValues = new Double[1]; dmvcValues[0]= reqdVarsL.get(i).getRuns().getConstVal(); } for (int j = 0; j < dmvcValues.length; j++){ if (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(0)){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put("0",dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin 0 is " + dmvcValues[j] + "\n"); out.write("bin 0 -> " + dmvcValues[j] + "; "); } else if (dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(thresholds.get(reqdVarsL.get(i).getName()).size() - 1)){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(thresholds.get(reqdVarsL.get(i).getName()).size()),dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + thresholds.get(reqdVarsL.get(i).getName()).size() + " is " + dmvcValues[j] + "\n"); out.write("bin " + thresholds.get(reqdVarsL.get(i).getName()).size() + " -> " + dmvcValues[j] + "; "); } else { for (int k = 0; k < thresholds.get(reqdVarsL.get(i).getName()).size()-1; k++){ if ((dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(k)) && (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(k+1))){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(k+1),dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + String.valueOf(k+1) + " is " + dmvcValues[j] + "\n"); out.write("bin " + (k+1) + " -> " + dmvcValues[j] + "; "); break; } } } //out.write(dmvcValues[j] + " "); //following not needed for calls from data2lhpn // dmvSplits.add((dmvcValuesUnique.get(reqdVarsL.get(i).getName()).get(dmvcValuesUnique.get(reqdVarsL.get(i).getName()).size() - 1) + dmvcValuesUnique.get(reqdVarsL.get(i).getName()).get(dmvcValuesUnique.get(reqdVarsL.get(i).getName()).size() - 2))/2); //} //for (int k = j+1; k < dmvcValues.length; k++){ // if (Math.abs((dmvcValues[j] - dmvcValues[k])) > epsilon){ // j = k-1; // break; // } // else if (k >= (dmvcValues.length -1)){ // j = k; // } //} } //dmvDivisions.put(reqdVarsL.get(i).getName(), dmvSplits); out.write("\n" + reqdVarsL.get(i).getName() + " is a dmvc \n"); } } } } }catch (IOException e) { e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } dmvDetectDone = true; return(dmvDivisions); } public double calcDelay(int i, int j) { return (data.get(0).get(j) - data.get(0).get(i)); // should add some next run logic later..? } public double calcDelayWithData(int i, int j, ArrayList<ArrayList<Double>> data) { return (data.get(0).get(j) - data.get(0).get(i)); } public void addValue(Properties p, String name, Double v) { Double vMin; Double vMax; if ((p.getProperty(name + "_vMin") == null) && (p.getProperty(name + "_vMax") == null)) { p.setProperty(name + "_vMin", v.toString()); p.setProperty(name + "_vMax", v.toString()); return; } else { vMin = Double.parseDouble(p.getProperty(name + "_vMin")); vMax = Double.parseDouble(p.getProperty(name + "_vMax")); if (v < vMin) { vMin = v; } else if (v > vMax) { vMax = v; } } p.setProperty(name + "_vMin", vMin.toString()); p.setProperty(name + "_vMax", vMax.toString()); } public void addRate(Properties p, String name, Double r) { Double rMin; Double rMax; if ((p.getProperty(name + "_rMin") == null) && (p.getProperty(name + "_rMax") == null)) { p.setProperty(name + "_rMin", r.toString()); p.setProperty(name + "_rMax", r.toString()); return; } else { rMin = Double.parseDouble(p.getProperty(name + "_rMin")); rMax = Double.parseDouble(p.getProperty(name + "_rMax")); if (r < rMin) { rMin = r; } else if (r > rMax) { rMax = r; } } p.setProperty(name + "_rMin", rMin.toString()); p.setProperty(name + "_rMax", rMax.toString()); } public void deleteInvalidDmvcTime(Properties p, Double t) { String[] times = null; String name = p.getProperty("DMVCVariable"); String s = p.getProperty("dmvcTime_" + name); String newS = null; Double dMin = null, dMax = null; if (s != null) { times = s.split(" "); for (int i = 0; i < times.length; i++) { if (Double.parseDouble(times[i]) != t) { if (newS == null){ newS = times[i]; dMin = Double.parseDouble(times[i]); dMax = Double.parseDouble(times[i]); } else{ newS += " " + times[i]; dMin = (Double.parseDouble(times[i]) < dMin) ? Double.parseDouble(times[i]) : dMin; dMax = (Double.parseDouble(times[i]) > dMax) ? Double.parseDouble(times[i]) : dMax; } } } p.setProperty("dmvcTime_" + name, newS); } if (dMin != null){ p.setProperty("dMin", dMin.toString()); p.setProperty("dMax", dMax.toString()); } } public HashMap<String,ArrayList<Double>> normalize() { HashMap<String,ArrayList<Double>> scaledThresholds = new HashMap<String,ArrayList<Double>>(); Boolean contVarExists = false; for (Variable v : reqdVarsL){ if (!v.isDmvc()){ contVarExists = true; } } // deep copy of divisions for (String s : thresholds.keySet()){ ArrayList<Double> o1 = thresholds.get(s); ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } scaledThresholds.put(s,tempDiv); } Double minDelay = getMinDelay(); Double maxDelay = getMaxDelay(); Double minDivision = getMinDiv(scaledThresholds); Double maxDivision = getMaxDiv(scaledThresholds); Double scaleFactor = 1.0; try { if ((valScaleFactor == -1.0) && (delayScaleFactor == -1.0)){ out.write("\nAuto determining both value and delay scale factors\n"); valScaleFactor = 1.0; delayScaleFactor = 1.0; out.write("minimum delay is " + minDelay + " before scaling time.\n"); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } out.write("minimum delay is " + scaleFactor * minDelay + "after scaling by " + scaleFactor + "\n"); delayScaleFactor = scaleFactor; scaleDelay(delayScaleFactor); } if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Rate Scaling has caused an overflow"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor = scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Division Scaling has caused an overflow"); } out.write("minimum division is " + minDivision * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor *= scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } }*/ // END TEMPORARY } } else if (valScaleFactor == -1.0){ //force delayScaling; automatic varScaling out.write("\nAuto determining value scale factor; Forcing delay scale factor\n"); valScaleFactor = 1.0; out.write("minimum delay is " + minDelay + " before scaling time.\n"); /*if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } if (scaleFactor > delayScaleFactor){ out.write("WARNING: Minimum delay won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); delayScaleFactor = scaleFactor; } //else delayScaleFactor = delayScaleFactor (user provided) scaleDelay(delayScaleFactor); } else { scaleDelay(delayScaleFactor);// Even if we can't calculate delayScaleFactor, use user provided one whatever it is out.write("min delay = 0. So, not checking whether the given delayScalefactor is correct\n"); }*/ out.write("minimum delay is " + delayScaleFactor * minDelay + "after scaling by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by // magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Rate Scaling has caused an overflow"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor = scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Division Scaling has caused an overflow"); } out.write("minimum division is " + minDivision * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor *= scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } }*/ // END TEMPORARY } } else if (delayScaleFactor == -1.0){ //force valueScaling; automatic delayScaling out.write("\nAuto determining delay scale factor; Forcing value scale factor\n"); //May be wrong in some cases delayScaleFactor = 1.0; minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); /*scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { out.write("ERROR: Division Scaling has caused an overflow"); } if (scaleFactor > valScaleFactor){ out.write("WARNING: Minimum threshold won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); valScaleFactor = scaleFactor; } out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // END TEMPORARY } else { scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("Min division is 0. So, not checking whether given value scale factor is correct"); }*/ scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { out.write("Rate Scaling has caused an overflow\n"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling delay by " + 1/scaleFactor + "\n"); scaleDelay(1/scaleFactor); delayScaleFactor = 1/scaleFactor; // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } scaleFactor = 1.0; minDelay = getMinDelay(); maxDelay = getMaxDelay(); out.write("minimum delay is " + minDelay + " before scaling time.\n"); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } delayScaleFactor = scaleFactor; out.write("minimum delay is " + delayScaleFactor * minDelay + "after scaling delay by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); } } else { //User forces both delay and value scaling factors. out.write("\nForcing delay and value scale factors by " + delayScaleFactor + " and " + valScaleFactor + " respectively \n"); minDivision = getMinDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaledThresholds = scaleValue(valScaleFactor, scaledThresholds); minDivision = getMinDiv(scaledThresholds); out.write("minimum division is " + minDivision + " after scaling for division.\n"); minDelay = getMinDelay(); out.write("minimum delay is " + minDivision + " before scaling for delay.\n"); scaleDelay(delayScaleFactor); minDelay = getMinDelay(); out.write("minimum delay is " + minDivision + " after scaling for delay.\n"); /* minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { out.write("ERROR: Division Scaling has caused an overflow"); } if (scaleFactor > valScaleFactor){ out.write("WARNING: Minimum threshold won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); valScaleFactor = scaleFactor; } out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // END TEMPORARY } else { scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("Min division is 0. So, not checking whether given value scale factor is correct"); } out.write("minimum delay is " + minDelay + " before scaling time.\n"); scaleFactor = 1.0; minDelay = getMinDelay(); maxDelay = getMaxDelay(); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } if (scaleFactor > delayScaleFactor){ out.write("WARNING: Minimum delay won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); delayScaleFactor = scaleFactor; } out.write("minimum delay value is " + delayScaleFactor * minDelay + "after scaling by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); } if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { out.write("Rate Scaling has caused an overflow\n"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling delay by " + scaleFactor + "\n"); if (scaleFactor > 1) out.write("The given value scaling factor is insufficient for rates. So increasing it to "+ scaleFactor*valScaleFactor); scaledThresholds = scaleValue(scaleFactor,scaledThresholds); valScaleFactor *= scaleFactor; // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // end TEMPORARY } }*/ } } catch (IOException e) { e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return(scaledThresholds); } public HashMap<String,ArrayList<Double>> scaleValue(Double scaleFactor, HashMap<String,ArrayList<Double>> localThresholds) { String place; Properties p; try{ for (String st1 : g.getPlaceList()) { if (!isTransientPlace(st1)){ place = getPlaceInfoIndex(st1); p = placeInfo.get(place); } else{ place = getTransientNetPlaceIndex(st1); p = transientNetPlaces.get(place); } if (place != "failProp"){ /* Related to the separate net for DMV input driver if (p.getProperty("type").equals("DMVC")) { p.setProperty("DMVCValue", Double.toString(Double.parseDouble(p.getProperty("DMVCValue"))* scaleFactor)); } else { */ for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMin"))* scaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMax"))* scaleFactor)); } else { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); if (!v.isInput()) { p.setProperty(v.getName() + "_vMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMin"))* scaleFactor)); p.setProperty(v.getName() + "_vMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMax")) * scaleFactor)); } } } //} } } /*int i = 0; for (Variable v : reqdVarsL) { v.scaleInitByVar(scaleFactor); for (int j = 0; j < divisions.get(i).size(); j++) { divisions.get(i).set(j,divisions.get(i).get(j) * scaleFactor); } i++; }*/ //commented above for replacing divisionsL with thresholds for (Variable v : reqdVarsL) { v.scaleInitByVar(scaleFactor); //System.out.println("After scaling init Val of " + v.getName() + " by factor " + scaleFactor + ", it is " + v.getInitValue() + "\n"); for (int j = 0; j < localThresholds.get(v.getName()).size(); j++) { localThresholds.get(v.getName()).set(j,localThresholds.get(v.getName()).get(j) * scaleFactor); } } for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace. for (String st2: st1.keySet()){ st1.put(st2,String.valueOf(Double.valueOf(st1.get(st2))*scaleFactor)); } } } catch (NullPointerException e){ e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Not all regions have values for all dmv variables", "ERROR!", JOptionPane.ERROR_MESSAGE); } return localThresholds; } public void scaleDelay(Double scaleFactor) { try{ String place; Properties p; for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); Double mind = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin")); Double maxd = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax")); transitionInfo.get(pPrev + "," + nextPlace).setProperty("dMin",Double.toString(mind*scaleFactor)); transitionInfo.get(pPrev + "," + nextPlace).setProperty("dMax",Double.toString(maxd*scaleFactor)); } else { System.out.println("Transition " + t + " has no index in transitionInfo. CHECK"); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); Double mind = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin")); Double maxd = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMax")); transientNetTransitions.get(pPrev+ "," +nextPlace).setProperty("dMin",Double.toString(mind*scaleFactor)); transientNetTransitions.get(pPrev+ "," +nextPlace).setProperty("dMax",Double.toString(maxd*scaleFactor)); } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); } } } } } for (String st1 : g.getPlaceList()) { if (!isTransientPlace(st1)){ place = getPlaceInfoIndex(st1); p = placeInfo.get(place); } else{ place = getTransientNetPlaceIndex(st1); p = transientNetPlaces.get(place); } if (place != "failProp"){ // p.setProperty("dMin",Integer.toString((int)(Double.parseDouble(p.getProperty("dMin"))*scaleFactor))); // p.setProperty("dMax",Integer.toString((int)(Double.parseDouble(p.getProperty("dMax"))*scaleFactor))); /* STORING DELAYS AT TRANSITIONS p.setProperty("dMin", Double.toString(Double.parseDouble(p .getProperty("dMin")) * scaleFactor)); p.setProperty("dMax", Double.toString(Double.parseDouble(p .getProperty("dMax")) * scaleFactor)); */ for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/scaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/scaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMin")) / scaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMax")) / scaleFactor)); } } //} } } for (Variable v : reqdVarsL) { // if (!v.isDmvc()){ this if maynot be required.. rates do exist for dmvc ones as well.. since calculated before detectDMV v.scaleInitByDelay(scaleFactor); // } } // SEE IF RATES IN TRANSITIONS HAVE TO BE ADJUSTED HERE } catch(NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Delay scaling error due to null. Check", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(java.lang.ArrayIndexOutOfBoundsException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Delay scaling error due to Array Index.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public Double getMinDiv(HashMap<String, ArrayList<Double>> divisions) { Double minDiv = null; for (String s : divisions.keySet()) { if (minDiv == null){ minDiv = divisions.get(s).get(0); } for (int j = 0; j < divisions.get(s).size(); j++) { if (divisions.get(s).get(j) < minDiv) { minDiv = divisions.get(s).get(j); } } } return minDiv; } public Double getMaxDiv(HashMap<String, ArrayList<Double>> divisions) { Double maxDiv = null; for (String s : divisions.keySet()) { if (maxDiv == null){ maxDiv = divisions.get(s).get(0); } for (int j = 0; j < divisions.get(s).size(); j++) { if (divisions.get(s).get(j) > maxDiv) { maxDiv = divisions.get(s).get(j); } } } return maxDiv; } public Double getMinRate() { // minimum of entire lpn Double minRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if (!v.isDmvc()){ if ((minRate == null) && (p.getProperty(v.getName() + "_rMin") != null)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } else if ((p.getProperty(v.getName() + "_rMin") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) < minRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) != 0.0)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } } } } } return minRate; } public Double getMaxRate() { Double maxRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if (!v.isDmvc()){ if ((maxRate == null) && (p.getProperty(v.getName() + "_rMax") != null)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } else if ((p.getProperty(v.getName() + "_rMax") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) > maxRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) != 0.0)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } } } } } return maxRate; } public Double getMinDelay() { Double minDelay = null; Double mind; try{ for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); out.write("Transition " + g.getTransition(t).getName() + " b/w " + pPrev + " and " + nextPlace + " : finding delay \n"); if (transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin") != null){ mind = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin")); if (minDelay == null) minDelay = mind; else if ((minDelay > mind) && (mind != 0)) minDelay = mind; } } else { System.out.println("ERROR: Transition " + t + " has no index in transitionInfo."); out.write("ERROR: Transition " + t + " has no index in transitionInfo."); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin") != null){ mind = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin")); if (minDelay == null) minDelay = mind; else if ((minDelay > mind) && (mind != 0)) minDelay = mind; } } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); out.write("ERROR: Transient transition " + t + " has no index in transientNetTransitions."); } } } } } /*for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if ((minDelay == null) && (p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } else if ((p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0) && (Double.parseDouble(p.getProperty("dMin")) < minDelay)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } //} }*/ } catch (IOException e){ e.printStackTrace(); } return minDelay; } public Double getMaxDelay() { Double maxDelay = null; Double maxd; for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax") != null){ maxd = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax")); if (maxDelay == null) maxDelay = maxd; else if ((maxDelay < maxd) && (maxd != 0)) maxDelay = maxd; } } else { System.out.println("Transition " + t + " has no index in transitionInfo. CHECK"); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dmax") != null){ maxd = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dmax")); if (maxDelay == null) maxDelay = maxd; else if ((maxDelay < maxd) && (maxd != 0)) maxDelay = maxd; } } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); } } } } } /*for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if ((maxDelay == null) && (p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } else if ((p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0) && (Double.parseDouble(p.getProperty("dMax")) > maxDelay)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } //} }*/ return maxDelay; } public void addDuration(Properties p, Double d) { Double dMin; Double dMax; // d = d*(10^6); if ((p.getProperty("dMin") == null) && (p.getProperty("dMax") == null)) { // p.setProperty("dMin", Integer.toString((int)(Math.floor(d)))); // p.setProperty("dMax", Integer.toString((int)(Math.floor(d)))); p.setProperty("dMin", d.toString()); p.setProperty("dMax", d.toString()); return; } else { dMin = Double.parseDouble(p.getProperty("dMin")); dMax = Double.parseDouble(p.getProperty("dMax")); if (d < dMin) { dMin = d; } else if (d > dMax) { dMax = d; } } p.setProperty("dMin", dMin.toString()); p.setProperty("dMax", dMax.toString()); // p.setProperty("dMin", Integer.toString((int)(Math.floor(dMin)))); // p.setProperty("dMax", Integer.toString((int)(Math.ceil(dMax)))); } public String getPlaceInfoIndex(String s) { String index = null; for (String st2 : placeInfo.keySet()) { if (("p" + placeInfo.get(st2).getProperty("placeNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransientNetPlaceIndex(String s) { String index = null; for (String st2 : transientNetPlaces.keySet()) { if (("p" + transientNetPlaces.get(st2).getProperty("placeNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransitionInfoIndex(String s) { String index = null; for (String st2 : transitionInfo.keySet()) { if (("t" + transitionInfo.get(st2).getProperty("transitionNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransientNetTransitionIndex(String s) { String index = null; for (String st2 : transientNetTransitions.keySet()) { if (("t" + transientNetTransitions.get(st2).getProperty("transitionNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public ArrayList<Integer> diff(String pre_bin, String post_bin) { //Parameters are bins formed from reqdVarsL (not just cares). ArrayList<Integer> diffL = new ArrayList<Integer>(); if ((pre_bin != null) && (post_bin != null)){ String[] preset_encoding = pre_bin.split(","); String[] postset_encoding = post_bin.split(","); for (int j = 0; j < preset_encoding.length; j++) { // to account for "" being created in the array if (Integer.parseInt(preset_encoding[j]) != Integer.parseInt(postset_encoding[j])) { diffL.add(j);// to account for "" being created in the array } } } return (diffL); } public Integer getMinRate(String place, String name) { Properties p = placeInfo.get(place); if (p.getProperty(name + "_rMin") != null) return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMin")))); else return null; // return(rMin[i]); } public Integer getMaxRate(String place, String name) { Properties p = placeInfo.get(place); if (p.getProperty(name + "_rMax") != null) return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMax")))); else return null; // return(rMin[i]); } /* public Double[][] getDataExtrema(ArrayList<ArrayList<Double>> data){ Double[][] extrema = new Double[reqdVarsL.size()][2]; for (int i=0; i<reqdVarsL.size(); i++){ //Object obj = Collections.min(data.get(reqdVarIndices.get(i))); Object obj = Collections.min(data.get(i+1)); extrema[i][0] = Double.parseDouble(obj.toString()); //obj = Collections.max(data.get(reqdVarIndices.get(i))); obj = Collections.max(data.get(i+1)); extrema[i][1] = Double.parseDouble(obj.toString()); } return extrema; } */ public HashMap <String, Double[]> getDataExtrema(ArrayList<ArrayList<Double>> data){ HashMap <String, Double[]> extrema = new HashMap <String, Double[]>(); for (int i=0; i<reqdVarsL.size(); i++){ //Object obj = Collections.min(data.get(reqdVarIndices.get(i))); Object obj = Collections.min(data.get(i+1)); extrema.put(reqdVarsL.get(i).getName(),new Double[2]); extrema.get(reqdVarsL.get(i).getName())[0] = Double.parseDouble(obj.toString()); //obj = Collections.max(data.get(reqdVarIndices.get(i))); obj = Collections.max(data.get(i+1)); extrema.get(reqdVarsL.get(i).getName())[1] = Double.parseDouble(obj.toString()); } return extrema; } public Double[] getMinMaxRates(Double[] rateList){ ArrayList<Double> cmpL = new ArrayList<Double>(); Double[] minMax = {null,null};// new Double[2]; for (Double r : rateList){ if (r != null){ cmpL.add(r); } } if (cmpL.size() > 0){ Object obj = Collections.min(cmpL); minMax[0] = Double.parseDouble(obj.toString()); obj = Collections.max(cmpL); minMax[1] = Double.parseDouble(obj.toString()); } return minMax; } public boolean compareBins(int j, int mark,int[][] bins) { for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true; } public void addPseudo(HashMap<String,ArrayList<Double>> scaledThresholds){ try{ lpnWithPseudo = new LhpnFile(); lpnWithPseudo = mergeLhpns(lpnWithPseudo,g); pseudoVars = new HashMap<String,Boolean>(); //pseudoVars.put("ctl",true); for (int i = 0; i < reqdVarsL.size(); i++) { if ((reqdVarsL.get(i).isInput()) && (reqdVarsL.get(i).isCare())){ pseudoVars.put(reqdVarsL.get(i).getName(),true); } } if ((pseudoVars != null) && (pseudoVars.size() != 0)){ for (String st : g.getPlaceList()){ currentPlace = st; //TODO: do this only if not prop type place if (getPlaceInfoIndex(st) != null) currPlaceBin = getPlaceInfoIndex(st).split(","); else if (getTransientNetPlaceIndex(st) != null) currPlaceBin = getTransientNetPlaceIndex(st).split(","); else out.write("WARNING: " + st + " is not in the placelist. It should be initPlace, otherwise something wrong\n"); // visitedPlaces = new HashMap<String,Boolean>(); // visitedPlaces.put(currentPlace, true); traverse(scaledThresholds); } } }catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } private void traverse(HashMap<String,ArrayList<Double>> scaledThresholds){ for (String nextPlace : g.getPlaceList()){ if ((!nextPlace.equalsIgnoreCase(currentPlace)) && (getPlaceInfoIndex(nextPlace) != null)){ if ((getPlaceInfoIndex(currentPlace) != null) && (!transitionInfo.containsKey(getPlaceInfoIndex(currentPlace) + "," + getPlaceInfoIndex(nextPlace)))){ addPseudoTrans(nextPlace, scaledThresholds); } else if ((getTransientNetPlaceIndex(currentPlace) != null) && (!transientNetTransitions.containsKey(getTransientNetPlaceIndex(currentPlace) + "," + getPlaceInfoIndex(nextPlace)))){ addPseudoTrans(nextPlace, scaledThresholds); } } } } private void addPseudoTrans(String nextPlace, HashMap<String, ArrayList<Double>> scaledThresholds){ // Adds pseudo transition b/w currentPlace and nextPlace String[] nextPlaceBin = getPlaceInfoIndex(nextPlace).split(","); String enabling = ""; int bin; String st; Boolean pseudo = false; try{ for (int i = 0; i < reqdVarsL.size(); i++) { if ((reqdVarsL.get(i).isInput()) && (reqdVarsL.get(i).isCare())){ if (Integer.valueOf(currPlaceBin[i]) == Integer.valueOf(nextPlaceBin[i])){ continue; } else { if (!pseudoVars.containsKey(reqdVarsL.get(i).getName())){ // If the 2 places differ in the bins of a non-pseudovar, then u can't add pseudotrans there coz other variables belong to diff bins in these 2 places pseudo = false; break; } if (Math.abs(Integer.valueOf(currPlaceBin[i]) - Integer.valueOf(nextPlaceBin[i])) > 1){ // If the 2 places differ in the bins of a pseudovar but are not adjacent, then u can't add pseudotrans there pseudo = false; break; } pseudo = true; bin = Integer.valueOf(nextPlaceBin[i]); st = reqdVarsL.get(i).getName(); if (bin == 0){ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } } else { if (Integer.valueOf(currPlaceBin[i]) != Integer.valueOf(nextPlaceBin[i])){ pseudo = false; break; } } } if (pseudo){ out.write("Adding pseudo-transition pt" + pseudoTransNum + " between " + currentPlace + " and " + nextPlace + " with enabling " + enabling + "\n"); lpnWithPseudo.addTransition("pt" + pseudoTransNum); lpnWithPseudo.addMovement(currentPlace, "pt" + pseudoTransNum); lpnWithPseudo.addMovement("pt" + pseudoTransNum, nextPlace); lpnWithPseudo.addEnabling("pt" + pseudoTransNum, enabling); pseudoTransNum++; } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void addMetaBins(){ // TODO: DIDN'T REPLACE divisionsL by thresholds IN THIS METHOD boolean foundBin = false; for (String st1 : g.getPlaceList()){ String p = getPlaceInfoIndex(st1); String[] binEncoding ; ArrayList<Integer> syncBinEncoding; String o1; // st1 w.r.t g // p w.r.t placeInfo if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { // String [] bE = p.split(""); String [] bE = p.split(","); binEncoding = new String[bE.length - 1]; for (int i = 0; i < bE.length; i++){ binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01 } for (int i = 0; i < binEncoding.length ; i++){ if (!reqdVarsL.get(i).isDmvc()){ if ((lowerLimit[i] != null) && (getMinRate(p,reqdVarsL.get(i).getName()) < 0)){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) - 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) != -1){ key += syncBinEncoding.get(m).toString(); } else{ key += "A"; // ***Encoding -1 as A } } if ((syncBinEncoding.get(i) == -1) && (!placeInfo.containsKey(key))){ foundBin = true; Properties p0 = new Properties(); placeInfo.put(key, p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","true"); p0.setProperty("metaVar", String.valueOf(i)); g.addPlace("p" + numPlaces, false); //ratePlaces.add("p"+numPlaces); numPlaces++; if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ // minrate is 0; maxrate remains the same if positive addRate(p0, reqdVarsL.get(i).getName(), 0.0); addRate(p0, reqdVarsL.get(i).getName(), (double)getMaxRate(p,reqdVarsL.get(i).getName())); /* * This transition should be added only in this case but * since dotty cribs if there's no place on a transition's postset, * moving this one down so that this transition is created even if the * min,max rate is 0 in which case it wouldn't make sense to have this * transition * Properties p2 = new Properties(); transitionInfo.put(key + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum")); g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")" + "&~fail"); numTransitions++; */ } else{ addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the maximum rate was negative, then make the min & max rates both as zero } Properties p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; Properties p2 = new Properties(); transitionInfo.put(key + "," + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + "," + p).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(key + "," + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); minr = getMinRate(p, reqdVarsL.get(i).getName()); maxr = getMaxRate(p, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } else if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } } } } if ((upperLimit[i] != null) && getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()+1); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) + 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){ key += syncBinEncoding.get(m).toString(); } else{ key += "Z"; // ***Encoding highest bin +1 as Z // encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future } } if ((syncBinEncoding.get(i) == divisionsL.get(i).size() + 1) && (!placeInfo.containsKey(key))){ // divisionsL.get(i).size() + 1 or divisionsL.get(i).size()??? foundBin = true; Properties p0 = new Properties(); placeInfo.put(key, p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","true"); p0.setProperty("metaVar", String.valueOf(i)); //ratePlaces.add("p"+numPlaces); g.addPlace("p" + numPlaces, false); numPlaces++; if (getMinRate(p,reqdVarsL.get(i).getName()) < 0){ // maxrate is 0; minrate remains the same if negative addRate(p0, reqdVarsL.get(i).getName(), 0.0); addRate(p0, reqdVarsL.get(i).getName(), (double)getMinRate(p,reqdVarsL.get(i).getName())); /* * This transition should be added only in this case but * since dotty cribs if there's no place on a transition's postset, * moving this one down so that this transition is created even if the * min,max rate is 0 in which case it wouldn't make sense to have this * transition * Properties p2 = new Properties(); transitionInfo.put(key + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum")); g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")" + "&~fail"); numTransitions++; */ } else{ addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the minimum rate was positive, then make the min & max rates both as zero } Properties p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; Properties p2 = new Properties(); transitionInfo.put(key + "," + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + "," + p).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(key + "," + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); minr = getMinRate(p, reqdVarsL.get(i).getName()); maxr = getMaxRate(p, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } else if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; } } } } } } } } } public void addMetaBinTransitions(){ // Adds transitions b/w existing metaBins. // Doesn't add any new metabins. Doesn't add transitions b/w metabins & normal bins boolean foundBin = false; for (String st1 : g.getPlaceList()){ String p = getPlaceInfoIndex(st1); Properties placeP = placeInfo.get(p); String[] binEncoding ; ArrayList<Integer> syncBinEncoding; String o1; // st1 w.r.t g // p w.r.t placeInfo if (placeP.getProperty("type").equalsIgnoreCase("RATE") && placeP.getProperty("metaType").equalsIgnoreCase("true")) { // String [] bE = p.split(""); String [] bE = p.split(","); binEncoding = new String[bE.length - 1]; for (int i = 0; i < bE.length; i++){ binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01 } for (int i = 0; i < binEncoding.length ; i++){ if ((!reqdVarsL.get(i).isDmvc()) && (Integer.parseInt(placeP.getProperty("metaVar")) != i)){ if ((getMinRate(p,reqdVarsL.get(i).getName()) < 0)){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) - 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) != -1){ key += syncBinEncoding.get(m).toString(); } else{ key += "A"; // ***Encoding -1 as A } } if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } } } } if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()+1); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) + 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){ key += syncBinEncoding.get(m).toString(); } else{ key += "Z"; // ***Encoding highest bin +1 as Z // encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future } } if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; } } } } } } } } } public void writeVHDLAMSFile(String vhdFile){ try{ ArrayList<String> ratePlaces = new ArrayList<String>(); ArrayList<String> dmvcPlaces = new ArrayList<String>(); File VHDLFile = new File(directory + separator + vhdFile); VHDLFile.createNewFile(); BufferedWriter vhdlAms = new BufferedWriter(new FileWriter(VHDLFile)); StringBuffer buffer = new StringBuffer(); String pNum; vhdlAms.write("library IEEE;\n"); vhdlAms.write("use IEEE.std_logic_1164.all;\n"); vhdlAms.write("use work.handshake.all;\n"); vhdlAms.write("use work.nondeterminism.all;\n\n"); vhdlAms.write("entity amsDesign is\n"); vhdlAms.write("end amsDesign;\n\n"); vhdlAms.write("architecture "+vhdFile.split("\\.")[0]+" of amsDesign is\n"); for (Variable v : reqdVarsL){ vhdlAms.write("\tquantity "+v.getName()+":real;\n"); } for (int i = 0; i < numPlaces; i++){ if (!isTransientPlace("p"+i)){ String p = getPlaceInfoIndex("p"+i); if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } else { String p = getTransientNetPlaceIndex("p"+i); if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } vhdlAms.write("\tshared variable place:integer:= "+i+";\n"); break; } if (failPropVHDL != null){ //TODO: Make this an assertion //vhdlAms.write("\tshared variable fail:boolean:= false;\n"); } for (String st1 : g.getPlaceList()){ if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) { dmvcPlaces.add(p); // w.r.t placeInfo here }*/ if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) { } } else{ String p = getTransientNetPlaceIndex(st1); if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){ ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){ dmvcPlaces.add(p); // w.r.t g here }*/ } } /*for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ /* Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ String v1 = placeInfo.get(a).getProperty("DMVCVariable"); String v2 = placeInfo.get(b).getProperty("DMVCVariable"); if (reqdVarsL.indexOf(v1) < reqdVarsL.indexOf(v2)){ return -1; } else if (reqdVarsL.indexOf(v1) == reqdVarsL.indexOf(v2)){ return 0; } else{ return 1; } } });*/ Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){ return -1; } else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){ return 0; } else{ return 1; } } }); Collections.sort(ratePlaces,new Comparator<String>(){ String v1,v2; public int compare(String a, String b){ if (!isTransientPlace(a) && !isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else if (!isTransientPlace(a) && isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } else if (isTransientPlace(a) && !isTransientPlace(b)){ v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else { v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); // sending the initial place to the end of the list. since if statements begin with preset of each place //ratePlaces.add(ratePlaces.get(0)); //ratePlaces.remove(0); /*System.out.println("after sorting:"); for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ vhdlAms.write("begin\n"); //buffer.append("\nbegin\n"); String[] vals; for (Variable v : reqdVarsL){ // taking the lower value from the initial value range. Ok? //vhdlAms.write("\tbreak "+v.getName()+" => "+((((v.getInitValue()).split("\\,"))[0]).split("\\["))[1]+".0;\n"); vals = v.getInitValue().split("\\,"); vhdlAms.write("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n"); //buffer.append("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n"); } vhdlAms.write("\n"); //buffer.append("\n"); for (Variable v : reqdVarsL){ if (v.isDmvc()){ vhdlAms.write("\t"+v.getName()+"'dot == 0.0;\n"); //buffer.append("\t"+v.getName()+"'dot == 0.0;\n"); } } vhdlAms.write("\n"); //buffer.append("\n"); ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>(); boolean contVarExists = false; for (Variable v: reqdVarsL){ dmvcVarPlaces.add(new ArrayList<String>()); if (v.isDmvc()){ continue; } else{ contVarExists = true; } } for (String st:dmvcPlaces){ dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st); } if (contVarExists){ if (ratePlaces.size() != 0){ //vhdlAms.write("\tcase place use\n"); buffer.append("\tcase place use\n"); } //vhdlAms.write("\ntype rate_places is ("); for (String p : ratePlaces){ pNum = p.split("p")[1]; //vhdlAms.write("\t\twhen "+p.split("p")[1] +" =>\n"); buffer.append("\t\twhen "+ pNum +" =>\n"); if (!isTransientPlace(p)){ for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ //vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); } } } else{ for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ //vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0);\n"); } } } } vhdlAms.write(buffer.toString()); vhdlAms.write("\t\twhen others =>\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == 0.0;\n"); } } vhdlAms.write("\tend case;\n"); } vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\tcase place is\n"); buffer.delete(0, buffer.length()); String[] transL; int transNum; for (String p : ratePlaces){ pNum = p.split("p")[1]; vhdlAms.write("\t\twhen "+pNum +" =>\n"); vhdlAms.write("\t\t\twait until "); transL = g.getPostset(p); if (transL.length == 1){ transNum = Integer.parseInt(transL[0].split("t")[1]); vhdlAms.write(transEnablingsVHDL[transNum] + ";\n"); if (transDelayAssignVHDL[transNum] != null){ vhdlAms.write("\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); //vhdlAms.write("\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ vhdlAms.write("\t\t\tbreak "+ s +";\n"); } } } if (g.getPostset(transL[0]).length != 0) vhdlAms.write("\t\t\tplace := " + g.getPostset(transL[0])[0].split("p")[1] + ";\n"); } else{ boolean firstTrans = true; buffer.delete(0, buffer.length()); for (String t : transL){ transNum = Integer.parseInt(t.split("t")[1]); if (firstTrans){ firstTrans = false; vhdlAms.write("(" + transEnablingsVHDL[transNum]); buffer.append("\t\t\tif " + transEnablingsVHDL[transNum] + " then\n"); if (transDelayAssignVHDL[transNum] != null){ buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ buffer.append("\t\t\t\tbreak "+ s +";\n"); } } } buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n"); } else{ vhdlAms.write(" or " +transEnablingsVHDL[transNum] ); buffer.append("\t\t\telsif " + transEnablingsVHDL[transNum] + " then\n"); if (transDelayAssignVHDL[transNum] != null){ buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); //buffer.append("\t\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ buffer.append("\t\t\t\tbreak "+ s +";\n"); } } } buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n"); } } vhdlAms.write(");\n"); buffer.append("\t\t\tend if;\n"); vhdlAms.write(buffer.toString()); } } vhdlAms.write("\t\twhen others =>\n\t\t\twait for 0.0;\n\t\t\tplace := "+ ratePlaces.get(0).split("p")[1] + ";\n\tend case;\n\tend process;\n"); for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); for (String p : dmvcVarPlaces.get(i)){ if (!transientNetPlaces.containsKey(p)){ vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(placeInfo.get(p).getProperty("dMax"))) +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("DMVCValue"))) + ".0;\n"); } else{ vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))) +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("DMVCValue"))) + ".0;\n"); } } vhdlAms.write("\tend process;\n\n"); } } if (failPropVHDL != null){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\t\twait until " + failPropVHDL + ";\n"); //TODO: Change this to assertion //vhdlAms.write("\t\tfail := true;\n"); vhdlAms.write("\tend process;\n\n"); } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n"); vhdlAms.close(); } catch(IOException e){ JOptionPane.showMessageDialog(BioSim.frame, "VHDL-AMS model couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(Exception e){ JOptionPane.showMessageDialog(BioSim.frame, "Error in VHDL-AMS model generation.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void writeVerilogAMSFile(String vamsFileName){ try{ ArrayList<String> ratePlaces = new ArrayList<String>(); ArrayList<String> dmvcPlaces = new ArrayList<String>(); File vamsFile = new File(directory + separator + vamsFileName); vamsFile.createNewFile(); Double rateFactor = valScaleFactor/delayScaleFactor; BufferedWriter vams = new BufferedWriter(new FileWriter(vamsFile)); StringBuffer buffer = new StringBuffer(); StringBuffer buffer2 = new StringBuffer(); StringBuffer buffer3 = new StringBuffer(); StringBuffer buffer4 = new StringBuffer(); StringBuffer initBuffer = new StringBuffer(); vams.write("`include \"constants.vams\"\n"); vams.write("`include \"disciplines.vams\"\n"); vams.write("`timescale 1ps/1ps\n\n"); vams.write("module "+vamsFileName.split("\\.")[0]+" ("); buffer.append("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n"); Variable v; String[] vals; for (int i = 0; i < reqdVarsL.size(); i++){ v = reqdVarsL.get(i); if ( i!= 0){ vams.write(","); } vams.write(" "+v.getName()); if (v.isInput()){ buffer.append("\tinput "+v.getName()+";\n\telectrical "+v.getName()+";\n"); } else{ buffer.append("\tinout "+v.getName()+";\n\telectrical "+v.getName()+";\n"); if (!v.isDmvc()){ buffer2.append("\treal change_"+v.getName()+";\n"); buffer2.append("\treal rate_"+v.getName()+";\n"); vals = v.getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\t\tchange_"+v.getName()+" = "+ spanAvg+";\n"); vals = v.getInitRate().split("\\,"); spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*rateFactor); initBuffer.append("\t\trate_"+v.getName()+" = "+ (int)spanAvg+";\n"); } else{ buffer2.append("\treal "+v.getName()+"Val;\n"); // changed from real to int.. check?? vals = reqdVarsL.get(i).getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\t\t"+reqdVarsL.get(i).getName()+"Val = "+ spanAvg+";\n"); } } } // if (failPropVHDL != null){ // buffer.append("\toutput reg fail;\n\tlogic fail;\n"); // vams.write(", fail"); // } vams.write(");\n" + buffer+"\n"); if (buffer2.length() != 0){ vams.write(buffer2.toString()); } vams.write("\treal entryTime;\n"); if (vamsRandom){ vams.write("\tinteger seed;\n\tinteger del;\n"); } vams.write("\tinteger place;\n\n\tinitial\n\tbegin\n"); vams.write(initBuffer.toString()); vams.write("\t\tentryTime = 0;\n"); if (vamsRandom){ vams.write("\t\tseed = 0;\n"); } buffer.delete(0, buffer.length()); buffer2.delete(0, buffer2.length()); for (int i = 0; i < numPlaces; i++){ String p; if (!isTransientPlace("p"+i)){ p = getPlaceInfoIndex("p"+i); if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } else{ p = getTransientNetPlaceIndex("p"+i); if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } vams.write("\t\tplace = "+i+";\n"); break; } //if (failPropVHDL != null){ // vams.write("\t\t\tfail = 1'b0;\n"); //} vams.write("\tend\n\n"); for (String st1 : g.getPlaceList()){ if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) { dmvcPlaces.add(p); // w.r.t placeInfo here }*/ if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) { } } else{ String p = getTransientNetPlaceIndex(st1); if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){ ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){ dmvcPlaces.add(p); // w.r.t placeInfo here }*/ } } /*for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){ return -1; } else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){ if (Integer.parseInt(a.split("_")[2]) < Integer.parseInt(b.split("_")[2])){ return -1; } else if (Integer.parseInt(a.split("_")[2]) == Integer.parseInt(b.split("_")[2])){ return 0; } else{ return 1; } } else{ return 1; } } }); Collections.sort(ratePlaces,new Comparator<String>(){ String v1,v2; public int compare(String a, String b){ if (!isTransientPlace(a) && !isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else if (!isTransientPlace(a) && isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } else if (isTransientPlace(a) && !isTransientPlace(b)){ v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else { v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); ArrayList<String> transitions = new ArrayList<String>(); for (String t : g.getTransitionList()){ transitions.add(t); } Collections.sort(transitions,new Comparator<String>(){ public int compare(String a, String b){ String v1 = a.split("t")[1]; String v2 = b.split("t")[1]; if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); // sending the initial place to the end of the list. since if statements begin with preset of each place //ratePlaces.add(ratePlaces.get(0)); //ratePlaces.remove(0); ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>(); boolean contVarExists = false; for (Variable var: reqdVarsL){ dmvcVarPlaces.add(new ArrayList<String>()); if (var.isDmvc()){ continue; } else{ contVarExists = true; } } for (String st:dmvcPlaces){ dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st); } int transNum; buffer.delete(0, buffer.length()); initBuffer.delete(0, initBuffer.length()); String presetPlace = null,postsetPlace = null; StringBuffer[] transBuffer = new StringBuffer[transitions.size()]; int cnt = 0; StringBuffer transAlwaysPlaceBuffer = new StringBuffer(); int placeAlwaysBlockNum = -1; for (String t : transitions){ presetPlace = g.getPreset(t)[0]; //if (g.getPostset(t) != null){ // postsetPlace = g.getPostset(t)[0]; //} transNum = Integer.parseInt(t.split("t")[1]); cnt = transNum; if (!isTransientTransition(t)){ if (placeInfo.get(getPlaceInfoIndex(presetPlace)).getProperty("type").equals("RATE")){ if (g.getPostset(t).length != 0) postsetPlace = g.getPostset(t)[0]; for (int j = 0; j < transNum; j++){ if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){ cnt = j; break; } } if ( cnt == transNum){ transBuffer[cnt] = new StringBuffer(); if (transEnablingsVAMS[transNum].equalsIgnoreCase("")){ //transBuffer[cnt].append("\talways@(place)" + "\n\tbegin\n"); May 14, 2010 placeAlwaysBlockNum = cnt; } else{ transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n"); if (g.getPostset(t).length != 0) transAlwaysPlaceBuffer.append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); } } else{ String s = transBuffer[cnt].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[cnt].delete(0, transBuffer[cnt].length()); transBuffer[cnt].append(s); if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n" + "\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); } } transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); if (transDelayAssignVAMS[transNum] != null){ transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n"); for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ if (transIntAssignVAMS[transNum][i] != null){ transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]); } } } transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n"); transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transAlwaysPlaceBuffer.append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); } } } transBuffer[cnt].append("\t\tend\n"); //if ( cnt == transNum){ transBuffer[cnt].append("\tend\n"); //} if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\tend\n"); } } } else{ if (transientNetPlaces.get(getTransientNetPlaceIndex(presetPlace)).getProperty("type").equals("RATE")){ if (g.getPostset(t).length != 0) postsetPlace = g.getPostset(t)[0]; for (int j = 0; j < transNum; j++){ if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){ cnt = j; break; } } if ( cnt == transNum){ transBuffer[cnt] = new StringBuffer(); transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); } else{ String s = transBuffer[cnt].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[cnt].delete(0, transBuffer[cnt].length()); transBuffer[cnt].append(s); } transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); if (transDelayAssignVAMS[transNum] != null){ transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n"); for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ if (transIntAssignVAMS[transNum][i] != null){ transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]); } } } transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n"); if (g.getPostset(t).length != 0) transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); } } transBuffer[cnt].append("\t\tend\n"); //if ( cnt == transNum){ transBuffer[cnt].append("\tend\n"); //} } } //if (transDelayAssignVAMS[transNum] != null){ // buffer.append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); // buffer.append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); // buffer.append("\t\t\t#"+transDelayAssignVAMS[transNum]+";\n"); // for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ // if (transIntAssignVAMS[transNum][i] != null){ // buffer.append("\t\t\t"+reqdVarsL.get(i).getName()+"Val = "+ transIntAssignVAMS[transNum][i]+";\n"); // } // } // buffer.append("\t\tend\n\tend\n"); //} } if (placeAlwaysBlockNum == -1){ vams.write("\talways@(place)" + "\n\tbegin\n"); vams.write(transAlwaysPlaceBuffer.toString()); vams.write("\tend\n"); } else{ String s = transBuffer[placeAlwaysBlockNum].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[placeAlwaysBlockNum].delete(0, transBuffer[placeAlwaysBlockNum].length()); transBuffer[placeAlwaysBlockNum].append("\talways@(place)" + "\n\tbegin\n"); transBuffer[placeAlwaysBlockNum].append(transAlwaysPlaceBuffer); transBuffer[placeAlwaysBlockNum].append(s); transBuffer[placeAlwaysBlockNum].append("\tend\n"); } for (int j = 0; j < transitions.size(); j++){ if (transBuffer[j] != null){ vams.write(transBuffer[j].toString()); } } vams.write("\tanalog\n\tbegin\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(change_" + reqdVarsL.get(j).getName() + " + rate_" + reqdVarsL.get(j).getName()+"*($abstime-entryTime));\n"); } if ((!reqdVarsL.get(j).isInput()) && (reqdVarsL.get(j).isDmvc())){ vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(" + reqdVarsL.get(j).getName() + "Val,delay,rtime,ftime);\n"); //vals = reqdVarsL.get(j).getInitValue().split("\\,"); //double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); //initBuffer.append("\t\t"+reqdVarsL.get(j).getName()+"Val = "+ spanAvg+";\n"); } } vams.write("\tend\n"); // if (initBuffer.length() != 0){ // vams.write("\n\tinitial\n\tbegin\n"+initBuffer+"\tend\n"); // } //if (buffer.length() != 0){ // vams.write(buffer.toString()); //} vams.write("endmodule\n\n"); buffer.delete(0, buffer.length()); buffer2.delete(0, buffer2.length()); initBuffer.delete(0, initBuffer.length()); int count = 0; for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ if (count == 0){ vams.write("module driver ( " + reqdVarsL.get(i).getName() + "drive "); count++; } else{ vams.write(", " + reqdVarsL.get(i).getName() + "drive "); count++; } buffer.append("\n\toutput "+ reqdVarsL.get(i).getName() + "drive;\n"); buffer.append("\telectrical "+ reqdVarsL.get(i).getName() + "drive;\n"); buffer2.append("\treal " + reqdVarsL.get(i).getName() + "Val" + ";\n"); vals = reqdVarsL.get(i).getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\n\tinitial\n\tbegin\n"+"\t\t"+ reqdVarsL.get(i).getName() + "Val = "+ spanAvg+";\n"); if ((count == 1) && (vamsRandom) ){ initBuffer.append("\t\tseed = 0;\n"); } //buffer3.append("\talways\n\tbegin\n"); boolean transientDoneFirst = false; for (String p : dmvcVarPlaces.get(i)){ if (!transientNetPlaces.containsKey(p)){ // since p is w.r.t placeInfo & not w.r.t g // buffer3.append("\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ // buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); if (transientDoneFirst){ initBuffer.append("\t\tforever\n\t\tbegin\n"); transientDoneFirst = false; } if (g.getPostset("p" + placeInfo.get(p).getProperty("placeNum")).length != 0){ if (!vamsRandom){ //initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) } else{ //initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9) initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9) } initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); } else{ } } else{ /*buffer3.append("\tinitial\n\tbegin\n"); buffer3.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); buffer3.append("\tend\n");*/ transientDoneFirst = true; if (!vamsRandom){ //initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) } else{ //initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9) initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9) } initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n" ); // initBuffer.append("\tend\n"); } } // buffer3.append("\tend\n"); initBuffer.append("\t\tend\n\tend\n"); buffer4.append("\t\tV("+reqdVarsL.get(i).getName() + "drive) <+ transition("+reqdVarsL.get(i).getName() + "Val,delay,rtime,ftime);\n"); } } BufferedWriter topV = new BufferedWriter(new FileWriter(new File(directory + separator + "top.vams"))); topV.write("`timescale 1ps/1ps\n\nmodule top();\n\n"); if (count != 0){ vams.write(");\n"); vams.write("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n"); if (vamsRandom){ vams.write("\tinteger del;\n\tinteger seed;\n"); } vams.write(buffer+"\n"+buffer2+initBuffer+buffer3); vams.write("\tanalog\n\tbegin\n"+buffer4+"\tend\nendmodule"); count = 0; for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ if (count == 0){ topV.write("\tdriver tb(\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")"); count++; } else{ topV.write(",\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")"); count++; } } } topV.write("\n\t);\n\n"); } for (int i = 0; i < reqdVarsL.size(); i++){ v = reqdVarsL.get(i); if ( i== 0){ topV.write("\t"+vamsFileName.split("\\.")[0]+" dut(\n\t\t."+ v.getName() + "(" + v.getName() + ")"); } else{ topV.write(",\n\t\t." + v.getName() + "(" + reqdVarsL.get(i).getName() + ")"); count++; } } topV.write("\n\t);\n\nendmodule"); topV.close(); vams.close(); /*if (failPropVHDL != null){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\t\twait until " + failPropVHDL + ";\n"); vhdlAms.write("\t\tfail := true;\n"); vhdlAms.write("\tend process;\n\n"); } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");*/ } catch(IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Verilog-AMS model couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(Exception e){ JOptionPane.showMessageDialog(BioSim.frame, "Error in Verilog-AMS model generation.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } //T[] aux = (T[])a.clone(); public LhpnFile mergeLhpns(LhpnFile l1,LhpnFile l2){//(LhpnFile l1, LhpnFile l2){ l1.save(directory + separator + "l1.lpn"); //since there's no deep copy method l2.save(directory + separator + "l2.lpn"); String place1 = "p([-\\d]+)", place2 = "P([-\\d]+)"; String transition1 = "t([-\\d]+)", transition2 = "T([-\\d]+)"; int placeNum, transitionNum; int minPlace=0, maxPlace=0, minTransition = 0, maxTransition = 0; Boolean first = true; LhpnFile l3 = new LhpnFile(); try{ for (String st1: l1.getPlaceList()){ if ((st1.matches(place1)) || (st1.matches(place2))){ st1 = st1.replaceAll("p", ""); st1 = st1.replaceAll("P", ""); placeNum = Integer.valueOf(st1); if (placeNum > maxPlace){ maxPlace = placeNum; if (first){ first = false; minPlace = placeNum; } } if (placeNum < minPlace){ minPlace = placeNum; if (first){ first = false; maxPlace = placeNum; } } } } for (String st1: l2.getPlaceList()){ if ((st1.matches(place1)) || (st1.matches(place2))){ st1 = st1.replaceAll("p", ""); st1 = st1.replaceAll("P", ""); placeNum = Integer.valueOf(st1); if (placeNum > maxPlace) maxPlace = placeNum; if (placeNum < minPlace) minPlace = placeNum; } } //System.out.println("min place and max place in both lpns are : " + minPlace + "," + maxPlace); for (String st2: l2.getPlaceList()){ for (String st1: l1.getPlaceList()){ if (st1.equalsIgnoreCase(st2)){ maxPlace++; l2.renamePlace(st2, "p" + maxPlace);//, l2.getPlace(st2).isMarked()); break; } } } first = true; for (String st1: l1.getTransitionList()){ if ((st1.matches(transition1)) || (st1.matches(transition2))){ st1 = st1.replaceAll("t", ""); st1 = st1.replaceAll("T", ""); transitionNum = Integer.valueOf(st1); if (transitionNum > maxTransition){ maxTransition = transitionNum; if (first){ first = false; minTransition = transitionNum; } } if (transitionNum < minTransition){ minTransition = transitionNum; if (first){ first = false; maxTransition = transitionNum; } } } } for (String st1: l2.getTransitionList()){ if ((st1.matches(transition1)) || (st1.matches(transition2))){ st1 = st1.replaceAll("t", ""); st1 = st1.replaceAll("T", ""); transitionNum = Integer.valueOf(st1); if (transitionNum > maxTransition) maxTransition = transitionNum; if (transitionNum < minTransition) minTransition = transitionNum; } } //System.out.println("min transition and max transition in both lpns are : " + minTransition + "," + maxTransition); for (String st2: l2.getTransitionList()){ for (String st1: l1.getTransitionList()){ if (st1.equalsIgnoreCase(st2)){ maxTransition++; l2.renameTransition(st2, "t" + maxTransition); break; } } } l2.save(directory + separator + "tmp.lpn"); l3 = new LhpnFile(); l3.load(directory + separator + "l1.lpn"); l3.load(directory + separator + "tmp.lpn"); l2 = new LhpnFile(); l2.load(directory + separator + "l2.lpn"); File l1File = new File(directory + separator + "l1.lpn"); File l2File = new File(directory + separator + "l2.lpn"); l1File.delete(); l2File.delete(); //l2.save(directory + separator + "tmp.lpn"); //l1.load(directory + separator + "tmp.lpn"); File tmp = new File(directory + separator + "tmp.lpn"); tmp.delete(); }catch(Exception e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Problem while merging lpns", "ERROR!", JOptionPane.ERROR_MESSAGE); } //return l1; return l3; } } /* private String traceBack(String place, String var){ String enabling = null; try{ visitedPlaces.put(place,true); for (String presetTrans : g.getPreset(place)){ ExprTree enableTree = g.getEnablingTree(presetTrans); if ((enableTree != null) && (enableTree.containsVar(var))){ enabling = enableTree.toString(); return enabling; } } for (String presetTrans : g.getPreset(place)){ for (String presetPlace : g.getPreset(presetTrans)){ if (!visitedPlaces.containsKey(presetPlace)){ enabling = traceBack(presetPlace,var); if (enabling != null) return enabling; } } } } catch (NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Exception while tracing back for making the enabling conditions mutually exclusive.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return enabling; } This method is used for creating separate nets for each DMV input variable driver. public void updateTimeInfo(int[][] bins, Properties cvgProp) { String prevPlace = null; String currPlace = null; Properties p3 = null; //ArrayList<String> dmvcPlaceL = new ArrayList<String>(); // only dmvc inputs boolean exists; // int dmvcCnt = 0; making this global .. rechk String[] places; try { for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isDmvc() && reqdVarsL.get(i).isInput()) { out.write(reqdVarsL.get(i).getName() + " is a dmvc input variable \n"); // dmvcCnt = 0; in case of multiple tsd files, this may be a problem. may create a new distinct place with an existing key.?? prevPlace = null; currPlace = null; p3 = null; Properties p2 = null; String k; DMVCrun runs = reqdVarsL.get(i).getRuns(); Double[] avgVals = runs.getAvgVals(); out.write("variable " + reqdVarsL.get(i).getName() + " Number of runs = " + avgVals.length + "Avg Values are : " + avgVals.toString() + "\n"); for (int j = 0; j < avgVals.length; j++) { // this gives number of runs/startpoints/endpoints exists = false; places = g.getPlaceList(); if (places.length > 1) { for (String st : places) { k = getPlaceInfoIndex(st); if (!isTransientPlace(st) && (placeInfo.get(k).getProperty("type").equalsIgnoreCase("DMVC"))) { if ((Math.abs(Double.parseDouble(placeInfo.get(k).getProperty("DMVCValue")) - avgVals[j]) < epsilon) && (placeInfo.get(k).getProperty("DMVCVariable").equalsIgnoreCase(reqdVarsL.get(i).getName()))) { // out.write("Place with key " + k + "already exists. so adding dmvcTime to it\n"); addDmvcTime(placeInfo.get(k), reqdVarsL.get(i).getName(), calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); addDuration(placeInfo.get(k),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); exists = true; prevPlace = currPlace; currPlace = getPlaceInfoIndex(st);// k; p2 = placeInfo.get(currPlace); //next few lines commented to remove multiple dmv input places of same variable from being marked initially. // if (j == 0) { // adding the place corresponding to the first dmv run to initial marking. // placeInfo.get(k).setProperty("initiallyMarked", "true"); // g.changeInitialMarking("p" + placeInfo.get(k).getProperty("placeNum"),true); //} // break ; here? } } } } if (!exists) { prevPlace = currPlace; currPlace = "d_" + i + "_" + dmvcCnt; p2 = new Properties(); p2.setProperty("placeNum", numPlaces.toString()); p2.setProperty("type", "DMVC"); p2.setProperty("DMVCVariable", reqdVarsL.get(i).getName()); p2.setProperty("DMVCValue", avgVals[j].toString()); p2.setProperty("initiallyMarked", "false"); addDmvcTime(p2, reqdVarsL.get(i).getName(),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); //placeInfo.put("d_" + i + "_" + dmvcCnt, p2); if (j == 0) { transientNetPlaces.put("d_" + i + "_" + dmvcCnt, p2); g.addPlace("p" + numPlaces, true); p2.setProperty("initiallyMarked", "true"); } else{ placeInfo.put("d_" + i + "_" + dmvcCnt, p2); g.addPlace("p" + numPlaces, false); } dmvcInputPlaces.add("p" + numPlaces); if (j == 0) { // adding the place corresponding to the first dmv run to initial marking p2.setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + p2.getProperty("placeNum"), true); } numPlaces++; out.write("Created new place with key " + "d_" + i + "_" + dmvcCnt + "\n"); dmvcCnt++; //dmvcPlaceL.add(currPlace); cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } Double d = calcDelay(runs.getStartPoint(j), runs.getEndPoint(j));// data.get(0).get(runs.getEndPoint(j)) - data.get(0).get(runs.getStartPoint(j)); // data.get(0).get(reqdVarsL.get(prevPlace.getDmvcVar()).getRuns().getEndPoint(j-1)); // TEMPORARY FIX //Double minTime = getMinDmvcTime(p2); //if ((d > minTime*Math.pow(10.0, 4.0))){ // && (getMinDmvcTime(p2) == getMaxDmvcTime(p2))){ // deleteInvalidDmvcTime(p2, getMinDmvcTime(p2)); // updates dmin,dmax too //} //END TEMPORARY FIX // For dmv input nets, transition's delay assignment is // it's preset's duration; value assgnmt is value in postset. addDuration(p2,d); //boolean transientNet = false; // out.write("Delay in place p"+ p2.getProperty("placeNum")+ " after updating " + d + " is ["+ p2.getProperty("dMin") + ","+ p2.getProperty("dMax") + "]\n"); if (prevPlace != null) { if (transitionInfo.containsKey(prevPlace + currPlace)) { p3 = transitionInfo.get(prevPlace + currPlace); } else { p3 = new Properties(); p3.setProperty("transitionNum", numTransitions.toString()); if (transientNetPlaces.containsKey(prevPlace)){ transientNetTransitions.put(prevPlace + currPlace, p3); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + transientNetPlaces.get(prevPlace).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum"), "p" + placeInfo.get(currPlace).getProperty("placeNum")); // transientNet = true; } else{ transitionInfo.put(prevPlace + currPlace, p3); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p"+ placeInfo.get(prevPlace).getProperty("placeNum"), "t"+ transitionInfo.get(prevPlace + currPlace).getProperty("transitionNum")); g.addMovement("t"+ transitionInfo.get(prevPlace+ currPlace).getProperty("transitionNum"),"p"+ placeInfo.get(currPlace).getProperty("placeNum")); } numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } //if (!transientNet){ // assuming postset duration // addDuration(p2, d); //} //else { // addTransientDuration(p2, d); //} } } else if (reqdVarsL.get(i).isDmvc()) { // non-input dmvc } } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } */ /* ArrayList<ArrayList<String>> ifL = new ArrayList<ArrayList<String>>(); ArrayList<ArrayList<String>> ifRateL = new ArrayList<ArrayList<String>>(); for (Variable v: reqdVarsL){ ifL.add(new ArrayList<String>()); ifRateL.add(new ArrayList<String>()); } String[] tL; for (String p : ratePlaces){ tL = g.getPreset(p); for (String t : tL){ if ((g.getPreset(t).length != 0) && (g.getPostset(t).length != 0) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); String ifStr = ""; String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(""); String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(""); boolean above; double val; for (int k : diffL) { if (Integer.parseInt(binIncoming[k + 1]) < Integer.parseInt(binOutgoing[k + 1])) { val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k + 1])).doubleValue(); above = true; } else { val = divisionsL.get(k).get(Integer.parseInt(binOutgoing[k + 1])).doubleValue(); above = false; } if (above) { ifStr = reqdVarsL.get(k).getName()+"'above("+val+")"; } else{ ifStr = "not "+ reqdVarsL.get(k).getName()+"'above("+val+")"; } for (int j = 0; j<reqdVarsL.size(); j++){ String rateStr = ""; if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ rateStr = reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0)"; ifL.get(j).add(ifStr); ifRateL.get(j).add(rateStr); } } } } } } for (int i = 0; i<reqdVarsL.size(); i++){ for (int j = 0; j<ifL.get(i).size(); j++){ if (j==0){ vhdlAms.write("\tif "+ifL.get(i).get(j)+" use\n"); } else{ vhdlAms.write("\telsif "+ifL.get(i).get(j)+" use\n"); } vhdlAms.write("\t\t"+ ifRateL.get(i).get(j)+";\n"); } if (ifL.get(i).size() != 0){ vhdlAms.write("\tend use;\n\n"); } } // vhdlAms.write("\tprocess\n"); // vhdlAms.write("\tbegin\n"); for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); for (String p : dmvcVarPlaces.get(i)){ vhdlAms.write("\t\twait for delay("+placeInfo.get(p).getProperty("dMax")+","+placeInfo.get(p).getProperty("dMin") +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ placeInfo.get(p).getProperty("DMVCValue") + ";\n"); } vhdlAms.write("\tend process;\n\n"); } } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n"); vhdlAms.close(); } catch(IOException e){ } } //T[] aux = (T[])a.clone(); } */ /* OBSOLETE METHODS public ArrayList<ArrayList<Double>> parseBinFile() { reqdVarsL = new ArrayList<Variable>(); ArrayList<String> linesBinFileL = null; int h = 0; //ArrayList<ArrayList<Double>> divisionsL = new ArrayList<ArrayList<Double>>(); try { Scanner f1 = new Scanner(new File(directory + separator + binFile)); // log.addText(directory + separator + binFile); linesBinFileL = new ArrayList<String>(); linesBinFileL.add(f1.nextLine()); while (f1.hasNextLine()) { linesBinFileL.add(f1.nextLine()); } out.write("Required variables and their levels are :"); for (String st : linesBinFileL) { divisionsL.add(new ArrayList<Double>()); String[] wordsBinFileL = st.split("\\s"); for (int i = 0; i < wordsBinFileL.length; i++) { if (i == 0) { reqdVarsL.add(new Variable(wordsBinFileL[i])); out.write("\n" + reqdVarsL.get(reqdVarsL.size() - 1).getName()); } else { divisionsL.get(h).add(Double.parseDouble(wordsBinFileL[i])); } } out.write(" " + divisionsL.get(h)); h++; // max = Math.max(max, wordsBinFileL.length + 1); } f1.close(); } catch (Exception e1) { } return divisionsL; } public String cleanRow (String row){ String rowNS,rowTS = null; try{ rowNS =lParenR.matcher(row).replaceAll(""); rowTS = rParenR.matcher(rowNS).replaceAll(""); return rowTS; } catch(PatternSyntaxException pse){ System.out.format("There is a problem withthe regular expression!%n"); System.out.format("The pattern in question is:%s%n",pse.getPattern()); System.out.format("The description is:%s%n",pse.getDescription()); System.out.format("The message is:%s%n",pse.getMessage()); System.out.format("The index is:%s%n",pse.getIndex()); System.exit(0); return rowTS; } } */
gui/src/learn/LearnModel.java
package learn; //import gcm2sbml.parser.GCMFile; import lhpn2sbml.parser.LhpnFile; import lhpn2sbml.parser.Lpn2verilog; import parser.*; import java.io.*; import java.util.*; import javax.swing.*; //import org.sbml.libsbml.*; import biomodelsim.*; /** * This class generates an LHPN model from the simulation traces provided * in the learn view. The generated LHPN is stored in an object of type * lhpn2sbml.parser.LHPNfile . It is then saved in *.lpn file using the * save() method of the above class. * * Rev. 1 - Kevin Jones * Rev. 2 - Scott Little (data2lhpn.py) * Rev. 3 - Satish Batchu ( dataToLHPN() ) */ public class LearnModel { // added ItemListener SB private static final long serialVersionUID = -5806315070287184299L; private String directory, lrnFile; private Log log; private String separator; private String learnFile, lhpnFile; private ArrayList<Variable> reqdVarsL; //private ArrayList<String> careVars; private ArrayList<Integer> reqdVarIndices; private ArrayList<ArrayList<Double>> data; private ArrayList<String> varNames; //private HashMap<String, int[]> careBins; private int[][] bins; private ArrayList<ArrayList<Double>> divisionsL; private HashMap<String, ArrayList<Double>> thresholds; private Double[][] rates; private double[][] values; private Double[] duration; private int pathLengthBin ; //= 7 ;// intFixed 25 pd 7 integrator 15; private int rateSampling ; //= -1 ; //intFixed 250; 20; //-1; private LhpnFile g; private Integer numPlaces = 0; private Integer numTransitions = 0; private HashMap<String, Properties> placeInfo; private HashMap<String, Properties> transitionInfo; private HashMap<String, Properties> cvgInfo; private Double minDelayVal = 10.0; private Double minRateVal = 10.0; private Double minDivisionVal = 10.0; private Double delayScaleFactor = 1.0; private Double valScaleFactor = 1.0; BufferedWriter out; File logFile; // Threshold parameters // private double epsilon ;//= 0.1; // What is the +/- epsilon where signals are considered to be equivalent private Integer runLength ; //= 15; // the number of time points that a value must persist to be considered constant private Double runTime ; // = 5e-12; // 10e-6 for intFixed; 5e-6 for integrator. 5e-12 for pd;// the amount of time that must pass to be considered constant when using absoluteTime private boolean absoluteTime ; // = true; // true for intfixed //false; true for pd; false for integrator// when False time points are used to determine DMVC and when true absolutime time is used to determine DMVC private double percent ; // = 0.8; // a decimal value representing the percent of the total trace that must be constant to qualify to become a DMVC var private Double[] lowerLimit; private Double[] upperLimit; private String[] transEnablingsVHDL; private String[][] transIntAssignVHDL; private String[] transDelayAssignVHDL; private String[] transEnablingsVAMS; private String[] transConditionalsVAMS; private String[][] transIntAssignVAMS; private String[] transDelayAssignVAMS; private String failPropVHDL; private HashMap<String, Properties> transientNetPlaces; private HashMap<String, Properties> transientNetTransitions; private ArrayList<String> propPlaces; private boolean vamsRandom = false; private HashMap<String,Properties> dmvcValuesUnique; private Double dsFactor, vsFactor; private String currentPlace; private String[] currPlaceBin; private LhpnFile lpnWithPseudo; private int pseudoTransNum = 0; private HashMap<String,Boolean> pseudoVars; private ArrayList<HashMap<String, String>> constVal; private boolean dmvDetectDone = false; private boolean dmvStatusLoaded = false; private int pathLengthVar = 40; private double unstableTime; private boolean binError; private HashMap<String, ArrayList<String>> destabMap; // Pattern lParenR = Pattern.compile("\\(+"); //Pattern floatingPointNum = Pattern.compile(">=(-*[0-9]+\\.*[0-9]*)"); // Pattern falseR = Pattern.compile("false",Pattern.CASE_INSENSITIVE); //pass the I flag to be case insensitive /** * This is a constructor for learning LPN models from simulation data. This could * have been just a method in LearnLHPN class but because it started with * a lot of global variables/fields, it ended up being a constructor in a * separate class. * * Version 1 : Kevin Jones (Perl) * Version 2 : Scott Little (data2lhpn.py) * Version 3 : Satish Batchu (LearnModel.java) */ public LhpnFile learnModel(String directory, Log log, BioSim biosim, int moduleNumber, HashMap<String, ArrayList<Double>> thresh, HashMap<String,Double> tPar, ArrayList<Variable> rVarsL, HashMap<String, ArrayList<String>> dstab, Boolean netForStable, Double vScaleFactor, Double dScaleFactor, String failProp) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Assign the parameters received from the call to the fields of this class this.log = log; this.directory = directory; this.reqdVarsL = rVarsL; this.thresholds = thresh; this.valScaleFactor = vScaleFactor; this.delayScaleFactor = dScaleFactor; this.destabMap = dstab; String[] getFilename = directory.split(separator); if (moduleNumber == 0) lhpnFile = getFilename[getFilename.length - 1] + ".lpn"; else lhpnFile = getFilename[getFilename.length - 1] + moduleNumber + ".lpn"; // epsilon = tPar.get("epsilon"); pathLengthBin = (int) tPar.get("pathLengthBin").doubleValue(); pathLengthVar = (int) tPar.get("pathLengthVar").doubleValue(); rateSampling = (int) tPar.get("rateSampling").doubleValue(); percent = tPar.get("percent"); if (tPar.containsKey("runTime")){ //only runTime or runLength is required based on gui selection runTime = tPar.get("runTime"); runLength = null; } else{ runLength = (int) tPar.get("runLength").doubleValue(); runTime = null; } unstableTime = tPar.get("unstableTime").doubleValue(); new File(directory + separator + lhpnFile).delete(); try { logFile = new File(directory + separator + "run.log"); if (moduleNumber == 0) logFile.createNewFile(); //create new file first time out = new BufferedWriter(new FileWriter(logFile,true)); //appending // resetAll(); numPlaces = 0; numTransitions = 0; out.write("Running: dataToLHPN for module " + moduleNumber + "\n"); TSDParser tsd = new TSDParser(directory + separator + "run-1.tsd", false); varNames = tsd.getSpecies(); //String[] learnDir = lrnFile.split("\\."); //File cvgFile = new File(directory + separator + learnDir[0] + ".cvg"); File cvgFile = new File(directory + separator + "run.cvg"); //cvgFile.createNewFile(); BufferedWriter coverage = new BufferedWriter(new FileWriter(cvgFile)); g = new LhpnFile(); // The generated lhpn is stored in this object placeInfo = new HashMap<String, Properties>(); transitionInfo = new HashMap<String, Properties>(); cvgInfo = new HashMap<String, Properties>(); transientNetPlaces = new HashMap<String, Properties>(); transientNetTransitions = new HashMap<String, Properties>(); if ((failProp != null)){ //Construct a property net with single place and a fail trans propPlaces = new ArrayList<String>(); Properties p0 = new Properties(); placeInfo.put("failProp", p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "PROP"); p0.setProperty("initiallyMarked", "true"); g.addPlace("p" + numPlaces, true); propPlaces.add("p" + numPlaces); numPlaces++; Properties p1 = new Properties(); transitionInfo.put("failProp", p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get("failProp").getProperty("placeNum"), "t" + transitionInfo.get("failProp").getProperty("transitionNum")); g.getTransition("t" + numTransitions).setFail(true); numTransitions++; } out.write("epsilon = " + "; ratesampling = " + rateSampling + "; pathLengthBin = " + pathLengthBin + "; percent = " + percent + "; runlength = " + runLength + "; runtime = " + runTime + "; absoluteTime = " + absoluteTime + "; delayscalefactor = " + delayScaleFactor + "; valuescalefactor = " + valScaleFactor + "\n"); dsFactor = this.delayScaleFactor; vsFactor = this.valScaleFactor; dmvcValuesUnique = new HashMap<String, Properties>(); constVal = new ArrayList<HashMap<String, String>>(); int tsdFileNum = 1; while (new File(directory + separator + "run-" + tsdFileNum + ".tsd").exists()) { Properties cProp = new Properties(); cvgInfo.put(String.valueOf(tsdFileNum), cProp); cProp.setProperty("places", String.valueOf(0)); cProp.setProperty("transitions", String.valueOf(0)); cProp.setProperty("rates", String.valueOf(0)); cProp.setProperty("delays", String.valueOf(0)); if (!netForStable) tsd = new TSDParser(directory + separator + "run-" + tsdFileNum + ".tsd", false); else tsd = new TSDParser(directory + separator + "runWithStables-" + tsdFileNum + ".tsd", false); data = tsd.getData(); varNames = tsd.getSpecies(); if ((destabMap != null) && (destabMap.size() != 0)){ out.write("Generating data for stables \n"); addStablesToData(thresholds, destabMap); for (String s : varNames) out.write(s + " "); out.write("\n"); tsd.setData(data); tsd.setSpecies(varNames); tsd.outputTSD(directory + separator + "runWithStables-" + tsdFileNum + ".tsd"); } findReqdVarIndices(); genBinsRates(thresholds); detectDMV(data,false); updateGraph(bins, rates, tsdFileNum, cProp); //cProp.store(coverage, "run-" + String.valueOf(i) + ".tsd"); coverage.write("run-" + String.valueOf(tsdFileNum) + ".tsd\t"); coverage.write("places : " + cProp.getProperty("places")); coverage.write("\ttransitions : " + cProp.getProperty("transitions") + "\n"); tsdFileNum++; } coverage.close(); for (String st1 : g.getTransitionList()) { out.write("\nTransition is " + st1); if (isTransientTransition(st1)){ out.write(" Incoming place " + g.getPreset(st1)[0]); if (g.getPostset(st1).length != 0){ out.write(" Outgoing place " + g.getPostset(st1)[0]); } continue; } String binEncoding = getPlaceInfoIndex(g.getPreset(st1)[0]); out.write(" Incoming place " + g.getPreset(st1)[0] + " Bin encoding is " + binEncoding); if (g.getPostset(st1).length != 0){ binEncoding = getPlaceInfoIndex(g.getPostset(st1)[0]); out.write(" Outgoing place " + g.getPostset(st1)[0] + " Bin encoding is " + binEncoding); } } out.write("\nTotal no of transitions : " + numTransitions); out.write("\nTotal no of places : " + numPlaces); Properties initCond = new Properties(); for (Variable v : reqdVarsL) { if (v.isDmvc()) { g.addInteger(v.getName(), v.getInitValue()); } else { initCond.put("value", v.getInitValue()); initCond.put("rate", v.getInitRate()); g.addContinuous(v.getName(), initCond); } } HashMap<String, ArrayList<Double>> scaledThresholds; scaledThresholds = normalize(); // globalValueScaling.setText(Double.toString(valScaleFactor)); // globalDelayScaling.setText(Double.toString(delayScaleFactor)); initCond = new Properties(); for (Variable v : reqdVarsL) { // Updating with scaled initial values & rates if (v.isDmvc()) { g.changeIntegerInitCond(v.getName(), v.getInitValue()); } else { initCond.put("value", v.getInitValue()); initCond.put("rate", v.getInitRate()); g.changeContInitCond(v.getName(), initCond); } } String[] transitionList = g.getTransitionList(); /* transEnablingsVAMS = new String[transitionList.length]; transConditionalsVAMS = new String[transitionList.length]; transIntAssignVAMS = new String[transitionList.length][reqdVarsL.size()]; transDelayAssignVAMS = new String[transitionList.length]; */ int transNum; for (String t : transitionList) { transNum = Integer.parseInt(t.split("t")[1]); if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { // g.getPreset(t).length != 0 && g.getPostset(t).length != 0 ?? String tKey = getTransitionInfoIndex(t); String prevPlaceFullKey = getPresetPlaceFullKey(tKey); String nextPlaceFullKey = getPostsetPlaceFullKey(tKey); //ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); ArrayList<Integer> diffL = diff(prevPlaceFullKey, nextPlaceFullKey); String condStr = ""; // transEnablingsVAMS[transNum] = ""; //String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(","); //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(","); String[] binIncoming = prevPlaceFullKey.split(","); String[] binOutgoing = nextPlaceFullKey.split(","); Boolean firstInputBinChg = true; Boolean firstOutputBinChg = true; Boolean careOpChange = false, careIpChange = false; for (int k : diffL) { if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) { // the above condition means that if the bin change is not on a non-input dmv variable, there won't be any enabling condition if (reqdVarsL.get(k).isCare()) careIpChange = true; if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) { //double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue(); double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])-1).doubleValue(); // changed on July 20, 2010 if (firstInputBinChg){ condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/valScaleFactor +"))"; } else{ condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/valScaleFactor +"))"; } } else { double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue(); if (firstInputBinChg){ condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; //changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/valScaleFactor +"))"; } else{ condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; //changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary // transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/valScaleFactor +"))"; } } //if (diffL.get(diffL.size() - 1) != k) { // condStr += "&"; ////COME BACK??? temporary transEnablingsVAMS[transNum] += //} firstInputBinChg = false; } // Enablings Till above.. Below one is dmvc delay,assignment. Whenever a transition's preset and postset places differ in dmvc vars, then this transition gets the assignment of the dmvc value in the postset place and delay assignment of the preset place's duration range. This has to be changed after taking the causal relation input if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis if (reqdVarsL.get(k).isCare()) careOpChange = true; // String pPrev = g.getPreset(t)[0]; // String nextPlace = g.getPostset(t)[0]; String nextPlaceKey = getPlaceInfoIndex(g.getPostset(t)[0]); //if (!isTransientTransition(t)){ // int mind = (int) Math.floor(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + "," + getPlaceInfoIndex(nextPlace)).getProperty("dMin"))); // int maxd = (int) Math.ceil(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + "," + getPlaceInfoIndex(nextPlace)).getProperty("dMax"))); int mind = (int) Math.floor(Double.parseDouble(transitionInfo.get(tKey).getProperty("dMin"))); int maxd = (int) Math.ceil(Double.parseDouble(transitionInfo.get(tKey).getProperty("dMax"))); if (mind != maxd) g.changeDelay(t, "uniform(" + mind + "," + maxd + ")"); else g.changeDelay(t, String.valueOf(mind)); //int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); //int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); if (minv != maxv) g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign(t,reqdVarsL.get(k).getName(), String.valueOf(minv)); int dmvTnum = Integer.parseInt(t.split("t")[1]); if (!vamsRandom){ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor)+";\n"; // transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) } else{ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf((int)Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/valScaleFactor)) + "," + String.valueOf((int)Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/valScaleFactor))+");\n"; // transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," +(int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9) } /*} else{ g.changeDelay(t, "[" + (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + "," + (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))) + "]"); g.addIntAssign(t,reqdVarsL.get(k).getName(),"[" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ","+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + "]"); int dmvTnum = Integer.parseInt(t.split("t")[1]); transIntAssignVAMS[dmvTnum][k] = ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor); transDelayAssignVAMS[dmvTnum] = (int)(((Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))))*Math.pow(10, 12))/(2.0*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) }*/ } } if (careIpChange & careOpChange){ // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration. if ((getPlaceInfoIndex(g.getPreset(t)[0]) != null) && (getPlaceInfoIndex(g.getPostset(t)[0]) != null)) //if (!(transitionInfo.get(getPlaceInfoIndex(g.getPreset(t)[0]) + "," + getPlaceInfoIndex(g.getPostset(t)[0])).containsKey("ioChangeDelay"))) if (!(transitionInfo.get(tKey).containsKey("ioChangeDelay"))){ g.changeDelay(t, "0"); } } // if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){ // transEnablingsVAMS[transNum] += ")"; // } if (!condStr.equalsIgnoreCase("")){ //condStr += enFailAnd; g.addEnabling(t, condStr); } else{ //Nothing added to Enabling condition. //condStr = enFail; //g.addEnabling(t, condStr); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); String prevPlaceFullKey = getPresetPlaceFullKey(tKey); String nextPlaceFullKey = getPostsetPlaceFullKey(tKey); //ArrayList<Integer> diffL = diff(getTransientNetPlaceIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); ArrayList<Integer> diffL = diff(prevPlaceFullKey, nextPlaceFullKey); String condStr = ""; // transEnablingsVAMS[transNum] = ""; //String[] binIncoming = getTransientNetPlaceIndex(g.getPreset(t)[0]).split(","); //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(","); String[] binIncoming = prevPlaceFullKey.split(","); String[] binOutgoing = nextPlaceFullKey.split(","); Boolean firstInputBinChg = true; Boolean careOpChange = false, careIpChange = false; for (int k : diffL) { if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) { if (reqdVarsL.get(k).isCare()) careIpChange = true; if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) { //double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue(); double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])-1).doubleValue(); // changed on July 20, 2010 if (firstInputBinChg){ condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary } else{ condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")"; // transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),+1)"; // += temporary } } else { double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue(); if (firstInputBinChg){ condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";//changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary } else { condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";//changed ceil to floor on aug 7,2010 // transEnablingsVAMS[transNum] = " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/valScaleFactor +"),-1)"; // +=; temporary } } //if (diffL.get(diffL.size() - 1) != k) { // condStr += "&"; // //COME BACK??? temporary transEnablingsVAMS[transNum] += //} firstInputBinChg = false; } if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis if (reqdVarsL.get(k).isCare()) careOpChange = true; //String pPrev = g.getPreset(t)[0]; //String nextPlace = g.getPostset(t)[0]; String nextPlaceKey = getPlaceInfoIndex(g.getPostset(t)[0]); //int mind = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+ "," +getPlaceInfoIndex(nextPlace)).getProperty("dMin"))); //int maxd = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+ "," +getPlaceInfoIndex(nextPlace)).getProperty("dMax"))); int mind = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(tKey).getProperty("dMin"))); int maxd = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(tKey).getProperty("dMax"))); if (mind != maxd) g.changeDelay(t, "uniform(" + mind + "," + maxd + ")"); else g.changeDelay(t, String.valueOf(mind)); //int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); //int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(nextPlaceKey).getProperty(reqdVarsL.get(k).getName() + "_vMax"))); if (minv != maxv) g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign(t,reqdVarsL.get(k).getName(),String.valueOf(minv)); int dmvTnum = Integer.parseInt(t.split("t")[1]); if (!vamsRandom){ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*valScaleFactor)+";\n";; // transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9) } else{ // transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf(Math.floor((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/valScaleFactor))) + "," + String.valueOf(Math.ceil((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/valScaleFactor)))+");\n"; // transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," + (int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9) } } } if (careIpChange & careOpChange){ // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration. if ((getTransientNetPlaceIndex(g.getPreset(t)[0]) != null) && (getPlaceInfoIndex(g.getPostset(t)[0]) != null)) //if (!(transientNetTransitions.get(getTransientNetPlaceIndex(g.getPreset(t)[0]) + "," + getPlaceInfoIndex(g.getPostset(t)[0])).containsKey("ioChangeDelay"))) if (!(transientNetTransitions.get(tKey).containsKey("ioChangeDelay"))) g.changeDelay(t, "0"); } if (diffL.size() > 1){ // transEnablingsVHDL[transNum] = "(" + transEnablingsVHDL[transNum] + ")"; } // if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){ // transEnablingsVAMS[transNum] += ")"; // } if (!condStr.equalsIgnoreCase("")){ g.addEnabling(t, condStr); } else{ //g.addEnabling(t, condStr); } } } } if (failProp != null){ if ((g.getPreset(t) != null) && (!isTransientTransition(t)) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("PROP"))){ g.addEnabling(t, failProp); } } } ArrayList<String> placesWithoutPostsetTrans = new ArrayList<String>(); ArrayList<String> dcVars = new ArrayList<String>(); for (Variable v : reqdVarsL){ if (!v.isCare()) dcVars.add(v.getName()); } for (String st1 : g.getPlaceList()) { if (g.getPostset(st1).length == 0){ // a place without a postset transition placesWithoutPostsetTrans.add(st1); } else if (g.getPostset(st1).length > 1){ HashMap<String,Boolean> varsInEnabling = new HashMap<String,Boolean>(); for (String st2 : g.getPostset(st1)){ if (g.getEnablingTree(st2) != null){ for (String st3 : g.getEnablingTree(st2).getVars()){ varsInEnabling.put(st3, true); } } } for (String st2 : g.getPostset(st1)){ if ((varsInEnabling.keySet().size() >= 1) || (dcVars.size() > 0)){ // && (g.getEnablingTree(st2) != null)) //String[] binOutgoing = getPlaceInfoIndex(g.getPostset(st2)[0]).split(","); String transKey; if (!isTransientTransition(st2)) transKey = getTransitionInfoIndex(st2); else transKey = getTransientNetTransitionIndex(st2); String[] binOutgoing = getPostsetPlaceFullKey(transKey).split(","); String condStr = ""; for (String st : varsInEnabling.keySet()){ int bin = Integer.valueOf(binOutgoing[findReqdVarslIndex(st)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on Aug7,2010 } } for (String st : dcVars){ if(!varsInEnabling.containsKey(st)){ int bin = Integer.valueOf(binOutgoing[findReqdVarslIndex(st)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } } out.write("Changed enabling of " + st2 + " to " + condStr + "\n"); g.addEnabling(st2, condStr); } } /*for (String st2 : g.getPostset(st1)){ ExprTree enableTree = g.getEnablingTree(st2); if (enableTree != null){ // If enabling of a transition is null then it's obviously not mutually exclusive of any other parallel transitions from that place for (String st3 : varsInEnabling.keySet()){ // TODO: CHECK THE BIN CHANGES HERE AND ADD ENABLING CONDITIONS if (!enableTree.containsVar(st3)){ // System.out.println("At place " + st1 + " for transition " + st2 + ",Get threshold of " + st3); visitedPlaces = new HashMap<String,Boolean>(); String completeEn =traceBack(st1,st3); System.out.println("At place " + st1 + " for transition " + st2 + ",Get threshold of " + st3+ " from " + completeEn); Pattern enPatternParan = Pattern.compile(".*?(~?\\(" + st3+ ".*?\\)*)[a-zA-Z]*.*"); Pattern enPattern; Matcher enMatcher; //Pattern enPatternNoParan = Pattern.compile(".*?(~?\\(?" + st3+ ".*?\\)*)[a-zA-Z]*.*"); Matcher enMatcherParan = enPatternParan.matcher(completeEn); if (enMatcherParan.find()) { enPattern = Pattern.compile(".*?(~?\\(" + st3+ ".*?\\)).*?"); System.out.println("Matching for pattern " + enPattern.toString()); enMatcher = enPattern.matcher(completeEn); String enCond = enMatcher.group(1); System.out.println("Extracted " +enCond); } else { enPattern = Pattern.compile(".*?(" + st3+ ".*?)[a-zA-Z]*.*?"); System.out.println("Matching for pattern " + enPattern.toString()); enMatcher = enPattern.matcher(completeEn); String enCond = enMatcher.group(1); System.out.println("Extracted " +enCond); } } } } }*/ } if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { if (g.getPreset(st1).length != 0){ for (String t : g.getPreset(st1)) { for (int k = 0; k < reqdVarsL.size(); k++) { if (!reqdVarsL.get(k).isDmvc()) { int minr = getMinRate(p, reqdVarsL.get(k).getName()); int maxr = getMaxRate(p, reqdVarsL.get(k).getName()); if (minr != maxr) g.addRateAssign(t, reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign(t, reqdVarsL.get(k).getName(), String.valueOf(minr)); } } } } } } } for (String st1 : transientNetTransitions.keySet()){ String s = g.getPostset("t" + transientNetTransitions.get(st1).getProperty("transitionNum"))[0]; // check TYPE of preset ???? String p = getPlaceInfoIndex(s); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { for (int k = 0; k < reqdVarsL.size(); k++) { if (!reqdVarsL.get(k).isDmvc()) { // out.write("<" + t + "=[" + reqdVarsL.get(k).getName() + ":=[" + getMinRate(p, reqdVarsL.get(k).getName()) + "," + getMaxRate(p, reqdVarsL.get(k).getName()) + "]]>"); int minr = getMinRate(p, reqdVarsL.get(k).getName()); int maxr = getMaxRate(p, reqdVarsL.get(k).getName()); if (minr != maxr) g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), String.valueOf(minr)); } } } } //Reversed the order of adding initPlace and removing placeswithout postset transitions. //This makes sure that signals which are constant throughout a trace are not completely lost. addInitPlace(scaledThresholds); for (String st1 : placesWithoutPostsetTrans){ placeInfo.remove(getPlaceInfoIndex(st1)); g.removePlace(st1); } if (moduleNumber == 0){ out.write("Adding pseudo transitions now. It'll be saved in " + directory + separator + "pseudo" + lhpnFile + "\n"); addPseudo(scaledThresholds); lpnWithPseudo.save(directory + separator + "pseudo" + lhpnFile); } // addMetaBins(); // addMetaBinTransitions(); if ((destabMap != null) || (destabMap.size() != 0)){ HashMap<String, ArrayList<String>> dMap = new HashMap<String, ArrayList<String>>(); int mNum = 1000; for (String destabOp : destabMap.keySet()){ out.write("Generating stable signals with reqdVarsL as "); ArrayList <Variable> varsT = new ArrayList <Variable>(); for (String d : destabMap.get(destabOp)){ Variable input = new Variable(""); input.copy(reqdVarsL.get(findReqdVarslIndex(d))); //input.setCare(true); varsT.add(input); out.write(input.getName() + " "); } Variable output = new Variable(""); output.copy(reqdVarsL.get(findReqdVarslIndex("stable_" + destabOp))); output.setInput(false); output.setOutput(true); output.setCare(true); varsT.add(output); out.write(output.getName() + "\n"); LearnModel l = new LearnModel(); LhpnFile moduleLPN = l.learnModel(directory, log, biosim, mNum, thresholds, tPar, varsT, dMap, true, valScaleFactor, delayScaleFactor, null); //true parameter above indicates that the net being generated is for assigning stable // new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile); g = mergeLhpns(moduleLPN,g); mNum++; } } out.write("learning module done. Saving stuff and learning other modules.\n"); g.save(directory + separator + lhpnFile); new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile); out.write("Returning " + directory + separator + lhpnFile + "\n"); out.close(); //writeVerilogAMSFile(lhpnFile.replace(".lpn",".vams")); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "LPN file couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (NullPointerException e4) { e4.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "LPN file couldn't be created/written. Null exception", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (ArrayIndexOutOfBoundsException e1) { // comes from initMark = -1 of updateGraph() e1.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Unable to calculate rates.\nWindow size or pathLengthBin must be reduced.\nLearning unsuccessful.", "ERROR!", JOptionPane.ERROR_MESSAGE); try { out.write("ERROR! Unable to calculate rates.\nIf Window size = -1, pathLengthBin must be reduced;\nElse, reduce windowsize\nLearning unsuccessful."); out.close(); } catch (IOException e2) { e2.printStackTrace(); } } catch (java.lang.IllegalStateException e3){ e3.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "LPN File not found for merging.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return (g); } public void addStablesToData(HashMap<String, ArrayList<Double>> localThresholds, HashMap<String, ArrayList<String>> useMap){ boolean sameBin = true; ArrayList<String> destabIps; HashMap<String, Integer> dataIndices; int point; for (String s : useMap.keySet()){ // destabIps = new ArrayList<String>(); // destabIps.add("ctl"); destabIps = useMap.get(s); dataIndices = new HashMap<String, Integer>(); for (int i = 0; i < destabIps.size(); i++) { String currentVar = destabIps.get(i);//reqdVarsL.get(i).getName(); for (int j = 1; j < varNames.size(); j++) { if (currentVar.equalsIgnoreCase(varNames.get(j))) { dataIndices.put(currentVar,Integer.valueOf(j)); } } } //int[] oldBin = new int[destabIps.size()]; //int[] newBin = new int[destabIps.size()]; int[] oldBin = new int[dataIndices.size()]; int[] newBin = new int[dataIndices.size()]; //double unstableTime = 5960.0; ArrayList<Double> dataForStable = new ArrayList<Double>(); point = 0; dataForStable.add(0.0); //Assume that always it starts unstable for (int j = 0; j < destabIps.size(); j++){ String d = destabIps.get(j); if (dataIndices.containsKey(d)) oldBin[j] = getRegion(data.get(dataIndices.get(d)).get(point),localThresholds.get(d)); } for (int i = point+1; i < data.get(0).size(); i++){ sameBin = true; for (int j = 0; j < destabIps.size(); j++){// check if all the responsible destabilizing variables are in the same bin at i as they were at point String d = destabIps.get(j); if (dataIndices.containsKey(d)){ newBin[j] = getRegion(data.get(dataIndices.get(d)).get(i),localThresholds.get(d)); if (oldBin[j] != newBin[j]){ sameBin = false; break; } } } if ((sameBin) && (dataIndices.size() != 0)){ if ((data.get(0).get(i) - data.get(0).get(point)) >= unstableTime){ //dataForStable.set(i, 1.0); dataForStable.add(1.0); } else { //dataForStable.set(i, 0.0); dataForStable.add(0.0); } } else { //dataForStable.set(i, 0.0); dataForStable.add(0.0); for (int j = 0; j < destabIps.size(); j++){ String d = destabIps.get(j); if (dataIndices.containsKey(d)) oldBin[j] = getRegion(data.get(dataIndices.get(d)).get(point),localThresholds.get(d)); } point = i; } } if (dataIndices.size() != 0){ data.add(dataForStable); varNames.add("stable_" + s); } } } public Double getDelayScaleFactor(){ return delayScaleFactor; } public Double getValueScaleFactor(){ return valScaleFactor; } private int findReqdVarslIndex(String s) { for (int i = 0; i < reqdVarsL.size() ; i++){ if (s.equalsIgnoreCase(reqdVarsL.get(i).getName())){ return i; } } return -1; } private boolean isTransientPlace(String st1) { for (String s : transientNetPlaces.keySet()){ if (st1.equalsIgnoreCase("p" + transientNetPlaces.get(s).getProperty("placeNum"))){ return true; } } return false; } private boolean isTransientTransition(String st1) { for (String s : transientNetTransitions.keySet()){ if (st1.equalsIgnoreCase("t" + transientNetTransitions.get(s).getProperty("transitionNum"))){ return true; } } return false; } public void resetAll(){ // dmvcCnt = 0; numPlaces = 0; numTransitions = 0; delayScaleFactor = 1.0; valScaleFactor = 1.0; for (Variable v: reqdVarsL){ v.reset(); } } public void findReqdVarIndices(){ reqdVarIndices = new ArrayList<Integer>(); for (int i = 0; i < reqdVarsL.size(); i++) { for (int j = 1; j < varNames.size(); j++) { if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) { reqdVarIndices.add(j); } } } } public int getCareIndex(int reqdVarsIndex){ int count = -1; for (int j = 0; j < reqdVarsL.size(); j++){ if (reqdVarsL.get(j).isCare()){ count++; } if (j == reqdVarsIndex) return count; } return -1; } public void addInitPlace(HashMap<String,ArrayList<Double>> scaledThresholds){ //Properties initPlace = new Properties(); //placeInfo.put("initMarked", p0); //initPlace.setProperty("placeNum", numPlaces.toString()); //initPlace.setProperty("type", "INIT"); //initPlace.setProperty("initiallyMarked", "true"); int initPlaceNum = numPlaces; g.addPlace("p" + numPlaces, true); //propPlaces.add("p" + numPlaces); numPlaces++; try{ try{ out.write("Transient places are : "); for (String st : transientNetPlaces.keySet()){ out.write(st + ";"); } out.write("\n"); for (String st : transientNetPlaces.keySet()){ //Properties p1 = new Properties(); //p1.setProperty("transitionNum", numTransitions.toString()); //initTransitions.put(key, p1); //from initPlaceNum to key g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + initPlaceNum, "t" + numTransitions); g.addMovement("t" + numTransitions, "p" + transientNetPlaces.get(st).getProperty("placeNum")); g.changeInitialMarking("p" + transientNetPlaces.get(st).getProperty("placeNum"), false); out.write("Added transition t" + numTransitions + " b/w initPlace and transient place p" + transientNetPlaces.get(st).getProperty("placeNum") + "\n"); String[] binOutgoing = st.split(","); String condStr = ""; for (int j = 0; j < reqdVarsL.size(); j++){ // preserving the order by having reqdVarsL as outer loop rather than care String st2 = reqdVarsL.get(j).getName(); if (reqdVarsL.get(j).isCare()){ if (reqdVarsL.get(j).isInput()){ int bin = Integer.valueOf(binOutgoing[getCareIndex(j)]); if (bin == 0){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "~(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st2).size())){ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")"; } else{ if (!condStr.equalsIgnoreCase("")) condStr += "&"; condStr += "(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin-1).doubleValue()) + ")&~(" + st2 + ">=" + (int) Math.floor(scaledThresholds.get(st2).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } else { if (reqdVarsL.get(j).isDmvc()){ int minv = (int) Math.floor(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMin"))); int maxv = (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(st).getProperty(st2 + "_vMax"))); if (minv != maxv) g.addIntAssign("t" + numTransitions,st2,"uniform(" + minv + ","+ maxv + ")"); else g.addIntAssign("t" + numTransitions,st2,String.valueOf(minv)); out.write("Added assignment to " + st2 + " at transition t" + numTransitions + "\n"); } // deal with rates for continuous here } } else { out.write(st2 + " was don't care " + "\n"); } } out.write("Changed enabling of t" + numTransitions + " to " + condStr + "\n"); g.addEnabling("t" + numTransitions, condStr); numTransitions++; } for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace. if (st1.size() != 0){ g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + initPlaceNum, "t" + numTransitions); for (String st2: st1.keySet()){ g.addIntAssign("t" + numTransitions,st2,st1.get(st2)); } numTransitions++; } } } catch (NullPointerException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Null exception in addInitPlace.", "ERROR!", JOptionPane.ERROR_MESSAGE); out.close(); } }catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened in addInitPlace.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void genBinsRates(HashMap<String, ArrayList<Double>> localThresholds) { // TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false); // genBins data = tsd.getData(); try{ reqdVarIndices = new ArrayList<Integer>(); //careBins = new HashMap<String, int[]>();//new int[reqdVarsL.size()][data.get(0).size()]; bins = new int[reqdVarsL.size()][data.get(0).size()]; for (int i = 0; i < reqdVarsL.size(); i++) { // System.out.println("Divisions " + divisionsL.get(i)); for (int j = 1; j < varNames.size(); j++) { String currentVar = reqdVarsL.get(i).getName(); if (currentVar.equalsIgnoreCase(varNames.get(j))) { // System.out.println(reqdVarsL.get(i) + " matched "+ // varNames.get(j) + " i = " + i + " j = " + j); reqdVarIndices.add(j); for (int k = 0; k < data.get(j).size(); k++) { // System.out.print(data.get(j).get(k) + " "); ArrayList<Double> thresh = localThresholds.get(currentVar); bins[i][k] = getRegion(data.get(j).get(k),thresh); if ((k != 0) && (bins[i][k] != bins[i][k-1])){ int length = 0; for (int m = k; m < data.get(j).size(); m++) { if (getRegion(data.get(j).get(m),thresh) == bins[i][k]) length++; else break; } if (length < pathLengthVar){ out.write("Short bin for variable " + currentVar + " at " + data.get(0).get(k) + " until " + data.get(0).get(k+length-1) + " due to min pathLengthVar. Using " + bins[i][k-1] + " instead of " + bins[i][k] + " \n"); for (int m = k; m < k+length; m++) { bins[i][m] = bins[i][k-1]; } } else { for (int m = k; m < k+length; m++) { bins[i][m] = bins[i][k]; } } k = k+length-1; } } if (binError) JOptionPane.showMessageDialog(BioSim.frame, "Bin couldn't be retrieved for a point. Please check thresholds.", "ERROR!", JOptionPane.ERROR_MESSAGE); // System.out.print(" "); break; } else { out.write("WARNING: A variable in reqdVarsL wasn't found in the complete list of names.\n"); } } } /* * System.out.println("array bins is :"); for (int i = 0; i < * reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + " * "); for (int k = 0; k < data.get(0).size(); k++) { * System.out.print(bins[i][k] + " "); } System.out.print("\n"); } */ // genRates rates = new Double[reqdVarsL.size()][data.get(0).size()]; values = new double[reqdVarsL.size()][data.get(0).size()]; duration = new Double[data.get(0).size()]; int mark, k, previous = 0, markFullPrev; // indices of rates not same as that of the variable. if // wanted, then size of rates array should be varNames // not reqdVars if (rateSampling == -1) { // replacing inf with -1 since int mark = 0; markFullPrev = 0; for (int i = 0; i < data.get(0).size(); i++) { if (i < mark) { continue; } markFullPrev = mark; //while ((mark < data.get(0).size()) && (compareBins(i, mark))) { while (mark < data.get(0).size()){ if (compareBins(i, mark)){ for (int j = 0; j < reqdVarsL.size(); j++){ k = reqdVarIndices.get(j); values[j][i] = (values[j][i]*(mark-i) + data.get(k).get(mark))/(mark-i+1); } mark++; } else break; //Assume that only inputs can be don't care if (!compareFullBinInputs(markFullPrev, mark-1)){ //mark-1 because of mark++ above markFullPrev = mark-1; } } if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLengthBin) && (mark != data.get(0).size())) { // && (mark != (data.get(0).size() - 1 condition added on nov 23.. to avoid the last region bcoz it's not complete. rechk if (!compareBins(previous,i)){ for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } //duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 duration[i] = data.get(0).get(mark) - data.get(0).get(markFullPrev); previous = i; if (markFullPrev != i) out.write("Some don't care input change in b/w a bin. So referencing off " + markFullPrev + " instead of " + i + "\n"); } else{ // There was a glitch and you returned to the same region for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous))); } if (mark < data.get(0).size()) //This if condition added to fix bug on sept 25 2010 duration[previous] = data.get(0).get(mark) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010 } } else if ((mark - i) < pathLengthBin) { // account for the glitch duration // out.write("Short bin at " + data.get(0).get(i) + " until " + data.get(0).get(mark) + " due to min pathLengthBin. This delay being added to " + previous + " \n"); duration[previous] += data.get(0).get(mark) - data.get(0).get(i); } else if (data.get(0).get(mark - 1) == data.get(0).get(i)){ // bin with only one point. Added this condition on June 9,2010 //Rates are meaningless here since the bin has just one point. //But calculating the rate because if it is null, then places won't be created in genBinsRates for one point bins. //Calculating rate b/w start point of next bin and start point of this bin out.write("Bin with one point at time " + data.get(0).get(i) + "\n"); for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark) - data.get(k).get(i)) / (data.get(0).get(mark) - data.get(0).get(i))); } duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 previous = i; } else if (mark == data.get(0).size()){ // long enough bin towards the end of trace. if (!compareBins(previous,i)){ for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i))); } //duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010 previous = i; } else{ // There was a glitch and you returned to the same region //Or signal is constant through out the trace for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous))); } //This duration shouldn't make any sense because there's no following transition duration[previous] = data.get(0).get(mark - 1) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010 } out.write("Bin at end of trace starts at " + previous + "\n"); } } } else { //TODO: This may have bugs in duration calculation etc. boolean calcRate; boolean prevFail = true; int binStartPoint = 0, binEndPoint = 0; for (int i = 0; i < (data.get(0).size() - rateSampling); i++) { calcRate = true; for (int l = 0; l < rateSampling; l++) { if (!compareBins(i, i + l)) { if (!prevFail){ binEndPoint = i -2 + rateSampling; duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint); } calcRate = false; prevFail = true; break; } } if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i))); } if (prevFail){ binStartPoint = i; } prevFail = false; } } // commented on nov 23. don't need this. should avoid rate calculation too for this region. but not avoiding now. /* if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint); }*/ } } catch (NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Bins/Rates could not be generated. Please check thresholds.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch (IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing genBinsRates messages.", "ERROR!", JOptionPane.ERROR_MESSAGE); } /*try { for (int i = 0; i < (data.get(0).size()); i++) { for (int j = 0; j < reqdVarsL.size(); j++) { k = reqdVarIndices.get(j); out.write(data.get(k).get(i) + " ");// + bins[j][i] + " " + // rates[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(bins[j][i] + " "); } for (int j = 0; j < reqdVarsL.size(); j++) { out.write(rates[j][i] + " "); } out.write(duration[i] + " "); out.write("\n"); } } catch (IOException e) { System.out .println("Log file couldn't be opened for writing rates and bins "); }*/ } public int getRegion(double value, ArrayList<Double> varThresholds){ int bin = 0; try{ for (int l = 0; l < varThresholds.size(); l++) { if (value <= varThresholds.get(l)) { bin = l; break; } else { bin = l + 1; } } } catch (NullPointerException e){ e.printStackTrace(); binError = true; } return bin; } public boolean compareBins(int j, int mark) { /*for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true;*/ /*for (String st : careVars) { // this way only when order of cares not important. since this is a hashmap if (bins[findReqdVarslIndex(st)][j]!= bins[findReqdVarslIndex(st)][mark]) { return false; } else { continue; } } return true;*/ for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isCare()){ if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } } return true; } public boolean compareFullBinInputs(int j, int mark) { for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isInput() && (bins[i][j] != bins[i][mark])) { return false; } else { continue; } } return true; } public void updateRateInfo(int[][] bins, Double[][] rates, int traceNum, Properties cvgProp) { String prevPlaceKey = "", prevPlaceFullKey = ""; // "" or " " ; rechk String key = "", fullKey = ""; Double prevPlaceDuration = null; String transId = null; Boolean prevIpChange = false, prevOpChange = false, ipChange = false, opChange = false, careIpChange = false; // boolean addNewPlace; ArrayList<String> ratePlaces = new ArrayList<String>(); // ratePlaces can include non-input dmv places. // boolean newRate = false; try{ Properties p0, p1 = null; out.write("In UpdateRateInfo\n"); for (int i = 0; i < (data.get(0).size() - 1); i++) { if (rates[0][i] != null) { // check if indices are ok. 0???? or 1??? prevPlaceKey = key; prevPlaceFullKey = fullKey; key = ""; fullKey = ""; //Full keys are for transitions; Just Keys are for Places for (int j = 0; j < reqdVarsL.size(); j++) { if (reqdVarsL.get(j).isCare()){ if (key.equalsIgnoreCase("")) key += bins[j][i]; else key += "," + bins[j][i]; } if (fullKey.equalsIgnoreCase("")) fullKey += bins[j][i]; else fullKey += "," + bins[j][i]; } out.write("Rates not null at " + i + "; key is " + key + "; full key is " + fullKey + ";\n"); if (placeInfo.containsKey(key) && (ratePlaces.size() != 0)) { p0 = placeInfo.get(key); out.write("Came back to existing place p" + p0.getProperty("placeNum") + " at time " + data.get(0).get(i) + " bins " + key + "\n"); if (traceNum > 1) ratePlaces.add("p" + p0.getProperty("placeNum")); } else if ((transientNetPlaces.containsKey(key)) && (((ratePlaces.size() == 1) && (traceNum == 1)) || ((ratePlaces.size() == 0) && (traceNum != 1)))){ // same transient in new trace => ratePlaces.size() < 1; same transient in same trace => ratePlaces.size() = 1 p0 = transientNetPlaces.get(key); out.write("Came back to existing transient place p" + p0.getProperty("placeNum") + " at time " + data.get(0).get(i) + " bins " + key + "\n"); if (ratePlaces.size() == 0){ // new trace ratePlaces.add("p" + p0.getProperty("placeNum")); } } else { p0 = new Properties(); if (ratePlaces.size() == 0){ transientNetPlaces.put(key, p0); g.addPlace("p" + numPlaces, true); } else{ placeInfo.put(key, p0); g.addPlace("p" + numPlaces, false); } p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","false"); // REMOVE LATER????? ratePlaces.add("p" + numPlaces); out.write("New place p" + numPlaces + " at time " + data.get(0).get(i) + " bins " + key + "\n"); numPlaces++; cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } for (int j = 0; j < reqdVarsL.size(); j++) { // rechk if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { // continue; // } if (reqdVarsL.get(j).isDmvc()) { // && !reqdVarsL.get(j).isInput()){ //System.out.println(reqdVarsL.get(j).getName() + " " + bins[j][i] + " " + dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i]))"\n"); out.write("Add value : " + reqdVarsL.get(j).getName() + " -> corresponding to bin " + bins[j][i] + " at place p" + p0.getProperty("placeNum") + "\n"); out.write("Add value : " + reqdVarsL.get(j).getName() + " -> " + Double.valueOf(dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i]))) + " at place p" + p0.getProperty("placeNum") + "\n"); addValue(p0,reqdVarsL.get(j).getName(),Double.valueOf(dmvcValuesUnique.get(reqdVarsL.get(j).getName()).getProperty(String.valueOf(bins[j][i])))); //out.write("Add value : " + reqdVarsL.get(j).getName() + " -> " + dmvcValuesUnique.get(reqdVarsL.get(j).getName()).get(bins[j][i]) + " at place p" + p0.getProperty("placeNum") + "\n"); continue; } addRate(p0, reqdVarsL.get(j).getName(), rates[j][i]); } boolean transientNet = false; if (!prevPlaceFullKey.equalsIgnoreCase(fullKey)) { if (!prevPlaceFullKey.equals("")){ ArrayList<Integer> diffL = diff(prevPlaceFullKey,fullKey); opChange = false; ipChange = false; careIpChange = false; for (int k : diffL) { if (reqdVarsL.get(k).isInput()) { ipChange = true; if (reqdVarsL.get(k).isCare()) careIpChange = true; } else { opChange = true; } } } else { ipChange = false; opChange = false; careIpChange = false; } if ((traceNum > 1) && transientNetTransitions.containsKey(prevPlaceFullKey + "," + fullKey) && (ratePlaces.size() == 2)) { // same transient transition as that from some previous trace p1 = transientNetTransitions.get(prevPlaceFullKey + "," + fullKey); transId = prevPlaceFullKey + "," + fullKey; out.write("Came back to existing transient transition t" + p1.getProperty("transitionNum") + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); } else if (transitionInfo.containsKey(prevPlaceFullKey + "," + fullKey) && (ratePlaces.size() > 2)) { // instead of tuple p1 = transitionInfo.get(prevPlaceFullKey + "," + fullKey); transId = prevPlaceFullKey + "," + fullKey; out.write("Came back to existing transition t" + p1.getProperty("transitionNum") + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); } else if (!prevPlaceFullKey.equalsIgnoreCase("")) { // transition = new Transition(reqdVarsL.size(),place,prevPlace); p1 = new Properties(); p1.setProperty("transitionNum", numTransitions.toString()); if (ratePlaces.size() == 2){ transientNetTransitions.put(prevPlaceFullKey + "," + fullKey, p1); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + transientNetPlaces.get(prevPlaceKey).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); transientNet = true; transId = prevPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } else { if (prevIpChange & !prevOpChange & opChange & !ipChange){ out.write("Should delete the transition" + transId+ " from "); if (transitionInfo.containsKey(transId)){ out.write("transitionInfo\n"); int removeTrans = Integer.valueOf(transitionInfo.get(transId).getProperty("transitionNum")); String lastLastPlace = g.getTransition("t" + removeTrans).getPreset()[0].getName(); //String lastLastPlaceKey = getPlaceInfoIndex(lastLastPlace); String lastLastPlaceFullKey = getPresetPlaceFullKey(transId); if (transitionInfo.containsKey(lastLastPlaceFullKey + "," + fullKey)){ p1 = transitionInfo.get(lastLastPlaceFullKey + "," + fullKey); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transitionInfo.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nFound an output change follwing a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and p" + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; merged transition already exists in the form of t" + p1.getProperty("transitionNum") + " b/w " + lastLastPlace + " and p" + placeInfo.get(key).getProperty("placeNum") + "\n"); transitionInfo.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; } else { transitionInfo.put(lastLastPlaceFullKey + "," + fullKey, p1); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transitionInfo.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement(lastLastPlace, "t" + transitionInfo.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nFound an output change follwing a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; add transition t" + numTransitions + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transitionInfo.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } else if (transientNetTransitions.containsKey(transId)){ out.write("transientNetTransitions\n"); int removeTrans = Integer.valueOf(transientNetTransitions.get(transId).getProperty("transitionNum")); String lastLastPlace = g.getTransition("t" + removeTrans).getPreset()[0].getName(); //String lastLastPlaceKey = getTransientNetPlaceIndex(lastLastPlace); String lastLastPlaceFullKey = getPresetPlaceFullKey(transId); if (transientNetTransitions.containsKey(lastLastPlaceFullKey + "," + fullKey)){ p1 = transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transientNetTransitions.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nTRANSIENT:Found an output change followed by a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; merged transition already exists in the form of t" + p1.getProperty("transitionNum") + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transientNetTransitions.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; } else { transientNetTransitions.put(lastLastPlaceFullKey + "," + fullKey, p1); p1.put("ioChangeDelay", "yes"); int removeTransNum = Integer.valueOf(transientNetTransitions.get(lastLastPlaceFullKey + "," + prevPlaceFullKey).getProperty("transitionNum")); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement(lastLastPlace, "t" + transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(lastLastPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); if (removeTransNum == numTransitions -1){ out.write("\n\n\nTRANSIENT:Found an output change followed by a previous input change; remove transition t" + removeTransNum + " between " + lastLastPlace + " and " + placeInfo.get(prevPlaceKey).getProperty("placeNum") + "; add transition t" + numTransitions + " b/w " + lastLastPlace + " and " + placeInfo.get(key).getProperty("placeNum") + "\n"); transientNetTransitions.remove(lastLastPlaceFullKey + "," + prevPlaceFullKey); //g.removeTransition("t" + (numTransitions -1)); g.removeTransition("t" + removeTransNum); } transId = lastLastPlaceFullKey + "," + fullKey; out.write("TRANSIENT:New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } else { out.write("transition " + transId+ " not present to delete\n"); System.out.println("transition " + transId+ " not present to delete\n"); } } else { transitionInfo.put(prevPlaceFullKey + "," + fullKey, p1); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(prevPlaceKey).getProperty("placeNum"), "t" + transitionInfo.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(prevPlaceFullKey + "," + fullKey).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); transId = prevPlaceFullKey + "," + fullKey; out.write("New transition t" + numTransitions + " at time " + data.get(0).get(i) + " " + prevPlaceFullKey + " -> " + fullKey); numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } // transition.setCore(true); } prevIpChange = ipChange; prevOpChange = opChange; //else if (prevPlaceKey == "") { // p1 = new Properties(); // p1.setProperty("transitionNum", numTransitions.toString()); // initTransitions.put(key, p1); //from initPlaceNum to key // g.addTransition("t" + numTransitions); // prevTranKey+key); // g.addMovement("p" + transientNetPlaces.get(prevPlaceKey).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum")); // g.addMovement("t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // numTransitions++; //} if (prevPlaceDuration != null){ //Delay on a transition is the duration spent at its preceding place /*if (!(ipChange & opChange)){ addDuration(p1, prevPlaceDuration); out.write(" Added duration " + prevPlaceDuration + " to transition t" + p1.getProperty("transitionNum") + "\n"); } else{ addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); }*/ if (!opChange){ //Commented above and changed to this on Aug 5,2010. When there's no o/p bin change, then thrs no need for delay. addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); } else if (careIpChange){ // Both o/p and a care i/p changed on the same transition. So, they changed at the same time. addDuration(p1, 0.0); out.write(" Added duration 0 to transition t" + p1.getProperty("transitionNum") + "\n"); } else { //o/p change alone or (o/p change and don't care i/p change) addDuration(p1, prevPlaceDuration); out.write(" Added duration " + prevPlaceDuration + " to transition t" + p1.getProperty("transitionNum") + "\n"); } } else { out.write(" Not adding duration here. CHECK\n"); } } prevPlaceDuration = duration[i]; /*if (duration[i] != null){ //STORING DELAYS AT TRANSITIONS NOW addDuration(p0, duration[i]); }*/ //else if (duration[i] != null && transientNet){ // addTransientDuration(p0, duration[i]); //} if (p1 != null) { for (int j = 0; j < reqdVarsL.size(); j++) { if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) { continue; } if (reqdVarsL.get(j).isDmvc()) { continue; } addRate(p1, reqdVarsL.get(j).getName(), rates[j][i]); } } } } }catch (IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing UpdateRateInfo messages.", "ERROR!", JOptionPane.ERROR_MESSAGE); }catch (NullPointerException e4) { e4.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Null exception during model generation in updateRate", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public String getPresetPlaceFullKey(String transition){ //out.write("preset key for " + transition + " is "); String fullKey = ""; if (transition != null){ String[] b = transition.split(","); for (int j = 0; j < reqdVarsL.size(); j++) { if (fullKey.equalsIgnoreCase("")) fullKey += b[j]; else fullKey += "," + b[j]; } //out.write(fullKey + "\n"); return(fullKey); } else return null; } public String getPostsetPlaceFullKey(String transition){ String fullKey = ""; if (transition != null){ String[] b = transition.split(","); for (int j = 0; j < reqdVarsL.size(); j++) { if (fullKey.equalsIgnoreCase("")) fullKey += b[j + reqdVarsL.size()]; else fullKey += "," + b[j + reqdVarsL.size()]; } return(fullKey); } else return null; } public void updateGraph(int[][] bins, Double[][] rates, int traceNum, Properties cvgProp) { updateRateInfo(bins, rates, traceNum, cvgProp); //updateTimeInfo(bins,cvgProp); int initMark = -1; int k; String key; constVal.add(new HashMap<String, String>()); for (int i = 0; i < reqdVarsL.size(); i++) { for (int j = 0; j < data.get(0).size(); j++) { if (rates[i][j] != null) { k = reqdVarIndices.get(i); // addInitValues(data.get(k).get(j), i); // k or i think ?? // addInitRates(rates[i][j], i);// k or i think?? reqdVarsL.get(i).addInitValues(data.get(k).get(j)); // Do the same for initvals too?? //reqdVarsL.get(i).addInitRates(rates[i][j]); // this just adds the first rate; not the rates of entire 1st region. initMark = j; break; } } if (initMark == -1){//constant throughout the trace? initMark = 0; k = reqdVarIndices.get(i); constVal.get(constVal.size() - 1).put(reqdVarsL.get(i).getName(),data.get(k).get(0).toString()); reqdVarsL.get(i).addInitValues(data.get(k).get(0)); } key = "" + bins[0][initMark]; for (int l = 1; l < reqdVarsL.size(); l++) { // key = key + "" + bins[l][initMark]; key = key + "," + bins[l][initMark]; } if (!reqdVarsL.get(i).isDmvc()){ reqdVarsL.get(i).addInitRates((double)getMinRate(key, reqdVarsL.get(i).getName())); reqdVarsL.get(i).addInitRates((double)getMaxRate(key, reqdVarsL.get(i).getName())); } /* if (placeInfo.get(key).getProperty("initiallyMarked").equalsIgnoreCase("false")) { placeInfo.get(key).setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + placeInfo.get(key).getProperty("placeNum"), true); } */ } } public HashMap<String, ArrayList<Double>> detectDMV(ArrayList<ArrayList<Double>> data, Boolean callFromAutogen) { int startPoint, endPoint, mark, numPoints; HashMap<String, ArrayList<Double>> dmvDivisions = new HashMap<String, ArrayList<Double>>(); double absTime; //dmvcValuesUnique = new HashMap<String, ArrayList<Double>>(); try{ for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isForcedCont()){ reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is forced to be continuous \n"); } else { absTime = 0; mark = 0; DMVCrun runs = reqdVarsL.get(i).getRuns(); runs.clearAll(); // flush all the runs from previous dat file. int lastRunPointsWithoutTransition = 0; Double lastRunTimeWithoutTransition = 0.0; Double lastRunValueWithoutTransition = null; out.write("Epsilon for " + reqdVarsL.get(i).getName() + " is " + reqdVarsL.get(i).getEpsilon()); if (!callFromAutogen) { // This flag is required because if the call is from autogenT, then data has just the reqdVarsL but otherwise, it has all other vars too. So reqdVarIndices not reqd when called from autogen for (int j = 0; j <= data.get(reqdVarIndices.get(i)).size(); j++) { // changed from data.get(0).size() to data.get(reqdVarIndices.get(i)).size() on july 31,2010. if (j < mark) // not reqd?? continue; if (((j+1) < data.get(reqdVarIndices.get(i)).size()) && Math.abs(data.get(reqdVarIndices.get(i)).get(j) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon()) { startPoint = j; runs.addValue(data.get(reqdVarIndices.get(i)).get(j)); // chk carefully reqdVarIndices.get(i) while (((j + 1) < data.get(0).size()) && (bins[i][startPoint] == bins[i][j+1]) && (Math.abs(data.get(reqdVarIndices.get(i)).get(startPoint) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= reqdVarsL.get(i).getEpsilon())) { //checking of same bins[] condition added on May 11,2010. runs.addValue(data.get(reqdVarIndices.get(i)).get(j + 1)); // chk carefully // reqdVarIndices.get(i) j++; } endPoint = j; if (!absoluteTime) { if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); } else if (((endPoint - startPoint) + 1) >= runLength) { lastRunPointsWithoutTransition = endPoint - startPoint + 1; lastRunValueWithoutTransition = runs.getLastValue(); } else { runs.removeValue(); } } else { if ((endPoint < (data.get(0).size() - 1)) && (calcDelay(startPoint, endPoint) >= runTime)) { runs.addStartPoint(startPoint); runs.addEndPoint(endPoint); absTime += calcDelay(startPoint, endPoint); } else if (calcDelay(startPoint, endPoint) >= runTime) { lastRunTimeWithoutTransition = calcDelay(startPoint, endPoint); lastRunValueWithoutTransition = runs.getLastValue(); } else { runs.removeValue(); } } mark = endPoint; } } numPoints = runs.getNumPoints(); if (!reqdVarsL.get(i).isForcedDmv() && ((absoluteTime && (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data .get(0).get(0))) < percent)) || (!absoluteTime && (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent)))){ // isForced condition added on may 28 runs.clearAll(); reqdVarsL.get(i).setDmvc(false); out.write(reqdVarsL.get(i).getName() + " is not a dmvc \n"); } else { reqdVarsL.get(i).setDmvc(true); Double[] dmvcValues; if (lastRunValueWithoutTransition != null ){ Double[] dVals = reqdVarsL.get(i).getRuns().getAvgVals(); dmvcValues = new Double[dVals.length + 1]; for (int j = 0; j < dVals.length; j++){ dmvcValues[j] = dVals[j]; } dmvcValues[dVals.length] = lastRunValueWithoutTransition; } else dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals(); Arrays.sort(dmvcValues); //System.out.println("Sorted DMV values of " + reqdVarsL.get(i).getName() + " are "); //for (Double l : dmvcValues){ // System.out.print(l + " "); //} //System.out.println(); if (!dmvcValuesUnique.containsKey(reqdVarsL.get(i).getName())) dmvcValuesUnique.put(reqdVarsL.get(i).getName(),new Properties()); out.write("DMV values of " + reqdVarsL.get(i).getName() + " are : "); if (dmvcValues.length == 0){// constant value throughout the trace dmvcValues = new Double[1]; dmvcValues[0]= reqdVarsL.get(i).getRuns().getConstVal(); } for (int j = 0; j < dmvcValues.length; j++){ if (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(0)){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put("0",dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin 0 is " + dmvcValues[j] + "\n"); out.write("bin 0 -> " + dmvcValues[j] + "; "); } else if (dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(thresholds.get(reqdVarsL.get(i).getName()).size() - 1)){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(thresholds.get(reqdVarsL.get(i).getName()).size()),dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + thresholds.get(reqdVarsL.get(i).getName()).size() + " is " + dmvcValues[j] + "\n"); out.write("bin " + thresholds.get(reqdVarsL.get(i).getName()).size() + " -> " + dmvcValues[j] + "; "); } else { for (int k = 0; k < thresholds.get(reqdVarsL.get(i).getName()).size()-1; k++){ if ((dmvcValues[j] >= thresholds.get(reqdVarsL.get(i).getName()).get(k)) && (dmvcValues[j] < thresholds.get(reqdVarsL.get(i).getName()).get(k+1))){ dmvcValuesUnique.get(reqdVarsL.get(i).getName()).put(String.valueOf(k+1),dmvcValues[j].toString()); //System.out.println("For variable " + reqdVarsL.get(i).getName() + " value for bin " + String.valueOf(k+1) + " is " + dmvcValues[j] + "\n"); out.write("bin " + (k+1) + " -> " + dmvcValues[j] + "; "); break; } } } //out.write(dmvcValues[j] + " "); //following not needed for calls from data2lhpn // dmvSplits.add((dmvcValuesUnique.get(reqdVarsL.get(i).getName()).get(dmvcValuesUnique.get(reqdVarsL.get(i).getName()).size() - 1) + dmvcValuesUnique.get(reqdVarsL.get(i).getName()).get(dmvcValuesUnique.get(reqdVarsL.get(i).getName()).size() - 2))/2); //} //for (int k = j+1; k < dmvcValues.length; k++){ // if (Math.abs((dmvcValues[j] - dmvcValues[k])) > epsilon){ // j = k-1; // break; // } // else if (k >= (dmvcValues.length -1)){ // j = k; // } //} } //dmvDivisions.put(reqdVarsL.get(i).getName(), dmvSplits); out.write("\n" + reqdVarsL.get(i).getName() + " is a dmvc \n"); } } } } }catch (IOException e) { e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } dmvDetectDone = true; return(dmvDivisions); } public double calcDelay(int i, int j) { return (data.get(0).get(j) - data.get(0).get(i)); // should add some next run logic later..? } public double calcDelayWithData(int i, int j, ArrayList<ArrayList<Double>> data) { return (data.get(0).get(j) - data.get(0).get(i)); } public void addValue(Properties p, String name, Double v) { Double vMin; Double vMax; if ((p.getProperty(name + "_vMin") == null) && (p.getProperty(name + "_vMax") == null)) { p.setProperty(name + "_vMin", v.toString()); p.setProperty(name + "_vMax", v.toString()); return; } else { vMin = Double.parseDouble(p.getProperty(name + "_vMin")); vMax = Double.parseDouble(p.getProperty(name + "_vMax")); if (v < vMin) { vMin = v; } else if (v > vMax) { vMax = v; } } p.setProperty(name + "_vMin", vMin.toString()); p.setProperty(name + "_vMax", vMax.toString()); } public void addRate(Properties p, String name, Double r) { Double rMin; Double rMax; if ((p.getProperty(name + "_rMin") == null) && (p.getProperty(name + "_rMax") == null)) { p.setProperty(name + "_rMin", r.toString()); p.setProperty(name + "_rMax", r.toString()); return; } else { rMin = Double.parseDouble(p.getProperty(name + "_rMin")); rMax = Double.parseDouble(p.getProperty(name + "_rMax")); if (r < rMin) { rMin = r; } else if (r > rMax) { rMax = r; } } p.setProperty(name + "_rMin", rMin.toString()); p.setProperty(name + "_rMax", rMax.toString()); } public void deleteInvalidDmvcTime(Properties p, Double t) { String[] times = null; String name = p.getProperty("DMVCVariable"); String s = p.getProperty("dmvcTime_" + name); String newS = null; Double dMin = null, dMax = null; if (s != null) { times = s.split(" "); for (int i = 0; i < times.length; i++) { if (Double.parseDouble(times[i]) != t) { if (newS == null){ newS = times[i]; dMin = Double.parseDouble(times[i]); dMax = Double.parseDouble(times[i]); } else{ newS += " " + times[i]; dMin = (Double.parseDouble(times[i]) < dMin) ? Double.parseDouble(times[i]) : dMin; dMax = (Double.parseDouble(times[i]) > dMax) ? Double.parseDouble(times[i]) : dMax; } } } p.setProperty("dmvcTime_" + name, newS); } if (dMin != null){ p.setProperty("dMin", dMin.toString()); p.setProperty("dMax", dMax.toString()); } } public HashMap<String,ArrayList<Double>> normalize() { HashMap<String,ArrayList<Double>> scaledThresholds = new HashMap<String,ArrayList<Double>>(); Boolean contVarExists = false; for (Variable v : reqdVarsL){ if (!v.isDmvc()){ contVarExists = true; } } // deep copy of divisions for (String s : thresholds.keySet()){ ArrayList<Double> o1 = thresholds.get(s); ArrayList<Double> tempDiv = new ArrayList<Double>(); for (Double o2 : o1){ tempDiv.add( o2.doubleValue()); // clone() not working here } scaledThresholds.put(s,tempDiv); } Double minDelay = getMinDelay(); Double maxDelay = getMaxDelay(); Double minDivision = getMinDiv(scaledThresholds); Double maxDivision = getMaxDiv(scaledThresholds); Double scaleFactor = 1.0; try { if ((valScaleFactor == -1.0) && (delayScaleFactor == -1.0)){ out.write("\nAuto determining both value and delay scale factors\n"); valScaleFactor = 1.0; delayScaleFactor = 1.0; out.write("minimum delay is " + minDelay + " before scaling time.\n"); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } out.write("minimum delay is " + scaleFactor * minDelay + "after scaling by " + scaleFactor + "\n"); delayScaleFactor = scaleFactor; scaleDelay(delayScaleFactor); } if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Rate Scaling has caused an overflow"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor = scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Division Scaling has caused an overflow"); } out.write("minimum division is " + minDivision * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor *= scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } }*/ // END TEMPORARY } } else if (valScaleFactor == -1.0){ //force delayScaling; automatic varScaling out.write("\nAuto determining value scale factor; Forcing delay scale factor\n"); valScaleFactor = 1.0; out.write("minimum delay is " + minDelay + " before scaling time.\n"); /*if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } if (scaleFactor > delayScaleFactor){ out.write("WARNING: Minimum delay won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); delayScaleFactor = scaleFactor; } //else delayScaleFactor = delayScaleFactor (user provided) scaleDelay(delayScaleFactor); } else { scaleDelay(delayScaleFactor);// Even if we can't calculate delayScaleFactor, use user provided one whatever it is out.write("min delay = 0. So, not checking whether the given delayScalefactor is correct\n"); }*/ out.write("minimum delay is " + delayScaleFactor * minDelay + "after scaling by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by // magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Rate Scaling has caused an overflow"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor = scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { System.out.println("Division Scaling has caused an overflow"); } out.write("minimum division is " + minDivision * scaleFactor + " after scaling by " + scaleFactor + "\n"); valScaleFactor *= scaleFactor; scaledThresholds = scaleValue(scaleFactor,scaledThresholds); // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } }*/ // END TEMPORARY } } else if (delayScaleFactor == -1.0){ //force valueScaling; automatic delayScaling out.write("\nAuto determining delay scale factor; Forcing value scale factor\n"); //May be wrong in some cases delayScaleFactor = 1.0; minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); /*scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { out.write("ERROR: Division Scaling has caused an overflow"); } if (scaleFactor > valScaleFactor){ out.write("WARNING: Minimum threshold won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); valScaleFactor = scaleFactor; } out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // END TEMPORARY } else { scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("Min division is 0. So, not checking whether given value scale factor is correct"); }*/ scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { out.write("Rate Scaling has caused an overflow\n"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling delay by " + 1/scaleFactor + "\n"); scaleDelay(1/scaleFactor); delayScaleFactor = 1/scaleFactor; // TEMPORARY /* for (String p : g.getPlaceList()){ if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); System.out.println(s); } } */ // end TEMPORARY } } scaleFactor = 1.0; minDelay = getMinDelay(); maxDelay = getMaxDelay(); out.write("minimum delay is " + minDelay + " before scaling time.\n"); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } delayScaleFactor = scaleFactor; out.write("minimum delay is " + delayScaleFactor * minDelay + "after scaling delay by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); } } else { //User forces both delay and value scaling factors. out.write("\nForcing delay and value scale factors by " + delayScaleFactor + " and " + valScaleFactor + " respectively \n"); minDivision = getMinDiv(scaledThresholds); out.write("minimum division is " + minDivision + " before scaling for division.\n"); scaledThresholds = scaleValue(valScaleFactor, scaledThresholds); minDivision = getMinDiv(scaledThresholds); out.write("minimum division is " + minDivision + " after scaling for division.\n"); minDelay = getMinDelay(); out.write("minimum delay is " + minDivision + " before scaling for delay.\n"); scaleDelay(delayScaleFactor); minDelay = getMinDelay(); out.write("minimum delay is " + minDivision + " after scaling for delay.\n"); /* minDivision = getMinDiv(scaledThresholds); maxDivision = getMaxDiv(scaledThresholds); scaleFactor = 1.0; if ((minDivision != null) && (minDivision != 0)) { for (int i = 0; i < 14; i++) { if (Math.abs(scaleFactor * minDivision) > minDivisionVal) { break; } scaleFactor *= 10; } if ((maxDivision != null) && (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) { out.write("ERROR: Division Scaling has caused an overflow"); } if (scaleFactor > valScaleFactor){ out.write("WARNING: Minimum threshold won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); valScaleFactor = scaleFactor; } out.write("minimum division is " + minDivision * valScaleFactor + " after scaling by " + valScaleFactor + "\n"); scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // END TEMPORARY } else { scaledThresholds = scaleValue(valScaleFactor,scaledThresholds); out.write("Min division is 0. So, not checking whether given value scale factor is correct"); } out.write("minimum delay is " + minDelay + " before scaling time.\n"); scaleFactor = 1.0; minDelay = getMinDelay(); maxDelay = getMaxDelay(); if ((minDelay != null) && (minDelay != 0)) { for (int i = 0; i < 18; i++) { if (scaleFactor > (minDelayVal / minDelay)) { break; } scaleFactor *= 10.0; } if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) { System.out.println("Delay Scaling has caused an overflow"); } if (scaleFactor > delayScaleFactor){ out.write("WARNING: Minimum delay won't be an integer with the given scale factor. So using " + scaleFactor + "instead."); delayScaleFactor = scaleFactor; } out.write("minimum delay value is " + delayScaleFactor * minDelay + "after scaling by " + delayScaleFactor + "\n"); scaleDelay(delayScaleFactor); } if (contVarExists){ scaleFactor = 1.0; Double minRate = getMinRate(); // minRate should return minimum by magnitude alone?? or even by sign.. Double maxRate = getMaxRate(); out.write("minimum rate is " + minRate + " before scaling the variable.\n"); if ((minRate != null) && (minRate != 0)) { for (int i = 0; i < 14; i++) { if (scaleFactor > Math.abs(minRateVal / minRate)) { break; } scaleFactor *= 10.0; } for (int i = 0; i < 14; i++) { if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) { break; } scaleFactor /= 10.0; } if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) { out.write("Rate Scaling has caused an overflow\n"); } out.write("minimum rate is " + minRate * scaleFactor + " after scaling delay by " + scaleFactor + "\n"); if (scaleFactor > 1) out.write("The given value scaling factor is insufficient for rates. So increasing it to "+ scaleFactor*valScaleFactor); scaledThresholds = scaleValue(scaleFactor,scaledThresholds); valScaleFactor *= scaleFactor; // TEMPORARY // for (String p : g.getPlaceList()){ //if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){ // String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor); // System.out.println(s); //} //} // end TEMPORARY } }*/ } } catch (IOException e) { e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return(scaledThresholds); } public HashMap<String,ArrayList<Double>> scaleValue(Double scaleFactor, HashMap<String,ArrayList<Double>> localThresholds) { String place; Properties p; try{ for (String st1 : g.getPlaceList()) { if (!isTransientPlace(st1)){ place = getPlaceInfoIndex(st1); p = placeInfo.get(place); } else{ place = getTransientNetPlaceIndex(st1); p = transientNetPlaces.get(place); } if (place != "failProp"){ /* Related to the separate net for DMV input driver if (p.getProperty("type").equals("DMVC")) { p.setProperty("DMVCValue", Double.toString(Double.parseDouble(p.getProperty("DMVCValue"))* scaleFactor)); } else { */ for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMin"))* scaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_rMax"))* scaleFactor)); } else { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/delayScaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/delayScaleFactor))); if (!v.isInput()) { p.setProperty(v.getName() + "_vMin", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMin"))* scaleFactor)); p.setProperty(v.getName() + "_vMax", Double .toString(Double.parseDouble(p.getProperty(v.getName() + "_vMax")) * scaleFactor)); } } } //} } } /*int i = 0; for (Variable v : reqdVarsL) { v.scaleInitByVar(scaleFactor); for (int j = 0; j < divisions.get(i).size(); j++) { divisions.get(i).set(j,divisions.get(i).get(j) * scaleFactor); } i++; }*/ //commented above for replacing divisionsL with thresholds for (Variable v : reqdVarsL) { v.scaleInitByVar(scaleFactor); //System.out.println("After scaling init Val of " + v.getName() + " by factor " + scaleFactor + ", it is " + v.getInitValue() + "\n"); for (int j = 0; j < localThresholds.get(v.getName()).size(); j++) { localThresholds.get(v.getName()).set(j,localThresholds.get(v.getName()).get(j) * scaleFactor); } } for (HashMap<String,String> st1 : constVal){ // for output signals that are constant throughout the trace. for (String st2: st1.keySet()){ st1.put(st2,String.valueOf(Double.valueOf(st1.get(st2))*scaleFactor)); } } } catch (NullPointerException e){ e.printStackTrace(); //System.out.println("LPN file couldn't be created/written "); JOptionPane.showMessageDialog(BioSim.frame, "Not all regions have values for all dmv variables", "ERROR!", JOptionPane.ERROR_MESSAGE); } return localThresholds; } public void scaleDelay(Double scaleFactor) { try{ String place; Properties p; for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); Double mind = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin")); Double maxd = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax")); transitionInfo.get(pPrev + "," + nextPlace).setProperty("dMin",Double.toString(mind*scaleFactor)); transitionInfo.get(pPrev + "," + nextPlace).setProperty("dMax",Double.toString(maxd*scaleFactor)); } else { System.out.println("Transition " + t + " has no index in transitionInfo. CHECK"); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); Double mind = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin")); Double maxd = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMax")); transientNetTransitions.get(pPrev+ "," +nextPlace).setProperty("dMin",Double.toString(mind*scaleFactor)); transientNetTransitions.get(pPrev+ "," +nextPlace).setProperty("dMax",Double.toString(maxd*scaleFactor)); } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); } } } } } for (String st1 : g.getPlaceList()) { if (!isTransientPlace(st1)){ place = getPlaceInfoIndex(st1); p = placeInfo.get(place); } else{ place = getTransientNetPlaceIndex(st1); p = transientNetPlaces.get(place); } if (place != "failProp"){ // p.setProperty("dMin",Integer.toString((int)(Double.parseDouble(p.getProperty("dMin"))*scaleFactor))); // p.setProperty("dMax",Integer.toString((int)(Double.parseDouble(p.getProperty("dMax"))*scaleFactor))); /* STORING DELAYS AT TRANSITIONS p.setProperty("dMin", Double.toString(Double.parseDouble(p .getProperty("dMin")) * scaleFactor)); p.setProperty("dMax", Double.toString(Double.parseDouble(p .getProperty("dMax")) * scaleFactor)); */ for (Variable v : reqdVarsL) { if (!v.isDmvc()) { // p.setProperty(v.getName() + // "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMin"))/scaleFactor))); // p.setProperty(v.getName() + // "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName() // + "_rMax"))/scaleFactor))); p.setProperty(v.getName() + "_rMin", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMin")) / scaleFactor)); p.setProperty(v.getName() + "_rMax", Double .toString(Double.parseDouble(p.getProperty(v .getName() + "_rMax")) / scaleFactor)); } } //} } } for (Variable v : reqdVarsL) { // if (!v.isDmvc()){ this if maynot be required.. rates do exist for dmvc ones as well.. since calculated before detectDMV v.scaleInitByDelay(scaleFactor); // } } // SEE IF RATES IN TRANSITIONS HAVE TO BE ADJUSTED HERE } catch(NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Delay scaling error due to null. Check", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(java.lang.ArrayIndexOutOfBoundsException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Delay scaling error due to Array Index.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public Double getMinDiv(HashMap<String, ArrayList<Double>> divisions) { Double minDiv = null; for (String s : divisions.keySet()) { if (minDiv == null){ minDiv = divisions.get(s).get(0); } for (int j = 0; j < divisions.get(s).size(); j++) { if (divisions.get(s).get(j) < minDiv) { minDiv = divisions.get(s).get(j); } } } return minDiv; } public Double getMaxDiv(HashMap<String, ArrayList<Double>> divisions) { Double maxDiv = null; for (String s : divisions.keySet()) { if (maxDiv == null){ maxDiv = divisions.get(s).get(0); } for (int j = 0; j < divisions.get(s).size(); j++) { if (divisions.get(s).get(j) > maxDiv) { maxDiv = divisions.get(s).get(j); } } } return maxDiv; } public Double getMinRate() { // minimum of entire lpn Double minRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if (!v.isDmvc()){ if ((minRate == null) && (p.getProperty(v.getName() + "_rMin") != null)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } else if ((p.getProperty(v.getName() + "_rMin") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) < minRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMin")) != 0.0)) { minRate = Double.parseDouble(p.getProperty(v.getName() + "_rMin")); } } } } } return minRate; } public Double getMaxRate() { Double maxRate = null; for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if (p.getProperty("type").equals("RATE")) { for (Variable v : reqdVarsL) { if (!v.isDmvc()){ if ((maxRate == null) && (p.getProperty(v.getName() + "_rMax") != null)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } else if ((p.getProperty(v.getName() + "_rMax") != null) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) > maxRate) && (Double.parseDouble(p.getProperty(v.getName() + "_rMax")) != 0.0)) { maxRate = Double.parseDouble(p.getProperty(v.getName() + "_rMax")); } } } } } return maxRate; } public Double getMinDelay() { Double minDelay = null; Double mind; try{ for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); out.write("Transition " + g.getTransition(t).getName() + " b/w " + pPrev + " and " + nextPlace + " : finding delay \n"); if (transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin") != null){ mind = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMin")); if (minDelay == null) minDelay = mind; else if ((minDelay > mind) && (mind != 0)) minDelay = mind; } } else { System.out.println("ERROR: Transition " + t + " has no index in transitionInfo."); out.write("ERROR: Transition " + t + " has no index in transitionInfo."); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin") != null){ mind = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dMin")); if (minDelay == null) minDelay = mind; else if ((minDelay > mind) && (mind != 0)) minDelay = mind; } } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); out.write("ERROR: Transient transition " + t + " has no index in transientNetTransitions."); } } } } } /*for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if ((minDelay == null) && (p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } else if ((p.getProperty("dMin") != null) && (Double.parseDouble(p.getProperty("dMin")) != 0) && (Double.parseDouble(p.getProperty("dMin")) < minDelay)) { minDelay = Double.parseDouble(p.getProperty("dMin")); } //} }*/ } catch (IOException e){ e.printStackTrace(); } return minDelay; } public Double getMaxDelay() { Double maxDelay = null; Double maxd; for (String t : g.getTransitionList()) { if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){ if (!isTransientTransition(t)){ if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { String tKey = getTransitionInfoIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax") != null){ maxd = Double.parseDouble(transitionInfo.get(pPrev + "," + nextPlace).getProperty("dMax")); if (maxDelay == null) maxDelay = maxd; else if ((maxDelay < maxd) && (maxd != 0)) maxDelay = maxd; } } else { System.out.println("Transition " + t + " has no index in transitionInfo. CHECK"); } } } else { if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition String tKey = getTransientNetTransitionIndex(t); if (tKey != null){ String pPrev = getPresetPlaceFullKey(tKey); String nextPlace = getPostsetPlaceFullKey(tKey); if (transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dmax") != null){ maxd = Double.parseDouble(transientNetTransitions.get(pPrev+ "," +nextPlace).getProperty("dmax")); if (maxDelay == null) maxDelay = maxd; else if ((maxDelay < maxd) && (maxd != 0)) maxDelay = maxd; } } else { System.out.println("Transient transition " + t + " has no index in transientNetTransitions. CHECK"); } } } } } /*for (String place : placeInfo.keySet()) { Properties p = placeInfo.get(place); if ((maxDelay == null) && (p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } else if ((p.getProperty("dMax") != null) && (Double.parseDouble(p.getProperty("dMax")) != 0) && (Double.parseDouble(p.getProperty("dMax")) > maxDelay)) { maxDelay = Double.parseDouble(p.getProperty("dMax")); } //} }*/ return maxDelay; } public void addDuration(Properties p, Double d) { Double dMin; Double dMax; // d = d*(10^6); if ((p.getProperty("dMin") == null) && (p.getProperty("dMax") == null)) { // p.setProperty("dMin", Integer.toString((int)(Math.floor(d)))); // p.setProperty("dMax", Integer.toString((int)(Math.floor(d)))); p.setProperty("dMin", d.toString()); p.setProperty("dMax", d.toString()); return; } else { dMin = Double.parseDouble(p.getProperty("dMin")); dMax = Double.parseDouble(p.getProperty("dMax")); if (d < dMin) { dMin = d; } else if (d > dMax) { dMax = d; } } p.setProperty("dMin", dMin.toString()); p.setProperty("dMax", dMax.toString()); // p.setProperty("dMin", Integer.toString((int)(Math.floor(dMin)))); // p.setProperty("dMax", Integer.toString((int)(Math.ceil(dMax)))); } public String getPlaceInfoIndex(String s) { String index = null; for (String st2 : placeInfo.keySet()) { if (("p" + placeInfo.get(st2).getProperty("placeNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransientNetPlaceIndex(String s) { String index = null; for (String st2 : transientNetPlaces.keySet()) { if (("p" + transientNetPlaces.get(st2).getProperty("placeNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransitionInfoIndex(String s) { String index = null; for (String st2 : transitionInfo.keySet()) { if (("t" + transitionInfo.get(st2).getProperty("transitionNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public String getTransientNetTransitionIndex(String s) { String index = null; for (String st2 : transientNetTransitions.keySet()) { if (("t" + transientNetTransitions.get(st2).getProperty("transitionNum")) .equalsIgnoreCase(s)) { index = st2; break; } } return index; } public ArrayList<Integer> diff(String pre_bin, String post_bin) { //Parameters are bins formed from reqdVarsL (not just cares). ArrayList<Integer> diffL = new ArrayList<Integer>(); if ((pre_bin != null) && (post_bin != null)){ String[] preset_encoding = pre_bin.split(","); String[] postset_encoding = post_bin.split(","); for (int j = 0; j < preset_encoding.length; j++) { // to account for "" being created in the array if (Integer.parseInt(preset_encoding[j]) != Integer.parseInt(postset_encoding[j])) { diffL.add(j);// to account for "" being created in the array } } } return (diffL); } public Integer getMinRate(String place, String name) { Properties p = placeInfo.get(place); if (p.getProperty(name + "_rMin") != null) return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMin")))); else return null; // return(rMin[i]); } public Integer getMaxRate(String place, String name) { Properties p = placeInfo.get(place); if (p.getProperty(name + "_rMax") != null) return ((int) Math.floor(Double.parseDouble(p.getProperty(name + "_rMax")))); else return null; // return(rMin[i]); } /* public Double[][] getDataExtrema(ArrayList<ArrayList<Double>> data){ Double[][] extrema = new Double[reqdVarsL.size()][2]; for (int i=0; i<reqdVarsL.size(); i++){ //Object obj = Collections.min(data.get(reqdVarIndices.get(i))); Object obj = Collections.min(data.get(i+1)); extrema[i][0] = Double.parseDouble(obj.toString()); //obj = Collections.max(data.get(reqdVarIndices.get(i))); obj = Collections.max(data.get(i+1)); extrema[i][1] = Double.parseDouble(obj.toString()); } return extrema; } */ public HashMap <String, Double[]> getDataExtrema(ArrayList<ArrayList<Double>> data){ HashMap <String, Double[]> extrema = new HashMap <String, Double[]>(); for (int i=0; i<reqdVarsL.size(); i++){ //Object obj = Collections.min(data.get(reqdVarIndices.get(i))); Object obj = Collections.min(data.get(i+1)); extrema.put(reqdVarsL.get(i).getName(),new Double[2]); extrema.get(reqdVarsL.get(i).getName())[0] = Double.parseDouble(obj.toString()); //obj = Collections.max(data.get(reqdVarIndices.get(i))); obj = Collections.max(data.get(i+1)); extrema.get(reqdVarsL.get(i).getName())[1] = Double.parseDouble(obj.toString()); } return extrema; } public Double[] getMinMaxRates(Double[] rateList){ ArrayList<Double> cmpL = new ArrayList<Double>(); Double[] minMax = {null,null};// new Double[2]; for (Double r : rateList){ if (r != null){ cmpL.add(r); } } if (cmpL.size() > 0){ Object obj = Collections.min(cmpL); minMax[0] = Double.parseDouble(obj.toString()); obj = Collections.max(cmpL); minMax[1] = Double.parseDouble(obj.toString()); } return minMax; } public boolean compareBins(int j, int mark,int[][] bins) { for (int i = 0; i < reqdVarsL.size(); i++) { if (bins[i][j] != bins[i][mark]) { return false; } else { continue; } } return true; } public void addPseudo(HashMap<String,ArrayList<Double>> scaledThresholds){ try{ lpnWithPseudo = new LhpnFile(); lpnWithPseudo = mergeLhpns(lpnWithPseudo,g); pseudoVars = new HashMap<String,Boolean>(); //pseudoVars.put("ctl",true); for (int i = 0; i < reqdVarsL.size(); i++) { if ((reqdVarsL.get(i).isInput()) && (reqdVarsL.get(i).isCare())){ pseudoVars.put(reqdVarsL.get(i).getName(),true); } } if ((pseudoVars != null) && (pseudoVars.size() != 0)){ for (String st : g.getPlaceList()){ currentPlace = st; //TODO: do this only if not prop type place if (getPlaceInfoIndex(st) != null) currPlaceBin = getPlaceInfoIndex(st).split(","); else if (getTransientNetPlaceIndex(st) != null) currPlaceBin = getTransientNetPlaceIndex(st).split(","); else out.write("WARNING: " + st + " is not in the placelist. It should be initPlace, otherwise something wrong\n"); // visitedPlaces = new HashMap<String,Boolean>(); // visitedPlaces.put(currentPlace, true); traverse(scaledThresholds); } } }catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } private void traverse(HashMap<String,ArrayList<Double>> scaledThresholds){ for (String nextPlace : g.getPlaceList()){ if ((!nextPlace.equalsIgnoreCase(currentPlace)) && (getPlaceInfoIndex(nextPlace) != null)){ if ((getPlaceInfoIndex(currentPlace) != null) && (!transitionInfo.containsKey(getPlaceInfoIndex(currentPlace) + "," + getPlaceInfoIndex(nextPlace)))){ addPseudoTrans(nextPlace, scaledThresholds); } else if ((getTransientNetPlaceIndex(currentPlace) != null) && (!transientNetTransitions.containsKey(getTransientNetPlaceIndex(currentPlace) + "," + getPlaceInfoIndex(nextPlace)))){ addPseudoTrans(nextPlace, scaledThresholds); } } } } private void addPseudoTrans(String nextPlace, HashMap<String, ArrayList<Double>> scaledThresholds){ // Adds pseudo transition b/w currentPlace and nextPlace String[] nextPlaceBin = getPlaceInfoIndex(nextPlace).split(","); String enabling = ""; int bin; String st; Boolean pseudo = false; try{ for (int i = 0; i < reqdVarsL.size(); i++) { if ((reqdVarsL.get(i).isInput()) && (reqdVarsL.get(i).isCare())){ if (Integer.valueOf(currPlaceBin[i]) == Integer.valueOf(nextPlaceBin[i])){ continue; } else { if (!pseudoVars.containsKey(reqdVarsL.get(i).getName())){ // If the 2 places differ in the bins of a non-pseudovar, then u can't add pseudotrans there coz other variables belong to diff bins in these 2 places pseudo = false; break; } if (Math.abs(Integer.valueOf(currPlaceBin[i]) - Integer.valueOf(nextPlaceBin[i])) > 1){ // If the 2 places differ in the bins of a pseudovar but are not adjacent, then u can't add pseudotrans there pseudo = false; break; } pseudo = true; bin = Integer.valueOf(nextPlaceBin[i]); st = reqdVarsL.get(i).getName(); if (bin == 0){ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } else if (bin == (scaledThresholds.get(st).size())){ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")"; } else{ if (!enabling.equalsIgnoreCase("")) enabling += "&"; enabling += "(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin-1).doubleValue()) + ")&~(" + st + ">=" + (int) Math.floor(scaledThresholds.get(st).get(bin).doubleValue()) + ")";//changed ceil to floor on aug 7,2010 } } } else { if (Integer.valueOf(currPlaceBin[i]) != Integer.valueOf(nextPlaceBin[i])){ pseudo = false; break; } } } if (pseudo){ out.write("Adding pseudo-transition pt" + pseudoTransNum + " between " + currentPlace + " and " + nextPlace + " with enabling " + enabling + "\n"); lpnWithPseudo.addTransition("pt" + pseudoTransNum); lpnWithPseudo.addMovement(currentPlace, "pt" + pseudoTransNum); lpnWithPseudo.addMovement("pt" + pseudoTransNum, nextPlace); lpnWithPseudo.addEnabling("pt" + pseudoTransNum, enabling); pseudoTransNum++; } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void addMetaBins(){ // TODO: DIDN'T REPLACE divisionsL by thresholds IN THIS METHOD boolean foundBin = false; for (String st1 : g.getPlaceList()){ String p = getPlaceInfoIndex(st1); String[] binEncoding ; ArrayList<Integer> syncBinEncoding; String o1; // st1 w.r.t g // p w.r.t placeInfo if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { // String [] bE = p.split(""); String [] bE = p.split(","); binEncoding = new String[bE.length - 1]; for (int i = 0; i < bE.length; i++){ binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01 } for (int i = 0; i < binEncoding.length ; i++){ if (!reqdVarsL.get(i).isDmvc()){ if ((lowerLimit[i] != null) && (getMinRate(p,reqdVarsL.get(i).getName()) < 0)){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) - 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) != -1){ key += syncBinEncoding.get(m).toString(); } else{ key += "A"; // ***Encoding -1 as A } } if ((syncBinEncoding.get(i) == -1) && (!placeInfo.containsKey(key))){ foundBin = true; Properties p0 = new Properties(); placeInfo.put(key, p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","true"); p0.setProperty("metaVar", String.valueOf(i)); g.addPlace("p" + numPlaces, false); //ratePlaces.add("p"+numPlaces); numPlaces++; if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ // minrate is 0; maxrate remains the same if positive addRate(p0, reqdVarsL.get(i).getName(), 0.0); addRate(p0, reqdVarsL.get(i).getName(), (double)getMaxRate(p,reqdVarsL.get(i).getName())); /* * This transition should be added only in this case but * since dotty cribs if there's no place on a transition's postset, * moving this one down so that this transition is created even if the * min,max rate is 0 in which case it wouldn't make sense to have this * transition * Properties p2 = new Properties(); transitionInfo.put(key + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum")); g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")" + "&~fail"); numTransitions++; */ } else{ addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the maximum rate was negative, then make the min & max rates both as zero } Properties p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; Properties p2 = new Properties(); transitionInfo.put(key + "," + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + "," + p).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(key + "," + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); minr = getMinRate(p, reqdVarsL.get(i).getName()); maxr = getMaxRate(p, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } else if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } } } } if ((upperLimit[i] != null) && getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()+1); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) + 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){ key += syncBinEncoding.get(m).toString(); } else{ key += "Z"; // ***Encoding highest bin +1 as Z // encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future } } if ((syncBinEncoding.get(i) == divisionsL.get(i).size() + 1) && (!placeInfo.containsKey(key))){ // divisionsL.get(i).size() + 1 or divisionsL.get(i).size()??? foundBin = true; Properties p0 = new Properties(); placeInfo.put(key, p0); p0.setProperty("placeNum", numPlaces.toString()); p0.setProperty("type", "RATE"); p0.setProperty("initiallyMarked", "false"); p0.setProperty("metaType","true"); p0.setProperty("metaVar", String.valueOf(i)); //ratePlaces.add("p"+numPlaces); g.addPlace("p" + numPlaces, false); numPlaces++; if (getMinRate(p,reqdVarsL.get(i).getName()) < 0){ // maxrate is 0; minrate remains the same if negative addRate(p0, reqdVarsL.get(i).getName(), 0.0); addRate(p0, reqdVarsL.get(i).getName(), (double)getMinRate(p,reqdVarsL.get(i).getName())); /* * This transition should be added only in this case but * since dotty cribs if there's no place on a transition's postset, * moving this one down so that this transition is created even if the * min,max rate is 0 in which case it wouldn't make sense to have this * transition * Properties p2 = new Properties(); transitionInfo.put(key + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum")); g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")" + "&~fail"); numTransitions++; */ } else{ addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the minimum rate was positive, then make the min & max rates both as zero } Properties p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; Properties p2 = new Properties(); transitionInfo.put(key + "," + p, p2); p2.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + "," + p).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(key + "," + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum")); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); minr = getMinRate(p, reqdVarsL.get(i).getName()); maxr = getMaxRate(p, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } else if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; } } } } } } } } } public void addMetaBinTransitions(){ // Adds transitions b/w existing metaBins. // Doesn't add any new metabins. Doesn't add transitions b/w metabins & normal bins boolean foundBin = false; for (String st1 : g.getPlaceList()){ String p = getPlaceInfoIndex(st1); Properties placeP = placeInfo.get(p); String[] binEncoding ; ArrayList<Integer> syncBinEncoding; String o1; // st1 w.r.t g // p w.r.t placeInfo if (placeP.getProperty("type").equalsIgnoreCase("RATE") && placeP.getProperty("metaType").equalsIgnoreCase("true")) { // String [] bE = p.split(""); String [] bE = p.split(","); binEncoding = new String[bE.length - 1]; for (int i = 0; i < bE.length; i++){ binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01 } for (int i = 0; i < binEncoding.length ; i++){ if ((!reqdVarsL.get(i).isDmvc()) && (Integer.parseInt(placeP.getProperty("metaVar")) != i)){ if ((getMinRate(p,reqdVarsL.get(i).getName()) < 0)){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) - 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) != -1){ key += syncBinEncoding.get(m).toString(); } else{ key += "A"; // ***Encoding -1 as A } } if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); numTransitions++; } } } } if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ syncBinEncoding = new ArrayList<Integer>(); // deep copy of bin encoding for (int n = 0; n < binEncoding.length; n++){ o1 = binEncoding[n]; if (o1 == "A"){ syncBinEncoding.add(-1); } else if (o1 == "Z"){ syncBinEncoding.add(divisionsL.get(n).size()+1); } else{ syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here } } foundBin = false; while (!foundBin){ syncBinEncoding.set(i,syncBinEncoding.get(i) + 1); String key = ""; for (int m = 0; m < syncBinEncoding.size(); m++){ if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){ key += syncBinEncoding.get(m).toString(); } else{ key += "Z"; // ***Encoding highest bin +1 as Z // encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future } } if (placeInfo.containsKey(key)){ foundBin = true; //Properties syncP = placeInfo.get(key); Properties p1; if (!transitionInfo.containsKey(p + "," + key)) { // instead of tuple p1 = new Properties(); transitionInfo.put(p + "," + key, p1); p1.setProperty("transitionNum", numTransitions.toString()); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + "," + key).getProperty("transitionNum")); g.addMovement("t" + transitionInfo.get(p + "," + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum")); // g.addEnabling("t" + numTransitions, "~fail"); int minr = getMinRate(key, reqdVarsL.get(i).getName()); int maxr = getMaxRate(key, reqdVarsL.get(i).getName()); if (minr != maxr) g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")"); else g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr)); g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")"); numTransitions++; } } } } } } } } } public void writeVHDLAMSFile(String vhdFile){ try{ ArrayList<String> ratePlaces = new ArrayList<String>(); ArrayList<String> dmvcPlaces = new ArrayList<String>(); File VHDLFile = new File(directory + separator + vhdFile); VHDLFile.createNewFile(); BufferedWriter vhdlAms = new BufferedWriter(new FileWriter(VHDLFile)); StringBuffer buffer = new StringBuffer(); String pNum; vhdlAms.write("library IEEE;\n"); vhdlAms.write("use IEEE.std_logic_1164.all;\n"); vhdlAms.write("use work.handshake.all;\n"); vhdlAms.write("use work.nondeterminism.all;\n\n"); vhdlAms.write("entity amsDesign is\n"); vhdlAms.write("end amsDesign;\n\n"); vhdlAms.write("architecture "+vhdFile.split("\\.")[0]+" of amsDesign is\n"); for (Variable v : reqdVarsL){ vhdlAms.write("\tquantity "+v.getName()+":real;\n"); } for (int i = 0; i < numPlaces; i++){ if (!isTransientPlace("p"+i)){ String p = getPlaceInfoIndex("p"+i); if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } else { String p = getTransientNetPlaceIndex("p"+i); if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } vhdlAms.write("\tshared variable place:integer:= "+i+";\n"); break; } if (failPropVHDL != null){ //TODO: Make this an assertion //vhdlAms.write("\tshared variable fail:boolean:= false;\n"); } for (String st1 : g.getPlaceList()){ if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) { dmvcPlaces.add(p); // w.r.t placeInfo here }*/ if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) { } } else{ String p = getTransientNetPlaceIndex(st1); if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){ ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){ dmvcPlaces.add(p); // w.r.t g here }*/ } } /*for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ /* Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ String v1 = placeInfo.get(a).getProperty("DMVCVariable"); String v2 = placeInfo.get(b).getProperty("DMVCVariable"); if (reqdVarsL.indexOf(v1) < reqdVarsL.indexOf(v2)){ return -1; } else if (reqdVarsL.indexOf(v1) == reqdVarsL.indexOf(v2)){ return 0; } else{ return 1; } } });*/ Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){ return -1; } else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){ return 0; } else{ return 1; } } }); Collections.sort(ratePlaces,new Comparator<String>(){ String v1,v2; public int compare(String a, String b){ if (!isTransientPlace(a) && !isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else if (!isTransientPlace(a) && isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } else if (isTransientPlace(a) && !isTransientPlace(b)){ v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else { v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); // sending the initial place to the end of the list. since if statements begin with preset of each place //ratePlaces.add(ratePlaces.get(0)); //ratePlaces.remove(0); /*System.out.println("after sorting:"); for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ vhdlAms.write("begin\n"); //buffer.append("\nbegin\n"); String[] vals; for (Variable v : reqdVarsL){ // taking the lower value from the initial value range. Ok? //vhdlAms.write("\tbreak "+v.getName()+" => "+((((v.getInitValue()).split("\\,"))[0]).split("\\["))[1]+".0;\n"); vals = v.getInitValue().split("\\,"); vhdlAms.write("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n"); //buffer.append("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n"); } vhdlAms.write("\n"); //buffer.append("\n"); for (Variable v : reqdVarsL){ if (v.isDmvc()){ vhdlAms.write("\t"+v.getName()+"'dot == 0.0;\n"); //buffer.append("\t"+v.getName()+"'dot == 0.0;\n"); } } vhdlAms.write("\n"); //buffer.append("\n"); ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>(); boolean contVarExists = false; for (Variable v: reqdVarsL){ dmvcVarPlaces.add(new ArrayList<String>()); if (v.isDmvc()){ continue; } else{ contVarExists = true; } } for (String st:dmvcPlaces){ dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st); } if (contVarExists){ if (ratePlaces.size() != 0){ //vhdlAms.write("\tcase place use\n"); buffer.append("\tcase place use\n"); } //vhdlAms.write("\ntype rate_places is ("); for (String p : ratePlaces){ pNum = p.split("p")[1]; //vhdlAms.write("\t\twhen "+p.split("p")[1] +" =>\n"); buffer.append("\t\twhen "+ pNum +" =>\n"); if (!isTransientPlace(p)){ for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ //vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); } } } else{ for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ //vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n"); buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0);\n"); } } } } vhdlAms.write(buffer.toString()); vhdlAms.write("\t\twhen others =>\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == 0.0;\n"); } } vhdlAms.write("\tend case;\n"); } vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\tcase place is\n"); buffer.delete(0, buffer.length()); String[] transL; int transNum; for (String p : ratePlaces){ pNum = p.split("p")[1]; vhdlAms.write("\t\twhen "+pNum +" =>\n"); vhdlAms.write("\t\t\twait until "); transL = g.getPostset(p); if (transL.length == 1){ transNum = Integer.parseInt(transL[0].split("t")[1]); vhdlAms.write(transEnablingsVHDL[transNum] + ";\n"); if (transDelayAssignVHDL[transNum] != null){ vhdlAms.write("\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); //vhdlAms.write("\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ vhdlAms.write("\t\t\tbreak "+ s +";\n"); } } } if (g.getPostset(transL[0]).length != 0) vhdlAms.write("\t\t\tplace := " + g.getPostset(transL[0])[0].split("p")[1] + ";\n"); } else{ boolean firstTrans = true; buffer.delete(0, buffer.length()); for (String t : transL){ transNum = Integer.parseInt(t.split("t")[1]); if (firstTrans){ firstTrans = false; vhdlAms.write("(" + transEnablingsVHDL[transNum]); buffer.append("\t\t\tif " + transEnablingsVHDL[transNum] + " then\n"); if (transDelayAssignVHDL[transNum] != null){ buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ buffer.append("\t\t\t\tbreak "+ s +";\n"); } } } buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n"); } else{ vhdlAms.write(" or " +transEnablingsVHDL[transNum] ); buffer.append("\t\t\telsif " + transEnablingsVHDL[transNum] + " then\n"); if (transDelayAssignVHDL[transNum] != null){ buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n"); //buffer.append("\t\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n"); for (String s : transIntAssignVHDL[transNum]){ if (s != null){ buffer.append("\t\t\t\tbreak "+ s +";\n"); } } } buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n"); } } vhdlAms.write(");\n"); buffer.append("\t\t\tend if;\n"); vhdlAms.write(buffer.toString()); } } vhdlAms.write("\t\twhen others =>\n\t\t\twait for 0.0;\n\t\t\tplace := "+ ratePlaces.get(0).split("p")[1] + ";\n\tend case;\n\tend process;\n"); for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); for (String p : dmvcVarPlaces.get(i)){ if (!transientNetPlaces.containsKey(p)){ vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(placeInfo.get(p).getProperty("dMax"))) +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("DMVCValue"))) + ".0;\n"); } else{ vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))) +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("DMVCValue"))) + ".0;\n"); } } vhdlAms.write("\tend process;\n\n"); } } if (failPropVHDL != null){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\t\twait until " + failPropVHDL + ";\n"); //TODO: Change this to assertion //vhdlAms.write("\t\tfail := true;\n"); vhdlAms.write("\tend process;\n\n"); } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n"); vhdlAms.close(); } catch(IOException e){ JOptionPane.showMessageDialog(BioSim.frame, "VHDL-AMS model couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(Exception e){ JOptionPane.showMessageDialog(BioSim.frame, "Error in VHDL-AMS model generation.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } public void writeVerilogAMSFile(String vamsFileName){ try{ ArrayList<String> ratePlaces = new ArrayList<String>(); ArrayList<String> dmvcPlaces = new ArrayList<String>(); File vamsFile = new File(directory + separator + vamsFileName); vamsFile.createNewFile(); Double rateFactor = valScaleFactor/delayScaleFactor; BufferedWriter vams = new BufferedWriter(new FileWriter(vamsFile)); StringBuffer buffer = new StringBuffer(); StringBuffer buffer2 = new StringBuffer(); StringBuffer buffer3 = new StringBuffer(); StringBuffer buffer4 = new StringBuffer(); StringBuffer initBuffer = new StringBuffer(); vams.write("`include \"constants.vams\"\n"); vams.write("`include \"disciplines.vams\"\n"); vams.write("`timescale 1ps/1ps\n\n"); vams.write("module "+vamsFileName.split("\\.")[0]+" ("); buffer.append("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n"); Variable v; String[] vals; for (int i = 0; i < reqdVarsL.size(); i++){ v = reqdVarsL.get(i); if ( i!= 0){ vams.write(","); } vams.write(" "+v.getName()); if (v.isInput()){ buffer.append("\tinput "+v.getName()+";\n\telectrical "+v.getName()+";\n"); } else{ buffer.append("\tinout "+v.getName()+";\n\telectrical "+v.getName()+";\n"); if (!v.isDmvc()){ buffer2.append("\treal change_"+v.getName()+";\n"); buffer2.append("\treal rate_"+v.getName()+";\n"); vals = v.getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\t\tchange_"+v.getName()+" = "+ spanAvg+";\n"); vals = v.getInitRate().split("\\,"); spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*rateFactor); initBuffer.append("\t\trate_"+v.getName()+" = "+ (int)spanAvg+";\n"); } else{ buffer2.append("\treal "+v.getName()+"Val;\n"); // changed from real to int.. check?? vals = reqdVarsL.get(i).getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\t\t"+reqdVarsL.get(i).getName()+"Val = "+ spanAvg+";\n"); } } } // if (failPropVHDL != null){ // buffer.append("\toutput reg fail;\n\tlogic fail;\n"); // vams.write(", fail"); // } vams.write(");\n" + buffer+"\n"); if (buffer2.length() != 0){ vams.write(buffer2.toString()); } vams.write("\treal entryTime;\n"); if (vamsRandom){ vams.write("\tinteger seed;\n\tinteger del;\n"); } vams.write("\tinteger place;\n\n\tinitial\n\tbegin\n"); vams.write(initBuffer.toString()); vams.write("\t\tentryTime = 0;\n"); if (vamsRandom){ vams.write("\t\tseed = 0;\n"); } buffer.delete(0, buffer.length()); buffer2.delete(0, buffer2.length()); for (int i = 0; i < numPlaces; i++){ String p; if (!isTransientPlace("p"+i)){ p = getPlaceInfoIndex("p"+i); if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } else{ p = getTransientNetPlaceIndex("p"+i); if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) { continue; } } vams.write("\t\tplace = "+i+";\n"); break; } //if (failPropVHDL != null){ // vams.write("\t\t\tfail = 1'b0;\n"); //} vams.write("\tend\n\n"); for (String st1 : g.getPlaceList()){ if (!isTransientPlace(st1)){ String p = getPlaceInfoIndex(st1); if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) { ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) { dmvcPlaces.add(p); // w.r.t placeInfo here }*/ if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) { } } else{ String p = getTransientNetPlaceIndex(st1); if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){ ratePlaces.add(st1); // w.r.t g here } /* Related to the separate net for DMV input driver if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){ dmvcPlaces.add(p); // w.r.t placeInfo here }*/ } } /*for (String st:dmvcPlaces){ System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable")); }*/ Collections.sort(dmvcPlaces,new Comparator<String>(){ public int compare(String a, String b){ if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){ return -1; } else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){ if (Integer.parseInt(a.split("_")[2]) < Integer.parseInt(b.split("_")[2])){ return -1; } else if (Integer.parseInt(a.split("_")[2]) == Integer.parseInt(b.split("_")[2])){ return 0; } else{ return 1; } } else{ return 1; } } }); Collections.sort(ratePlaces,new Comparator<String>(){ String v1,v2; public int compare(String a, String b){ if (!isTransientPlace(a) && !isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else if (!isTransientPlace(a) && isTransientPlace(b)){ v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } else if (isTransientPlace(a) && !isTransientPlace(b)){ v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum"); } else { v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum"); v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum"); } if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); ArrayList<String> transitions = new ArrayList<String>(); for (String t : g.getTransitionList()){ transitions.add(t); } Collections.sort(transitions,new Comparator<String>(){ public int compare(String a, String b){ String v1 = a.split("t")[1]; String v2 = b.split("t")[1]; if (Integer.parseInt(v1) < Integer.parseInt(v2)){ return -1; } else if (Integer.parseInt(v1) == Integer.parseInt(v2)){ return 0; } else{ return 1; } } }); // sending the initial place to the end of the list. since if statements begin with preset of each place //ratePlaces.add(ratePlaces.get(0)); //ratePlaces.remove(0); ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>(); boolean contVarExists = false; for (Variable var: reqdVarsL){ dmvcVarPlaces.add(new ArrayList<String>()); if (var.isDmvc()){ continue; } else{ contVarExists = true; } } for (String st:dmvcPlaces){ dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st); } int transNum; buffer.delete(0, buffer.length()); initBuffer.delete(0, initBuffer.length()); String presetPlace = null,postsetPlace = null; StringBuffer[] transBuffer = new StringBuffer[transitions.size()]; int cnt = 0; StringBuffer transAlwaysPlaceBuffer = new StringBuffer(); int placeAlwaysBlockNum = -1; for (String t : transitions){ presetPlace = g.getPreset(t)[0]; //if (g.getPostset(t) != null){ // postsetPlace = g.getPostset(t)[0]; //} transNum = Integer.parseInt(t.split("t")[1]); cnt = transNum; if (!isTransientTransition(t)){ if (placeInfo.get(getPlaceInfoIndex(presetPlace)).getProperty("type").equals("RATE")){ if (g.getPostset(t).length != 0) postsetPlace = g.getPostset(t)[0]; for (int j = 0; j < transNum; j++){ if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){ cnt = j; break; } } if ( cnt == transNum){ transBuffer[cnt] = new StringBuffer(); if (transEnablingsVAMS[transNum].equalsIgnoreCase("")){ //transBuffer[cnt].append("\talways@(place)" + "\n\tbegin\n"); May 14, 2010 placeAlwaysBlockNum = cnt; } else{ transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n"); if (g.getPostset(t).length != 0) transAlwaysPlaceBuffer.append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); } } else{ String s = transBuffer[cnt].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[cnt].delete(0, transBuffer[cnt].length()); transBuffer[cnt].append(s); if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n" + "\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); } } transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); if (transDelayAssignVAMS[transNum] != null){ transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n"); for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ if (transIntAssignVAMS[transNum][i] != null){ transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]); } } } transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n"); transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transAlwaysPlaceBuffer.append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); } } } transBuffer[cnt].append("\t\tend\n"); //if ( cnt == transNum){ transBuffer[cnt].append("\tend\n"); //} if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){ transAlwaysPlaceBuffer.append("\t\tend\n"); } } } else{ if (transientNetPlaces.get(getTransientNetPlaceIndex(presetPlace)).getProperty("type").equals("RATE")){ if (g.getPostset(t).length != 0) postsetPlace = g.getPostset(t)[0]; for (int j = 0; j < transNum; j++){ if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){ cnt = j; break; } } if ( cnt == transNum){ transBuffer[cnt] = new StringBuffer(); transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); } else{ String s = transBuffer[cnt].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[cnt].delete(0, transBuffer[cnt].length()); transBuffer[cnt].append(s); } transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); if (transDelayAssignVAMS[transNum] != null){ transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n"); for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ if (transIntAssignVAMS[transNum][i] != null){ transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]); } } } transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n"); if (g.getPostset(t).length != 0) transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n"); transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n"); } } transBuffer[cnt].append("\t\tend\n"); //if ( cnt == transNum){ transBuffer[cnt].append("\tend\n"); //} } } //if (transDelayAssignVAMS[transNum] != null){ // buffer.append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n"); // buffer.append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n"); // buffer.append("\t\t\t#"+transDelayAssignVAMS[transNum]+";\n"); // for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){ // if (transIntAssignVAMS[transNum][i] != null){ // buffer.append("\t\t\t"+reqdVarsL.get(i).getName()+"Val = "+ transIntAssignVAMS[transNum][i]+";\n"); // } // } // buffer.append("\t\tend\n\tend\n"); //} } if (placeAlwaysBlockNum == -1){ vams.write("\talways@(place)" + "\n\tbegin\n"); vams.write(transAlwaysPlaceBuffer.toString()); vams.write("\tend\n"); } else{ String s = transBuffer[placeAlwaysBlockNum].toString(); s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n"); transBuffer[placeAlwaysBlockNum].delete(0, transBuffer[placeAlwaysBlockNum].length()); transBuffer[placeAlwaysBlockNum].append("\talways@(place)" + "\n\tbegin\n"); transBuffer[placeAlwaysBlockNum].append(transAlwaysPlaceBuffer); transBuffer[placeAlwaysBlockNum].append(s); transBuffer[placeAlwaysBlockNum].append("\tend\n"); } for (int j = 0; j < transitions.size(); j++){ if (transBuffer[j] != null){ vams.write(transBuffer[j].toString()); } } vams.write("\tanalog\n\tbegin\n"); for (int j = 0; j<reqdVarsL.size(); j++){ if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(change_" + reqdVarsL.get(j).getName() + " + rate_" + reqdVarsL.get(j).getName()+"*($abstime-entryTime));\n"); } if ((!reqdVarsL.get(j).isInput()) && (reqdVarsL.get(j).isDmvc())){ vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(" + reqdVarsL.get(j).getName() + "Val,delay,rtime,ftime);\n"); //vals = reqdVarsL.get(j).getInitValue().split("\\,"); //double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); //initBuffer.append("\t\t"+reqdVarsL.get(j).getName()+"Val = "+ spanAvg+";\n"); } } vams.write("\tend\n"); // if (initBuffer.length() != 0){ // vams.write("\n\tinitial\n\tbegin\n"+initBuffer+"\tend\n"); // } //if (buffer.length() != 0){ // vams.write(buffer.toString()); //} vams.write("endmodule\n\n"); buffer.delete(0, buffer.length()); buffer2.delete(0, buffer2.length()); initBuffer.delete(0, initBuffer.length()); int count = 0; for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ if (count == 0){ vams.write("module driver ( " + reqdVarsL.get(i).getName() + "drive "); count++; } else{ vams.write(", " + reqdVarsL.get(i).getName() + "drive "); count++; } buffer.append("\n\toutput "+ reqdVarsL.get(i).getName() + "drive;\n"); buffer.append("\telectrical "+ reqdVarsL.get(i).getName() + "drive;\n"); buffer2.append("\treal " + reqdVarsL.get(i).getName() + "Val" + ";\n"); vals = reqdVarsL.get(i).getInitValue().split("\\,"); double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*valScaleFactor); initBuffer.append("\n\tinitial\n\tbegin\n"+"\t\t"+ reqdVarsL.get(i).getName() + "Val = "+ spanAvg+";\n"); if ((count == 1) && (vamsRandom) ){ initBuffer.append("\t\tseed = 0;\n"); } //buffer3.append("\talways\n\tbegin\n"); boolean transientDoneFirst = false; for (String p : dmvcVarPlaces.get(i)){ if (!transientNetPlaces.containsKey(p)){ // since p is w.r.t placeInfo & not w.r.t g // buffer3.append("\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ // buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); if (transientDoneFirst){ initBuffer.append("\t\tforever\n\t\tbegin\n"); transientDoneFirst = false; } if (g.getPostset("p" + placeInfo.get(p).getProperty("placeNum")).length != 0){ if (!vamsRandom){ //initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) } else{ //initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9) initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9) } initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); } else{ } } else{ /*buffer3.append("\tinitial\n\tbegin\n"); buffer3.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n"); buffer3.append("\tend\n");*/ transientDoneFirst = true; if (!vamsRandom){ //initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9) } else{ //initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9) initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9) } initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/valScaleFactor + ";\n" ); // initBuffer.append("\tend\n"); } } // buffer3.append("\tend\n"); initBuffer.append("\t\tend\n\tend\n"); buffer4.append("\t\tV("+reqdVarsL.get(i).getName() + "drive) <+ transition("+reqdVarsL.get(i).getName() + "Val,delay,rtime,ftime);\n"); } } BufferedWriter topV = new BufferedWriter(new FileWriter(new File(directory + separator + "top.vams"))); topV.write("`timescale 1ps/1ps\n\nmodule top();\n\n"); if (count != 0){ vams.write(");\n"); vams.write("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n"); if (vamsRandom){ vams.write("\tinteger del;\n\tinteger seed;\n"); } vams.write(buffer+"\n"+buffer2+initBuffer+buffer3); vams.write("\tanalog\n\tbegin\n"+buffer4+"\tend\nendmodule"); count = 0; for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ if (count == 0){ topV.write("\tdriver tb(\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")"); count++; } else{ topV.write(",\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")"); count++; } } } topV.write("\n\t);\n\n"); } for (int i = 0; i < reqdVarsL.size(); i++){ v = reqdVarsL.get(i); if ( i== 0){ topV.write("\t"+vamsFileName.split("\\.")[0]+" dut(\n\t\t."+ v.getName() + "(" + v.getName() + ")"); } else{ topV.write(",\n\t\t." + v.getName() + "(" + reqdVarsL.get(i).getName() + ")"); count++; } } topV.write("\n\t);\n\nendmodule"); topV.close(); vams.close(); /*if (failPropVHDL != null){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); vhdlAms.write("\t\twait until " + failPropVHDL + ";\n"); vhdlAms.write("\t\tfail := true;\n"); vhdlAms.write("\tend process;\n\n"); } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");*/ } catch(IOException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Verilog-AMS model couldn't be created/written.", "ERROR!", JOptionPane.ERROR_MESSAGE); } catch(Exception e){ JOptionPane.showMessageDialog(BioSim.frame, "Error in Verilog-AMS model generation.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } //T[] aux = (T[])a.clone(); public LhpnFile mergeLhpns(LhpnFile l1,LhpnFile l2){//(LhpnFile l1, LhpnFile l2){ l1.save(directory + separator + "l1.lpn"); //since there's no deep copy method l2.save(directory + separator + "l2.lpn"); String place1 = "p([-\\d]+)", place2 = "P([-\\d]+)"; String transition1 = "t([-\\d]+)", transition2 = "T([-\\d]+)"; int placeNum, transitionNum; int minPlace=0, maxPlace=0, minTransition = 0, maxTransition = 0; Boolean first = true; LhpnFile l3 = new LhpnFile(); try{ for (String st1: l1.getPlaceList()){ if ((st1.matches(place1)) || (st1.matches(place2))){ st1 = st1.replaceAll("p", ""); st1 = st1.replaceAll("P", ""); placeNum = Integer.valueOf(st1); if (placeNum > maxPlace){ maxPlace = placeNum; if (first){ first = false; minPlace = placeNum; } } if (placeNum < minPlace){ minPlace = placeNum; if (first){ first = false; maxPlace = placeNum; } } } } for (String st1: l2.getPlaceList()){ if ((st1.matches(place1)) || (st1.matches(place2))){ st1 = st1.replaceAll("p", ""); st1 = st1.replaceAll("P", ""); placeNum = Integer.valueOf(st1); if (placeNum > maxPlace) maxPlace = placeNum; if (placeNum < minPlace) minPlace = placeNum; } } //System.out.println("min place and max place in both lpns are : " + minPlace + "," + maxPlace); for (String st2: l2.getPlaceList()){ for (String st1: l1.getPlaceList()){ if (st1.equalsIgnoreCase(st2)){ maxPlace++; l2.renamePlace(st2, "p" + maxPlace);//, l2.getPlace(st2).isMarked()); break; } } } first = true; for (String st1: l1.getTransitionList()){ if ((st1.matches(transition1)) || (st1.matches(transition2))){ st1 = st1.replaceAll("t", ""); st1 = st1.replaceAll("T", ""); transitionNum = Integer.valueOf(st1); if (transitionNum > maxTransition){ maxTransition = transitionNum; if (first){ first = false; minTransition = transitionNum; } } if (transitionNum < minTransition){ minTransition = transitionNum; if (first){ first = false; maxTransition = transitionNum; } } } } for (String st1: l2.getTransitionList()){ if ((st1.matches(transition1)) || (st1.matches(transition2))){ st1 = st1.replaceAll("t", ""); st1 = st1.replaceAll("T", ""); transitionNum = Integer.valueOf(st1); if (transitionNum > maxTransition) maxTransition = transitionNum; if (transitionNum < minTransition) minTransition = transitionNum; } } //System.out.println("min transition and max transition in both lpns are : " + minTransition + "," + maxTransition); for (String st2: l2.getTransitionList()){ for (String st1: l1.getTransitionList()){ if (st1.equalsIgnoreCase(st2)){ maxTransition++; l2.renameTransition(st2, "t" + maxTransition); break; } } } l2.save(directory + separator + "tmp.lpn"); l3 = new LhpnFile(); l3.load(directory + separator + "l1.lpn"); l3.load(directory + separator + "tmp.lpn"); l2 = new LhpnFile(); l2.load(directory + separator + "l2.lpn"); File l1File = new File(directory + separator + "l1.lpn"); File l2File = new File(directory + separator + "l2.lpn"); l1File.delete(); l2File.delete(); //l2.save(directory + separator + "tmp.lpn"); //l1.load(directory + separator + "tmp.lpn"); File tmp = new File(directory + separator + "tmp.lpn"); tmp.delete(); }catch(Exception e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Problem while merging lpns", "ERROR!", JOptionPane.ERROR_MESSAGE); } //return l1; return l3; } } /* private String traceBack(String place, String var){ String enabling = null; try{ visitedPlaces.put(place,true); for (String presetTrans : g.getPreset(place)){ ExprTree enableTree = g.getEnablingTree(presetTrans); if ((enableTree != null) && (enableTree.containsVar(var))){ enabling = enableTree.toString(); return enabling; } } for (String presetTrans : g.getPreset(place)){ for (String presetPlace : g.getPreset(presetTrans)){ if (!visitedPlaces.containsKey(presetPlace)){ enabling = traceBack(presetPlace,var); if (enabling != null) return enabling; } } } } catch (NullPointerException e){ e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Exception while tracing back for making the enabling conditions mutually exclusive.", "ERROR!", JOptionPane.ERROR_MESSAGE); } return enabling; } This method is used for creating separate nets for each DMV input variable driver. public void updateTimeInfo(int[][] bins, Properties cvgProp) { String prevPlace = null; String currPlace = null; Properties p3 = null; //ArrayList<String> dmvcPlaceL = new ArrayList<String>(); // only dmvc inputs boolean exists; // int dmvcCnt = 0; making this global .. rechk String[] places; try { for (int i = 0; i < reqdVarsL.size(); i++) { if (reqdVarsL.get(i).isDmvc() && reqdVarsL.get(i).isInput()) { out.write(reqdVarsL.get(i).getName() + " is a dmvc input variable \n"); // dmvcCnt = 0; in case of multiple tsd files, this may be a problem. may create a new distinct place with an existing key.?? prevPlace = null; currPlace = null; p3 = null; Properties p2 = null; String k; DMVCrun runs = reqdVarsL.get(i).getRuns(); Double[] avgVals = runs.getAvgVals(); out.write("variable " + reqdVarsL.get(i).getName() + " Number of runs = " + avgVals.length + "Avg Values are : " + avgVals.toString() + "\n"); for (int j = 0; j < avgVals.length; j++) { // this gives number of runs/startpoints/endpoints exists = false; places = g.getPlaceList(); if (places.length > 1) { for (String st : places) { k = getPlaceInfoIndex(st); if (!isTransientPlace(st) && (placeInfo.get(k).getProperty("type").equalsIgnoreCase("DMVC"))) { if ((Math.abs(Double.parseDouble(placeInfo.get(k).getProperty("DMVCValue")) - avgVals[j]) < epsilon) && (placeInfo.get(k).getProperty("DMVCVariable").equalsIgnoreCase(reqdVarsL.get(i).getName()))) { // out.write("Place with key " + k + "already exists. so adding dmvcTime to it\n"); addDmvcTime(placeInfo.get(k), reqdVarsL.get(i).getName(), calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); addDuration(placeInfo.get(k),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); exists = true; prevPlace = currPlace; currPlace = getPlaceInfoIndex(st);// k; p2 = placeInfo.get(currPlace); //next few lines commented to remove multiple dmv input places of same variable from being marked initially. // if (j == 0) { // adding the place corresponding to the first dmv run to initial marking. // placeInfo.get(k).setProperty("initiallyMarked", "true"); // g.changeInitialMarking("p" + placeInfo.get(k).getProperty("placeNum"),true); //} // break ; here? } } } } if (!exists) { prevPlace = currPlace; currPlace = "d_" + i + "_" + dmvcCnt; p2 = new Properties(); p2.setProperty("placeNum", numPlaces.toString()); p2.setProperty("type", "DMVC"); p2.setProperty("DMVCVariable", reqdVarsL.get(i).getName()); p2.setProperty("DMVCValue", avgVals[j].toString()); p2.setProperty("initiallyMarked", "false"); addDmvcTime(p2, reqdVarsL.get(i).getName(),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j))); //placeInfo.put("d_" + i + "_" + dmvcCnt, p2); if (j == 0) { transientNetPlaces.put("d_" + i + "_" + dmvcCnt, p2); g.addPlace("p" + numPlaces, true); p2.setProperty("initiallyMarked", "true"); } else{ placeInfo.put("d_" + i + "_" + dmvcCnt, p2); g.addPlace("p" + numPlaces, false); } dmvcInputPlaces.add("p" + numPlaces); if (j == 0) { // adding the place corresponding to the first dmv run to initial marking p2.setProperty("initiallyMarked", "true"); g.changeInitialMarking("p" + p2.getProperty("placeNum"), true); } numPlaces++; out.write("Created new place with key " + "d_" + i + "_" + dmvcCnt + "\n"); dmvcCnt++; //dmvcPlaceL.add(currPlace); cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1)); } Double d = calcDelay(runs.getStartPoint(j), runs.getEndPoint(j));// data.get(0).get(runs.getEndPoint(j)) - data.get(0).get(runs.getStartPoint(j)); // data.get(0).get(reqdVarsL.get(prevPlace.getDmvcVar()).getRuns().getEndPoint(j-1)); // TEMPORARY FIX //Double minTime = getMinDmvcTime(p2); //if ((d > minTime*Math.pow(10.0, 4.0))){ // && (getMinDmvcTime(p2) == getMaxDmvcTime(p2))){ // deleteInvalidDmvcTime(p2, getMinDmvcTime(p2)); // updates dmin,dmax too //} //END TEMPORARY FIX // For dmv input nets, transition's delay assignment is // it's preset's duration; value assgnmt is value in postset. addDuration(p2,d); //boolean transientNet = false; // out.write("Delay in place p"+ p2.getProperty("placeNum")+ " after updating " + d + " is ["+ p2.getProperty("dMin") + ","+ p2.getProperty("dMax") + "]\n"); if (prevPlace != null) { if (transitionInfo.containsKey(prevPlace + currPlace)) { p3 = transitionInfo.get(prevPlace + currPlace); } else { p3 = new Properties(); p3.setProperty("transitionNum", numTransitions.toString()); if (transientNetPlaces.containsKey(prevPlace)){ transientNetTransitions.put(prevPlace + currPlace, p3); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p" + transientNetPlaces.get(prevPlace).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum")); g.addMovement("t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum"), "p" + placeInfo.get(currPlace).getProperty("placeNum")); // transientNet = true; } else{ transitionInfo.put(prevPlace + currPlace, p3); g.addTransition("t" + numTransitions); // prevTranKey+key); g.addMovement("p"+ placeInfo.get(prevPlace).getProperty("placeNum"), "t"+ transitionInfo.get(prevPlace + currPlace).getProperty("transitionNum")); g.addMovement("t"+ transitionInfo.get(prevPlace+ currPlace).getProperty("transitionNum"),"p"+ placeInfo.get(currPlace).getProperty("placeNum")); } numTransitions++; cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1)); } } //if (!transientNet){ // assuming postset duration // addDuration(p2, d); //} //else { // addTransientDuration(p2, d); //} } } else if (reqdVarsL.get(i).isDmvc()) { // non-input dmvc } } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(BioSim.frame, "Log file couldn't be opened for writing rates and bins.", "ERROR!", JOptionPane.ERROR_MESSAGE); } } */ /* ArrayList<ArrayList<String>> ifL = new ArrayList<ArrayList<String>>(); ArrayList<ArrayList<String>> ifRateL = new ArrayList<ArrayList<String>>(); for (Variable v: reqdVarsL){ ifL.add(new ArrayList<String>()); ifRateL.add(new ArrayList<String>()); } String[] tL; for (String p : ratePlaces){ tL = g.getPreset(p); for (String t : tL){ if ((g.getPreset(t).length != 0) && (g.getPostset(t).length != 0) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE")) && (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) { ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0])); String ifStr = ""; String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(""); String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(""); boolean above; double val; for (int k : diffL) { if (Integer.parseInt(binIncoming[k + 1]) < Integer.parseInt(binOutgoing[k + 1])) { val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k + 1])).doubleValue(); above = true; } else { val = divisionsL.get(k).get(Integer.parseInt(binOutgoing[k + 1])).doubleValue(); above = false; } if (above) { ifStr = reqdVarsL.get(k).getName()+"'above("+val+")"; } else{ ifStr = "not "+ reqdVarsL.get(k).getName()+"'above("+val+")"; } for (int j = 0; j<reqdVarsL.size(); j++){ String rateStr = ""; if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){ //if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){ rateStr = reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0)"; ifL.get(j).add(ifStr); ifRateL.get(j).add(rateStr); } } } } } } for (int i = 0; i<reqdVarsL.size(); i++){ for (int j = 0; j<ifL.get(i).size(); j++){ if (j==0){ vhdlAms.write("\tif "+ifL.get(i).get(j)+" use\n"); } else{ vhdlAms.write("\telsif "+ifL.get(i).get(j)+" use\n"); } vhdlAms.write("\t\t"+ ifRateL.get(i).get(j)+";\n"); } if (ifL.get(i).size() != 0){ vhdlAms.write("\tend use;\n\n"); } } // vhdlAms.write("\tprocess\n"); // vhdlAms.write("\tbegin\n"); for (int i = 0; i < dmvcVarPlaces.size(); i++){ if (dmvcVarPlaces.get(i).size() != 0){ vhdlAms.write("\tprocess\n"); vhdlAms.write("\tbegin\n"); for (String p : dmvcVarPlaces.get(i)){ vhdlAms.write("\t\twait for delay("+placeInfo.get(p).getProperty("dMax")+","+placeInfo.get(p).getProperty("dMin") +");\n"); // recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/ vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ placeInfo.get(p).getProperty("DMVCValue") + ";\n"); } vhdlAms.write("\tend process;\n\n"); } } // vhdlAms.write("\tend process;\n\n"); vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n"); vhdlAms.close(); } catch(IOException e){ } } //T[] aux = (T[])a.clone(); } */ /* OBSOLETE METHODS public ArrayList<ArrayList<Double>> parseBinFile() { reqdVarsL = new ArrayList<Variable>(); ArrayList<String> linesBinFileL = null; int h = 0; //ArrayList<ArrayList<Double>> divisionsL = new ArrayList<ArrayList<Double>>(); try { Scanner f1 = new Scanner(new File(directory + separator + binFile)); // log.addText(directory + separator + binFile); linesBinFileL = new ArrayList<String>(); linesBinFileL.add(f1.nextLine()); while (f1.hasNextLine()) { linesBinFileL.add(f1.nextLine()); } out.write("Required variables and their levels are :"); for (String st : linesBinFileL) { divisionsL.add(new ArrayList<Double>()); String[] wordsBinFileL = st.split("\\s"); for (int i = 0; i < wordsBinFileL.length; i++) { if (i == 0) { reqdVarsL.add(new Variable(wordsBinFileL[i])); out.write("\n" + reqdVarsL.get(reqdVarsL.size() - 1).getName()); } else { divisionsL.get(h).add(Double.parseDouble(wordsBinFileL[i])); } } out.write(" " + divisionsL.get(h)); h++; // max = Math.max(max, wordsBinFileL.length + 1); } f1.close(); } catch (Exception e1) { } return divisionsL; } public String cleanRow (String row){ String rowNS,rowTS = null; try{ rowNS =lParenR.matcher(row).replaceAll(""); rowTS = rParenR.matcher(rowNS).replaceAll(""); return rowTS; } catch(PatternSyntaxException pse){ System.out.format("There is a problem withthe regular expression!%n"); System.out.format("The pattern in question is:%s%n",pse.getPattern()); System.out.format("The description is:%s%n",pse.getDescription()); System.out.format("The message is:%s%n",pse.getMessage()); System.out.format("The index is:%s%n",pse.getIndex()); System.exit(0); return rowTS; } } */
added method for adding stables to data
gui/src/learn/LearnModel.java
added method for adding stables to data
Java
apache-2.0
43a6e33f44ef2ae044065c6761909b164aa6b68c
0
sshtools/forker,sshtools/forker,sshtools/forker
package com.sshtools.forker.wrapper; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.MXBean; import javax.management.ObjectName; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import com.sshtools.forker.client.EffectiveUserFactory; import com.sshtools.forker.client.ForkerBuilder; import com.sshtools.forker.client.OSCommand; import com.sshtools.forker.common.CSystem; import com.sshtools.forker.common.Cookie.Instance; import com.sshtools.forker.common.IO; import com.sshtools.forker.common.OS; import com.sshtools.forker.common.Priority; import com.sshtools.forker.common.Util; import com.sshtools.forker.daemon.CommandHandler; import com.sshtools.forker.daemon.Forker; import com.sshtools.forker.daemon.Forker.Client; import com.sshtools.forker.wrapper.JVM.Version; /** * <i>Forker Wrapper</i> can be used to wrap java applications in a manner * similar to other Java projects such as JSW, YAJSW and more. It provides the * following features :- * <ul> * <li>Multiple ways of configuration, including via command line options, * system properties, configuration files and environment variables.</li> * <li>JVM selection</li> * <li>JVM timeout detection</li> * <li>Run as administrator or another user</li> * <li>Run in background</li> * <li>Capture output to log</li> * <li>Restart on certain exit codes</li> * <li>Run scripts or Java classes on events</li> * <li>Wrap native commands</li> * <li>Embeddable or standalone use</li> * <li>Single instance enforcement</li> * <li>PID file writing</li> * <li>Process priority and affinity</li> * <li>Forker Daemon integration</li> * <li>Wildcard classpaths</li> * <li>.. and more</li> * </ul> * */ @MXBean public class ForkerWrapper implements ForkerWrapperMXBean { public final static String EXITED_WRAPPER = "exited-wrapper"; public final static String EXITING_WRAPPER = "exiting-wrapper"; public final static String STARTING_FORKER_DAEMON = "started-forker-daemon"; public final static String STARTED_FORKER_DAEMON = "started-forker-daemon"; public final static String STARTING_APPLICATION = "starting-application"; public final static String STARTED_APPLICATION = "started-application"; public final static String RESTARTING_APPLICATION = "restarting-application"; public final static String APPPLICATION_STOPPED = "application-stopped"; public final static String[] EVENT_NAMES = { EXITED_WRAPPER, EXITING_WRAPPER, STARTING_FORKER_DAEMON, STARTED_FORKER_DAEMON, STARTED_APPLICATION, STARTING_APPLICATION, RESTARTING_APPLICATION, APPPLICATION_STOPPED }; public static class KeyValuePair { private String key; private String value; private boolean bool; public KeyValuePair(String line) { key = line; int idx = line.indexOf('='); int spcidx = line.indexOf(' '); if (spcidx != -1 && (spcidx < idx || idx == -1)) { idx = spcidx; } if (idx != -1) { value = line.substring(idx + 1); key = line.substring(0, idx); } else { bool = true; } } public KeyValuePair(String key, String value) { this.key = key; this.value = value; } public String getName() { return key; } public String getValue() { return value; } public boolean isBool() { return bool; } public void setValue(String value) { this.value = value; } } public enum ArgMode { FORCE, APPEND, PREPEND, DEFAULT } private String classname; private String[] arguments; private CommandLine cmd; private List<KeyValuePair> properties = new ArrayList<KeyValuePair>(); private Forker daemon; private Instance cookie; private Process process; private boolean tempRestartOnExit; private String[] originalArgs; private Logger logger = Logger.getLogger(ForkerWrapper.class.getSimpleName()); private boolean inited; private PrintStream defaultOut = System.out; private PrintStream defaultErr = System.err; private InputStream defaultIn = System.in; private boolean stopping = false; private boolean preventRestart = false; public String[] getArguments() { return arguments; } public InputStream getDefaultIn() { return defaultIn; } public void setDefaultIn(InputStream defaultIn) { this.defaultIn = defaultIn; } public PrintStream getDefaultOut() { return defaultOut; } public void setDefaultOut(PrintStream defaultOut) { this.defaultOut = defaultOut; } public PrintStream getDefaultErr() { return defaultErr; } public void setDefaultErr(PrintStream defaultErr) { this.defaultErr = defaultErr; } public void setArguments(String... arguments) { this.arguments = arguments; } public void setProperty(String key, Object value) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) { nvp.setValue(String.valueOf(value)); return; } } properties.add(new KeyValuePair(key, String.valueOf(value))); } public String getClassname() { return classname; } public File relativize(File context, String path) throws IOException { File p = new File(path); if (p.isAbsolute()) { return p.getCanonicalFile(); } return new File(context, p.getPath()).getCanonicalFile(); } public void restart() throws InterruptedException { restart(true); } public void restart(boolean wait) throws InterruptedException { stop(true, true); } public void stop() throws InterruptedException { stop(true); } public void stop(boolean wait) throws InterruptedException { stop(wait, false); } @SuppressWarnings("resource") public int start() throws IOException, InterruptedException { if (!inited) init(null); /* * Calculate CWD. All file paths from this point are calculated relative * to the CWD */ String cwdpath = getOptionValue("cwd", null); File cwd = new File(System.getProperty("user.dir")); if (StringUtils.isNotBlank(cwdpath)) { cwd = relativize(cwd, cwdpath); if (!cwd.exists()) throw new IOException(String.format("No such directory %s", cwd)); } String javaExe = getJVMPath(); String forkerClasspath = System.getProperty("java.class.path"); String wrapperClasspath = getOptionValue("classpath", forkerClasspath); String bootClasspath = getOptionValue("boot-classpath", null); final boolean nativeMain = getSwitch("native", false); final boolean useDaemon = !nativeMain && !getSwitch("no-forker-daemon", nativeMain); List<String> jvmArgs = getOptionValues("jvmarg"); if (nativeMain && StringUtils.isNotBlank(getOptionValue("classpath", null))) { throw new IOException("Native main may not be used with classpath option."); } if (nativeMain && !jvmArgs.isEmpty()) { throw new IOException("Native main may not be used with jvmarg option."); } boolean daemonize = getSwitch("daemon", false); String pidfile = getOptionValue("pidfile", null); final int exitWait = Integer.parseInt(getOptionValue("exit-wait", "10")); if (daemonize(cwd, javaExe, forkerClasspath, daemonize, pidfile)) return 0; /** * LDP: Does not work on OSX. Prevented setProcname from throwing an * exception */ if (!OS.setProcname(classname)) { logger.warning(String.format("Failed to set process name to %s", classname)); } try { ManagementFactory.getPlatformMBeanServer().registerMBean(this, new ObjectName("com.sshtools.forker.wrapper:type=Wrapper")); } catch (Exception e) { throw new IOException("Failed to register MBean.", e); } /* * Create a lock file if 'single instance' was specified */ FileLock lock = null; FileChannel lockChannel = null; File lockFile = new File(new File(System.getProperty("java.io.tmpdir")), "forker-wrapper-" + classname + ".lock"); addShutdownHook(useDaemon, exitWait); try { if (getSwitch("single-instance", false)) { lockChannel = new RandomAccessFile(lockFile, "rw").getChannel(); try { logger.info(String.format("Attempting to acquire lock on %s", lockFile)); lock = lockChannel.tryLock(); if (lock == null) throw new OverlappingFileLockException(); lockFile.deleteOnExit(); } catch (OverlappingFileLockException ofle) { throw new IOException(String.format("The application %s is already running.", classname)); } } if (useDaemon) { monitorWrappedApplication(); } int retval = 2; int times = 0; int lastRetVal = -1; while (true) { times++; stopping = false; process = null; boolean quiet = getSwitch("quiet", false); boolean quietStdErr = quiet || getSwitch("quiet-stderr", false); boolean quietStdOut = quiet || getSwitch("quiet-stdout", false); boolean logoverwrite = getSwitch("log-overwrite", false); /* Build the command to launch the application itself */ ForkerBuilder appBuilder = new ForkerBuilder(); if (!nativeMain) { appBuilder.command().add(javaExe); String classpath = buildClasspath(cwd, getSwitch("no-forker-classpath", false) ? null : forkerClasspath, wrapperClasspath, true); if (classpath != null) { appBuilder.command().add("-classpath"); appBuilder.command().add(classpath); } boolean hasBootCp = false; for (String val : jvmArgs) { if (val.startsWith("-Xbootclasspath")) hasBootCp = true; appBuilder.command().add(val); } if (!hasBootCp) { String bootcp = buildClasspath(cwd, null, bootClasspath, false); if (bootcp != null && !bootcp.equals("")) { /* * Do our own processing of append/prepend as there * are special JVM arguments for it */ if (bootClasspath != null && bootClasspath.startsWith("+")) appBuilder.command().add("-Xbootclasspath/a:" + bootcp); else if (bootClasspath != null && bootClasspath.startsWith("-")) appBuilder.command().add("-Xbootclasspath/p:" + bootcp); else appBuilder.command().add("-Xbootclasspath:" + bootcp); } } } if (!getSwitch("no-info", false)) { if (lastRetVal > -1) { appBuilder.command().add(String.format("-Dforker.info.lastExitCode=%d", lastRetVal)); } appBuilder.command().add(String.format("-Dforker.info.attempts=%d", times)); } /* * If the daemon should be used, we assume that forker-client is * on the classpath and execute the application via that, pssing * the forker daemon cookie via stdin. * */ if (useDaemon) { /* * Otherwise we are just running the application directly */ appBuilder.command().add(com.sshtools.forker.client.Forker.class.getName()); appBuilder.command().add(String.valueOf(OS.isAdministrator())); appBuilder.command().add(classname); if (arguments != null) appBuilder.command().addAll(Arrays.asList(arguments)); } else { /* * Otherwise we are just running the application directly */ appBuilder.command().add(classname); if (arguments != null) appBuilder.command().addAll(Arrays.asList(arguments)); } String priStr = getOptionValue("priority", null); if (priStr != null) { appBuilder.priority(Priority.valueOf(priStr)); } appBuilder.io(IO.DEFAULT); appBuilder.directory(cwd); /* Environment variables */ for (String env : getOptionValues("setenv")) { String key = env; String value = ""; int idx = env.indexOf('='); if (idx != -1) { key = env.substring(0, idx); value = env.substring(idx + 1); } appBuilder.environment().put(key, value); } List<String> cpus = getOptionValues("cpu"); for (String cpu : cpus) { appBuilder.affinity().add(Integer.parseInt(cpu)); } if (getSwitch("administrator", false)) { if (!OS.isAdministrator()) { logger.info("Raising privileges to administartor"); appBuilder.effectiveUser(EffectiveUserFactory.getDefault().administrator()); } } else { String runas = getOptionValue("run-as", null); if (runas != null && !runas.equals(System.getProperty("user.name"))) { logger.info(String.format("Switching user to %s", runas)); appBuilder.effectiveUser(EffectiveUserFactory.getDefault().getUserForUsername(runas)); } } daemon = null; cookie = null; if (useDaemon) { startForkerDaemon(); } event(STARTING_APPLICATION, String.valueOf(times), cwd.getAbsolutePath(), classname, String.valueOf(lastRetVal)); process = appBuilder.start(); event(STARTED_APPLICATION, classname); if (useDaemon) { process.getOutputStream().write(cookie.toString().getBytes("UTF-8")); process.getOutputStream().write("\r\n".getBytes("UTF-8")); process.getOutputStream().flush(); } String logpath = getOptionValue("log", null); String errpath = getOptionValue("errors", null); if (errpath == null) errpath = logpath; OutputStream outlog = null; OutputStream errlog = null; long logDelay = Long.parseLong(getOptionValue("log-write-delay", "50")); if (StringUtils.isNotBlank(logpath)) { logger.info(String.format("Writing stdout output to %s", logpath)); outlog = new LazyLogStream(logDelay, makeDirectoryForFile(relativize(cwd, logpath)), !logoverwrite); } if (errpath != null) { if (Objects.equals(logpath, errpath)) errlog = outlog; else { logger.info(String.format("Writing stderr output to %s", logpath)); errlog = new LazyLogStream(logDelay, makeDirectoryForFile(relativize(cwd, errpath)), !logoverwrite); } } OutputStream stdout = quietStdOut ? null : defaultOut; OutputStream out = null; if (stdout != null) { if (outlog != null) { out = new TeeOutputStream(stdout, outlog); } else { out = stdout; } } else if (outlog != null) out = outlog; if (out == null) { out = new SinkOutputStream(); } OutputStream stderr = quietStdErr ? null : defaultErr; OutputStream err = null; if (stderr != null) { if (errlog != null) { err = new TeeOutputStream(stderr, errlog); } else { err = stderr; } } else if (errlog != null) err = errlog; if (err == null) { err = out; } Thread errThread = new Thread(copyRunnable(process.getErrorStream(), err), "StdErr"); errThread.setDaemon(true); errThread.start(); Thread inThread = null; try { if (!daemonize) { inThread = new Thread(copyRunnable(defaultIn, process.getOutputStream()), "StdIn"); inThread.setDaemon(true); inThread.start(); } try { copy(process.getInputStream(), out, newBuffer()); } catch (IOException ioe) { if (!stopping) throw ioe; } retval = process.waitFor(); } finally { if (inThread != null) { inThread.interrupt(); } errThread.interrupt(); if (outlog != null && !outlog.equals(defaultOut)) { outlog.close(); } if (errlog != null && errlog != outlog && !errlog.equals(defaultErr)) { errlog.close(); } if (daemon != null) { daemon.shutdown(true); } } List<String> restartValues = Arrays.asList(getOptionValue("restart-on", "").split(",")); List<String> dontRestartValues = new ArrayList<String>( Arrays.asList(getOptionValue("dont-restart-on", "0,1,2").split(","))); dontRestartValues.removeAll(restartValues); String strret = String.valueOf(retval); event(APPPLICATION_STOPPED, strret, classname); boolean restart = !preventRestart && (((restartValues.size() == 1 && restartValues.get(0).equals("")) || restartValues.size() == 0 || restartValues.contains(strret)) && !dontRestartValues.contains(strret)); if (tempRestartOnExit || restart) { try { tempRestartOnExit = false; int waitSec = Integer.parseInt(getOptionValue("restart-wait", "0")); if (waitSec == 0) throw new NumberFormatException(); event(RESTARTING_APPLICATION, classname, String.valueOf(waitSec)); logger.warning(String.format("Process exited with %d, attempting restart in %d seconds", retval, waitSec)); lastRetVal = retval; Thread.sleep(waitSec * 1000); } catch (NumberFormatException nfe) { event(RESTARTING_APPLICATION, classname, "0"); logger.warning(String.format("Process exited with %d, attempting restart", retval)); } } else break; } // TODO cant find out why just exiting fails (process stays // running). // Cant get a trace on what is still running either // PtyHelpers.getInstance().kill(PtyHelpers.getInstance().getpid(), // 9); // OSCommand.run("kill", "-9", // String.valueOf(PtyHelpers.getInstance().getpid())); return retval; } finally { if (lock != null) { logger.fine(String.format("Release lock %s", lockFile)); lock.release(); } if (lockChannel != null) { lockChannel.close(); } stopping = false; preventRestart = false; tempRestartOnExit = false; } } public ArgMode getArgMode() { return ArgMode.valueOf(getOptionValue("argmode", ArgMode.DEFAULT.name())); } public List<KeyValuePair> getProperties() { return properties; } public void setClassname(String classname) { this.classname = classname; } public void readConfigFile(File file) throws IOException { logger.info(String.format("Loading configuration file %s", file)); BufferedReader fin = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = fin.readLine()) != null) { if (!line.trim().startsWith("#") && !line.trim().equals("")) { properties.add(new KeyValuePair(ReplacementUtils.replaceSystemProperties(line))); } } } finally { fin.close(); } } public static String getAppName() { String an = System.getenv("FORKER_APPNAME"); return an == null || an.length() == 0 ? ForkerWrapper.class.getName() : an; } public static void main(String[] args) { ForkerWrapper wrapper = new ForkerWrapper(); wrapper.originalArgs = args; Options opts = new Options(); // Add the options always available wrapper.addOptions(opts); // Add the command line launch options opts.addOption(Option.builder("c").argName("file").hasArg() .desc("A file to read configuration. The file " + "should contain name=value pairs, where name is the same name as used for command line " + "arguments (see --help for a list of these)") .longOpt("configuration").build()); opts.addOption(Option.builder("C").argName("directory").hasArg() .desc("A directory to read configuration files from. Each file " + "should contain name=value pairs, where name is the same name as used for command line " + "arguments (see --help for a list of these)") .longOpt("configuration-directory").build()); opts.addOption(Option.builder("h") .desc("Show command line help. When the optional argument is supplied, help will " + "be displayed for the option with that name") .optionalArg(true).hasArg().argName("option").longOpt("help").build()); opts.addOption(Option.builder("O").desc("File descriptor for stdout").optionalArg(true).hasArg().argName("fd") .longOpt("fdout").build()); opts.addOption(Option.builder("E").desc("File descriptor for stderr").optionalArg(true).hasArg().argName("fd") .longOpt("fderr").build()); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); try { CommandLine cmd = parser.parse(opts, args); wrapper.init(cmd); String outFdStr = wrapper.getOptionValue("fdout", null); if (outFdStr != null) { Constructor<FileDescriptor> cons = FileDescriptor.class.getDeclaredConstructor(int.class); cons.setAccessible(true); FileDescriptor fdOut = cons.newInstance(Integer.parseInt(outFdStr)); System.setOut(new PrintStream(new FileOutputStream(fdOut), true)); } String errFdStr = wrapper.getOptionValue("fdout", null); if (errFdStr != null) { Constructor<FileDescriptor> cons = FileDescriptor.class.getDeclaredConstructor(int.class); cons.setAccessible(true); FileDescriptor fdErr = cons.newInstance(Integer.parseInt(errFdStr)); System.setErr(new PrintStream(new FileOutputStream(fdErr), true)); } if (cmd.hasOption('h')) { String optionName = cmd.getOptionValue('h'); if (optionName == null) { formatter.printHelp(new PrintWriter(System.err, true), 132, getAppName(), " <application.class.name> [<argument> [<argument> ..]]\n\n" + "Forker Wrapper is used to launch Java applications, optionally changing " + "the user they are run as, providing automatic restarting, signal handling and " + "other facilities that will be useful running applications as a 'service'.\n\n" + "Configuration may be passed to Forker Wrapper in four different ways :-\n\n" + "1. Command line options.\n" + "2. Configuration files (see -c and -C options)\n" + "3. Java system properties. The key of which is option name prefixed with 'forker.' and with - replaced with a dot (.)\n" + "4. Environment variables. The key of which is the option name prefixed with 'FORKER_' (in upper case) with - replaced with _\n\n", opts, 2, 5, "\nProvided by SSHTOOLS Limited.", true); System.exit(1); } else { Option opt = opts.getOption(optionName); if (opt == null) { throw new Exception(String.format("No option named", optionName)); } else { System.err.println(optionName); System.err.println(); System.err.println(opt.getDescription()); } } } if (cmd.hasOption("configuration")) { wrapper.readConfigFile(new File(cmd.getOptionValue('c'))); } String cfgDir = wrapper.getOptionValue("configuration-directory", null); if (cfgDir != null) { File dir = new File(cfgDir); if (dir.exists()) { for (File f : dir.listFiles()) { if (f.isFile() && !f.isHidden()) wrapper.readConfigFile(f); } } } wrapper.process(); } catch (Throwable e) { System.err.println(String.format("%s: %s\n", wrapper.getClass().getName(), e.getMessage())); formatter.printUsage(new PrintWriter(System.err, true), 80, String.format("%s <application.class.name> [<argument> [<argument> ..]]", getAppName())); System.exit(1); } try { System.exit(wrapper.start()); } catch (Throwable e) { e.printStackTrace(); System.err.println(String.format("%s: %s\n", wrapper.getClass().getName(), e.getMessage())); formatter.printUsage(new PrintWriter(System.err, true), 80, String.format("%s <application.class.name> [<argument> [<argument> ..]]", getAppName())); System.exit(1); } } public void init(CommandLine cmd) { if (!inited) { this.cmd = cmd; String levelName = getOptionValue("level", "WARNING"); logger.setLevel(Level.parse(levelName)); inited = true; } } protected void stop(boolean wait, boolean restart) throws InterruptedException { stopping = true; preventRestart = !restart; tempRestartOnExit = restart; if (process != null) { process.destroy(); if (wait) { process.waitFor(); } } } protected String getJVMPath() throws IOException { String javaExe = getOptionValue("java", System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); if (SystemUtils.IS_OS_WINDOWS && !javaExe.endsWith(".exe")) javaExe += ".exe"; String minjava = getOptionValue("min-java", null); String maxjava = getOptionValue("max-java", null); if (StringUtils.isNotBlank(minjava) || StringUtils.isNotBlank(maxjava)) { if (StringUtils.isBlank(minjava)) minjava = "0.0.0"; if (StringUtils.isBlank(maxjava)) maxjava = "9999.9999.9999"; Version minver = new Version(minjava); Version maxver = new Version(maxjava); JVM jvm = new JVM(javaExe); if (jvm.getVersion().compareTo(minver) < 0 || jvm.getVersion().compareTo(maxver) > 0) { logger.info(String.format("Initially chosen JVM %s (%s) is not within the JVM version range of %s to %s", javaExe, jvm.getVersion(), minver, maxver)); for (JVM altJvm : JVM.jvms()) { if (altJvm.getVersion().compareTo(minver) >= 0 && altJvm.getVersion().compareTo(maxver) <= 0) { javaExe = altJvm.getPath(); logger.info(String.format("Using alternative JVM %s which version %s", javaExe, altJvm.getVersion())); break; } } } else { logger.info(String.format("Initially chosen JVM %s (%s) is valid for the version range %s to %s", javaExe, jvm.getVersion(), minver, maxver)); } } return javaExe; } protected void event(String name, String... args) throws IOException { String eventHandler = getOptionValue("on-" + name, null); logger.info(String.format("Event " + name + ": %s", Arrays.asList(args))); if (StringUtils.isNotBlank(eventHandler)) { // Parse the event handler script List<String> handlerArgs = Util.parseQuotedString(eventHandler); for (int i = 0; i < handlerArgs.size(); i++) { handlerArgs.set(i, handlerArgs.get(i).replace("%0", eventHandler)); for (int j = 0; j < args.length; j++) handlerArgs.set(i, handlerArgs.get(i).replace("%" + (j + 1), args[j])); handlerArgs.set(i, handlerArgs.get(i).replace("%%", "%")); } String cmd = handlerArgs.remove(0); try { if (!cmd.contains(".")) throw new Exception("Not a class"); int idx = cmd.indexOf("#"); String methodName = "main"; if (idx != -1) { methodName = cmd.substring(idx + 1); cmd = cmd.substring(0, idx); } Class<?> clazz = Class.forName(cmd); Method method = clazz.getMethod(methodName, String[].class); try { logger.info(String.format("Handling with Java class %s (%s)", eventHandler, Arrays.asList(args))); method.invoke(null, new Object[] { args }); } catch (Exception e) { throw new IOException("Exception thrown during event handler.", e); } } catch (Exception cnfe) { // Assume to be native command List<String> allArgs = new ArrayList<String>(); allArgs.add(cmd); allArgs.addAll(handlerArgs); try { logger.info(String.format("Handling with command %s", allArgs.toString())); OSCommand.run(allArgs); } catch (Exception e) { throw new IOException("Exception thrown during event handler.", e); } } } } protected void addOptions(Options options) { for (String event : EVENT_NAMES) { options.addOption(Option.builder().longOpt("on-" + event).hasArg(true).argName("command-or-classname") .desc("Executes a script or a Java class (that must be on wrappers own classpath) " + "when a particular event occurs. If a Java class is to be execute, it " + "must contain a main(String[] args) method. Each event may pass a number of arguments.") .build()); } options.addOption(new Option("x", "allow-execute", true, "The wrapped application can use it's wrapper to execute commands on it's behalf. If the " + "wrapper itself runs under an administrative user, and the application as a non-privileged user," + "you may wish to restrict which commands may be run. One or more of these options specifies the " + "name of the command that may be run. The value may be a regular expression, see also 'prevent-execute'")); options.addOption(new Option("X", "reject-execute", true, "The wrapped application can use it's wrapper to execute commands on it's behalf. If the " + "wrapper itself runs under an administrative user, and the application as a non-privileged user," + "you may wish to restrict which commands may be run. One or more of these options specifies the " + "name of the commands that may NOT be run. The value may be a regular expression, see also 'allow-execute'")); options.addOption(new Option("F", "no-forker-classpath", false, "When the forker daemon is being used, the wrappers own classpath will be appened to " + "to the application classpath. This option prevents that behaviour for example if " + "the application includes the modules itself.")); options.addOption(new Option("r", "restart-on", true, "Which exit values from the spawned process will cause the wrapper to attempt to restart it. When not specified, all exit " + "values will cause a restart except those that are configure not to (see dont-restart-on).")); options.addOption(new Option("R", "dont-restart-on", true, "Which exit values from the spawned process will NOT cause the wrapper to attempt to restart it. By default," + "this is set to 0, 1 and 2. See also 'restart-on'")); options.addOption(new Option("w", "restart-wait", true, "How long (in seconds) to wait before attempting a restart.")); options.addOption(new Option("d", "daemon", false, "Fork the process and exit, leaving it running in the background.")); options.addOption(new Option("n", "no-forker-daemon", false, "Do not enable the forker daemon. This will prevent the forked application from executing elevated commands via the daemon and will also disable JVM timeout detection.")); options.addOption(new Option("q", "quiet", false, "Do not output anything on stderr or stdout from the wrapped process.")); options.addOption(new Option("z", "quiet-stderr", false, "Do not output anything on stderr from the wrapped process.")); options.addOption(new Option("Z", "quiet-stdout", false, "Do not output anything on stdout from the wrapped process.")); options.addOption(new Option("S", "single-instance", false, "Only allow one instance of the wrapped application to be active at any one time. " + "This is achieved through locked files.")); options.addOption(new Option("s", "setenv", false, "Set an environment on the wrapped process. This is in the format NAME=VALUE. The option may be " + "specified multiple times to specify multiple environment variables.")); options.addOption(new Option("N", "native", false, "This option signals that main is not a Java classname, it is instead the name " + "of a native command. This option is incompatible with 'classpath' and also " + "means the forker daemon will not be used and so hang detection and some other " + "features will not be available.")); options.addOption(new Option("I", "no-info", false, "Ordinary, forker will set some system properties in the wrapped application. These " + "communicate things such as the last exited code (forker.info.lastExitCode), number " + "of times start via (forker.info.attempts) and more. This option prevents those being set.")); options.addOption(new Option("o", "log-overwrite", false, "Overwriite logfiles instead of appending.")); options.addOption(new Option("l", "log", true, "Where to log stdout (and by default stderr) output. If not specified, will be output on stdout (or stderr) of this process.")); options.addOption(new Option("L", "level", true, "Output level for information and debug output from wrapper itself (NOT the application). By default " + "this is WARNING, with other possible levels being FINE, FINER, FINEST, SEVERE, INFO, ALL.")); options.addOption(new Option("D", "log-write-delay", true, "In order to be compatible with external log rotation, log files are closed as soon as they are " + "written to. You can delay the closing of the log file, so that any new log messages that are " + "written within this time will not need to open the file again. The time is in milliseconds " + "with a default of 50ms. A value of zero indicates to always immmediately reopen the log.")); options.addOption(new Option("e", "errors", true, "Where to log stderr. If not specified, will be output on stderr of this process or to 'log' if specified.")); options.addOption(new Option("cp", "classpath", true, "The classpath to use to run the application. If not set, the current runtime classpath is used (the java.class.path system property). Prefix the " + "path with '+' to add it to the end of the existing classpath, or '-' to add it to the start.")); options.addOption(new Option("bcp", "boot-classpath", true, "The boot classpath to use to run the application. If not set, the current runtime classpath is used (the java.class.path system property). Prefix the " + "path with '+' to add it to the end of the existing classpath, or '-' to add it to the start. Use of a jvmarg that starts with '-Xbootclasspath' will " + "override this setting.")); options.addOption(new Option("u", "run-as", true, "The user to run the application as.")); options.addOption(new Option("a", "administrator", false, "Run as administrator.")); options.addOption(new Option("p", "pidfile", true, "A filename to write the process ID to. May be used " + "by external application to obtain the PID to send signals to.")); options.addOption(new Option("b", "buffer-size", true, "How big (in byte) to make the I/O buffer. By default this is 1 byte for immediate output.")); options.addOption(new Option("B", "cpu", true, "Bind to a particular CPU, may be specified multiple times to bind to multiple CPUs.")); options.addOption(new Option("j", "java", true, "Alternative path to java runtime launcher.")); options.addOption( new Option("J", "jvmarg", true, "Additional VM argument. Specify multiple times for multiple arguments.")); options.addOption( new Option("W", "cwd", true, "Change working directory, the wrapped process will be run from this location.")); options.addOption( new Option("t", "timeout", true, "How long to wait since the last 'ping' from the launched application before " + "considering the process as hung. Requires forker daemon is enabled.")); options.addOption(new Option("m", "main", true, "The classname to run. If this is specified, then the first argument passed to the command " + "becomes the first app argument.")); options.addOption(new Option("E", "exit-wait", true, "How long to wait after attempting to stop a wrapped appllication before giving up and forcibly killing the applicaton.")); options.addOption(new Option("M", "argmode", true, "Determines how apparg options are treated. May be one FORCE, APPEND, PREPEND or DEFAULT. FORCE " + "passed on only the appargs specified by configuration. APPEND will append all appargs to " + "any command line arguments, PREPEND will prepend them. Finally DEFAULT is the default behaviour " + "and any command line arguments will override all appargs.")); options.addOption(new Option("A", "apparg", true, "Application arguments. How these are treated depends on argmode, but by default the will be overridden by any command line arguments passed in.")); options.addOption(new Option("P", "priority", true, "Scheduling priority, may be one of LOW, NORMAL, HIGH or REALTIME (where supported).")); options.addOption(new Option("Y", "min-java", true, "Minimum java version. If the selected JVM (default or otherwise) is lower than this, an " + "attempt will be made to locate a later version.")); options.addOption(new Option("y", "max-java", true, "Maximum java version. If the selected JVM (default or otherwise) is lower than this, an " + "attempt will be made to locate an earlier version.")); } protected String buildClasspath(File cwd, String defaultClasspath, String classpath, boolean appendByDefault) throws IOException { boolean append = appendByDefault; boolean prepend = false; if (classpath != null) { if (classpath.startsWith("-")) { prepend = true; classpath = classpath.substring(1); } else if (classpath.startsWith("+")) { classpath = classpath.substring(1); append = true; } else if (classpath.startsWith("=")) { classpath = classpath.substring(1); append = false; prepend = false; } } StringBuilder newClasspath = new StringBuilder(); if (StringUtils.isNotBlank(classpath)) { for (String el : classpath.split(File.pathSeparator)) { String basename = FilenameUtils.getName(el); if (basename.contains("*") || basename.contains("?")) { String dirname = FilenameUtils.getFullPathNoEndSeparator(el); File dir = relativize(cwd, dirname); if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (FilenameUtils.wildcardMatch(file.getName(), basename)) { if (newClasspath.length() > 0) newClasspath.append(File.pathSeparator); newClasspath.append(file.getAbsolutePath()); } } } else { appendPath(newClasspath, el); } } else { appendPath(newClasspath, el); } } else { appendPath(newClasspath, el); } } } if (StringUtils.isNotBlank(defaultClasspath)) { String cp = newClasspath.toString(); if (append) { classpath = defaultClasspath + File.pathSeparator + cp; } else if (prepend) { classpath = cp + File.pathSeparator + defaultClasspath; } else { classpath = cp; } } else classpath = newClasspath.toString(); return classpath; } protected void startForkerDaemon() throws IOException { /* * Prepare to start a forker daemon. The client application may (if it * wishes) include the forker-client module and use the daemon to * execute administrator commands and perform other forker daemon * operations. */ daemon = new Forker(); daemon.setIsolated(true); /* Prepare command permissions if there are any */ CommandHandler cmd = daemon.getHandler(CommandHandler.class); CheckCommandPermission permi = cmd.getExecutor(CheckCommandPermission.class); permi.setAllow(getOptionValues("allow-execute")); permi.setReject(getOptionValues("reject-execute")); cookie = daemon.prepare(); event(STARTING_FORKER_DAEMON, cookie.getCookie(), String.valueOf(cookie.getPort())); new Thread() { public void run() { try { daemon.start(cookie); event(STARTED_FORKER_DAEMON, cookie.getCookie(), String.valueOf(cookie.getPort())); } catch (IOException e) { } } }.start(); } protected boolean daemonize(File cwd, String javaExe, String forkerClasspath, boolean daemonize, String pidfile) throws IOException { if (daemonize && getOptionValue("fallback-active", null) == null) { if ("true".equals(getOptionValue("native-fork", "false"))) { /* * This doesn't yet work because of how JNA / Pty4J work with * their native library extraction. The forked VM will not * completely exit. It you use 'pstack' to show the native stack * of the process, it will that it is in a native call for a * file that has been deleted (when the parent process exited). * Both of these libraries by default will extract the native * libraries to files, and mark them as to be deleted when JVM * exit. Because once forked, the original JVM does exit, these * files are deleted, but they are needed by the forked process. */ logger.info("Running in background using native fork"); int pid = CSystem.INSTANCE.fork(); if (pid > 0) { if (pidfile != null) { FileUtils.writeLines(makeDirectoryForFile(relativize(cwd, pidfile)), Arrays.asList(String.valueOf(pid))); } return true; } } else { /* * Fallback. Attempt to rebuild the command line. This will not * be exact */ if (originalArgs == null) throw new IllegalStateException("Original arguments must be set."); ForkerBuilder fb = new ForkerBuilder(javaExe); fb.command().add("-classpath"); fb.command().add(forkerClasspath); for (String s : Arrays.asList("java.library.path", "jna.library.path")) { if (System.getProperty(s) != null) fb.command().add("-D" + s + "=" + System.getProperty(s)); } fb.environment().put("FORKER_FALLBACK_ACTIVE", "true"); // Currently needs to be quiet :( fb.environment().put("FORKER_QUIET", "true"); // Doesnt seemm to work // fb.environment().put("FORKER_FDOUT", "1"); // fb.environment().put("FORKER_FDERR", "2"); fb.command().add(ForkerWrapper.class.getName()); // fb.command().add("--fdout=1"); // fb.command().add("--fderr=2"); fb.command().addAll(Arrays.asList(originalArgs)); fb.background(true); fb.io(IO.OUTPUT); fb.start(); logger.info("Exiting initial runtime"); return true; } } else { if (pidfile != null) { int pid = OS.getPID(); logger.info(String.format("Writing PID %d", pid)); FileUtils.writeLines(makeDirectoryForFile(relativize(cwd, pidfile)), Arrays.asList(String.valueOf(pid))); } } return false; } protected void addShutdownHook(final boolean useDaemon, final int exitWait) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { event(EXITING_WRAPPER); } catch (IOException e1) { } logger.info("In Shutdown Hook"); Process p = process; Forker f = daemon; if (p != null && useDaemon && f != null) { /* * Close the client control connection. This will cause the * wrapped process to System.exit(), and so cleanly shutdown */ List<Client> clients = f.getClients(); synchronized (clients) { for (Client c : clients) { if (c.getType() == 2) { try { logger.info("Closing control connection"); c.close(); } catch (IOException e) { } } } } } else { /* Not using daemon, so just destroy process */ p.destroy(); } final Thread current = Thread.currentThread(); Thread exitWaitThread = null; if (exitWait > 0) { exitWaitThread = new Thread() { { setDaemon(true); setName("ExitMonitor"); } public void run() { try { Thread.sleep(exitWait * 1000); current.interrupt(); } catch (InterruptedException e) { } } }; exitWaitThread.start(); } /* Now wait for it to actually exit */ try { logger.info("Closing control connection"); p.waitFor(); try { event(EXITED_WRAPPER); } catch (IOException e1) { } } catch (InterruptedException e) { p.destroy(); } finally { if (exitWaitThread != null) { exitWaitThread.interrupt(); } } } }); } protected void monitorWrappedApplication() { final int timeout = Integer.parseInt(getOptionValue("timeout", "60")); if (timeout > 0) { new Thread() { { setName("ForkerWrapperMonitor"); setDaemon(true); } public void run() { logger.info("Monitoring pings from wrapped application"); try { while (!stopping) { if (process != null && daemon != null) { WrapperHandler wrapper = daemon.getHandler(WrapperHandler.class); if (wrapper.getLastPing() > 0 && (wrapper.getLastPing() + timeout * 1000) <= System.currentTimeMillis()) { logger.warning(String .format("Process has not sent a ping in %d seconds, attempting to terminate", timeout)); tempRestartOnExit = true; /* * TODO may need to be more forceful than * this, e.g. OS kill */ process.destroy(); } } Thread.sleep(1000); } } catch (InterruptedException ie) { } } }.start(); } } protected void appendPath(StringBuilder newClasspath, String el) { if (newClasspath.length() > 0) newClasspath.append(File.pathSeparator); newClasspath.append(el); } protected boolean getSwitch(String key, boolean defaultValue) { if (cmd != null && cmd.hasOption(key)) return true; if (isBool(key)) { return true; } return !"false".equals(getOptionValue(key, String.valueOf(defaultValue))); } protected boolean isBool(String key) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) return nvp.isBool(); } return false; } protected String getProperty(String key) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) return nvp.getValue(); } return null; } protected List<String> getOptionValues(String key) { String[] vals = cmd == null ? null : cmd.getOptionValues(key); if (vals != null) return Arrays.asList(vals); List<String> valList = new ArrayList<String>(); for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key) && nvp.getValue() != null) { valList.add(nvp.getValue()); } } /* * System properties, e.g. forker.somevar.1=val, forker.somevar.2=val2 */ List<String> varNames = new ArrayList<String>(); for (Map.Entry<Object, Object> en : System.getProperties().entrySet()) { if (((String) en.getKey()).startsWith("forker." + (key.replace("-", ".")) + ".")) { varNames.add((String) en.getKey()); } } Collections.sort(varNames); for (String vn : varNames) { valList.add(System.getProperty(vn)); } /* * Environment variables, e.g. FORKER_SOMEVAR_1=val, * FORKER_SOMEVAR_2=val2 */ varNames.clear(); for (Map.Entry<String, String> en : System.getenv().entrySet()) { if (en.getKey().startsWith("FORKER_" + (key.toUpperCase().replace("-", "_")) + "_")) { varNames.add(en.getKey()); } } Collections.sort(varNames); for (String vn : varNames) { valList.add(System.getenv(vn)); } return valList; } protected String getOptionValue(String key, String defaultValue) { String val = cmd == null ? null : cmd.getOptionValue(key); if (val == null) { val = System.getProperty("forkerwrapper." + key.replace("-", ".")); if (val == null) { val = System.getenv("FORKER_" + key.replace("-", "_").toUpperCase()); if (val == null) { val = getProperty(key); if (val == null) val = defaultValue; } } } return val; } private File makeDirectoryForFile(File file) throws IOException { File dir = file.getParentFile(); if (dir != null && !dir.exists() && !dir.mkdirs()) throw new IOException(String.format("Failed to create directory %s", dir)); return file; } private byte[] newBuffer() { return new byte[Integer.parseInt(getOptionValue("buffer-size", "1024"))]; } private void copy(final InputStream in, final OutputStream out, byte[] buf) throws IOException { int r; while ((r = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, r); out.flush(); } } private Runnable copyRunnable(final InputStream in, final OutputStream out) { return new Runnable() { @Override public void run() { try { copy(in, out == null ? new SinkOutputStream() : out, newBuffer()); } catch (EOFException e) { } catch (IOException ioe) { } } }; } private void process() throws ParseException, IOException { List<String> args = cmd.getArgList(); String main = getOptionValue("main", null); if (main == null) { if (args.isEmpty()) throw new ParseException("Must supply class name of application that contains a main() method."); classname = args.remove(0); } else classname = main; List<String> arguments = getOptionValues("apparg"); ArgMode argMode = getArgMode(); if (argMode != ArgMode.FORCE) { if (!args.isEmpty()) { switch (argMode) { case APPEND: arguments.addAll(0, args); break; case PREPEND: arguments.addAll(args); break; default: arguments = args; break; } } } this.arguments = arguments.toArray(new String[0]); } class SinkOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } } }
forker-wrapper/src/main/java/com/sshtools/forker/wrapper/ForkerWrapper.java
package com.sshtools.forker.wrapper; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.management.MXBean; import javax.management.ObjectName; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import com.sshtools.forker.client.EffectiveUserFactory; import com.sshtools.forker.client.ForkerBuilder; import com.sshtools.forker.client.OSCommand; import com.sshtools.forker.common.CSystem; import com.sshtools.forker.common.Cookie.Instance; import com.sshtools.forker.common.IO; import com.sshtools.forker.common.OS; import com.sshtools.forker.common.Priority; import com.sshtools.forker.common.Util; import com.sshtools.forker.daemon.CommandHandler; import com.sshtools.forker.daemon.Forker; import com.sshtools.forker.daemon.Forker.Client; import com.sshtools.forker.wrapper.JVM.Version; /** * <i>Forker Wrapper</i> can be used to wrap java applications in a manner * similar to other Java projects such as JSW, YAJSW and more. It provides the * following features :- * <ul> * <li>Multiple ways of configuration, including via command line options, * system properties, configuration files and environment variables.</li> * <li>JVM selection</li> * <li>JVM timeout detection</li> * <li>Run as administrator or another user</li> * <li>Run in background</li> * <li>Capture output to log</li> * <li>Restart on certain exit codes</li> * <li>Run scripts or Java classes on events</li> * <li>Wrap native commands</li> * <li>Embeddable or standalone use</li> * <li>Single instance enforcement</li> * <li>PID file writing</li> * <li>Process priority and affinity</li> * <li>Forker Daemon integration</li> * <li>Wildcard classpaths</li> * <li>.. and more</li> * </ul> * */ @MXBean public class ForkerWrapper implements ForkerWrapperMXBean { public final static String EXITED_WRAPPER = "exited-wrapper"; public final static String EXITING_WRAPPER = "exiting-wrapper"; public final static String STARTING_FORKER_DAEMON = "started-forker-daemon"; public final static String STARTED_FORKER_DAEMON = "started-forker-daemon"; public final static String STARTING_APPLICATION = "starting-application"; public final static String STARTED_APPLICATION = "started-application"; public final static String RESTARTING_APPLICATION = "restarting-application"; public final static String APPPLICATION_STOPPED = "application-stopped"; public final static String[] EVENT_NAMES = { EXITED_WRAPPER, EXITING_WRAPPER, STARTING_FORKER_DAEMON, STARTED_FORKER_DAEMON, STARTED_APPLICATION, STARTING_APPLICATION, RESTARTING_APPLICATION, APPPLICATION_STOPPED }; public static class KeyValuePair { private String key; private String value; private boolean bool; public KeyValuePair(String line) { key = line; int idx = line.indexOf('='); int spcidx = line.indexOf(' '); if (spcidx != -1 && (spcidx < idx || idx == -1)) { idx = spcidx; } if (idx != -1) { value = line.substring(idx + 1); key = line.substring(0, idx); } else { bool = true; } } public KeyValuePair(String key, String value) { this.key = key; this.value = value; } public String getName() { return key; } public String getValue() { return value; } public boolean isBool() { return bool; } public void setValue(String value) { this.value = value; } } public enum ArgMode { FORCE, APPEND, PREPEND, DEFAULT } private String classname; private String[] arguments; private CommandLine cmd; private List<KeyValuePair> properties = new ArrayList<KeyValuePair>(); private Forker daemon; private Instance cookie; private Process process; private boolean tempRestartOnExit; private String[] originalArgs; private Logger logger = Logger.getLogger(ForkerWrapper.class.getSimpleName()); private boolean inited; private PrintStream defaultOut = System.out; private PrintStream defaultErr = System.err; private InputStream defaultIn = System.in; private boolean stopping = false; private boolean preventRestart = false; public String[] getArguments() { return arguments; } public InputStream getDefaultIn() { return defaultIn; } public void setDefaultIn(InputStream defaultIn) { this.defaultIn = defaultIn; } public PrintStream getDefaultOut() { return defaultOut; } public void setDefaultOut(PrintStream defaultOut) { this.defaultOut = defaultOut; } public PrintStream getDefaultErr() { return defaultErr; } public void setDefaultErr(PrintStream defaultErr) { this.defaultErr = defaultErr; } public void setArguments(String... arguments) { this.arguments = arguments; } public void setProperty(String key, Object value) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) { nvp.setValue(String.valueOf(value)); return; } } properties.add(new KeyValuePair(key, String.valueOf(value))); } public String getClassname() { return classname; } public File relativize(File context, String path) throws IOException { File p = new File(path); if (p.isAbsolute()) { return p.getCanonicalFile(); } return new File(context, p.getPath()).getCanonicalFile(); } public void restart() throws InterruptedException { restart(true); } public void restart(boolean wait) throws InterruptedException { stop(true, true); } public void stop() throws InterruptedException { stop(true); } public void stop(boolean wait) throws InterruptedException { stop(wait, false); } @SuppressWarnings("resource") public int start() throws IOException, InterruptedException { if (!inited) init(null); /* * Calculate CWD. All file paths from this point are calculated relative * to the CWD */ String cwdpath = getOptionValue("cwd", null); File cwd = new File(System.getProperty("user.dir")); if (StringUtils.isNotBlank(cwdpath)) { cwd = relativize(cwd, cwdpath); if (!cwd.exists()) throw new IOException(String.format("No such directory %s", cwd)); } String javaExe = getJVMPath(); String forkerClasspath = System.getProperty("java.class.path"); String wrapperClasspath = getOptionValue("classpath", forkerClasspath); String bootClasspath = getOptionValue("boot-classpath", null); final boolean nativeMain = getSwitch("native", false); final boolean useDaemon = !nativeMain && !getSwitch("no-forker-daemon", nativeMain); List<String> jvmArgs = getOptionValues("jvmarg"); if (nativeMain && StringUtils.isNotBlank(getOptionValue("classpath", null))) { throw new IOException("Native main may not be used with classpath option."); } if (nativeMain && !jvmArgs.isEmpty()) { throw new IOException("Native main may not be used with jvmarg option."); } boolean daemonize = getSwitch("daemon", false); String pidfile = getOptionValue("pidfile", null); final int exitWait = Integer.parseInt(getOptionValue("exit-wait", "10")); if (daemonize(cwd, javaExe, forkerClasspath, daemonize, pidfile)) return 0; /** * LDP: Does not work on OSX. Prevented setProcname from throwing an * exception */ if (!OS.setProcname(classname)) { logger.warning(String.format("Failed to set process name to %s", classname)); } try { ManagementFactory.getPlatformMBeanServer().registerMBean(this, new ObjectName("com.sshtools.forker.wrapper:type=Wrapper")); } catch (Exception e) { throw new IOException("Failed to register MBean.", e); } /* * Create a lock file if 'single instance' was specified */ FileLock lock = null; FileChannel lockChannel = null; File lockFile = new File(new File(System.getProperty("java.io.tmpdir")), "forker-wrapper-" + classname + ".lock"); addShutdownHook(useDaemon, exitWait); try { if (getSwitch("single-instance", false)) { lockChannel = new RandomAccessFile(lockFile, "rw").getChannel(); try { logger.info(String.format("Attempting to acquire lock on %s", lockFile)); lock = lockChannel.tryLock(); if (lock == null) throw new OverlappingFileLockException(); lockFile.deleteOnExit(); } catch (OverlappingFileLockException ofle) { throw new IOException(String.format("The application %s is already running.", classname)); } } if (useDaemon) { monitorWrappedApplication(); } int retval = 2; int times = 0; int lastRetVal = -1; while (true) { times++; stopping = false; process = null; boolean quiet = getSwitch("quiet", false); boolean quietStdErr = quiet || getSwitch("quiet-stderr", false); boolean quietStdOut = quiet || getSwitch("quiet-stdout", false); boolean logoverwrite = getSwitch("log-overwrite", false); /* Build the command to launch the application itself */ ForkerBuilder appBuilder = new ForkerBuilder(); if (!nativeMain) { appBuilder.command().add(javaExe); String classpath = buildClasspath(cwd, getSwitch("no-forker-classpath", false) ? null : forkerClasspath, wrapperClasspath); if (classpath != null) { appBuilder.command().add("-classpath"); appBuilder.command().add(classpath); } boolean hasBootCp = false; for (String val : jvmArgs) { if (val.startsWith("-Xbootclasspath")) hasBootCp = true; appBuilder.command().add(val); } if (!hasBootCp) { String bootcp = buildClasspath(cwd, null, bootClasspath); if (bootcp != null && !bootcp.equals("")) { /* * Do our own processing of append/prepend as there * are special JVM arguments for it */ if (bootClasspath != null && bootClasspath.startsWith("+")) appBuilder.command().add("-Xbootclasspath/a:" + bootcp); else if (bootClasspath != null && bootClasspath.startsWith("-")) appBuilder.command().add("-Xbootclasspath/p:" + bootcp); else appBuilder.command().add("-Xbootclasspath:" + bootcp); } } } if (!getSwitch("no-info", false)) { if (lastRetVal > -1) { appBuilder.command().add(String.format("-Dforker.info.lastExitCode=%d", lastRetVal)); } appBuilder.command().add(String.format("-Dforker.info.attempts=%d", times)); } /* * If the daemon should be used, we assume that forker-client is * on the classpath and execute the application via that, pssing * the forker daemon cookie via stdin. * */ if (useDaemon) { /* * Otherwise we are just running the application directly */ appBuilder.command().add(com.sshtools.forker.client.Forker.class.getName()); appBuilder.command().add(String.valueOf(OS.isAdministrator())); appBuilder.command().add(classname); if (arguments != null) appBuilder.command().addAll(Arrays.asList(arguments)); } else { /* * Otherwise we are just running the application directly */ appBuilder.command().add(classname); if (arguments != null) appBuilder.command().addAll(Arrays.asList(arguments)); } String priStr = getOptionValue("priority", null); if (priStr != null) { appBuilder.priority(Priority.valueOf(priStr)); } appBuilder.io(IO.DEFAULT); appBuilder.directory(cwd); /* Environment variables */ for (String env : getOptionValues("setenv")) { String key = env; String value = ""; int idx = env.indexOf('='); if (idx != -1) { key = env.substring(0, idx); value = env.substring(idx + 1); } appBuilder.environment().put(key, value); } List<String> cpus = getOptionValues("cpu"); for (String cpu : cpus) { appBuilder.affinity().add(Integer.parseInt(cpu)); } if (getSwitch("administrator", false)) { if (!OS.isAdministrator()) { logger.info("Raising privileges to administartor"); appBuilder.effectiveUser(EffectiveUserFactory.getDefault().administrator()); } } else { String runas = getOptionValue("run-as", null); if (runas != null && !runas.equals(System.getProperty("user.name"))) { logger.info(String.format("Switching user to %s", runas)); appBuilder.effectiveUser(EffectiveUserFactory.getDefault().getUserForUsername(runas)); } } daemon = null; cookie = null; if (useDaemon) { startForkerDaemon(); } event(STARTING_APPLICATION, String.valueOf(times), cwd.getAbsolutePath(), classname, String.valueOf(lastRetVal)); process = appBuilder.start(); event(STARTED_APPLICATION, classname); if (useDaemon) { process.getOutputStream().write(cookie.toString().getBytes("UTF-8")); process.getOutputStream().write("\r\n".getBytes("UTF-8")); process.getOutputStream().flush(); } String logpath = getOptionValue("log", null); String errpath = getOptionValue("errors", null); if (errpath == null) errpath = logpath; OutputStream outlog = null; OutputStream errlog = null; long logDelay = Long.parseLong(getOptionValue("log-write-delay", "50")); if (StringUtils.isNotBlank(logpath)) { logger.info(String.format("Writing stdout output to %s", logpath)); outlog = new LazyLogStream(logDelay, makeDirectoryForFile(relativize(cwd, logpath)), !logoverwrite); } if (errpath != null) { if (Objects.equals(logpath, errpath)) errlog = outlog; else { logger.info(String.format("Writing stderr output to %s", logpath)); errlog = new LazyLogStream(logDelay, makeDirectoryForFile(relativize(cwd, errpath)), !logoverwrite); } } OutputStream stdout = quietStdOut ? null : defaultOut; OutputStream out = null; if (stdout != null) { if (outlog != null) { out = new TeeOutputStream(stdout, outlog); } else { out = stdout; } } else if (outlog != null) out = outlog; if (out == null) { out = new SinkOutputStream(); } OutputStream stderr = quietStdErr ? null : defaultErr; OutputStream err = null; if (stderr != null) { if (errlog != null) { err = new TeeOutputStream(stderr, errlog); } else { err = stderr; } } else if (errlog != null) err = errlog; if (err == null) { err = out; } Thread errThread = new Thread(copyRunnable(process.getErrorStream(), err), "StdErr"); errThread.setDaemon(true); errThread.start(); Thread inThread = null; try { if (!daemonize) { inThread = new Thread(copyRunnable(defaultIn, process.getOutputStream()), "StdIn"); inThread.setDaemon(true); inThread.start(); } try { copy(process.getInputStream(), out, newBuffer()); } catch (IOException ioe) { if (!stopping) throw ioe; } retval = process.waitFor(); } finally { if (inThread != null) { inThread.interrupt(); } errThread.interrupt(); if (outlog != null && !outlog.equals(defaultOut)) { outlog.close(); } if (errlog != null && errlog != outlog && !errlog.equals(defaultErr)) { errlog.close(); } if (daemon != null) { daemon.shutdown(true); } } List<String> restartValues = Arrays.asList(getOptionValue("restart-on", "").split(",")); List<String> dontRestartValues = new ArrayList<String>( Arrays.asList(getOptionValue("dont-restart-on", "0,1,2").split(","))); dontRestartValues.removeAll(restartValues); String strret = String.valueOf(retval); event(APPPLICATION_STOPPED, strret, classname); boolean restart = !preventRestart && (((restartValues.size() == 1 && restartValues.get(0).equals("")) || restartValues.size() == 0 || restartValues.contains(strret)) && !dontRestartValues.contains(strret)); if (tempRestartOnExit || restart) { try { tempRestartOnExit = false; int waitSec = Integer.parseInt(getOptionValue("restart-wait", "0")); if (waitSec == 0) throw new NumberFormatException(); event(RESTARTING_APPLICATION, classname, String.valueOf(waitSec)); logger.warning(String.format("Process exited with %d, attempting restart in %d seconds", retval, waitSec)); lastRetVal = retval; Thread.sleep(waitSec * 1000); } catch (NumberFormatException nfe) { event(RESTARTING_APPLICATION, classname, "0"); logger.warning(String.format("Process exited with %d, attempting restart", retval)); } } else break; } // TODO cant find out why just exiting fails (process stays // running). // Cant get a trace on what is still running either // PtyHelpers.getInstance().kill(PtyHelpers.getInstance().getpid(), // 9); // OSCommand.run("kill", "-9", // String.valueOf(PtyHelpers.getInstance().getpid())); return retval; } finally { if (lock != null) { logger.fine(String.format("Release lock %s", lockFile)); lock.release(); } if (lockChannel != null) { lockChannel.close(); } stopping = false; preventRestart = false; tempRestartOnExit = false; } } public ArgMode getArgMode() { return ArgMode.valueOf(getOptionValue("argmode", ArgMode.DEFAULT.name())); } public List<KeyValuePair> getProperties() { return properties; } public void setClassname(String classname) { this.classname = classname; } public void readConfigFile(File file) throws IOException { logger.info(String.format("Loading configuration file %s", file)); BufferedReader fin = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = fin.readLine()) != null) { if (!line.trim().startsWith("#") && !line.trim().equals("")) { properties.add(new KeyValuePair(ReplacementUtils.replaceSystemProperties(line))); } } } finally { fin.close(); } } public static String getAppName() { String an = System.getenv("FORKER_APPNAME"); return an == null || an.length() == 0 ? ForkerWrapper.class.getName() : an; } public static void main(String[] args) { ForkerWrapper wrapper = new ForkerWrapper(); wrapper.originalArgs = args; Options opts = new Options(); // Add the options always available wrapper.addOptions(opts); // Add the command line launch options opts.addOption(Option.builder("c").argName("file").hasArg() .desc("A file to read configuration. The file " + "should contain name=value pairs, where name is the same name as used for command line " + "arguments (see --help for a list of these)") .longOpt("configuration").build()); opts.addOption(Option.builder("C").argName("directory").hasArg() .desc("A directory to read configuration files from. Each file " + "should contain name=value pairs, where name is the same name as used for command line " + "arguments (see --help for a list of these)") .longOpt("configuration-directory").build()); opts.addOption(Option.builder("h") .desc("Show command line help. When the optional argument is supplied, help will " + "be displayed for the option with that name") .optionalArg(true).hasArg().argName("option").longOpt("help").build()); opts.addOption(Option.builder("O").desc("File descriptor for stdout").optionalArg(true).hasArg().argName("fd") .longOpt("fdout").build()); opts.addOption(Option.builder("E").desc("File descriptor for stderr").optionalArg(true).hasArg().argName("fd") .longOpt("fderr").build()); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); try { CommandLine cmd = parser.parse(opts, args); wrapper.init(cmd); String outFdStr = wrapper.getOptionValue("fdout", null); if (outFdStr != null) { Constructor<FileDescriptor> cons = FileDescriptor.class.getDeclaredConstructor(int.class); cons.setAccessible(true); FileDescriptor fdOut = cons.newInstance(Integer.parseInt(outFdStr)); System.setOut(new PrintStream(new FileOutputStream(fdOut), true)); } String errFdStr = wrapper.getOptionValue("fdout", null); if (errFdStr != null) { Constructor<FileDescriptor> cons = FileDescriptor.class.getDeclaredConstructor(int.class); cons.setAccessible(true); FileDescriptor fdErr = cons.newInstance(Integer.parseInt(errFdStr)); System.setErr(new PrintStream(new FileOutputStream(fdErr), true)); } if (cmd.hasOption('h')) { String optionName = cmd.getOptionValue('h'); if (optionName == null) { formatter.printHelp(new PrintWriter(System.err, true), 132, getAppName(), " <application.class.name> [<argument> [<argument> ..]]\n\n" + "Forker Wrapper is used to launch Java applications, optionally changing " + "the user they are run as, providing automatic restarting, signal handling and " + "other facilities that will be useful running applications as a 'service'.\n\n" + "Configuration may be passed to Forker Wrapper in four different ways :-\n\n" + "1. Command line options.\n" + "2. Configuration files (see -c and -C options)\n" + "3. Java system properties. The key of which is option name prefixed with 'forker.' and with - replaced with a dot (.)\n" + "4. Environment variables. The key of which is the option name prefixed with 'FORKER_' (in upper case) with - replaced with _\n\n", opts, 2, 5, "\nProvided by SSHTOOLS Limited.", true); System.exit(1); } else { Option opt = opts.getOption(optionName); if (opt == null) { throw new Exception(String.format("No option named", optionName)); } else { System.err.println(optionName); System.err.println(); System.err.println(opt.getDescription()); } } } if (cmd.hasOption("configuration")) { wrapper.readConfigFile(new File(cmd.getOptionValue('c'))); } String cfgDir = wrapper.getOptionValue("configuration-directory", null); if (cfgDir != null) { File dir = new File(cfgDir); if (dir.exists()) { for (File f : dir.listFiles()) { if (f.isFile() && !f.isHidden()) wrapper.readConfigFile(f); } } } wrapper.process(); } catch (Throwable e) { System.err.println(String.format("%s: %s\n", wrapper.getClass().getName(), e.getMessage())); formatter.printUsage(new PrintWriter(System.err, true), 80, String.format("%s <application.class.name> [<argument> [<argument> ..]]", getAppName())); System.exit(1); } try { System.exit(wrapper.start()); } catch (Throwable e) { e.printStackTrace(); System.err.println(String.format("%s: %s\n", wrapper.getClass().getName(), e.getMessage())); formatter.printUsage(new PrintWriter(System.err, true), 80, String.format("%s <application.class.name> [<argument> [<argument> ..]]", getAppName())); System.exit(1); } } public void init(CommandLine cmd) { if (!inited) { this.cmd = cmd; String levelName = getOptionValue("level", "WARNING"); logger.setLevel(Level.parse(levelName)); inited = true; } } protected void stop(boolean wait, boolean restart) throws InterruptedException { stopping = true; preventRestart = !restart; tempRestartOnExit = restart; if (process != null) { process.destroy(); if (wait) { process.waitFor(); } } } protected String getJVMPath() throws IOException { String javaExe = getOptionValue("java", System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); if (SystemUtils.IS_OS_WINDOWS && !javaExe.endsWith(".exe")) javaExe += ".exe"; String minjava = getOptionValue("min-java", null); String maxjava = getOptionValue("max-java", null); if (StringUtils.isNotBlank(minjava) || StringUtils.isNotBlank(maxjava)) { if (StringUtils.isBlank(minjava)) minjava = "0.0.0"; if (StringUtils.isBlank(maxjava)) maxjava = "9999.9999.9999"; Version minver = new Version(minjava); Version maxver = new Version(maxjava); JVM jvm = new JVM(javaExe); if (jvm.getVersion().compareTo(minver) < 0 || jvm.getVersion().compareTo(maxver) > 0) { logger.info(String.format("Initially chosen JVM %s (%s) is not within the JVM version range of %s to %s", javaExe, jvm.getVersion(), minver, maxver)); for (JVM altJvm : JVM.jvms()) { if (altJvm.getVersion().compareTo(minver) >= 0 && altJvm.getVersion().compareTo(maxver) <= 0) { javaExe = altJvm.getPath(); logger.info(String.format("Using alternative JVM %s which version %s", javaExe, altJvm.getVersion())); break; } } } else { logger.info(String.format("Initially chosen JVM %s (%s) is valid for the version range %s to %s", javaExe, jvm.getVersion(), minver, maxver)); } } return javaExe; } protected void event(String name, String... args) throws IOException { String eventHandler = getOptionValue("on-" + name, null); logger.info(String.format("Event " + name + ": %s", Arrays.asList(args))); if (StringUtils.isNotBlank(eventHandler)) { // Parse the event handler script List<String> handlerArgs = Util.parseQuotedString(eventHandler); for (int i = 0; i < handlerArgs.size(); i++) { handlerArgs.set(i, handlerArgs.get(i).replace("%0", eventHandler)); for (int j = 0; j < args.length; j++) handlerArgs.set(i, handlerArgs.get(i).replace("%" + (j + 1), args[j])); handlerArgs.set(i, handlerArgs.get(i).replace("%%", "%")); } String cmd = handlerArgs.remove(0); try { if (!cmd.contains(".")) throw new Exception("Not a class"); int idx = cmd.indexOf("#"); String methodName = "main"; if (idx != -1) { methodName = cmd.substring(idx + 1); cmd = cmd.substring(0, idx); } Class<?> clazz = Class.forName(cmd); Method method = clazz.getMethod(methodName, String[].class); try { logger.info(String.format("Handling with Java class %s (%s)", eventHandler, Arrays.asList(args))); method.invoke(null, new Object[] { args }); } catch (Exception e) { throw new IOException("Exception thrown during event handler.", e); } } catch (Exception cnfe) { // Assume to be native command List<String> allArgs = new ArrayList<String>(); allArgs.add(cmd); allArgs.addAll(handlerArgs); try { logger.info(String.format("Handling with command %s", allArgs.toString())); OSCommand.run(allArgs); } catch (Exception e) { throw new IOException("Exception thrown during event handler.", e); } } } } protected void addOptions(Options options) { for (String event : EVENT_NAMES) { options.addOption(Option.builder().longOpt("on-" + event).hasArg(true).argName("command-or-classname") .desc("Executes a script or a Java class (that must be on wrappers own classpath) " + "when a particular event occurs. If a Java class is to be execute, it " + "must contain a main(String[] args) method. Each event may pass a number of arguments.") .build()); } options.addOption(new Option("x", "allow-execute", true, "The wrapped application can use it's wrapper to execute commands on it's behalf. If the " + "wrapper itself runs under an administrative user, and the application as a non-privileged user," + "you may wish to restrict which commands may be run. One or more of these options specifies the " + "name of the command that may be run. The value may be a regular expression, see also 'prevent-execute'")); options.addOption(new Option("X", "reject-execute", true, "The wrapped application can use it's wrapper to execute commands on it's behalf. If the " + "wrapper itself runs under an administrative user, and the application as a non-privileged user," + "you may wish to restrict which commands may be run. One or more of these options specifies the " + "name of the commands that may NOT be run. The value may be a regular expression, see also 'allow-execute'")); options.addOption(new Option("F", "no-forker-classpath", false, "When the forker daemon is being used, the wrappers own classpath will be appened to " + "to the application classpath. This option prevents that behaviour for example if " + "the application includes the modules itself.")); options.addOption(new Option("r", "restart-on", true, "Which exit values from the spawned process will cause the wrapper to attempt to restart it. When not specified, all exit " + "values will cause a restart except those that are configure not to (see dont-restart-on).")); options.addOption(new Option("R", "dont-restart-on", true, "Which exit values from the spawned process will NOT cause the wrapper to attempt to restart it. By default," + "this is set to 0, 1 and 2. See also 'restart-on'")); options.addOption(new Option("w", "restart-wait", true, "How long (in seconds) to wait before attempting a restart.")); options.addOption(new Option("d", "daemon", false, "Fork the process and exit, leaving it running in the background.")); options.addOption(new Option("n", "no-forker-daemon", false, "Do not enable the forker daemon. This will prevent the forked application from executing elevated commands via the daemon and will also disable JVM timeout detection.")); options.addOption(new Option("q", "quiet", false, "Do not output anything on stderr or stdout from the wrapped process.")); options.addOption(new Option("z", "quiet-stderr", false, "Do not output anything on stderr from the wrapped process.")); options.addOption(new Option("Z", "quiet-stdout", false, "Do not output anything on stdout from the wrapped process.")); options.addOption(new Option("S", "single-instance", false, "Only allow one instance of the wrapped application to be active at any one time. " + "This is achieved through locked files.")); options.addOption(new Option("s", "setenv", false, "Set an environment on the wrapped process. This is in the format NAME=VALUE. The option may be " + "specified multiple times to specify multiple environment variables.")); options.addOption(new Option("N", "native", false, "This option signals that main is not a Java classname, it is instead the name " + "of a native command. This option is incompatible with 'classpath' and also " + "means the forker daemon will not be used and so hang detection and some other " + "features will not be available.")); options.addOption(new Option("I", "no-info", false, "Ordinary, forker will set some system properties in the wrapped application. These " + "communicate things such as the last exited code (forker.info.lastExitCode), number " + "of times start via (forker.info.attempts) and more. This option prevents those being set.")); options.addOption(new Option("o", "log-overwrite", false, "Overwriite logfiles instead of appending.")); options.addOption(new Option("l", "log", true, "Where to log stdout (and by default stderr) output. If not specified, will be output on stdout (or stderr) of this process.")); options.addOption(new Option("L", "level", true, "Output level for information and debug output from wrapper itself (NOT the application). By default " + "this is WARNING, with other possible levels being FINE, FINER, FINEST, SEVERE, INFO, ALL.")); options.addOption(new Option("D", "log-write-delay", true, "In order to be compatible with external log rotation, log files are closed as soon as they are " + "written to. You can delay the closing of the log file, so that any new log messages that are " + "written within this time will not need to open the file again. The time is in milliseconds " + "with a default of 50ms. A value of zero indicates to always immmediately reopen the log.")); options.addOption(new Option("e", "errors", true, "Where to log stderr. If not specified, will be output on stderr of this process or to 'log' if specified.")); options.addOption(new Option("cp", "classpath", true, "The classpath to use to run the application. If not set, the current runtime classpath is used (the java.class.path system property). Prefix the " + "path with '+' to add it to the end of the existing classpath, or '-' to add it to the start.")); options.addOption(new Option("bcp", "boot-classpath", true, "The boot classpath to use to run the application. If not set, the current runtime classpath is used (the java.class.path system property). Prefix the " + "path with '+' to add it to the end of the existing classpath, or '-' to add it to the start. Use of a jvmarg that starts with '-Xbootclasspath' will " + "override this setting.")); options.addOption(new Option("u", "run-as", true, "The user to run the application as.")); options.addOption(new Option("a", "administrator", false, "Run as administrator.")); options.addOption(new Option("p", "pidfile", true, "A filename to write the process ID to. May be used " + "by external application to obtain the PID to send signals to.")); options.addOption(new Option("b", "buffer-size", true, "How big (in byte) to make the I/O buffer. By default this is 1 byte for immediate output.")); options.addOption(new Option("B", "cpu", true, "Bind to a particular CPU, may be specified multiple times to bind to multiple CPUs.")); options.addOption(new Option("j", "java", true, "Alternative path to java runtime launcher.")); options.addOption( new Option("J", "jvmarg", true, "Additional VM argument. Specify multiple times for multiple arguments.")); options.addOption( new Option("W", "cwd", true, "Change working directory, the wrapped process will be run from this location.")); options.addOption( new Option("t", "timeout", true, "How long to wait since the last 'ping' from the launched application before " + "considering the process as hung. Requires forker daemon is enabled.")); options.addOption(new Option("m", "main", true, "The classname to run. If this is specified, then the first argument passed to the command " + "becomes the first app argument.")); options.addOption(new Option("E", "exit-wait", true, "How long to wait after attempting to stop a wrapped appllication before giving up and forcibly killing the applicaton.")); options.addOption(new Option("M", "argmode", true, "Determines how apparg options are treated. May be one FORCE, APPEND, PREPEND or DEFAULT. FORCE " + "passed on only the appargs specified by configuration. APPEND will append all appargs to " + "any command line arguments, PREPEND will prepend them. Finally DEFAULT is the default behaviour " + "and any command line arguments will override all appargs.")); options.addOption(new Option("A", "apparg", true, "Application arguments. How these are treated depends on argmode, but by default the will be overridden by any command line arguments passed in.")); options.addOption(new Option("P", "priority", true, "Scheduling priority, may be one of LOW, NORMAL, HIGH or REALTIME (where supported).")); options.addOption(new Option("Y", "min-java", true, "Minimum java version. If the selected JVM (default or otherwise) is lower than this, an " + "attempt will be made to locate a later version.")); options.addOption(new Option("y", "max-java", true, "Maximum java version. If the selected JVM (default or otherwise) is lower than this, an " + "attempt will be made to locate an earlier version.")); } protected String buildClasspath(File cwd, String defaultClasspath, String classpath) throws IOException { boolean append = false; boolean prepend = false; if (classpath != null) { if (classpath.startsWith("+")) { classpath = classpath.substring(1); append = true; } else if (classpath.startsWith("-")) { prepend = true; classpath = classpath.substring(1); } } StringBuilder newClasspath = new StringBuilder(); if (StringUtils.isNotBlank(classpath)) { for (String el : classpath.split(File.pathSeparator)) { String basename = FilenameUtils.getName(el); if (basename.contains("*") || basename.contains("?")) { String dirname = FilenameUtils.getFullPathNoEndSeparator(el); File dir = relativize(cwd, dirname); if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (FilenameUtils.wildcardMatch(file.getName(), basename)) { if (newClasspath.length() > 0) newClasspath.append(File.pathSeparator); newClasspath.append(file.getAbsolutePath()); } } } else { appendPath(newClasspath, el); } } else { appendPath(newClasspath, el); } } else { appendPath(newClasspath, el); } } } if (StringUtils.isNotBlank(defaultClasspath)) { String cp = newClasspath.toString(); if (append) { classpath = defaultClasspath + File.pathSeparator + cp; } else if (prepend) { classpath = cp + File.pathSeparator + defaultClasspath; } else { classpath = cp; } } else classpath = newClasspath.toString(); return classpath; } protected void startForkerDaemon() throws IOException { /* * Prepare to start a forker daemon. The client application may (if it * wishes) include the forker-client module and use the daemon to * execute administrator commands and perform other forker daemon * operations. */ daemon = new Forker(); daemon.setIsolated(true); /* Prepare command permissions if there are any */ CommandHandler cmd = daemon.getHandler(CommandHandler.class); CheckCommandPermission permi = cmd.getExecutor(CheckCommandPermission.class); permi.setAllow(getOptionValues("allow-execute")); permi.setReject(getOptionValues("reject-execute")); cookie = daemon.prepare(); event(STARTING_FORKER_DAEMON, cookie.getCookie(), String.valueOf(cookie.getPort())); new Thread() { public void run() { try { daemon.start(cookie); event(STARTED_FORKER_DAEMON, cookie.getCookie(), String.valueOf(cookie.getPort())); } catch (IOException e) { } } }.start(); } protected boolean daemonize(File cwd, String javaExe, String forkerClasspath, boolean daemonize, String pidfile) throws IOException { if (daemonize && getOptionValue("fallback-active", null) == null) { if ("true".equals(getOptionValue("native-fork", "false"))) { /* * This doesn't yet work because of how JNA / Pty4J work with * their native library extraction. The forked VM will not * completely exit. It you use 'pstack' to show the native stack * of the process, it will that it is in a native call for a * file that has been deleted (when the parent process exited). * Both of these libraries by default will extract the native * libraries to files, and mark them as to be deleted when JVM * exit. Because once forked, the original JVM does exit, these * files are deleted, but they are needed by the forked process. */ logger.info("Running in background using native fork"); int pid = CSystem.INSTANCE.fork(); if (pid > 0) { if (pidfile != null) { FileUtils.writeLines(makeDirectoryForFile(relativize(cwd, pidfile)), Arrays.asList(String.valueOf(pid))); } return true; } } else { /* * Fallback. Attempt to rebuild the command line. This will not * be exact */ if (originalArgs == null) throw new IllegalStateException("Original arguments must be set."); ForkerBuilder fb = new ForkerBuilder(javaExe); fb.command().add("-classpath"); fb.command().add(forkerClasspath); for (String s : Arrays.asList("java.library.path", "jna.library.path")) { if (System.getProperty(s) != null) fb.command().add("-D" + s + "=" + System.getProperty(s)); } fb.environment().put("FORKER_FALLBACK_ACTIVE", "true"); // Currently needs to be quiet :( fb.environment().put("FORKER_QUIET", "true"); // Doesnt seemm to work // fb.environment().put("FORKER_FDOUT", "1"); // fb.environment().put("FORKER_FDERR", "2"); fb.command().add(ForkerWrapper.class.getName()); // fb.command().add("--fdout=1"); // fb.command().add("--fderr=2"); fb.command().addAll(Arrays.asList(originalArgs)); fb.background(true); fb.io(IO.OUTPUT); fb.start(); logger.info("Exiting initial runtime"); return true; } } else { if (pidfile != null) { int pid = OS.getPID(); logger.info(String.format("Writing PID %d", pid)); FileUtils.writeLines(makeDirectoryForFile(relativize(cwd, pidfile)), Arrays.asList(String.valueOf(pid))); } } return false; } protected void addShutdownHook(final boolean useDaemon, final int exitWait) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { event(EXITING_WRAPPER); } catch (IOException e1) { } logger.info("In Shutdown Hook"); Process p = process; Forker f = daemon; if (p != null && useDaemon && f != null) { /* * Close the client control connection. This will cause the * wrapped process to System.exit(), and so cleanly shutdown */ List<Client> clients = f.getClients(); synchronized (clients) { for (Client c : clients) { if (c.getType() == 2) { try { logger.info("Closing control connection"); c.close(); } catch (IOException e) { } } } } } else { /* Not using daemon, so just destroy process */ p.destroy(); } final Thread current = Thread.currentThread(); Thread exitWaitThread = null; if (exitWait > 0) { exitWaitThread = new Thread() { { setDaemon(true); setName("ExitMonitor"); } public void run() { try { Thread.sleep(exitWait * 1000); current.interrupt(); } catch (InterruptedException e) { } } }; exitWaitThread.start(); } /* Now wait for it to actually exit */ try { logger.info("Closing control connection"); p.waitFor(); try { event(EXITED_WRAPPER); } catch (IOException e1) { } } catch (InterruptedException e) { p.destroy(); } finally { if (exitWaitThread != null) { exitWaitThread.interrupt(); } } } }); } protected void monitorWrappedApplication() { final int timeout = Integer.parseInt(getOptionValue("timeout", "60")); if (timeout > 0) { new Thread() { { setName("ForkerWrapperMonitor"); setDaemon(true); } public void run() { logger.info("Monitoring pings from wrapped application"); try { while (!stopping) { if (process != null && daemon != null) { WrapperHandler wrapper = daemon.getHandler(WrapperHandler.class); if (wrapper.getLastPing() > 0 && (wrapper.getLastPing() + timeout * 1000) <= System.currentTimeMillis()) { logger.warning(String .format("Process has not sent a ping in %d seconds, attempting to terminate", timeout)); tempRestartOnExit = true; /* * TODO may need to be more forceful than * this, e.g. OS kill */ process.destroy(); } } Thread.sleep(1000); } } catch (InterruptedException ie) { } } }.start(); } } protected void appendPath(StringBuilder newClasspath, String el) { if (newClasspath.length() > 0) newClasspath.append(File.pathSeparator); newClasspath.append(el); } protected boolean getSwitch(String key, boolean defaultValue) { if (cmd != null && cmd.hasOption(key)) return true; if (isBool(key)) { return true; } return !"false".equals(getOptionValue(key, String.valueOf(defaultValue))); } protected boolean isBool(String key) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) return nvp.isBool(); } return false; } protected String getProperty(String key) { for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key)) return nvp.getValue(); } return null; } protected List<String> getOptionValues(String key) { String[] vals = cmd == null ? null : cmd.getOptionValues(key); if (vals != null) return Arrays.asList(vals); List<String> valList = new ArrayList<String>(); for (KeyValuePair nvp : properties) { if (nvp.getName().equals(key) && nvp.getValue() != null) { valList.add(nvp.getValue()); } } /* * System properties, e.g. forker.somevar.1=val, forker.somevar.2=val2 */ List<String> varNames = new ArrayList<String>(); for (Map.Entry<Object, Object> en : System.getProperties().entrySet()) { if (((String) en.getKey()).startsWith("forker." + (key.replace("-", ".")) + ".")) { varNames.add((String) en.getKey()); } } Collections.sort(varNames); for (String vn : varNames) { valList.add(System.getProperty(vn)); } /* * Environment variables, e.g. FORKER_SOMEVAR_1=val, * FORKER_SOMEVAR_2=val2 */ varNames.clear(); for (Map.Entry<String, String> en : System.getenv().entrySet()) { if (en.getKey().startsWith("FORKER_" + (key.toUpperCase().replace("-", "_")) + "_")) { varNames.add(en.getKey()); } } Collections.sort(varNames); for (String vn : varNames) { valList.add(System.getenv(vn)); } return valList; } protected String getOptionValue(String key, String defaultValue) { String val = cmd == null ? null : cmd.getOptionValue(key); if (val == null) { val = System.getProperty("forkerwrapper." + key.replace("-", ".")); if (val == null) { val = System.getenv("FORKER_" + key.replace("-", "_").toUpperCase()); if (val == null) { val = getProperty(key); if (val == null) val = defaultValue; } } } return val; } private File makeDirectoryForFile(File file) throws IOException { File dir = file.getParentFile(); if (dir != null && !dir.exists() && !dir.mkdirs()) throw new IOException(String.format("Failed to create directory %s", dir)); return file; } private byte[] newBuffer() { return new byte[Integer.parseInt(getOptionValue("buffer-size", "1024"))]; } private void copy(final InputStream in, final OutputStream out, byte[] buf) throws IOException { int r; while ((r = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, r); out.flush(); } } private Runnable copyRunnable(final InputStream in, final OutputStream out) { return new Runnable() { @Override public void run() { try { copy(in, out == null ? new SinkOutputStream() : out, newBuffer()); } catch (EOFException e) { } catch (IOException ioe) { } } }; } private void process() throws ParseException, IOException { List<String> args = cmd.getArgList(); String main = getOptionValue("main", null); if (main == null) { if (args.isEmpty()) throw new ParseException("Must supply class name of application that contains a main() method."); classname = args.remove(0); } else classname = main; List<String> arguments = getOptionValues("apparg"); ArgMode argMode = getArgMode(); if (argMode != ArgMode.FORCE) { if (!args.isEmpty()) { switch (argMode) { case APPEND: arguments.addAll(0, args); break; case PREPEND: arguments.addAll(args); break; default: arguments = args; break; } } } this.arguments = arguments.toArray(new String[0]); } class SinkOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } } }
If the forker daemon is in use, the 'classpath' does not have a '+', and the forker utilities library is not included in that classpath, the forker daemon will not be found. This regression was introduced by the +/- feature that was intended for *boot* classpath. I ended up re-using the same code, but didn't consider the backward compatibility issue that might arise from doing so. No the lack or + or - on the classpath, means append is used by default. If you WANT to replace the classpath entirely, the path should now be prefixed with a =
forker-wrapper/src/main/java/com/sshtools/forker/wrapper/ForkerWrapper.java
If the forker daemon is in use, the 'classpath' does not have a '+', and the forker utilities library is not included in that classpath, the forker daemon will not be found.
Java
apache-2.0
641967c0dd7f89eed53455441be2ad06e9c96c10
0
amoghmargoor/qds-sdk-java,tubemogul/qds-sdk-java,abhisheksr8/qds-sdk-java,qubole/qds-sdk-java
/** * Copyright 2014- Qubole Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qubole.qds.sdk.java.details; import com.google.common.collect.Maps; import com.qubole.qds.sdk.java.api.SchemaCommandBuilder; import com.qubole.qds.sdk.java.client.QdsClient; import com.qubole.qds.sdk.java.entities.Schema; import javax.ws.rs.core.GenericType; import java.util.List; import java.util.Map; class SchemaCommandBuilderImpl extends InvocationCallbackBase<List<Schema>> implements SchemaCommandBuilder { private final QdsClient client; private String filter; private boolean describe; private String schemaName = "default"; @Override public SchemaCommandBuilder filter(String filter) { this.filter = filter; return this; } @Override public SchemaCommandBuilder described() { describe = true; return this; } @Override public SchemaCommandBuilder schemaName(String schemaName) { this.schemaName = schemaName; return this; } @Override protected InvokeArguments<List<Schema>> getInvokeArguments() { Map<String, String> params = Maps.newHashMap(); if ( filter != null ) { params.put("filter", filter); } if ( describe ) { params.put("describe", "true"); } GenericType<List<Schema>> responseType = new GenericType<List<Schema>>(){}; return new InvokeArguments<List<Schema>>(client, null, new RequestDetails(null, RequestDetails.Method.GET, params), responseType, "hive", schemaName); } SchemaCommandBuilderImpl(QdsClient client) { this.client = client; } }
src/main/java/com/qubole/qds/sdk/java/details/SchemaCommandBuilderImpl.java
/** * Copyright 2014- Qubole Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qubole.qds.sdk.java.details; import com.google.common.collect.Maps; import com.qubole.qds.sdk.java.api.SchemaCommandBuilder; import com.qubole.qds.sdk.java.client.QdsClient; import com.qubole.qds.sdk.java.entities.Schema; import javax.ws.rs.core.GenericType; import java.util.List; import java.util.Map; class SchemaCommandBuilderImpl extends InvocationCallbackBase<List<Schema>> implements SchemaCommandBuilder { private final QdsClient client; private String filter; private boolean describe; private String schemaName = "default"; @Override public SchemaCommandBuilder filter(String filter) { this.filter = filter; return this; } @Override public SchemaCommandBuilder described() { describe = true; return this; } @Override public SchemaCommandBuilder schemaName(String schemaName) { this.schemaName = schemaName; return this; } @Override protected InvokeArguments<List<Schema>> getInvokeArguments() { Map<String, String> params = Maps.newHashMap(); if ( filter != null ) { params.put("filter", filter); } if ( describe ) { params.put("describe", "true"); } GenericType<List<Schema>> responseType = new GenericType<List<Schema>>(){}; return new InvokeArguments<List<Schema>>(client, null, new RequestDetails(null, RequestDetails.Method.GET, params), responseType, "hive", "default"); } SchemaCommandBuilderImpl(QdsClient client) { this.client = client; } }
fix: dev: Fix non default schema bug. This was missed in 9ca0fac4. This change was present in PR #26 but got missed in #28.
src/main/java/com/qubole/qds/sdk/java/details/SchemaCommandBuilderImpl.java
fix: dev: Fix non default schema bug.
Java
apache-2.0
6aa743b04d3a9296392bb5d792027070e81ef863
0
tavultesoft/keymanweb,tavultesoft/keymanweb
package com.tavultesoft.kmea; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.inputmethodservice.Keyboard; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.tavultesoft.kmea.util.MapCompat; import java.util.ArrayList; import java.util.HashMap; /** * Keyman Settings --> Languages Settings --> Language Settings --> Models Picker * Displays a list of available models for a language ID. */ public final class ModelsPickerActivity extends AppCompatActivity { private Context context; private static Toolbar toolbar = null; private static ListView listView = null; private static ArrayList<HashMap<String, String>> lexicalModelsList = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); context = this; setContentView(R.layout.activity_list_layout); toolbar = (Toolbar) findViewById(R.id.list_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); TextView textView = (TextView) findViewById(R.id.bar_title); Bundle bundle = getIntent().getExtras(); String languageID = "", languageName = ""; if (bundle != null) { languageID = bundle.getString(KMManager.KMKey_LanguageID); languageName = bundle.getString(KMManager.KMKey_LanguageName); } textView.setText(String.format("%s model", languageName)); listView = (ListView) findViewById(R.id.listView); listView.setFastScrollEnabled(true); lexicalModelsList = getModelsList(context, languageID); String[] from = new String[]{"leftIcon", KMManager.KMKey_LexicalModelName, KMManager.KMKey_Icon}; int[] to = new int[]{R.id.image1, R.id.text1, R.id.image2}; ListAdapter listAdapter = new KMListAdapter(context, lexicalModelsList, R.layout.models_list_row_layout, from, to); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { listView.setItemChecked(position, true); listView.setSelection(position); // Start intent for selected Predictive Text Model screen HashMap<String, String> modelInfo = lexicalModelsList.get(position); Bundle bundle = new Bundle(); bundle.putString(KMManager.KMKey_LexicalModelID, modelInfo.get(KMManager.KMKey_LexicalModelID)); bundle.putString(KMManager.KMKey_LexicalModelName, modelInfo.get(KMManager.KMKey_LexicalModelName)); bundle.putString(KMManager.KMKey_LexicalModelVersion, modelInfo.get(KMManager.KMKey_LexicalModelVersion)); String isCustom = MapCompat.getOrDefault(modelInfo, KMManager.KMKey_CustomModel, "N"); bundle.putBoolean(KMManager.KMKey_CustomModel, isCustom.toUpperCase().equals("Y")); Intent i = new Intent(context, ModelInfoActivity.class); i.putExtras(bundle); startActivity(i); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onBackPressed() { finish(); } public static ArrayList<HashMap<String, String>> getModelsList(Context context, String languageID) { ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); // Start with the list of currently installed models ArrayList<HashMap<String, String>> availableLexicalModels = KeyboardPickerActivity.getLexicalModelsList(context); for(HashMap<String, String> modelInfo : availableLexicalModels) { if (modelInfo.get(KMManager.KMKey_LanguageID).equalsIgnoreCase(languageID)) { // Add icons showing model is installed (check) modelInfo.put("leftIcon", String.valueOf(R.drawable.ic_check)); modelInfo.put(KMManager.KMKey_Icon, String.valueOf(R.drawable.ic_arrow_forward)); modelInfo.put("isEnabled", "true"); list.add(modelInfo); } } // TODO: Check the list with models available in cloud. api.keyman.com needs to be done in a background network task return list; } }
android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelsPickerActivity.java
package com.tavultesoft.kmea; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.inputmethodservice.Keyboard; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import java.util.ArrayList; import java.util.HashMap; /** * Keyman Settings --> Languages Settings --> Language Settings --> Models Picker * Displays a list of available models for a language ID. */ public final class ModelsPickerActivity extends AppCompatActivity { private Context context; private static Toolbar toolbar = null; private static ListView listView = null; private static ArrayList<HashMap<String, String>> lexicalModelsList = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); context = this; setContentView(R.layout.activity_list_layout); toolbar = (Toolbar) findViewById(R.id.list_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); TextView textView = (TextView) findViewById(R.id.bar_title); Bundle bundle = getIntent().getExtras(); String languageID = "", languageName = ""; if (bundle != null) { languageID = bundle.getString(KMManager.KMKey_LanguageID); languageName = bundle.getString(KMManager.KMKey_LanguageName); } textView.setText(String.format("%s model", languageName)); listView = (ListView) findViewById(R.id.listView); listView.setFastScrollEnabled(true); lexicalModelsList = getModelsList(context, languageID); String[] from = new String[]{"leftIcon", KMManager.KMKey_LexicalModelName, KMManager.KMKey_Icon}; int[] to = new int[]{R.id.image1, R.id.text1, R.id.image2}; ListAdapter listAdapter = new KMListAdapter(context, lexicalModelsList, R.layout.models_list_row_layout, from, to); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { listView.setItemChecked(position, true); listView.setSelection(position); // TODO: Start intent for selected Predictive Text Model screen } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onBackPressed() { finish(); } public static ArrayList<HashMap<String, String>> getModelsList(Context context, String languageID) { ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); // Start with the list of currently installed models ArrayList<HashMap<String, String>> availableLexicalModels = KeyboardPickerActivity.getLexicalModelsList(context); for(HashMap<String, String> modelInfo : availableLexicalModels) { if (modelInfo.get(KMManager.KMKey_LanguageID).equalsIgnoreCase(languageID)) { // Add icons showing model is installed (check) modelInfo.put("leftIcon", String.valueOf(R.drawable.ic_check)); modelInfo.put(KMManager.KMKey_Icon, String.valueOf(R.drawable.ic_arrow_forward)); modelInfo.put("isEnabled", "true"); list.add(modelInfo); } } // TODO: Check the list with models available in cloud. api.keyman.com needs to be done in a background network task return list; } }
Connect ModelInfo to ModelsPicker
android/KMEA/app/src/main/java/com/tavultesoft/kmea/ModelsPickerActivity.java
Connect ModelInfo to ModelsPicker
Java
apache-2.0
9ff8655e173440d99a6b99bf7eb88b56f13f403a
0
feiteira/KATools
package com.kapouta.katools; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class KActivity extends Activity { public static final int GA_DISPATCH_PERIOD = 10; public static final String PARENT_URL_KEY = "Parent URL!"; public static final String GA_UA_CODE = "TBD -01"; protected static GoogleAnalyticsTracker tracker = null; private String analytics_url; private String tracking_name; private boolean doNotTrackThisTime; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.doNotTrackThisTime = false; if (tracker == null) { tracker = GoogleAnalyticsTracker.getInstance(); // tracker.setDebug(true); tracker.startNewSession(getAnalyticsUACode(), this); tracker.setSampleRate(100); // tracker.setDispatchPeriod(GA_DISPATCH_PERIOD); } } protected GoogleAnalyticsTracker getTracker() { return tracker; } public void onResume() { super.onResume(); if (this.doNotTrackThisTime) { this.doNotTrackThisTime = false; return; } // System.out.println("Session: [" + getAnalyticsUACode() + "]"); // System.out.println("URL: " + getActivityAnalyticsURL()); tracker.trackPageView(getActivityAnalyticsURL()); tracker.dispatch(); // tracker.stopSession(); } public void skipTrackingThisOnce() { this.doNotTrackThisTime = true; } public void onDestroy() { // tracker.dispatch(); // tracker.stopSession(); super.onDestroy(); } public String getActivityAnalyticsURL() { if (this.analytics_url == null) { Bundle extras = getIntent().getExtras(); if (extras != null && extras.getString(KActivity.PARENT_URL_KEY) != null) { this.analytics_url = extras.getString(KActivity.PARENT_URL_KEY) + getTrackingName(); } else this.analytics_url = getTrackingName(); } return this.analytics_url; } public String getTrackingName() { if (this.tracking_name == null) { this.tracking_name = "/" + this.getClass().getSimpleName(); this.tracking_name = this.tracking_name .replaceFirst("Activity", ""); } return this.tracking_name; } public String getAnalyticsUACode() { return GA_UA_CODE; // return this.getString(R.string.ga_api_key); } private void addSelfAsParent(Intent intent) { intent.putExtra(KActivity.PARENT_URL_KEY, getActivityAnalyticsURL()); } @Override public void startActivity(Intent intent) { addSelfAsParent(intent); super.startActivity(intent); } @Override public void startActivityForResult(Intent intent, int requestCode) { addSelfAsParent(intent); super.startActivityForResult(intent, requestCode); } @Override public void startActivityFromChild(Activity child, Intent intent, int requestCode) { addSelfAsParent(intent); super.startActivityFromChild(child, intent, requestCode); } @Override public boolean startActivityIfNeeded(Intent intent, int requestCode) { addSelfAsParent(intent); return super.startActivityIfNeeded(intent, requestCode); } }
KATools/src/com/kapouta/katools/KActivity.java
package com.kapouta.katools; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class KActivity extends Activity { public static final int GA_DISPATCH_PERIOD = 10; public static final String PARENT_URL_KEY = "Parent URL!"; public static final String GA_UA_CODE = "TBD"; protected static GoogleAnalyticsTracker tracker = null; private String analytics_url; private String tracking_name; private boolean doNotTrackThisTime; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.doNotTrackThisTime = false; if (tracker == null) { tracker = GoogleAnalyticsTracker.getInstance(); // tracker.setDebug(true); tracker.startNewSession(getAnalyticsUACode(), this); tracker.setSampleRate(100); // tracker.setDispatchPeriod(GA_DISPATCH_PERIOD); } } protected GoogleAnalyticsTracker getTracker() { return tracker; } public void onResume() { super.onResume(); if (this.doNotTrackThisTime) { this.doNotTrackThisTime = false; return; } // System.out.println("Session: [" + getAnalyticsUACode() + "]"); // System.out.println("URL: " + getActivityAnalyticsURL()); tracker.trackPageView(getActivityAnalyticsURL()); tracker.dispatch(); // tracker.stopSession(); } public void skipTrackingThisOnce() { this.doNotTrackThisTime = true; } public void onDestroy() { // tracker.dispatch(); // tracker.stopSession(); super.onDestroy(); } public String getActivityAnalyticsURL() { if (this.analytics_url == null) { Bundle extras = getIntent().getExtras(); if (extras != null && extras.getString(KActivity.PARENT_URL_KEY) != null) { this.analytics_url = extras.getString(KActivity.PARENT_URL_KEY) + getTrackingName(); } else this.analytics_url = getTrackingName(); } return this.analytics_url; } public String getTrackingName() { if (this.tracking_name == null) { this.tracking_name = "/" + this.getClass().getSimpleName(); this.tracking_name = this.tracking_name .replaceFirst("Activity", ""); } return this.tracking_name; } public String getAnalyticsUACode() { return GA_UA_CODE; // return this.getString(R.string.ga_api_key); } private void addSelfAsParent(Intent intent) { intent.putExtra(KActivity.PARENT_URL_KEY, getActivityAnalyticsURL()); } @Override public void startActivity(Intent intent) { addSelfAsParent(intent); super.startActivity(intent); } @Override public void startActivityForResult(Intent intent, int requestCode) { addSelfAsParent(intent); super.startActivityForResult(intent, requestCode); } @Override public void startActivityFromChild(Activity child, Intent intent, int requestCode) { addSelfAsParent(intent); super.startActivityFromChild(child, intent, requestCode); } @Override public boolean startActivityIfNeeded(Intent intent, int requestCode) { addSelfAsParent(intent); return super.startActivityIfNeeded(intent, requestCode); } }
Testing commit via EGit
KATools/src/com/kapouta/katools/KActivity.java
Testing commit via EGit
Java
apache-2.0
e228bbb51fd7106ec4481dda602193efce9b266e
0
airbnb/lottie-android,airbnb/lottie-android,airbnb/lottie-android,airbnb/lottie-android,sudaoblinnnk/donghua
package com.airbnb.lottie; import android.graphics.Bitmap; import android.graphics.BitmapShader; 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.Shader; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; import java.util.ArrayList; import java.util.Collections; import java.util.List; class LayerView extends AnimatableLayer { private MaskLayer mask; private LayerView matteLayer; private final List<LayerView> transformLayers = new ArrayList<>(); private final Paint mainCanvasPaint = new Paint(); @Nullable private final Bitmap contentBitmap; @Nullable private final Bitmap maskBitmap; @Nullable private final Bitmap matteBitmap; @Nullable private Canvas contentCanvas; @Nullable private Canvas maskCanvas; @Nullable private Canvas matteCanvas; private final Paint maskShapePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint mattePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Layer layerModel; private final LottieComposition composition; @Nullable private LayerView parentLayer; LayerView(Layer layerModel, LottieComposition composition, Callback callback, @Nullable Bitmap mainBitmap, @Nullable Bitmap maskBitmap, @Nullable Bitmap matteBitmap) { super(callback); this.layerModel = layerModel; this.composition = composition; this.maskBitmap = maskBitmap; this.matteBitmap = matteBitmap; this.contentBitmap = mainBitmap; mattePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); setBounds(composition.getBounds()); if (contentBitmap != null) { contentCanvas = new Canvas(contentBitmap); if (maskBitmap != null) { maskPaint.setShader( new BitmapShader(contentBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); } } List<Layer> precomps = composition.getPrecomps(layerModel.getPrecompId()); LongSparseArray<LayerView> precompMap = new LongSparseArray<>(); if (precomps != null) { for (int i = precomps.size() - 1; i >= 0; i--) { LayerView precompLayerView = new LayerView( precomps.get(i), composition, callback, mainBitmap, maskBitmap, matteBitmap); addLayer(precompLayerView); precompMap.put(precompLayerView.getId(), precompLayerView); } } for (AnimatableLayer layer : layers) { if (!(layer instanceof LayerView)) { continue; } long parentId = ((LayerView) layer).getLayerModel().getParentId(); if (parentId == -1) { continue; } LayerView parentLayer = precompMap.get(parentId); if (parentLayer == null) { continue; } ((LayerView) layer).setParentLayer(parentLayer); } setupForModel(); } private void setupForModel() { setBackgroundColor(layerModel.getSolidColor()); setBounds(0, 0, layerModel.getSolidWidth(), layerModel.getSolidHeight()); setPosition(layerModel.getPosition().createAnimation()); setAnchorPoint(layerModel.getAnchor().createAnimation()); setTransform(layerModel.getScale().createAnimation()); setRotation(layerModel.getRotation().createAnimation()); setAlpha(layerModel.getOpacity().createAnimation()); // TODO: determine if this is necessary // setVisible(layerModel.getInOutKeyframes() != null, false); List<Object> reversedItems = new ArrayList<>(layerModel.getShapes()); Collections.reverse(reversedItems); Transform currentTransform = null; ShapeTrimPath currentTrim = null; ShapeFill currentFill = null; ShapeStroke currentStroke = null; for (int i = 0; i < reversedItems.size(); i++) { Object item = reversedItems.get(i); if (item instanceof ShapeGroup) { GroupLayerView groupLayer = new GroupLayerView((ShapeGroup) item, currentFill, currentStroke, currentTrim, currentTransform, getCallback()); addLayer(groupLayer); } else if (item instanceof ShapeTransform) { currentTransform = (ShapeTransform) item; } else if (item instanceof ShapeFill) { currentFill = (ShapeFill) item; } else if (item instanceof ShapeTrimPath) { currentTrim = (ShapeTrimPath) item; } else if (item instanceof ShapeStroke) { currentStroke = (ShapeStroke) item; } else if (item instanceof ShapePath) { ShapePath shapePath = (ShapePath) item; ShapeLayerView shapeLayer = new ShapeLayerView(shapePath, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof RectangleShape) { RectangleShape shapeRect = (RectangleShape) item; RectLayer shapeLayer = new RectLayer(shapeRect, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof CircleShape) { CircleShape shapeCircle = (CircleShape) item; EllipseLayer shapeLayer = new EllipseLayer(shapeCircle, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof PolystarShape) { PolystarShape polystarShape = (PolystarShape) item; PolystarLayer shapeLayer = new PolystarLayer(polystarShape, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } } if (maskBitmap != null && layerModel.getMasks() != null && !layerModel.getMasks().isEmpty()) { setMask(new MaskLayer(layerModel.getMasks(), getCallback())); maskCanvas = new Canvas(maskBitmap); } buildAnimations(); } private void buildAnimations() { if (!layerModel.getInOutKeyframes().isEmpty()) { FloatKeyframeAnimation inOutAnimation = new FloatKeyframeAnimation(layerModel.getInOutKeyframes()); inOutAnimation.setIsDiscrete(); inOutAnimation.addUpdateListener(new KeyframeAnimation.AnimationListener<Float>() { @Override public void onValueChanged(Float value) { setVisible(value == 1f, false); } }); setVisible(inOutAnimation.getValue() == 1f, false); addAnimation(inOutAnimation); } else { setVisible(true, false); } } Layer getLayerModel() { return layerModel; } void setParentLayer(@Nullable LayerView parentLayer) { this.parentLayer = parentLayer; } @Nullable private LayerView getParentLayer() { return parentLayer; } private void setMask(MaskLayer mask) { this.mask = mask; // TODO: make this a field like other animation listeners and remove existing ones. for (BaseKeyframeAnimation<?, Path> animation : mask.getMasks()) { addAnimation(animation); animation.addUpdateListener(new KeyframeAnimation.AnimationListener<Path>() { @Override public void onValueChanged(Path value) { invalidateSelf(); } }); } } void setMatteLayer(LayerView matteLayer) { if (matteBitmap == null) { throw new IllegalArgumentException("Cannot set a matte if no matte bitmap was given!"); } this.matteLayer = matteLayer; matteCanvas = new Canvas(matteBitmap); } @Override public void draw(@NonNull Canvas mainCanvas) { if (contentBitmap != null) { if (contentBitmap.isRecycled()) { return; } contentBitmap.eraseColor(Color.TRANSPARENT); } if (maskBitmap != null) { maskBitmap.eraseColor(Color.TRANSPARENT); } if (matteBitmap != null) { matteBitmap.eraseColor(Color.TRANSPARENT); } if (!isVisible() || mainCanvasPaint.getAlpha() == 0) { return; } // Make a list of all parent layers. transformLayers.clear(); LayerView parent = parentLayer; while (parent != null) { transformLayers.add(parent); parent = parent.getParentLayer(); } if (contentCanvas == null || contentBitmap == null) { int mainCanvasCount = saveCanvas(mainCanvas); // Now apply the parent transformations from the top down. for (int i = transformLayers.size() - 1; i >= 0; i--) { LayerView layer = transformLayers.get(i); applyTransformForLayer(mainCanvas, layer); } super.draw(mainCanvas); mainCanvas.restoreToCount(mainCanvasCount); return; } int contentCanvasCount = saveCanvas(contentCanvas); int maskCanvasCount = saveCanvas(maskCanvas); // Now apply the parent transformations from the top down. for (int i = transformLayers.size() - 1; i >= 0 ; i--) { LayerView layer = transformLayers.get(i); applyTransformForLayer(contentCanvas, layer); applyTransformForLayer(maskCanvas, layer); } // We only have to apply the transformation to the mask because it's normally handed in // AnimatableLayer#draw but masks don't go through that. applyTransformForLayer(maskCanvas, this); super.draw(contentCanvas); Bitmap mainBitmap; if (hasMasks()) { for (int i = 0; i < mask.getMasks().size(); i++) { Path path = mask.getMasks().get(i).getValue(); //noinspection ConstantConditions maskCanvas.drawPath(path, maskShapePaint); } if (!hasMattes()) { mainCanvas.drawBitmap(maskBitmap, 0, 0, maskPaint); } mainBitmap = maskBitmap; } else { if (!hasMattes()) { mainCanvas.drawBitmap(contentBitmap, 0, 0, mainCanvasPaint); } mainBitmap = contentBitmap; } restoreCanvas(contentCanvas, contentCanvasCount); restoreCanvas(maskCanvas, maskCanvasCount); if (hasMattes()) { //noinspection ConstantConditions matteLayer.draw(matteCanvas); matteCanvas.drawBitmap(mainBitmap, 0, 0, mattePaint); mainCanvas.drawBitmap(matteBitmap, 0, 0, mainCanvasPaint); } } private boolean hasMattes() { return matteCanvas != null && matteBitmap != null && matteLayer != null; } private boolean hasMasks() { return maskBitmap != null && maskCanvas != null && mask != null && !mask.getMasks().isEmpty(); } @Override public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) { super.setProgress(progress); if (matteLayer != null) { matteLayer.setProgress(progress); } } long getId() { return layerModel.getId(); } @Override public String toString() { return layerModel.toString(); } }
lottie/src/main/java/com/airbnb/lottie/LayerView.java
package com.airbnb.lottie; import android.graphics.Bitmap; import android.graphics.BitmapShader; 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.Shader; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.LongSparseArray; import java.util.ArrayList; import java.util.Collections; import java.util.List; class LayerView extends AnimatableLayer { private MaskLayer mask; private LayerView matteLayer; private final List<LayerView> transformLayers = new ArrayList<>(); private final Paint mainCanvasPaint = new Paint(); @Nullable private final Bitmap contentBitmap; @Nullable private final Bitmap maskBitmap; @Nullable private final Bitmap matteBitmap; @Nullable private Canvas contentCanvas; @Nullable private Canvas maskCanvas; @Nullable private Canvas matteCanvas; private final Paint maskShapePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint mattePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Layer layerModel; private final LottieComposition composition; @Nullable private LayerView parentLayer; LayerView(Layer layerModel, LottieComposition composition, Callback callback, @Nullable Bitmap mainBitmap, @Nullable Bitmap maskBitmap, @Nullable Bitmap matteBitmap) { super(callback); this.layerModel = layerModel; this.composition = composition; this.maskBitmap = maskBitmap; this.matteBitmap = matteBitmap; this.contentBitmap = mainBitmap; mattePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); setBounds(composition.getBounds()); if (contentBitmap != null) { contentCanvas = new Canvas(contentBitmap); if (maskBitmap != null) { maskPaint.setShader( new BitmapShader(contentBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); } } List<Layer> precomps = composition.getPrecomps(layerModel.getPrecompId()); LongSparseArray<LayerView> precompMap = new LongSparseArray<>(); if (precomps != null) { for (int i = precomps.size() - 1; i >= 0; i--) { LayerView precompLayerView = new LayerView( precomps.get(i), composition, callback, mainBitmap, maskBitmap, matteBitmap); addLayer(precompLayerView); precompMap.put(precompLayerView.getId(), precompLayerView); } } for (AnimatableLayer layer : layers) { if (!(layer instanceof LayerView)) { continue; } long parentId = ((LayerView) layer).getLayerModel().getParentId(); if (parentId == -1) { continue; } LayerView parentLayer = precompMap.get(parentId); if (parentLayer == null) { continue; } ((LayerView) layer).setParentLayer(parentLayer); } setupForModel(); } private void setupForModel() { setBackgroundColor(layerModel.getSolidColor()); setBounds(0, 0, layerModel.getSolidWidth(), layerModel.getSolidHeight()); setPosition(layerModel.getPosition().createAnimation()); setAnchorPoint(layerModel.getAnchor().createAnimation()); setTransform(layerModel.getScale().createAnimation()); setRotation(layerModel.getRotation().createAnimation()); setAlpha(layerModel.getOpacity().createAnimation()); // TODO: determine if this is necessary // setVisible(layerModel.getInOutKeyframes() != null, false); List<Object> reversedItems = new ArrayList<>(layerModel.getShapes()); Collections.reverse(reversedItems); Transform currentTransform = null; ShapeTrimPath currentTrim = null; ShapeFill currentFill = null; ShapeStroke currentStroke = null; for (int i = 0; i < reversedItems.size(); i++) { Object item = reversedItems.get(i); if (item instanceof ShapeGroup) { GroupLayerView groupLayer = new GroupLayerView((ShapeGroup) item, currentFill, currentStroke, currentTrim, currentTransform, getCallback()); addLayer(groupLayer); } else if (item instanceof ShapeTransform) { currentTransform = (ShapeTransform) item; } else if (item instanceof ShapeFill) { currentFill = (ShapeFill) item; } else if (item instanceof ShapeTrimPath) { currentTrim = (ShapeTrimPath) item; } else if (item instanceof ShapeStroke) { currentStroke = (ShapeStroke) item; } else if (item instanceof ShapePath) { ShapePath shapePath = (ShapePath) item; ShapeLayerView shapeLayer = new ShapeLayerView(shapePath, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof RectangleShape) { RectangleShape shapeRect = (RectangleShape) item; RectLayer shapeLayer = new RectLayer(shapeRect, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof CircleShape) { CircleShape shapeCircle = (CircleShape) item; EllipseLayer shapeLayer = new EllipseLayer(shapeCircle, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } else if (item instanceof PolystarShape) { PolystarShape polystarShape = (PolystarShape) item; PolystarLayer shapeLayer = new PolystarLayer(polystarShape, currentFill, currentStroke, currentTrim, new ShapeTransform(composition), getCallback()); addLayer(shapeLayer); } } if (maskBitmap != null && layerModel.getMasks() != null && !layerModel.getMasks().isEmpty()) { setMask(new MaskLayer(layerModel.getMasks(), getCallback())); maskCanvas = new Canvas(maskBitmap); } buildAnimations(); } private void buildAnimations() { if (!layerModel.getInOutKeyframes().isEmpty()) { FloatKeyframeAnimation inOutAnimation = new FloatKeyframeAnimation(layerModel.getInOutKeyframes()); inOutAnimation.setIsDiscrete(); inOutAnimation.addUpdateListener(new KeyframeAnimation.AnimationListener<Float>() { @Override public void onValueChanged(Float value) { setVisible(value == 1f, false); } }); setVisible(inOutAnimation.getValue() == 1f, false); addAnimation(inOutAnimation); } else { setVisible(true, false); } } Layer getLayerModel() { return layerModel; } void setParentLayer(@Nullable LayerView parentLayer) { this.parentLayer = parentLayer; } @Nullable private LayerView getParentLayer() { return parentLayer; } private void setMask(MaskLayer mask) { this.mask = mask; // TODO: make this a field like other animation listeners and remove existing ones. for (BaseKeyframeAnimation<?, Path> animation : mask.getMasks()) { addAnimation(animation); animation.addUpdateListener(new KeyframeAnimation.AnimationListener<Path>() { @Override public void onValueChanged(Path value) { invalidateSelf(); } }); } } void setMatteLayer(LayerView matteLayer) { if (matteBitmap == null) { throw new IllegalArgumentException("Cannot set a matte if no matte bitmap was given!"); } this.matteLayer = matteLayer; matteCanvas = new Canvas(matteBitmap); } @Override public void draw(@NonNull Canvas mainCanvas) { if (contentBitmap != null) { if (contentBitmap.isRecycled()) { return; } contentBitmap.eraseColor(Color.TRANSPARENT); } if (maskBitmap != null) { maskBitmap.eraseColor(Color.TRANSPARENT); } if (matteBitmap != null) { matteBitmap.eraseColor(Color.TRANSPARENT); } if (!isVisible() || mainCanvasPaint.getAlpha() == 0) { return; } // Make a list of all parent layers. transformLayers.clear(); LayerView parent = parentLayer; while (parent != null) { transformLayers.add(parent); parent = parent.getParentLayer(); } if (contentCanvas == null || contentBitmap == null) { int mainCanvasCount = saveCanvas(mainCanvas); // Now apply the parent transformations from the top down. for (int i = 0; i < transformLayers.size(); i++) { LayerView layer = transformLayers.get(i); applyTransformForLayer(mainCanvas, layer); } super.draw(mainCanvas); mainCanvas.restoreToCount(mainCanvasCount); return; } int contentCanvasCount = saveCanvas(contentCanvas); int maskCanvasCount = saveCanvas(maskCanvas); // Now apply the parent transformations from the top down. for (int i = transformLayers.size() - 1; i >= 0 ; i--) { LayerView layer = transformLayers.get(i); applyTransformForLayer(contentCanvas, layer); applyTransformForLayer(maskCanvas, layer); } // We only have to apply the transformation to the mask because it's normally handed in // AnimatableLayer#draw but masks don't go through that. applyTransformForLayer(maskCanvas, this); super.draw(contentCanvas); Bitmap mainBitmap; if (hasMasks()) { for (int i = 0; i < mask.getMasks().size(); i++) { Path path = mask.getMasks().get(i).getValue(); //noinspection ConstantConditions maskCanvas.drawPath(path, maskShapePaint); } if (!hasMattes()) { mainCanvas.drawBitmap(maskBitmap, 0, 0, maskPaint); } mainBitmap = maskBitmap; } else { if (!hasMattes()) { mainCanvas.drawBitmap(contentBitmap, 0, 0, mainCanvasPaint); } mainBitmap = contentBitmap; } restoreCanvas(contentCanvas, contentCanvasCount); restoreCanvas(maskCanvas, maskCanvasCount); if (hasMattes()) { //noinspection ConstantConditions matteLayer.draw(matteCanvas); matteCanvas.drawBitmap(mainBitmap, 0, 0, mattePaint); mainCanvas.drawBitmap(matteBitmap, 0, 0, mainCanvasPaint); } } private boolean hasMattes() { return matteCanvas != null && matteBitmap != null && matteLayer != null; } private boolean hasMasks() { return maskBitmap != null && maskCanvas != null && mask != null && !mask.getMasks().isEmpty(); } @Override public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) { super.setProgress(progress); if (matteLayer != null) { matteLayer.setProgress(progress); } } long getId() { return layerModel.getId(); } @Override public String toString() { return layerModel.toString(); } }
Fix parent view iteration in LayerView
lottie/src/main/java/com/airbnb/lottie/LayerView.java
Fix parent view iteration in LayerView
Java
apache-2.0
72a03dcc43ed98829786f4d6f9856d143424a555
0
ssoerensen/docker-integration
/* * Copyright 2015 Steffen Folman Sørensen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dk.sublife.docker.integration; import com.google.common.collect.ImmutableList; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerException; import com.spotify.docker.client.DockerRequestException; import com.spotify.docker.client.ImageNotFoundException; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import java.io.IOException; import java.net.UnknownHostException; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import static com.spotify.docker.client.DockerClient.LogsParam.stderr; import static com.spotify.docker.client.DockerClient.LogsParam.stdout; /** * Docker container class. * <p/> * Implement this class to create a docker container designed for use with * integration testing. */ abstract public class Container implements InitializingBean, DisposableBean { /** * slf4j logger instance. */ private static final Logger LOGGER = LoggerFactory.getLogger(Container.class); /** * Docker container instance. */ private ContainerCreation container; /** * Docker client. */ @Autowired private DockerClient dockerClient; /** * Docker host config */ @Autowired private HostConfig hostConfig; private boolean isUp = false; @Value("${dk.sublife.dk.docker.integration.waitForTimeout:60}") private Integer waitForTimeout; /** * Create docker container config. * * @return docker container config */ abstract protected ContainerConfig createContainerConfig() throws Exception; /** * Check if service is up and running. * <p/> * Retry policies is enforced by the waitFor method. * * @return true if service is up and running */ abstract public boolean isUp(); /** * Post create actions. * * Implement this method to perform post startup actions. * This method is executed after docker container is created. This is the * first time it is possible to inspect the container. This allows for * retrieval of the ip address and for example copy files into the container * before the is actually started. * * @return boolean true if everything went according to plan */ protected boolean postCreateContainer() { return true; } /** * Post container start actions. * * Implement this method to perform post container startup actions. * This method is executed after the container is started but before isUp has been run to verify that the container * is fully started. * * @return boolean true if everything went according to plan */ protected boolean postStartContainer() { return true; } /** * Post startup actions. * * Implement this method to perform post startup actions. * This method is executed after isUp returns true but before waitFor returns. * * @return boolean postStartup actions. */ protected boolean postStartup(){ return true; } /** * Create default docker host configuration. * <p/> * Default host configuration can be overwritten by creating a bean which * exposes a {@link HostConfig} instance. * <p/> * To create a custom host config for a container simply overwrite this method. * * @return host config */ protected HostConfig createHostConfig(){ return hostConfig; } /** * Create Container config builder from image. * * @param image docker image * @param env Environment variables * @return Container config builder */ protected ContainerConfig.Builder image(final String image, String... env){ return ContainerConfig.builder() .hostConfig(createHostConfig()) .env(ImmutableList.copyOf(env)) .image(image); } /** * Wait for isUp method call is satisfied. * <p/> * Overwrite this method to change the default wait timeout, before returning * errors. the default timout is 60 seconds. * * @return true if images is running * @throws InterruptedException */ public boolean waitFor() throws Exception { return waitFor(waitForTimeout); } /** * Wait for isUp method call is satisfied. * * @param timoutSeconds seconds before failing * @return true when service is available * @throws InterruptedException */ protected boolean waitFor(long timoutSeconds) throws Exception { final Instant start = Instant.now(); final ContainerInfo inspect = inspect(); final String name = inspect.name(); final String image = inspect.config().image(); if(LOGGER.isInfoEnabled() && !isUp){ LOGGER.info("Waiting for container is up: {}{}", image, name); } while(!isUp){ try { if (inspect().state().running()) { isUp = isUp(); if(isUp){ if(LOGGER.isInfoEnabled()){ LOGGER.info("Running post startup actions..."); } if (!postStartup()) { throw new RuntimeException("Post startup failed!"); } } } else { LOGGER.error("Container is not up: {}{}", image, name); logFromContainer(); throw new RuntimeException("Container died."); } } catch (RuntimeException e){ throw e; } catch (Exception e) { LOGGER.info(e.getMessage()); } final long seconds = Duration.between(start, Instant.now()).getSeconds(); if(seconds > timoutSeconds){ try { if (inspect().state().running()) { LOGGER.error("Container is running but not up: {}{}", image, name); logFromContainer(); } } catch (final Exception e) { LOGGER.error("Error inspecting container!", e); } throw new RuntimeException("Wait time exceeded."); } Thread.sleep(5000); } if(LOGGER.isInfoEnabled()){ LOGGER.info("container is up {}{}", image, name); } return true; } protected void logFromContainer() throws DockerException, InterruptedException { final ContainerInfo inspect = inspect(); final String id = inspect.id(); final String name = inspect.name(); final String image = inspect.config().image(); try (final LogStream logs = dockerClient.logs(id, stderr(), stdout())) { final String fullLog = logs.readFully(); LOGGER.error("Container logs from {}{}:\n {}", image, name, fullLog); } } /** * Get docker container ip address * * @return IP Address * @throws DockerException * @throws InterruptedException * @throws UnknownHostException */ public String address() throws DockerException, InterruptedException, UnknownHostException { return inspect().networkSettings().ipAddress(); } /** * Get docker container name * * @return container name * @throws DockerException * @throws InterruptedException * @throws UnknownHostException */ public String name() throws DockerException, InterruptedException, UnknownHostException { return inspect().name(); } /** * Inspect docker container. * * @return * @throws DockerException * @throws InterruptedException */ public ContainerInfo inspect() throws DockerException, InterruptedException { return dockerClient.inspectContainer(container.id()); } /** * Pull docker image. * * @param images * @throws DockerException * @throws InterruptedException */ protected void pull(final String images) throws DockerException, InterruptedException { dockerClient.pull(images); } /** * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). * <p>This method allows the bean instance to perform initialization only * possible when all bean properties have been set and to throw an * exception in the event of misconfiguration. * * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails. */ @Override synchronized public void afterPropertiesSet() throws Exception { final ContainerConfig containerConfig = createContainerConfig(); this.container = createContainer(containerConfig); try { if (!postCreateContainer()) { throw new RuntimeException("Post create container failed!"); } LOGGER.info("Starting container: image: {}, name: {}, address: {}", containerConfig.image(), name(), address()); startContainer(); try { if (!postStartContainer()) { throw new RuntimeException("Post start container failed!"); } } catch (final Exception postStartContainerException) { killContainer(); throw postStartContainerException; } } catch (final Exception postCreateContainerException) { removeContainer(); throw new RuntimeException(postCreateContainerException); } } protected ContainerCreation createContainer(final ContainerConfig containerConfig) throws DockerException, InterruptedException { pull(containerConfig.image()); return dockerClient.createContainer(containerConfig); } protected void startContainer() throws DockerException, InterruptedException, UnknownHostException { final String id = container.id(); try { inspect().config().env().forEach(s -> LOGGER.info("Environment Variable: {}", s)); } catch (NullPointerException e){ LOGGER.info("No environment variables set for container"); } dockerClient.startContainer(id); } /** * Invoked by a BeanFactory on destruction of a singleton. * * @throws Exception in case of shutdown errors. * Exceptions will get logged but not rethrown to allow * other beans to release their resources too. */ @Override public void destroy() throws Exception { try { killContainer(); } finally { removeContainer(); } } protected void killContainer() throws DockerException, InterruptedException { final String id = container.id(); final String name = dockerClient.inspectContainer(id).name(); LOGGER.info("Stopping container: {}", name); try { dockerClient.killContainer(container.id()); } catch (final DockerRequestException e) { LOGGER.warn("Docker request error during kill!", e); } LOGGER.info("Container stopped: {}", name); } protected void removeContainer() throws DockerException, InterruptedException { final String id = container.id(); final String name = dockerClient.inspectContainer(id).name(); LOGGER.info("Removing container: {}", name); dockerClient.removeContainer(id, true); LOGGER.info("Container removed: {}", name); } /** /** * Copies a local directory to the container. * * @param localDirectory The local directory to send to the container. * @param containerDirectory The directory inside the container where the files are copied to. */ public void copyToContainer(final Path localDirectory, final Path containerDirectory) throws InterruptedException, DockerException, IOException { final String id = container.id(); dockerClient.copyToContainer(localDirectory, id, containerDirectory.toString()); } }
docker-integration/src/main/java/dk/sublife/docker/integration/Container.java
/* * Copyright 2015 Steffen Folman Sørensen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dk.sublife.docker.integration; import com.google.common.collect.ImmutableList; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerException; import com.spotify.docker.client.DockerRequestException; import com.spotify.docker.client.ImageNotFoundException; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import java.io.IOException; import java.net.UnknownHostException; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import static com.spotify.docker.client.DockerClient.LogsParam.stderr; import static com.spotify.docker.client.DockerClient.LogsParam.stdout; /** * Docker container class. * <p/> * Implement this class to create a docker container designed for use with * integration testing. */ abstract public class Container implements InitializingBean, DisposableBean { /** * slf4j logger instance. */ private static final Logger LOGGER = LoggerFactory.getLogger(Container.class); /** * Docker container instance. */ private ContainerCreation container; /** * Docker client. */ @Autowired private DockerClient dockerClient; /** * Docker host config */ @Autowired private HostConfig hostConfig; private boolean isUp = false; @Value("${dk.sublife.dk.docker.integration.waitForTimeout:60}") private Integer waitForTimeout; /** * Create docker container config. * * @return docker container config */ abstract protected ContainerConfig createContainerConfig() throws Exception; /** * Check if service is up and running. * <p/> * Retry policies is enforced by the waitFor method. * * @return true if service is up and running */ abstract public boolean isUp(); /** * Post create actions. * * Implement this method to perform post startup actions. * This method is executed after docker container is created. This is the * first time it is possible to inspect the container. This allows for * retrieval of the ip address and for example copy files into the container * before the is actually started. * * @return boolean true if everything went according to plan */ protected boolean postCreateContainer() { return true; } /** * Post container start actions. * * Implement this method to perform post container startup actions. * This method is executed after the container is started but before isUp has been run to verify that the container * is fully started. * * @return boolean true if everything went according to plan */ protected boolean postStartContainer() { return true; } /** * Post startup actions. * * Implement this method to perform post startup actions. * This method is executed after isUp returns true but before waitFor returns. * * @return boolean postStartup actions. */ protected boolean postStartup(){ return true; } /** * Create default docker host configuration. * <p/> * Default host configuration can be overwritten by creating a bean which * exposes a {@link HostConfig} instance. * <p/> * To create a custom host config for a container simply overwrite this method. * * @return host config */ protected HostConfig createHostConfig(){ return hostConfig; } /** * Create Container config builder from image. * * @param image docker image * @param env Environment variables * @return Container config builder */ protected ContainerConfig.Builder image(final String image, String... env){ return ContainerConfig.builder() .hostConfig(createHostConfig()) .env(ImmutableList.copyOf(env)) .image(image); } /** * Wait for isUp method call is satisfied. * <p/> * Overwrite this method to change the default wait timeout, before returning * errors. the default timout is 60 seconds. * * @return true if images is running * @throws InterruptedException */ public boolean waitFor() throws Exception { return waitFor(waitForTimeout); } /** * Wait for isUp method call is satisfied. * * @param timoutSeconds seconds before failing * @return true when service is available * @throws InterruptedException */ protected boolean waitFor(long timoutSeconds) throws Exception { final Instant start = Instant.now(); final ContainerInfo inspect = inspect(); final String name = inspect.name(); final String image = inspect.config().image(); if(LOGGER.isInfoEnabled() && !isUp){ LOGGER.info("Waiting for container is up: {}{}", image, name); } while(!isUp){ try { if (inspect().state().running()) { isUp = isUp(); if(isUp){ if(LOGGER.isInfoEnabled()){ LOGGER.info("Running post startup actions..."); } if (!postStartup()) { throw new RuntimeException("Post startup failed!"); } } } else { LOGGER.error("Container is not up: {}{}", image, name); logFromContainer(); throw new RuntimeException("Container died."); } } catch (RuntimeException e){ throw e; } catch (Exception e) { LOGGER.info(e.getMessage()); } final long seconds = Duration.between(start, Instant.now()).getSeconds(); if(seconds > timoutSeconds){ try { if (inspect().state().running()) { LOGGER.error("Container is running but not up: {}{}", image, name); logFromContainer(); } } catch (final Exception e) { LOGGER.error("Error inspecting container!", e); } throw new RuntimeException("Wait time exceeded."); } Thread.sleep(5000); } if(LOGGER.isInfoEnabled()){ LOGGER.info("container is up {}{}", image, name); } return true; } protected void logFromContainer() throws DockerException, InterruptedException { final ContainerInfo inspect = inspect(); final String id = inspect.id(); final String name = inspect.name(); final String image = inspect.config().image(); try (final LogStream logs = dockerClient.logs(id, stderr(), stdout())) { final String fullLog = logs.readFully(); LOGGER.error("Container logs from {}{}:\n {}", image, name, fullLog); } } /** * Get docker container ip address * * @return IP Address * @throws DockerException * @throws InterruptedException * @throws UnknownHostException */ public String address() throws DockerException, InterruptedException, UnknownHostException { return inspect().networkSettings().ipAddress(); } /** * Get docker container name * * @return container name * @throws DockerException * @throws InterruptedException * @throws UnknownHostException */ public String name() throws DockerException, InterruptedException, UnknownHostException { return inspect().name(); } /** * Inspect docker container. * * @return * @throws DockerException * @throws InterruptedException */ public ContainerInfo inspect() throws DockerException, InterruptedException { return dockerClient.inspectContainer(container.id()); } /** * Pull docker image. * * @param images * @throws DockerException * @throws InterruptedException */ protected void pull(final String images) throws DockerException, InterruptedException { dockerClient.pull(images); } /** * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). * <p>This method allows the bean instance to perform initialization only * possible when all bean properties have been set and to throw an * exception in the event of misconfiguration. * * @throws Exception in the event of misconfiguration (such * as failure to set an essential property) or if initialization fails. */ @Override synchronized public void afterPropertiesSet() throws Exception { final ContainerConfig containerConfig = createContainerConfig(); this.container = createContainer(containerConfig); try { if (!postCreateContainer()) { throw new RuntimeException("Post create container failed!"); } LOGGER.info("Starting container: image: {}, name: {}, address: {}", containerConfig.image(), name(), address()); startContainer(); try { if (!postStartContainer()) { throw new RuntimeException("Post start container failed!"); } } catch (final Exception postStartContainerException) { killContainer(); throw postStartContainerException; } } catch (final Exception postCreateContainerException) { removeContainer(); throw new RuntimeException(postCreateContainerException); } } protected ContainerCreation createContainer(final ContainerConfig containerConfig) throws DockerException, InterruptedException { try { dockerClient.inspectImage(containerConfig.image()); } catch (ImageNotFoundException e){ LOGGER.warn("Image not found: {}. Reason {}", containerConfig.image(), e.getMessage()); pull(containerConfig.image()); } return dockerClient.createContainer(containerConfig); } protected void startContainer() throws DockerException, InterruptedException, UnknownHostException { final String id = container.id(); try { inspect().config().env().forEach(s -> LOGGER.info("Environment Variable: {}", s)); } catch (NullPointerException e){ LOGGER.info("No environment variables set for container"); } dockerClient.startContainer(id); } /** * Invoked by a BeanFactory on destruction of a singleton. * * @throws Exception in case of shutdown errors. * Exceptions will get logged but not rethrown to allow * other beans to release their resources too. */ @Override public void destroy() throws Exception { try { killContainer(); } finally { removeContainer(); } } protected void killContainer() throws DockerException, InterruptedException { final String id = container.id(); final String name = dockerClient.inspectContainer(id).name(); LOGGER.info("Stopping container: {}", name); try { dockerClient.killContainer(container.id()); } catch (final DockerRequestException e) { LOGGER.warn("Docker request error during kill!", e); } LOGGER.info("Container stopped: {}", name); } protected void removeContainer() throws DockerException, InterruptedException { final String id = container.id(); final String name = dockerClient.inspectContainer(id).name(); LOGGER.info("Removing container: {}", name); dockerClient.removeContainer(id, true); LOGGER.info("Container removed: {}", name); } /** /** * Copies a local directory to the container. * * @param localDirectory The local directory to send to the container. * @param containerDirectory The directory inside the container where the files are copied to. */ public void copyToContainer(final Path localDirectory, final Path containerDirectory) throws InterruptedException, DockerException, IOException { final String id = container.id(); dockerClient.copyToContainer(localDirectory, id, containerDirectory.toString()); } }
We now pull every time we use createContainer. So latest images are updated.
docker-integration/src/main/java/dk/sublife/docker/integration/Container.java
We now pull every time we use createContainer.
Java
apache-2.0
b84b87d90c767fdddda7582f7da2bdd9f03f04d1
0
tijanat/arx,tijanat/arx,RaffaelBild/arx,kentoa/arx,bitraten/arx,COWYARD/arx,fstahnke/arx,kentoa/arx,COWYARD/arx,jgaupp/arx,bitraten/arx,TheRealRasu/arx,kbabioch/arx,arx-deidentifier/arx,jgaupp/arx,fstahnke/arx,arx-deidentifier/arx,TheRealRasu/arx,kbabioch/arx,RaffaelBild/arx
/* * ARX: Powerful Data Anonymization * Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.deidentifier.arx.criteria; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.DataSubset; import org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry; import org.deidentifier.arx.framework.data.DataManager; /** * The d-presence criterion * Published in: * Nergiz M, Atzori M, Clifton C. * Hiding the presence of individuals from shared databases. * Proceedings of the 2007 ACM SIGMOD international conference on Management of data. 2007:665-676. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class DPresence extends ImplicitPrivacyCriterion{ private static final long serialVersionUID = 8534004943055128797L; /** Delta min*/ private final double dMin; /** Delta max*/ private final double dMax; /** A compressed representation of the research subset*/ private DataSubset subset; /** * Creates a new instance of the d-presence criterion as proposed in: * Nergiz M, Atzori M, Clifton C. * Hiding the presence of individuals from shared databases. * Proceedings of the 2007 ACM SIGMOD international conference on Management of data. 2007:665-676. * @param dMin Delta min * @param dMax Delta max * @param subset Research subset */ public DPresence(double dMin, double dMax, DataSubset subset) { super(false); this.dMin = dMin; this.dMax = dMax; this.subset = subset; } /** * For building the inclusion criterion * @param subset */ protected DPresence(DataSubset subset) { super(true); this.dMin = 0d; this.dMax = 1d; this.subset = subset; } @Override public void initialize(DataManager manager) { // Nothing to do } @Override public int getRequirements(){ // Requires two counters return ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_SECONDARY_COUNTER; } @Override public boolean isAnonymous(HashGroupifyEntry entry) { double delta = entry.count == 0 ? 0d : (double) entry.count / (double) entry.pcount; return (delta >= dMin) && (delta <= dMax); } /** * Returns the research subset * @return */ public DataSubset getSubset() { return this.subset; } /** * Returns dMin * @return */ public double getDMin() { return dMin; } /** * Returns dMax * @return */ public double getDMax() { return dMax; } @Override public String toString() { return "("+dMin+","+dMax+")-presence"; } }
src/main/org/deidentifier/arx/criteria/DPresence.java
/* * ARX: Powerful Data Anonymization * Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.deidentifier.arx.criteria; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.DataSubset; import org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry; import org.deidentifier.arx.framework.data.DataManager; /** * The d-presence criterion * Published in: * Nergiz M, Atzori M, Clifton C. * Hiding the presence of individuals from shared databases. * Proceedings of the 2007 ACM SIGMOD international conference on Management of data. 2007:665-676. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class DPresence extends ImplicitPrivacyCriterion{ private static final long serialVersionUID = 8534004943055128797L; /** Delta min*/ private final double dMin; /** Delta max*/ private final double dMax; /** A compressed representation of the research subset*/ private DataSubset subset; /** * Creates a new instance of the d-presence criterion as proposed in: * Nergiz M, Atzori M, Clifton C. * Hiding the presence of individuals from shared databases. * Proceedings of the 2007 ACM SIGMOD international conference on Management of data. 2007:665-676. * @param dMin Delta min * @param dMax Delta max * @param subset Research subset */ public DPresence(double dMin, double dMax, DataSubset subset) { super(false); this.dMin = dMin; this.dMax = dMax; this.subset = subset; } /** * For building the inclusion criterion * @param subset */ protected DPresence(DataSubset subset) { super(true); this.dMin = 0d; this.dMax = 1d; this.subset = subset; } @Override public void initialize(DataManager manager) { // Nothing to do } @Override public int getRequirements(){ // Requires two counters return ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_SECONDARY_COUNTER; } @Override public boolean isAnonymous(HashGroupifyEntry entry) { if (entry.count > 0) { double dCurrent = (double) entry.count / (double) entry.pcount; // current_delta has to be between delta_min and delta_max return (dCurrent >= dMin) && (dCurrent <= dMax); } else { return true; } } /** * Returns the research subset * @return */ public DataSubset getSubset() { return this.subset; } /** * Returns dMin * @return */ public double getDMin() { return dMin; } /** * Returns dMax * @return */ public double getDMax() { return dMax; } @Override public String toString() { return "("+dMin+","+dMax+")-presence"; } }
Bugfix: d-presence: also consider dmin for equivalence classes from the public dataset that have no matching equivalence class in the private research subset
src/main/org/deidentifier/arx/criteria/DPresence.java
Bugfix: d-presence: also consider dmin for equivalence classes from the public dataset that have no matching equivalence class in the private research subset
Java
apache-2.0
462f4d2e9b84a82c3f19dbda85cb109f22648e85
0
mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData,mpi2/PhenotypeData
/******************************************************************************* * Copyright © 2013 - 2015 EMBL - European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package uk.ac.ebi.phenotype.web.controller; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.poi.ss.usermodel.Workbook; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.hibernate.HibernateException; import org.mousephenotype.cda.db.dao.*; import org.mousephenotype.cda.db.pojo.*; import org.mousephenotype.cda.db.pojo.ReferenceDTO; import org.mousephenotype.cda.enumerations.SexType; import org.mousephenotype.cda.solr.generic.util.PhenotypeCallSummarySolr; import org.mousephenotype.cda.solr.generic.util.PhenotypeFacetResult; import org.mousephenotype.cda.solr.generic.util.Tools; import org.mousephenotype.cda.solr.service.ExperimentService; import org.mousephenotype.cda.solr.service.GeneService; import org.mousephenotype.cda.solr.service.MpService; import org.mousephenotype.cda.solr.service.SolrIndex; import org.mousephenotype.cda.solr.service.SolrIndex.AnnotNameValCount; import org.mousephenotype.cda.solr.service.dto.*; import org.mousephenotype.cda.solr.web.dto.DataTableRow; import org.mousephenotype.cda.solr.web.dto.GenePageTableRow; import org.mousephenotype.cda.solr.web.dto.PhenotypePageTableRow; import org.mousephenotype.cda.solr.web.dto.SimpleOntoTerm; import org.mousephenotype.cda.utilities.CommonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import uk.ac.ebi.generic.util.ExcelWorkBook; import uk.ac.sanger.phenodigm2.dao.PhenoDigmWebDao; import uk.ac.sanger.phenodigm2.model.GeneIdentifier; import uk.ac.sanger.phenodigm2.web.AssociationSummary; import uk.ac.sanger.phenodigm2.web.DiseaseAssociationSummary; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; @Controller public class FileExportController { protected CommonUtils commonUtils = new CommonUtils(); private final Logger log = LoggerFactory.getLogger(this.getClass().getCanonicalName()); @Autowired public PhenotypeCallSummaryDAO phenotypeCallSummaryDAO; @Autowired private SolrIndex solrIndex; @Autowired private GeneService geneService; @Autowired @Qualifier("phenotypePipelineDAOImpl") private PhenotypePipelineDAO ppDAO; @Resource(name = "globalConfiguration") private Map<String, String> config; @Autowired private ExperimentService experimentService; @Autowired OrganisationDAO organisationDao; @Autowired StrainDAO strainDAO; @Autowired AlleleDAO alleleDAO; @Autowired private MpService mpService; @Autowired private PhenotypeCallSummarySolr phenoDAO; private String NO_INFO_MSG = "No information available"; private String hostName; @Autowired @Qualifier("admintoolsDataSource") private DataSource admintoolsDataSource; @Autowired private ReferenceDAO referenceDAO; @Autowired private GwasDAO gwasDao; @Autowired private GenomicFeatureDAO genesDao; @Autowired private PhenoDigmWebDao phenoDigmDao; private final double rawScoreCutoff = 1.97; /** * Return a TSV formatted response which contains all datapoints * * @param phenotypingCenterParameter * @param pipelineStableId * @param procedureStableId * @param parameterStableId * @param alleleAccession * @param sexesParameter * @param zygositiesParameter * @param strainParameter * @return * @throws SolrServerException * @throws IOException * @throws URISyntaxException */ @ResponseBody @RequestMapping(value = "/exportraw", method = RequestMethod.GET) public String getExperimentalData( @RequestParam(value = "phenotyping_center", required = true) String phenotypingCenterParameter, @RequestParam(value = "pipeline_stable_id", required = true) String pipelineStableId, @RequestParam(value = "procedure_stable_id", required = true) String procedureStableId, @RequestParam(value = "parameter_stable_id", required = true) String parameterStableId, @RequestParam(value = "allele_accession", required = true) String alleleAccession, @RequestParam(value = "sex", required = false) String[] sexesParameter, @RequestParam(value = "zygosity", required = false) String[] zygositiesParameter, @RequestParam(value = "strain", required = false) String strainParameter) throws SolrServerException, IOException, URISyntaxException { Organisation phenotypingCenter = organisationDao.getOrganisationByName(phenotypingCenterParameter); Pipeline pipeline = ppDAO.getPhenotypePipelineByStableId(pipelineStableId); Parameter parameter = ppDAO.getParameterByStableId(parameterStableId); Allele allele = alleleDAO.getAlleleByAccession(alleleAccession); SexType sex = (sexesParameter != null && sexesParameter.length > 1) ? SexType.valueOf(sexesParameter[0]) : null; List<String> zygosities = (zygositiesParameter == null) ? null : Arrays.asList(zygositiesParameter); String center = phenotypingCenter.getName(); Integer centerId = phenotypingCenter.getId(); String geneAcc = allele.getGene().getId().getAccession(); String alleleAcc = allele.getId().getAccession(); String strainAccession = null; if (strainParameter != null) { Strain s = strainDAO.getStrainByName(strainParameter); if (s != null) { strainAccession = s.getId().getAccession(); } } List<ExperimentDTO> experiments = experimentService.getExperimentDTO(parameter.getId(), pipeline.getId(), geneAcc, sex, centerId, zygosities, strainAccession, null, Boolean.FALSE, alleleAcc); List<String> rows = new ArrayList<>(); rows.add(StringUtils.join(new String[] { "Experiment", "Center", "Pipeline", "Procedure", "Parameter", "Strain", "Colony", "Gene", "Allele", "MetadataGroup", "Zygosity", "Sex", "AssayDate", "Value", "Metadata" }, ", ")); Integer i = 1; for (ExperimentDTO experiment : experiments) { // Adding all data points to the export Set<ObservationDTO> observations = experiment.getControls(); observations.addAll(experiment.getMutants()); for (ObservationDTO observation : observations) { List<String> row = new ArrayList<>(); row.add("Exp" + i.toString()); row.add(center); row.add(pipelineStableId); row.add(procedureStableId); row.add(parameterStableId); row.add(observation.getStrain()); row.add((observation.getGroup().equals("control")) ? "+/+" : observation.getColonyId()); row.add((observation.getGroup().equals("control")) ? "\"\"" : geneAcc); row.add((observation.getGroup().equals("control")) ? "\"\"" : alleleAcc); row.add((observation.getMetadataGroup() != null && !observation.getMetadataGroup().isEmpty()) ? observation.getMetadataGroup() : "\"\""); row.add((observation.getZygosity() != null && !observation.getZygosity().isEmpty()) ? observation.getZygosity() : "\"\""); row.add(observation.getSex()); row.add(observation.getDateOfExperimentString()); String dataValue = observation.getCategory(); if (dataValue == null) { dataValue = observation.getDataPoint().toString(); } row.add(dataValue); row.add("\"" + StringUtils.join(observation.getMetadata(), "::") + "\""); rows.add(StringUtils.join(row, ", ")); } // Next experiment i++; } return StringUtils.join(rows, "\n"); } /** * <p> * Export table as TSV or Excel file. * </p> * * @param model * @return */ @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportTableAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "externalDbId", required = true) Integer extDbId, @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "fileName", required = true) String fileName, @RequestParam(value = "legacyOnly", required = false, defaultValue = "false") Boolean legacyOnly, @RequestParam(value = "allele_accession", required = false) String[] allele, @RequestParam(value = "rowStart", required = false) Integer rowStart, @RequestParam(value = "length", required = false) Integer length, @RequestParam(value = "panel", required = false) String panelName, @RequestParam(value = "mpId", required = false) String mpId, @RequestParam(value = "mpTerm", required = false) String mpTerm, @RequestParam(value = "mgiGeneId", required = false) String[] mgiGeneId, @RequestParam(value = "parameterStableId", required = false) String[] parameterStableId, // should // be // filled // for // graph // data // export @RequestParam(value = "zygosity", required = false) String[] zygosities, // should // be // filled // for // graph // data // export @RequestParam(value = "strains", required = false) String[] strains, // should // be // filled // for // graph // data // export @RequestParam(value = "geneSymbol", required = false) String geneSymbol, @RequestParam(value = "solrCoreName", required = false) String solrCoreName, @RequestParam(value = "params", required = false) String solrFilters, @RequestParam(value = "gridFields", required = false) String gridFields, @RequestParam(value = "showImgView", required = false, defaultValue = "false") Boolean showImgView, @RequestParam(value = "dumpMode", required = false) String dumpMode, @RequestParam(value = "baseUrl", required = false) String baseUrl, @RequestParam(value = "sex", required = false) String sex, @RequestParam(value = "phenotypingCenter", required = false) String[] phenotypingCenter, @RequestParam(value = "pipelineStableId", required = false) String[] pipelineStableId, @RequestParam(value = "dogoterm", required = false, defaultValue = "false") Boolean dogoterm, @RequestParam(value = "gocollapse", required = false, defaultValue = "false") Boolean gocollapse, @RequestParam(value = "gene2pfam", required = false, defaultValue = "false") Boolean gene2pfam, @RequestParam(value = "doAlleleRef", required = false, defaultValue = "false") Boolean doAlleleRef, @RequestParam(value = "filterStr", required = false) String filterStr, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { hostName = request.getAttribute("mappedHostname").toString().replace("https:", "http:"); System.out.println("------------\nEXPORT \n---------"); String query = "*:*"; // default String fqStr = null; log.debug("solr params: " + solrFilters); String[] pairs = solrFilters.split("&"); for (String pair : pairs) { try { String[] parts = pair.split("="); if (parts[0].equals("q")) { query = parts[1]; } else if (parts[0].equals("fq")) { fqStr = parts[1]; } } catch (Exception e) { log.error("Error getting value of q"); e.printStackTrace(); } } Workbook wb = null; List<String> dataRows = new ArrayList(); // Default to exporting 10 rows length = length != null ? length : 10; panelName = panelName == null ? "" : panelName; if (!solrCoreName.isEmpty()) { if (dumpMode.equals("all")) { rowStart = 0; // length = parseMaxRow(solrParams); // this is the facetCount length = 10000000; } if (solrCoreName.equalsIgnoreCase("experiment")) { ArrayList<Integer> phenotypingCenterIds = new ArrayList<Integer>(); try { for (int i = 0; i < phenotypingCenter.length; i++) { phenotypingCenterIds.add(organisationDao .getOrganisationByName(phenotypingCenter[i].replaceAll("%20", " ")).getId()); } } catch (NullPointerException e) { log.error("Cannot find organisation ID for org with name " + phenotypingCenter); } List<String> zygList = null; if (zygosities != null) { zygList = Arrays.asList(zygosities); } String s = (sex.equalsIgnoreCase("null")) ? null : sex; dataRows = composeExperimentDataExportRows(parameterStableId, mgiGeneId, allele, s, phenotypingCenterIds, zygList, strains, pipelineStableId); } else if (solrCoreName.equalsIgnoreCase("genotype-phenotype")) { if (mgiGeneId != null) { dataRows = composeDataRowGeneOrPhenPage(mgiGeneId[0], request.getParameter("page"), solrFilters, request); } else if (mpId != null) { dataRows = composeDataRowGeneOrPhenPage(mpId, request.getParameter("page"), solrFilters, request); } } else if (dogoterm) { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeGene2GoAnnotationDataRows(json, request, dogoterm, gocollapse); } else if (gene2pfam) { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeGene2PfamClansDataRows(json, request); } else if (doAlleleRef) { dataRows = composeAlleleRefExportRows(length, rowStart, filterStr, dumpMode); } else { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeDataTableExportRows(query, solrCoreName, json, rowStart, length, showImgView, solrFilters, request, legacyOnly, fqStr); } } writeOutputFile(response, dataRows, fileType, fileName, wb); } private int parseMaxRow(String solrParams) { String[] paramsList = solrParams.split("&"); int facetCount = 0; for (String str : paramsList) { if (str.startsWith("facetCount=")) { String[] vals = str.split("="); facetCount = Integer.parseInt(vals[1]); } } return facetCount; } public List<String> composeExperimentDataExportRows(String[] parameterStableId, String[] geneAccession, String allele[], String gender, ArrayList<Integer> phenotypingCenterIds, List<String> zygosity, String[] strain, String[] pipelines) throws SolrServerException, IOException, URISyntaxException, SQLException { List<String> rows = new ArrayList(); SexType sex = null; if (gender != null) { sex = SexType.valueOf(gender); } if (phenotypingCenterIds == null) { throw new RuntimeException("ERROR: phenotypingCenterIds is null. Expected non-null value."); } if (phenotypingCenterIds.isEmpty()) { phenotypingCenterIds.add(null); } if (strain == null || strain.length == 0) { strain = new String[1]; strain[0] = null; } if (allele == null || allele.length == 0) { allele = new String[1]; allele[0] = null; } ArrayList<Integer> pipelineIds = new ArrayList<>(); if (pipelines != null) { for (String pipe : pipelines) { pipelineIds.add(ppDAO.getPhenotypePipelineByStableId(pipe).getId()); } } if (pipelineIds.isEmpty()) { pipelineIds.add(null); } List<ExperimentDTO> experimentList; for (int k = 0; k < parameterStableId.length; k++) { for (int mgiI = 0; mgiI < geneAccession.length; mgiI++) { for (Integer pCenter : phenotypingCenterIds) { for (Integer pipelineId : pipelineIds) { for (int strainI = 0; strainI < strain.length; strainI++) { for (int alleleI = 0; alleleI < allele.length; alleleI++) { experimentList = experimentService.getExperimentDTO(parameterStableId[k], pipelineId, geneAccession[mgiI], sex, pCenter, zygosity, strain[strainI]); if (experimentList.size() > 0) { for (ExperimentDTO experiment : experimentList) { rows.addAll(experiment.getTabbedToString(ppDAO)); } } } } } } } } return rows; } public List<String> composeDataTableExportRows(String query, String solrCoreName, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String solrParams, HttpServletRequest request, boolean legacyOnly, String fqStr) throws IOException, URISyntaxException { List<String> rows = null; if (solrCoreName.equals("gene")) { rows = composeGeneDataTableRows(json, request, legacyOnly); } else if (solrCoreName.equals("mp")) { rows = composeMpDataTableRows(json, request); } else if (solrCoreName.equals("ma")) { rows = composeMaDataTableRows(json, request); } else if (solrCoreName.equals("pipeline")) { rows = composeProtocolDataTableRows(json, request); } else if (solrCoreName.equals("images")) { rows = composeImageDataTableRows(query, json, iDisplayStart, iDisplayLength, showImgView, solrParams, request); } else if (solrCoreName.equals("impc_images")) { rows = composeImpcImageDataTableRows(query, json, iDisplayStart, iDisplayLength, showImgView, fqStr, request); } else if (solrCoreName.equals("disease")) { rows = composeDiseaseDataTableRows(json, request); } return rows; } private List<String> composeProtocolDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String impressBaseUrl = request.getAttribute("drupalBaseUrl").toString().replace("https", "http") + "/impress/impress/displaySOP/"; // String impressBaseUrl = request.getAttribute("drupalBaseUrl") + // "/impress/impress/displaySOP/"; List<String> rowData = new ArrayList(); rowData.add("Parameter\tProcedure\tProcedure Impress link\tPipeline"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("parameter_name")); JSONArray procedures = doc.getJSONArray("procedure_name"); JSONArray procedure_stable_keys = doc.getJSONArray("procedure_stable_key"); List<String> procedureLinks = new ArrayList<String>(); for (int p = 0; p < procedures.size(); p++) { // String procedure = procedures.get(p).toString(); String procedure_stable_key = procedure_stable_keys.get(p).toString(); procedureLinks.add(impressBaseUrl + procedure_stable_key); } // String procedure = doc.getString("procedure_name"); // data.add(procedure); data.add(StringUtils.join(procedures, "|")); // String procedure_stable_key = // doc.getString("procedure_stable_key"); // String procedureLink = impressBaseUrl + procedure_stable_key; // data.add(procedureLink); data.add(StringUtils.join(procedureLinks, "|")); data.add(doc.getString("pipeline_name")); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeImageDataTableRows(String query, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String solrParams, HttpServletRequest request) { // System.out.println("query: "+ query + " -- "+ solrParams); String mediaBaseUrl = config.get("mediaBaseUrl").replace("https:", "http:"); List<String> rowData = new ArrayList(); String mpBaseUrl = request.getAttribute("baseUrl") + "/phenotypes/"; String maBaseUrl = request.getAttribute("baseUrl") + "/anatomy/"; String geneBaseUrl = request.getAttribute("baseUrl") + "/genes/"; if (showImgView) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); rowData.add("Annotation term\tAnnotation id\tAnnotation id link\tImage link"); // column // names for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); List<String> data = new ArrayList(); List<String> lists = new ArrayList(); List<String> termLists = new ArrayList(); List<String> link_lists = new ArrayList(); String[] fields = { "annotationTermId", "expName", "symbol_gene" }; for (String fld : fields) { if (doc.has(fld)) { JSONArray list = doc.getJSONArray(fld); if (fld.equals("annotationTermId")) { JSONArray termList = doc.containsKey("annotationTermName") ? doc.getJSONArray("annotationTermName") : new JSONArray(); for (int l = 0; l < list.size(); l++) { String value = list.getString(l); String termVal = termList.size() == 0 ? NO_INFO_MSG : termList.getString(l); if (value.startsWith("MP:")) { link_lists.add(hostName + mpBaseUrl + value); termLists.add("MP:" + termVal); } if (value.startsWith("MA:")) { link_lists.add(hostName + maBaseUrl + value); termLists.add("MA:" + termVal); } lists.add(value); // id } } else if (fld.equals("symbol_gene")) { // gene symbol and its link for (int l = 0; l < list.size(); l++) { String[] parts = list.getString(l).split("_"); String symbol = parts[0]; String mgiId = parts[1]; termLists.add("Gene:" + symbol); lists.add(mgiId); link_lists.add(hostName + geneBaseUrl + mgiId); } } else if (fld.equals("expName")) { for (int l = 0; l < list.size(); l++) { String value = list.getString(l); termLists.add("Procedure:" + value); lists.add(NO_INFO_MSG); link_lists.add(NO_INFO_MSG); } } } } data.add(termLists.size() == 0 ? NO_INFO_MSG : StringUtils.join(termLists, "|")); // term // names data.add(StringUtils.join(lists, "|")); data.add(StringUtils.join(link_lists, "|")); data.add(mediaBaseUrl + "/" + doc.getString("largeThumbnailFilePath")); rowData.add(StringUtils.join(data, "\t")); } } else { // System.out.println("MODE: annotview " + showImgView); // annotation view // annotation view: images group by annotationTerm per row rowData.add( "Annotation type\tAnnotation term\tAnnotation id\tAnnotation id link\tRelated image count\tImages link"); // column // names JSONObject facetFields = json.getJSONObject("facet_counts").getJSONObject("facet_fields"); JSONArray sumFacets = solrIndex.mergeFacets(facetFields); int numFacets = sumFacets.size(); int quotient = (numFacets / 2) / iDisplayLength - ((numFacets / 2) % iDisplayLength) / iDisplayLength; int remainder = (numFacets / 2) % iDisplayLength; int start = iDisplayStart * 2; // 2 elements(name, count), hence // multiply by 2 int end = iDisplayStart == quotient * iDisplayLength ? (iDisplayStart + remainder) * 2 : (iDisplayStart + iDisplayLength) * 2; for (int i = start; i < end; i = i + 2) { List<String> data = new ArrayList(); // array element is an alternate of facetField and facetCount String[] names = sumFacets.get(i).toString().split("_"); if (names.length == 2) { // only want facet value of xxx_yyy String annotName = names[0]; Map<String, String> hm = solrIndex.renderFacetField(names, request.getAttribute("mappedHostname").toString(), request.getAttribute("baseUrl").toString()); data.add(hm.get("label")); data.add(annotName); data.add(hm.get("id")); // System.out.println("annotname: "+ annotName); if (hm.get("fullLink") != null) { data.add(hm.get("fullLink").toString()); } else { data.add(NO_INFO_MSG); } String imgCount = sumFacets.get(i + 1).toString(); data.add(imgCount); String facetField = hm.get("field"); solrParams = solrParams.replaceAll("&q=.+&", "&q=" + query + " AND " + facetField + ":\"" + names[0] + "\"&"); String imgSubSetLink = hostName + request.getAttribute("baseUrl") + "/imagesb?" + solrParams; data.add(imgSubSetLink); rowData.add(StringUtils.join(data, "\t")); } } } return rowData; } private List<String> composeImpcImageDataTableRows(String query, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String fqStrOri, HttpServletRequest request) throws IOException, URISyntaxException { // currently just use the solr field value // String mediaBaseUrl = config.get("impcMediaBaseUrl").replace("https:", "http:"); List<String> rowData = new ArrayList(); //String mediaBaseUrl = config.get("mediaBaseUrl"); String baseUrl = request.getAttribute("baseUrl").toString(); String mpBaseUrl = baseUrl + "/phenotypes/"; String maBaseUrl = baseUrl + "/anatomy/"; String geneBaseUrl = baseUrl + "/genes/"; if (showImgView) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // rowData.add("Annotation term\tAnnotation id\tAnnotation id // link\tProcedure\tGene symbol\tGene symbol link\tImage link"); // // column names rowData.add("Procedure\tGene symbol\tGene symbol link\tMA term\tMA term link\tImage link"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); // String[] fields = {"annotationTermName", "annotationTermId", // "expName", "symbol_gene"}; String[] fields = { "procedure_name", "gene_symbol", "ma_term" }; for (String fld : fields) { if (doc.has(fld)) { List<String> lists = new ArrayList(); if (fld.equals("gene_symbol")) { data.add(doc.getString("gene_symbol")); data.add(hostName + geneBaseUrl + doc.getString("gene_accession_id")); } else if (fld.equals("procedure_name")) { data.add(doc.getString("procedure_name")); } else if (fld.equals("ma_term")) { JSONArray maTerms = doc.getJSONArray("ma_term"); JSONArray maIds = doc.getJSONArray("ma_id"); List<String> ma_Terms = new ArrayList<>(); List<String> ma_links = new ArrayList<>(); for (int m = 0; m < maTerms.size(); m++) { ma_Terms.add(maTerms.get(m).toString()); ma_links.add(hostName + maBaseUrl + maIds.get(m).toString()); } data.add(StringUtils.join(ma_Terms, "|")); data.add(StringUtils.join(ma_links, "|")); } } else { /* * if ( fld.equals("annotationTermId") ){ * data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); * data.add(NO_INFO_MSG); } else if ( * fld.equals("symbol_gene") ){ */ if (fld.equals("gene_symbol")) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } else if (fld.equals("procedure_name")) { data.add(NO_INFO_MSG); } else if (fld.equals("ma_term")) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } } } data.add(doc.containsKey("jpeg_url") ? doc.getString("jpeg_url") : NO_INFO_MSG); rowData.add(StringUtils.join(data, "\t")); } } else { // annotation view: images group by annotationTerm per row //String mediaBaseUrl = config.get("mediaBaseUrl"); // need to add hostname as this is for excel and not browser String mediaBaseUrl = request.getAttribute("mappedHostname").toString() + baseUrl + "/impcImages/images?"; //System.out.println("MEDIABASEURL: "+ mediaBaseUrl); rowData.add( "Annotation type\tAnnotation term\tAnnotation id\tAnnotation id link\tRelated image count\tImages link"); // column // names String fqStr = query; String defaultQStr = "observation_type:image_record&qf=auto_suggest&defType=edismax"; if (query != "") { defaultQStr = "q=" + query + " AND " + defaultQStr; } else { defaultQStr = "q=" + defaultQStr; } String defaultFqStr = "fq=(biological_sample_group:experimental)"; JSONObject facetFields = json.getJSONObject("facet_counts").getJSONObject("facet_fields"); List<AnnotNameValCount> annots = solrIndex.mergeImpcFacets(json, baseUrl); int numFacets = annots.size(); int start = iDisplayStart; // 2 elements(name, count), hence // multiply by 2 int end = iDisplayStart + iDisplayLength; end = end > numFacets ? numFacets : end; for (int i = start; i < end; i++) { List<String> data = new ArrayList(); AnnotNameValCount annot = annots.get(i); String displayAnnotName = annot.name; data.add(displayAnnotName); String annotVal = annot.val; data.add(annotVal); if (annot.id != null) { data.add(annot.id); data.add(annot.link); } else { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } String thisFqStr = defaultFqStr + " AND " + annot.facet + ":\"" + annotVal + "\""; List pathAndImgCount = solrIndex.fetchImpcImagePathByAnnotName(query, thisFqStr); int imgCount = (int) pathAndImgCount.get(1); StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(imgCount); data.add(sb.toString()); String imgSubSetLink = mediaBaseUrl + defaultQStr + "&" + thisFqStr; //System.out.println("IMG LINK: " + imgSubSetLink ); data.add(imgSubSetLink); rowData.add(StringUtils.join(data, "\t")); } } return rowData; } private List<String> composeMpDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/phenotypes/"; List<String> rowData = new ArrayList(); rowData.add( "Mammalian phenotype term\tMammalian phenotype id\tMammalian phenotype id link\tMammalian phenotype definition\tMammalian phenotype synonym\tMammalian phenotype top level term\tComputationally mapped human phenotype terms\tComputationally mapped human phenotype term Ids\tPostqc call(s)"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("mp_term")); String mpId = doc.getString("mp_id"); data.add(mpId); data.add(hostName + baseUrl + mpId); if (doc.has("mp_definition")) { data.add(doc.getString("mp_definition")); } else { data.add(NO_INFO_MSG); } if (doc.has("mp_term_synonym")) { List<String> syns = new ArrayList(); JSONArray syn = doc.getJSONArray("mp_term_synonym"); for (int t = 0; t < syn.size(); t++) { syns.add(syn.getString(t)); } data.add(StringUtils.join(syns, "|")); } else { data.add(NO_INFO_MSG); } if (doc.has("top_level_mp_term")) { List<String> tops = new ArrayList(); JSONArray top = doc.getJSONArray("top_level_mp_term"); for (int t = 0; t < top.size(); t++) { tops.add(top.getString(t)); } data.add(StringUtils.join(tops, "|")); } else { data.add(NO_INFO_MSG); } if (doc.has("hp_term")) { Set<SimpleOntoTerm> hpTerms = mpService.getComputationalHPTerms(doc); List<String> terms = new ArrayList<String>(); List<String> ids = new ArrayList<String>(); for (SimpleOntoTerm term : hpTerms) { ids.add(term.getTermId()); terms.add(term.getTermName().equals("") ? NO_INFO_MSG : term.getTermName()); } data.add(StringUtils.join(terms, "|")); data.add(StringUtils.join(ids, "|")); } else { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } // number of genes annotated to this MP int numCalls = doc.containsKey("pheno_calls") ? doc.getInt("pheno_calls") : 0; data.add(Integer.toString(numCalls)); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeMaDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/anatomy/"; List<String> rowData = new ArrayList(); rowData.add( "Mouse adult gross anatomy term\tMouse adult gross anatomy id\tMouse adult gross anatomy id link\tMouse adult gross anatomy synonym"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("ma_term")); String maId = doc.getString("ma_id"); data.add(maId); data.add(hostName + baseUrl + maId); if (doc.has("ma_term_synonym")) { List<String> syns = new ArrayList(); JSONArray syn = doc.getJSONArray("ma_term_synonym"); for (int t = 0; t < syn.size(); t++) { syns.add(syn.getString(t)); } data.add(StringUtils.join(syns, "|")); } else { data.add(NO_INFO_MSG); } // will have these cols coming later /* * if(doc.has("mp_definition")) { * data.add(doc.getString("mp_definition")); } else { * data.add(NO_INFO_MSG); } * * if(doc.has("top_level_mp_term")) { List<String> tops = new * ArrayList<String>(); JSONArray top = * doc.getJSONArray("top_level_mp_term"); for(int t=0; * t<top.size();t++) { tops.add(top.getString(t)); } * data.add(StringUtils.join(tops, "|")); } else { * data.add(NO_INFO_MSG); } */ rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeGeneDataTableRows(JSONObject json, HttpServletRequest request, boolean legacyOnly) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); List<String> rowData = new ArrayList(); rowData.add( "Gene symbol\tHuman ortholog\tGene id\tGene name\tGene synonym\tProduction status\tPhenotype status\tPhenotype status link"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("marker_symbol")); if (doc.has("human_gene_symbol")) { List<String> hsynData = new ArrayList(); JSONArray hs = doc.getJSONArray("human_gene_symbol"); for (int s = 0; s < hs.size(); s++) { hsynData.add(hs.getString(s)); } data.add(StringUtils.join(hsynData, "|")); // use | as a // multiValue // separator in CSV // output } else { data.add(NO_INFO_MSG); } // MGI gene id data.add(doc.getString("mgi_accession_id")); // Sanger problem, they should have use string for marker_name and // not array // data.add(doc.getJSONArray("marker_name").getString(0)); // now corrected using httpdatasource in dataImportHandler if (doc.has("marker_name")) { data.add(doc.getString("marker_name")); } else { data.add(NO_INFO_MSG); } if (doc.has("marker_synonym")) { List<String> synData = new ArrayList(); JSONArray syn = doc.getJSONArray("marker_synonym"); for (int s = 0; s < syn.size(); s++) { synData.add(syn.getString(s)); } data.add(StringUtils.join(synData, "|")); // use | as a // multiValue // separator in CSV // output } else { data.add(NO_INFO_MSG); } // ES/Mice production status boolean toExport = true; String mgiId = doc.getString(GeneDTO.MGI_ACCESSION_ID); String genePageUrl = request.getAttribute("mappedHostname").toString() + request.getAttribute("baseUrl").toString() + "/genes/" + mgiId; String prodStatus = geneService.getProductionStatusForEsCellAndMice(doc, genePageUrl, toExport); data.add(prodStatus); String statusField = (doc.containsKey(GeneDTO.LATEST_PHENOTYPE_STATUS)) ? doc.getString(GeneDTO.LATEST_PHENOTYPE_STATUS) : null; Integer legacyPhenotypeStatus = (doc.containsKey(GeneDTO.LEGACY_PHENOTYPE_STATUS)) ? doc.getInt(GeneDTO.LEGACY_PHENOTYPE_STATUS) : null; Integer hasQc = (doc.containsKey(GeneDTO.HAS_QC)) ? doc.getInt(GeneDTO.HAS_QC) : null; String phenotypeStatus = geneService.getPhenotypingStatus(statusField, hasQc, legacyPhenotypeStatus, genePageUrl, toExport, legacyOnly); if (phenotypeStatus.isEmpty()) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); // link column } else if (phenotypeStatus.contains("___")) { // multiple phenotyping statusses, eg, complete and legacy String[] phStatuses = phenotypeStatus.split("___"); List<String> labelList = new ArrayList<>(); List<String> urlList = new ArrayList<>(); for (int c = 0; c < phStatuses.length; c++) { String[] parts = phStatuses[c].split("\\|"); if (parts.length != 2) { System.out.println( "fileExport: '" + phStatuses[c] + "' --- Expeced length 2 but got " + parts.length); } else { String url = parts[0].replace("https", "http"); String label = parts[1]; labelList.add(label); urlList.add(url); } } data.add(StringUtils.join(labelList, "|")); data.add(StringUtils.join(urlList, "|")); } else if (phenotypeStatus.startsWith("http://") || phenotypeStatus.startsWith("https://")) { String[] parts = phenotypeStatus.split("\\|"); if (parts.length != 2) { System.out.println("fileExport: '" + phenotypeStatus + "' --- Expeced length 2 but got " + parts.length); } else { String url = parts[0].replace("https", "http"); String label = parts[1]; data.add(label); data.add(url); } } else { data.add(phenotypeStatus); } // put together as tab delimited rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeDiseaseDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/disease/"; List<String> rowData = new ArrayList(); // column names rowData.add("Disease id" + "\tDisease id link" + "\tDisease name" + "\tSource" + "\tCurated genes from human (OMIM, Orphanet)" + "\tCurated genes from mouse (MGI)" + "\tCurated genes from human data with IMPC prediction" + "\tCurated genes from human data with MGI prediction" + "\tCandidate genes by phenotype - IMPC data" + "\tCandidate genes by phenotype - Novel IMPC prediction in linkage locus" + "\tCandidate genes by phenotype - MGI data" + "\tCandidate genes by phenotype - Novel MGI prediction in linkage locus"); for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); String omimId = doc.getString("disease_id"); data.add(omimId); data.add(hostName + baseUrl + omimId); data.add(doc.getString("disease_term")); data.add(doc.getString("disease_source")); data.add(doc.getString("human_curated")); data.add(doc.getString("mouse_curated")); data.add(doc.getString("impc_predicted_known_gene")); data.add(doc.getString("mgi_predicted_known_gene")); data.add(doc.getString("impc_predicted")); data.add(doc.getString("impc_novel_predicted_in_locus")); data.add(doc.getString("mgi_predicted")); data.add(doc.getString("mgi_novel_predicted_in_locus")); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeDataRowGeneOrPhenPage(String id, String pageName, String filters, HttpServletRequest request) { List<String> res = new ArrayList<>(); List<PhenotypeCallSummary> phenotypeList = new ArrayList(); PhenotypeFacetResult phenoResult; String targetGraphUrl = (String) request.getAttribute("mappedHostname") + request.getAttribute("baseUrl"); if (pageName.equalsIgnoreCase("gene")) { try { phenoResult = phenoDAO.getPhenotypeCallByGeneAccessionAndFilter(id, filters); phenotypeList = phenoResult.getPhenotypeCallSummaries(); } catch (HibernateException | JSONException e) { log.error("ERROR GETTING PHENOTYPE LIST"); e.printStackTrace(); phenotypeList = new ArrayList(); } catch (Exception e) { e.printStackTrace(); } ArrayList<GenePageTableRow> phenotypes = new ArrayList(); for (PhenotypeCallSummary pcs : phenotypeList) { GenePageTableRow pr = new GenePageTableRow(pcs, targetGraphUrl, config); phenotypes.add(pr); } Collections.sort(phenotypes); // sort in same order as gene page. res.add("Phenotype\tAllele\tZygosity\tSex\tProcedure | Parameter\tPhenotyping Center\tSource\tP Value\tGraph"); for (DataTableRow pr : phenotypes) { res.add(pr.toTabbedString("gene")); } } else if (pageName.equalsIgnoreCase("phenotype")) { phenotypeList = new ArrayList(); try { phenoResult = phenoDAO.getPhenotypeCallByMPAccessionAndFilter(id.replaceAll("\"", ""), filters); phenotypeList = phenoResult.getPhenotypeCallSummaries(); } catch (HibernateException | JSONException e) { log.error("ERROR GETTING PHENOTYPE LIST"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } ArrayList<PhenotypePageTableRow> phenotypes = new ArrayList(); res.add("Gene\tAllele\tZygosity\tSex\tPhenotype\tProcedure | Parameter\tPhenotyping Center\tSource\tP Value\tGraph"); for (PhenotypeCallSummary pcs : phenotypeList) { PhenotypePageTableRow pr = new PhenotypePageTableRow(pcs, targetGraphUrl, config); if (pr.getParameter() != null && pr.getProcedure() != null) { phenotypes.add(pr); } } Collections.sort(phenotypes); // sort in same order as phenotype // page. for (DataTableRow pr : phenotypes) { res.add(pr.toTabbedString("phenotype")); } } return res; } private List<String> composeGene2PfamClansDataRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // System.out.println(" GOT " + docs.size() + " docs"); String baseUrl = request.getAttribute("baseUrl") + "/genes/"; List<String> rowData = new ArrayList<>(); // column names // latest_phenotype_status,mgi_accession_id,marker_symbol,pfama_id,pfama_acc,clan_id,clan_acc,clan_desc String fields = "Gene Symbol" + "\tMGI gene link" + "\tPhenotyping status" + "\tPfam Id" + "\tClan Id" + "\tClan Acc" + "\tClan Description"; rowData.add(fields); String NOINFO = "no info available"; for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); String gId = doc.getString("mgi_accession_id"); String phenoStatus = doc.getString("latest_phenotype_status"); JSONArray _pfamaIds = doc.containsKey("pfama_id") ? doc.getJSONArray("pfama_id") : new JSONArray(); JSONArray _clanIds = doc.containsKey("clan_id") ? doc.getJSONArray("clan_id") : new JSONArray(); JSONArray _clanAccs = doc.containsKey("clan_acc") ? doc.getJSONArray("clan_acc") : new JSONArray(); JSONArray _clanDescs = doc.containsKey("clan_desc") ? doc.getJSONArray("clan_desc") : new JSONArray(); if (_pfamaIds.size() == 0) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); rowData.add(StringUtils.join(data, "\t")); } else { for (int j = 0; j < _clanIds.size(); j++) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(doc.containsKey("pfama_id") ? _pfamaIds.getString(j) : NOINFO); data.add(doc.containsKey("clan_id") ? _clanIds.getString(j) : NOINFO); data.add(doc.containsKey("clan_acc") ? _clanAccs.getString(j) : NOINFO); data.add(doc.containsKey("clan_desc") ? _clanDescs.getString(j) : NOINFO); rowData.add(StringUtils.join(data, "\t")); } } } return rowData; } private List<String> composeAlleleRefExportRows(int iDisplayLength, int iDisplayStart, String sSearch, String dumpMode) throws SQLException { List<String> rowData = new ArrayList<>(); rowData.add(referenceDAO.heading); List<ReferenceDTO> references = referenceDAO.getReferenceRows(sSearch); for (ReferenceDTO reference : references) { List<String> row = new ArrayList(); row.add(StringUtils.join(reference.getAlleleSymbols(), "|")); row.add(StringUtils.join(reference.getAlleleAccessionIds(), "|")); row.add(StringUtils.join(reference.getImpcGeneLinks(), "|")); row.add(StringUtils.join(reference.getMgiAlleleNames(), "|")); row.add(reference.getTitle()); row.add(reference.getJournal()); row.add(reference.getPmid()); row.add(reference.getDateOfPublication()); row.add(StringUtils.join(reference.getGrantIds(), "|")); row.add(StringUtils.join(reference.getGrantAgencies(), "|")); row.add(StringUtils.join(reference.getPaperUrls(), "|")); rowData.add(StringUtils.join(row, "\t")); } return rowData; } private List<String> composeAlleleRefEditExportRows(int iDisplayLength, int iDisplayStart, String sSearch, String dumpMode) throws SQLException { Connection conn = admintoolsDataSource.getConnection(); String like = "%" + sSearch + "%"; String query = null; if (!sSearch.isEmpty()) { query = "select * from allele_ref where " + " acc like ?" + " or symbol like ?" + " or pmid like ?" + " or date_of_publication like ?" + " or grant_id like ?" + " or agency like ?" + " or acronym like ?" + " order by reviewed desc" + " limit ?, ?"; } else { query = "select * from allele_ref order by reviewed desc limit ?,?"; } // System.out.println("query: "+ query); String mgiAlleleBaseUrl = "http://www.informatics.jax.org/allele/"; List<String> rowData = new ArrayList<>(); String fields = "Reviewed" + "\tMGI allele symbol" + "\tMGI allele id" + "\tMGI allele link" + "\tMGI allele name" + "\tPMID" + "\tDate of publication" + "\tGrant id" + "\tGrant agency" + "\tGrant acronym" + "\tPaper link"; rowData.add(fields); try (PreparedStatement p2 = conn.prepareStatement(query)) { if (!sSearch.isEmpty()) { for (int i = 1; i < 10; i++) { p2.setString(i, like); if (i == 8) { p2.setInt(i, iDisplayStart); } else if (i == 9) { p2.setInt(i, iDisplayLength); } } } else { p2.setInt(1, iDisplayStart); p2.setInt(2, iDisplayLength); } ResultSet resultSet = p2.executeQuery(); while (resultSet.next()) { List<String> data = new ArrayList<String>(); data.add(resultSet.getString("reviewed")); // rowData.add(resultSet.getString("acc")); String alleleSymbol = Tools.superscriptify(resultSet.getString("symbol")); data.add(alleleSymbol); String acc = resultSet.getString("acc"); String alLink = acc.equals("") ? "" : mgiAlleleBaseUrl + resultSet.getString("acc"); data.add(acc); data.add(alLink); data.add(resultSet.getString("name")); // rowData.add(resultSet.getString("name")); data.add(resultSet.getString("pmid")); data.add(resultSet.getString("date_of_publication")); data.add(resultSet.getString("grant_id")); data.add(resultSet.getString("agency")); data.add(resultSet.getString("acronym")); String url = resultSet.getString("paper_url"); if (url.equals("")) { data.add(url); } else { String[] urls = resultSet.getString("paper_url").split(","); List<String> links = new ArrayList<>(); for (int i = 0; i < urls.length; i++) { links.add(urls[i]); } data.add(StringUtils.join(links, "|")); } rowData.add(StringUtils.join(data, "\t")); } } catch (Exception e) { e.printStackTrace(); } conn.close(); // System.out.println("Rows returned: "+rowData.size()); return rowData; } private List<String> composeGene2GoAnnotationDataRows(JSONObject json, HttpServletRequest request, boolean hasgoterm, boolean gocollapse) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // System.out.println(" GOT " + docs.size() + " docs"); String baseUrl = request.getAttribute("baseUrl") + "/genes/"; // List<String> evidsList = new // ArrayList<String>(Arrays.asList(request.getParameter("goevids").split(","))); List<String> rowData = new ArrayList(); // column names String fields = null; if (gocollapse) { fields = "Gene Symbol" + "\tIMPC gene link" + "\tGO annotated" + "\tGO evidence Category"; } else { fields = "Gene Symbol" + "\tIMPC gene link" + "\tPhenotyping status" + "\tUniprot protein" + "\tGO Term Id" + "\tGO Term Name" + "\tGO Term Evidence" + "\tGO evidence Category" + "\tGO Term Domain"; } rowData.add(fields); // GO evidence code ranking mapping Map<String, Integer> codeRank = commonUtils.getGoCodeRank(); // GO evidence rank to category mapping Map<Integer, String> evidRankCat = SolrIndex.getGomapCategory(); String NOINFO = "no info available"; for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); String gId = doc.getString("mgi_accession_id"); String phenoStatus = doc.containsKey("latest_phenotype_status") ? doc.getString("latest_phenotype_status") : NOINFO; if (!doc.containsKey("evidCodeRank")) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); rowData.add(StringUtils.join(data, "\t")); } else if (gocollapse) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(Integer.toString(doc.getInt("go_count"))); int evidCodeRank = doc.getInt("evidCodeRank"); data.add(evidRankCat.get(evidCodeRank)); rowData.add(StringUtils.join(data, "\t")); } else { int evidCodeRank = doc.getInt("evidCodeRank"); JSONArray _goTermIds = doc.containsKey("go_term_id") ? doc.getJSONArray("go_term_id") : new JSONArray(); JSONArray _goTermNames = doc.containsKey("go_term_name") ? doc.getJSONArray("go_term_name") : new JSONArray(); JSONArray _goTermEvids = doc.containsKey("go_term_evid") ? doc.getJSONArray("go_term_evid") : new JSONArray(); JSONArray _goTermDomains = doc.containsKey("go_term_domain") ? doc.getJSONArray("go_term_domain") : new JSONArray(); JSONArray _goUniprotAccs = doc.containsKey("go_uniprot") ? doc.getJSONArray("go_uniprot") : new JSONArray(); for (int j = 0; j < _goTermEvids.size(); j++) { String evid = _goTermEvids.get(j).toString(); if (codeRank.get(evid) == evidCodeRank) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); String go2Uniprot = _goUniprotAccs.size() > 0 ? _goUniprotAccs.get(j).toString() : NOINFO; String uniprotAcc = go2Uniprot.replaceAll("[A-Z0-9:]+__", ""); data.add(uniprotAcc); data.add(_goTermIds.size() > 0 ? _goTermIds.get(j).toString() : NOINFO); data.add(_goTermNames.size() > 0 ? _goTermNames.get(j).toString() : NOINFO); data.add(_goTermEvids.size() > 0 ? _goTermEvids.get(j).toString() : NOINFO); data.add(evidRankCat.get(evidCodeRank)); data.add(_goTermDomains.size() > 0 ? _goTermDomains.get(j).toString() : NOINFO); rowData.add(StringUtils.join(data, "\t")); } } } } return rowData; } @RequestMapping(value = "/impc2gwasExport", method = RequestMethod.GET) public void exportImpc2GwasMappingAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "mgiGeneSymbol", required = true) String mgiGeneSymbol, @RequestParam(value = "gridFields", required = true) String gridFields, @RequestParam(value = "currentTraitName", required = false) String currentTraitName, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { List<String> dataRows = fetchImpc2GwasMappingData(request, mgiGeneSymbol, gridFields, currentTraitName); Workbook wb = null; String fileName = "impc_to_Gwas_mapping_dataset"; writeOutputFile(response, dataRows, fileType, fileName, wb); } private List<String> fetchImpc2GwasMappingData(HttpServletRequest request, String mgiGeneSymbol, String gridFields, String currentTraitName) throws SQLException { // GWAS Gene to IMPC gene mapping List<GwasDTO> gwasMappings = gwasDao.getGwasMappingRows("mgi_gene_symbol", mgiGeneSymbol.toUpperCase()); // System.out.println("FileExportController FOUND " + // gwasMappings.size() + " phenotype to gwas trait mappings"); List<String> rowData = new ArrayList(); rowData.add(gridFields); for (GwasDTO gw : gwasMappings) { String traitName = gw.getDiseaseTrait(); if (currentTraitName != null && !traitName.equals(currentTraitName)) { continue; } List<String> data = new ArrayList(); data.add(gw.getMgiGeneSymbol()); data.add(gw.getMgiGeneId()); data.add(gw.getMgiAlleleId()); data.add(gw.getMgiAlleleName()); data.add(gw.getMouseGender()); data.add(gw.getMpTermId()); data.add(gw.getMpTermName()); data.add(traitName); data.add(gw.getSnpId()); data.add(Float.toString(gw.getPvalue())); data.add(gw.getMappedGene()); data.add(gw.getReportedGene()); data.add(gw.getUpstreamGene()); data.add(gw.getDownstreamGene()); data.add(gw.getPhenoMappingCategory()); rowData.add(StringUtils.join(data, "\t")); } return rowData; } @RequestMapping(value = "/bqExport", method = RequestMethod.POST) public void exportBqTableAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "coreName", required = true) String dataTypeName, @RequestParam(value = "idList", required = true) String idlist, @RequestParam(value = "gridFields", required = true) String gridFields, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { String dumpMode = "all"; List<String> queryIds = Arrays.asList(idlist.split(",")); Long time = System.currentTimeMillis(); List<String> mgiIds = new ArrayList<>(); List<GeneDTO> genes = new ArrayList<>(); List<QueryResponse> solrResponses = new ArrayList<>(); List<String> batchIdList = new ArrayList<>(); String batchIdListStr = null; int counter = 0; for (String id : queryIds) { counter++; // do the batch size if (counter % 500 == 0) { batchIdList.add(id); // batch solr query batchIdListStr = StringUtils.join(batchIdList, ","); // System.out.println(batchIdListStr); solrResponses.add(solrIndex.getBatchQueryJson(batchIdListStr, gridFields, dataTypeName)); batchIdList = new ArrayList<>(); } else { batchIdList.add(id); } } if (batchIdList.size() > 0) { // do the rest // batch solr query batchIdListStr = StringUtils.join(batchIdList, ","); solrResponses.add(solrIndex.getBatchQueryJson(batchIdListStr, gridFields, dataTypeName)); } List<String> dataRows = composeBatchQueryDataTableRows(solrResponses, dataTypeName, gridFields, request, queryIds); Workbook wb = null; String fileName = "batch_query_dataset"; writeOutputFile(response, dataRows, fileType, fileName, wb); } private List<String> composeBatchQueryDataTableRows(List<QueryResponse> solrResponses, String dataTypeName, String gridFields, HttpServletRequest request, List<String> queryIds) throws UnsupportedEncodingException { Set<String> foundIds = new HashSet<>(); System.out.println("Number of responses: " + solrResponses.size()); SolrDocumentList results = new SolrDocumentList(); for (QueryResponse solrResponse : solrResponses) { results.addAll(solrResponse.getResults()); } int totalDocs = results.size(); System.out.println("TOTAL DOCS FOUND: " + totalDocs); String hostName = request.getAttribute("mappedHostname").toString().replace("https:", "http:"); String baseUrl = request.getAttribute("baseUrl").toString(); String NA = "Info not available"; String imgBaseUrl = request.getAttribute("baseUrl") + "/impcImages/images?"; String oriDataTypeNAme = dataTypeName; if (dataTypeName.equals("ensembl") || dataTypeName.equals("marker_symbol")) { dataTypeName = "gene"; } Map<String, String> dataTypeId = new HashMap<>(); dataTypeId.put("gene", "mgi_accession_id"); dataTypeId.put("mp", "mp_id"); dataTypeId.put("ma", "ma_id"); dataTypeId.put("hp", "hp_id"); dataTypeId.put("disease", "disease_id"); Map<String, String> dataTypePath = new HashMap<>(); dataTypePath.put("gene", "genes"); dataTypePath.put("mp", "phenotypes"); dataTypePath.put("ma", "anatomy"); dataTypePath.put("hp", ""); dataTypePath.put("disease", "disease"); // column names // String idLinkColName = dataTypeId.get(dataType) + "_link"; String idLinkColName = "id_link"; gridFields = idLinkColName + "," + gridFields; // xx_id_link column only // for export, not // dataTable String[] cols = StringUtils.split(gridFields, ","); // List<String> foundIds = new ArrayList<>(); // swap cols cols[0] = dataTypeId.get(dataTypeName); cols[1] = idLinkColName; List<String> colList = new ArrayList<>(); for (int i = 0; i < cols.length; i++) { colList.add(cols[i]); } List<String> rowData = new ArrayList(); rowData.add(StringUtils.join(colList, "\t")); System.out.println("grid fields: " + colList); for (int i = 0; i < results.size(); i++) { SolrDocument doc = results.get(i); System.out.println("Working on document " + i + " of " + totalDocs); Map<String, Collection<Object>> docMap = doc.getFieldValuesMap(); // Note // getFieldValueMap() // returns // only // String // System.out.println("DOCMAP: "+docMap.toString()); List<String> orthologousDiseaseIdAssociations = new ArrayList<>(); List<String> orthologousDiseaseTermAssociations = new ArrayList<>(); List<String> phenotypicDiseaseIdAssociations = new ArrayList<>(); List<String> phenotypicDiseaseTermAssociations = new ArrayList<>(); if (docMap.get("mgi_accession_id") != null && !(dataTypeName.equals("ma") || dataTypeName.equals("disease"))) { Collection<Object> mgiGeneAccs = docMap.get("mgi_accession_id"); for (Object acc : mgiGeneAccs) { String mgi_gene_id = (String) acc; // System.out.println("mgi_gene_id: "+ mgi_gene_id); GeneIdentifier geneIdentifier = new GeneIdentifier(mgi_gene_id, mgi_gene_id); List<DiseaseAssociationSummary> diseaseAssociationSummarys = new ArrayList<>(); try { // log.info("{} - getting disease-gene associations // using cutoff {}", geneIdentifier, rawScoreCutoff); diseaseAssociationSummarys = phenoDigmDao.getGeneToDiseaseAssociationSummaries(geneIdentifier, rawScoreCutoff); //System.out.println("received " + diseaseAssociationSummarys.size() + " disease-gene associations"); // log.info("{} - received {} disease-gene // associations", geneIdentifier, // diseaseAssociationSummarys.size()); } catch (RuntimeException e) { log.error(ExceptionUtils.getFullStackTrace(e)); // log.error("Error retrieving disease data for {}", // geneIdentifier); } for (DiseaseAssociationSummary diseaseAssociationSummary : diseaseAssociationSummarys) { AssociationSummary associationSummary = diseaseAssociationSummary.getAssociationSummary(); if (associationSummary.isAssociatedInHuman()) { // System.out.println("DISEASE ID: " + // diseaseAssociationSummary.getDiseaseIdentifier().toString()); // System.out.println("DISEASE ID: " + // diseaseAssociationSummary.getDiseaseIdentifier().getDatabaseAcc()); // System.out.println("DISEASE TERM: " + // diseaseAssociationSummary.getDiseaseTerm()); orthologousDiseaseIdAssociations .add(diseaseAssociationSummary.getDiseaseIdentifier().toString()); orthologousDiseaseTermAssociations.add(diseaseAssociationSummary.getDiseaseTerm()); } else { phenotypicDiseaseIdAssociations .add(diseaseAssociationSummary.getDiseaseIdentifier().toString()); phenotypicDiseaseTermAssociations.add(diseaseAssociationSummary.getDiseaseTerm()); } } } } List<String> data = new ArrayList(); // for (String fieldName : doc.getFieldNames()) { for (int k = 0; k < cols.length; k++) { String fieldName = cols[k]; // System.out.println("DataTableController: "+ fieldName + " - // value: " + docMap.get(fieldName)); if (fieldName.equals("id_link")) { Collection<Object> accs = docMap.get(dataTypeId.get(dataTypeName)); String accStr = null; for (Object acc : accs) { accStr = (String) acc; } // System.out.println("idlink id: " + accStr); if (!oriDataTypeNAme.equals("ensembl") && !oriDataTypeNAme.equals("marker_symbol")) { System.out.println("idlink check: " + accStr); foundIds.add("\"" + accStr + "\""); } String link = null; if (dataTypePath.get(dataTypeName).isEmpty()) { link = ""; } else { link = hostName + baseUrl + "/" + dataTypePath.get(dataTypeName) + "/" + accStr; } // System.out.println("idlink: " + link); data.add(link); } else if (fieldName.equals("images_link")) { String impcImgBaseUrl = baseUrl + "/impcImages/images?"; String qryField = null; String imgQryField = null; if (dataTypeName.equals("gene")) { qryField = "mgi_accession_id"; imgQryField = "gene_accession_id"; } else if (dataTypeName.equals("ma")) { qryField = "ma_id"; imgQryField = "ma_id"; } Collection<Object> accs = docMap.get(qryField); String accStr = null; for (Object acc : accs) { accStr = imgQryField + ":\"" + (String) acc + "\""; } String imgLink = "<a target='_blank' href='" + hostName + impcImgBaseUrl + "q=" + accStr + " AND observation_type:image_record&fq=biological_sample_group:experimental" + "'>image url</a>"; data.add(imgLink); } else if (docMap.get(fieldName) == null) { String vals = NA; if (fieldName.equals("disease_id_by_gene_orthology")) { vals = orthologousDiseaseIdAssociations.size() == 0 ? NA : StringUtils.join(orthologousDiseaseIdAssociations, ", "); } else if (fieldName.equals("disease_term_by_gene_orthology")) { vals = orthologousDiseaseTermAssociations.size() == 0 ? NA : StringUtils.join(orthologousDiseaseTermAssociations, ", "); } else if (fieldName.equals("disease_id_by_phenotypic_similarity")) { vals = phenotypicDiseaseIdAssociations.size() == 0 ? NA : StringUtils.join(phenotypicDiseaseIdAssociations, ", "); } else if (fieldName.equals("disease_term_by_phenotypic_similarity")) { vals = phenotypicDiseaseTermAssociations.size() == 0 ? NA : StringUtils.join(phenotypicDiseaseTermAssociations, ", "); } data.add(vals); } else { try { String value = null; // System.out.println("TEST CLASS: "+ // docMap.get(fieldName).getClass()); try { Collection<Object> vals = docMap.get(fieldName); Set<Object> valSet = new HashSet<>(vals); if (oriDataTypeNAme.equals("ensembl") && fieldName.equals("ensembl_gene_id")) { for (Object val : valSet) { foundIds.add("\"" + val + "\""); } } if (oriDataTypeNAme.equals("marker_symbol") && fieldName.equals("marker_symbol")) { for (Object val : valSet) { foundIds.add("\"" + val.toString().toUpperCase() + "\""); } } else if (dataTypeName.equals("hp") && dataTypeId.get(dataTypeName).equals(fieldName)) { for (Object val : valSet) { foundIds.add("\"" + val + "\""); } } value = StringUtils.join(valSet, "|"); /* * if ( !dataTypeName.equals("hp") && * dataTypeId.get(dataTypeName).equals(fieldName) ){ * String coreName = * dataTypeName.equals("marker_symbol") || * dataTypeName.equals("ensembl") ? "gene" : * dataTypeName; foundIds.add("\"" + value + "\""); * * System.out.println("fieldname: " + fieldName + * " datatype: " + dataTypeName); //value = * "<a target='_blank' href='" + hostName + baseUrl * + "/" + dataTypePath.get(coreName) + "/" + value * + "'>" + value + "</a>"; } else if ( * dataTypeName.equals("hp") && * dataTypeId.get(dataTypeName).equals(fieldName) ){ * foundIds.add("\"" + value + "\""); } */ } catch (ClassCastException c) { value = docMap.get(fieldName).toString(); } // System.out.println("row " + i + ": field: " + k + " // -- " + fieldName + " - " + value); data.add(value); } catch (Exception e) { // e.printStackTrace(); if (e.getMessage().equals("java.lang.Integer cannot be cast to java.lang.String")) { Collection<Object> vals = docMap.get(fieldName); if (vals.size() > 0) { Iterator it = vals.iterator(); String value = (String) it.next(); // String value = Integer.toString(val); data.add(value); } } } } } // System.out.println("DATA: "+ StringUtils.join(data, "\t") ); rowData.add(StringUtils.join(data, "\t")); } // find the ids that are not found and displays them to users ArrayList nonFoundIds = (java.util.ArrayList) CollectionUtils.disjunction(queryIds, new ArrayList(foundIds)); // System.out.println("Query ids: "+ queryIds); // System.out.println("Found ids: "+ new ArrayList(foundIds)); System.out.println("non found ids: " + nonFoundIds.size()); for (int i = 0; i < nonFoundIds.size(); i++) { List<String> data = new ArrayList<String>(); for (int l = 0; l < cols.length; l++) { data.add(l == 0 ? nonFoundIds.get(i).toString().replaceAll("\"", "") : NA); } rowData.add(StringUtils.join(data, "\t")); } return rowData; } private void writeOutputFile(HttpServletResponse response, List<String> dataRows, String fileType, String fileName, Workbook wb) { response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); String outfile = fileName + "." + fileType; try { System.out.println("File to export: " + outfile); if (fileType.equals("tsv")) { response.setContentType("text/tsv; charset=utf-8"); response.setHeader("Content-disposition", "attachment; filename=" + outfile); // ServletOutputStream output = response.getOutputStream(); // ckc note: switch to use getWriter() so that we don't get // error like // java.io.CharConversionException: Not an ISO 8859-1 character // and if we do, the error will cause the dump to end // prematurely // and we may not get the full rows (depending on which row // causes error) PrintWriter output = response.getWriter(); for (String line : dataRows) { // System.out.println("line: " + line); line = line.replaceAll("\\t//", "\thttp://"); output.println(line); } output.flush(); output.close(); } else if (fileType.equals("xls")) { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + outfile); String sheetName = fileName; String[] titles = null; String[][] tableData = new String[0][0]; if (!dataRows.isEmpty()) { // titles = dataRows.remove(0).split("\t"); titles = dataRows.get(0).split("\t"); tableData = Tools.composeXlsTableData(dataRows); } wb = new ExcelWorkBook(titles, tableData, sheetName).fetchWorkBook(); ServletOutputStream output = response.getOutputStream(); try { wb.write(output); output.close(); } catch (IOException ioe) { log.error("ExcelWorkBook Error: " + ioe.getMessage()); ioe.printStackTrace(); } } } catch (Exception e) { log.error("Error: " + e.getMessage()); e.printStackTrace(); } } }
web/src/main/java/uk/ac/ebi/phenotype/web/controller/FileExportController.java
/******************************************************************************* * Copyright © 2013 - 2015 EMBL - European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package uk.ac.ebi.phenotype.web.controller; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.poi.ss.usermodel.Workbook; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.hibernate.HibernateException; import org.mousephenotype.cda.db.dao.*; import org.mousephenotype.cda.db.pojo.*; import org.mousephenotype.cda.db.pojo.ReferenceDTO; import org.mousephenotype.cda.enumerations.SexType; import org.mousephenotype.cda.solr.generic.util.PhenotypeCallSummarySolr; import org.mousephenotype.cda.solr.generic.util.PhenotypeFacetResult; import org.mousephenotype.cda.solr.generic.util.Tools; import org.mousephenotype.cda.solr.service.ExperimentService; import org.mousephenotype.cda.solr.service.GeneService; import org.mousephenotype.cda.solr.service.MpService; import org.mousephenotype.cda.solr.service.SolrIndex; import org.mousephenotype.cda.solr.service.SolrIndex.AnnotNameValCount; import org.mousephenotype.cda.solr.service.dto.*; import org.mousephenotype.cda.solr.web.dto.DataTableRow; import org.mousephenotype.cda.solr.web.dto.GenePageTableRow; import org.mousephenotype.cda.solr.web.dto.PhenotypePageTableRow; import org.mousephenotype.cda.solr.web.dto.SimpleOntoTerm; import org.mousephenotype.cda.utilities.CommonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import uk.ac.ebi.generic.util.ExcelWorkBook; import uk.ac.sanger.phenodigm2.dao.PhenoDigmWebDao; import uk.ac.sanger.phenodigm2.model.GeneIdentifier; import uk.ac.sanger.phenodigm2.web.AssociationSummary; import uk.ac.sanger.phenodigm2.web.DiseaseAssociationSummary; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; @Controller public class FileExportController { protected CommonUtils commonUtils = new CommonUtils(); private final Logger log = LoggerFactory.getLogger(this.getClass().getCanonicalName()); @Autowired public PhenotypeCallSummaryDAO phenotypeCallSummaryDAO; @Autowired private SolrIndex solrIndex; @Autowired private GeneService geneService; @Autowired @Qualifier("phenotypePipelineDAOImpl") private PhenotypePipelineDAO ppDAO; @Resource(name = "globalConfiguration") private Map<String, String> config; @Autowired private ExperimentService experimentService; @Autowired OrganisationDAO organisationDao; @Autowired StrainDAO strainDAO; @Autowired AlleleDAO alleleDAO; @Autowired private MpService mpService; @Autowired private PhenotypeCallSummarySolr phenoDAO; private String NO_INFO_MSG = "No information available"; private String hostName; @Autowired @Qualifier("admintoolsDataSource") private DataSource admintoolsDataSource; @Autowired private ReferenceDAO referenceDAO; @Autowired private GwasDAO gwasDao; @Autowired private GenomicFeatureDAO genesDao; @Autowired private PhenoDigmWebDao phenoDigmDao; private final double rawScoreCutoff = 1.97; /** * Return a TSV formatted response which contains all datapoints * * @param phenotypingCenterParameter * @param pipelineStableId * @param procedureStableId * @param parameterStableId * @param alleleAccession * @param sexesParameter * @param zygositiesParameter * @param strainParameter * @return * @throws SolrServerException * @throws IOException * @throws URISyntaxException */ @ResponseBody @RequestMapping(value = "/exportraw", method = RequestMethod.GET) public String getExperimentalData( @RequestParam(value = "phenotyping_center", required = true) String phenotypingCenterParameter, @RequestParam(value = "pipeline_stable_id", required = true) String pipelineStableId, @RequestParam(value = "procedure_stable_id", required = true) String procedureStableId, @RequestParam(value = "parameter_stable_id", required = true) String parameterStableId, @RequestParam(value = "allele_accession", required = true) String alleleAccession, @RequestParam(value = "sex", required = false) String[] sexesParameter, @RequestParam(value = "zygosity", required = false) String[] zygositiesParameter, @RequestParam(value = "strain", required = false) String strainParameter) throws SolrServerException, IOException, URISyntaxException { Organisation phenotypingCenter = organisationDao.getOrganisationByName(phenotypingCenterParameter); Pipeline pipeline = ppDAO.getPhenotypePipelineByStableId(pipelineStableId); Parameter parameter = ppDAO.getParameterByStableId(parameterStableId); Allele allele = alleleDAO.getAlleleByAccession(alleleAccession); SexType sex = (sexesParameter != null && sexesParameter.length > 1) ? SexType.valueOf(sexesParameter[0]) : null; List<String> zygosities = (zygositiesParameter == null) ? null : Arrays.asList(zygositiesParameter); String center = phenotypingCenter.getName(); Integer centerId = phenotypingCenter.getId(); String geneAcc = allele.getGene().getId().getAccession(); String alleleAcc = allele.getId().getAccession(); String strainAccession = null; if (strainParameter != null) { Strain s = strainDAO.getStrainByName(strainParameter); if (s != null) { strainAccession = s.getId().getAccession(); } } List<ExperimentDTO> experiments = experimentService.getExperimentDTO(parameter.getId(), pipeline.getId(), geneAcc, sex, centerId, zygosities, strainAccession, null, Boolean.FALSE, alleleAcc); List<String> rows = new ArrayList<>(); rows.add(StringUtils.join(new String[] { "Experiment", "Center", "Pipeline", "Procedure", "Parameter", "Strain", "Colony", "Gene", "Allele", "MetadataGroup", "Zygosity", "Sex", "AssayDate", "Value", "Metadata" }, ", ")); Integer i = 1; for (ExperimentDTO experiment : experiments) { // Adding all data points to the export Set<ObservationDTO> observations = experiment.getControls(); observations.addAll(experiment.getMutants()); for (ObservationDTO observation : observations) { List<String> row = new ArrayList<>(); row.add("Exp" + i.toString()); row.add(center); row.add(pipelineStableId); row.add(procedureStableId); row.add(parameterStableId); row.add(observation.getStrain()); row.add((observation.getGroup().equals("control")) ? "+/+" : observation.getColonyId()); row.add((observation.getGroup().equals("control")) ? "\"\"" : geneAcc); row.add((observation.getGroup().equals("control")) ? "\"\"" : alleleAcc); row.add((observation.getMetadataGroup() != null && !observation.getMetadataGroup().isEmpty()) ? observation.getMetadataGroup() : "\"\""); row.add((observation.getZygosity() != null && !observation.getZygosity().isEmpty()) ? observation.getZygosity() : "\"\""); row.add(observation.getSex()); row.add(observation.getDateOfExperimentString()); String dataValue = observation.getCategory(); if (dataValue == null) { dataValue = observation.getDataPoint().toString(); } row.add(dataValue); row.add("\"" + StringUtils.join(observation.getMetadata(), "::") + "\""); rows.add(StringUtils.join(row, ", ")); } // Next experiment i++; } return StringUtils.join(rows, "\n"); } /** * <p> * Export table as TSV or Excel file. * </p> * * @param model * @return */ @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportTableAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "externalDbId", required = true) Integer extDbId, @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "fileName", required = true) String fileName, @RequestParam(value = "legacyOnly", required = false, defaultValue = "false") Boolean legacyOnly, @RequestParam(value = "allele_accession", required = false) String[] allele, @RequestParam(value = "rowStart", required = false) Integer rowStart, @RequestParam(value = "length", required = false) Integer length, @RequestParam(value = "panel", required = false) String panelName, @RequestParam(value = "mpId", required = false) String mpId, @RequestParam(value = "mpTerm", required = false) String mpTerm, @RequestParam(value = "mgiGeneId", required = false) String[] mgiGeneId, @RequestParam(value = "parameterStableId", required = false) String[] parameterStableId, // should // be // filled // for // graph // data // export @RequestParam(value = "zygosity", required = false) String[] zygosities, // should // be // filled // for // graph // data // export @RequestParam(value = "strains", required = false) String[] strains, // should // be // filled // for // graph // data // export @RequestParam(value = "geneSymbol", required = false) String geneSymbol, @RequestParam(value = "solrCoreName", required = false) String solrCoreName, @RequestParam(value = "params", required = false) String solrFilters, @RequestParam(value = "gridFields", required = false) String gridFields, @RequestParam(value = "showImgView", required = false, defaultValue = "false") Boolean showImgView, @RequestParam(value = "dumpMode", required = false) String dumpMode, @RequestParam(value = "baseUrl", required = false) String baseUrl, @RequestParam(value = "sex", required = false) String sex, @RequestParam(value = "phenotypingCenter", required = false) String[] phenotypingCenter, @RequestParam(value = "pipelineStableId", required = false) String[] pipelineStableId, @RequestParam(value = "dogoterm", required = false, defaultValue = "false") Boolean dogoterm, @RequestParam(value = "gocollapse", required = false, defaultValue = "false") Boolean gocollapse, @RequestParam(value = "gene2pfam", required = false, defaultValue = "false") Boolean gene2pfam, @RequestParam(value = "doAlleleRef", required = false, defaultValue = "false") Boolean doAlleleRef, @RequestParam(value = "filterStr", required = false) String filterStr, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { hostName = request.getAttribute("mappedHostname").toString().replace("https:", "http:"); System.out.println("------------\nEXPORT \n---------"); String query = "*:*"; // default String fqStr = null; log.debug("solr params: " + solrFilters); String[] pairs = solrFilters.split("&"); for (String pair : pairs) { try { String[] parts = pair.split("="); if (parts[0].equals("q")) { query = parts[1]; } else if (parts[0].equals("fq")) { fqStr = parts[1]; } } catch (Exception e) { log.error("Error getting value of q"); e.printStackTrace(); } } Workbook wb = null; List<String> dataRows = new ArrayList(); // Default to exporting 10 rows length = length != null ? length : 10; panelName = panelName == null ? "" : panelName; if (!solrCoreName.isEmpty()) { if (dumpMode.equals("all")) { rowStart = 0; // length = parseMaxRow(solrParams); // this is the facetCount length = 10000000; } if (solrCoreName.equalsIgnoreCase("experiment")) { ArrayList<Integer> phenotypingCenterIds = new ArrayList<Integer>(); try { for (int i = 0; i < phenotypingCenter.length; i++) { phenotypingCenterIds.add(organisationDao .getOrganisationByName(phenotypingCenter[i].replaceAll("%20", " ")).getId()); } } catch (NullPointerException e) { log.error("Cannot find organisation ID for org with name " + phenotypingCenter); } List<String> zygList = null; if (zygosities != null) { zygList = Arrays.asList(zygosities); } String s = (sex.equalsIgnoreCase("null")) ? null : sex; dataRows = composeExperimentDataExportRows(parameterStableId, mgiGeneId, allele, s, phenotypingCenterIds, zygList, strains, pipelineStableId); } else if (solrCoreName.equalsIgnoreCase("genotype-phenotype")) { if (mgiGeneId != null) { dataRows = composeDataRowGeneOrPhenPage(mgiGeneId[0], request.getParameter("page"), solrFilters, request); } else if (mpId != null) { dataRows = composeDataRowGeneOrPhenPage(mpId, request.getParameter("page"), solrFilters, request); } } else if (dogoterm) { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeGene2GoAnnotationDataRows(json, request, dogoterm, gocollapse); } else if (gene2pfam) { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeGene2PfamClansDataRows(json, request); } else if (doAlleleRef) { dataRows = composeAlleleRefExportRows(length, rowStart, filterStr, dumpMode); } else { JSONObject json = solrIndex.getDataTableExportRows(solrCoreName, solrFilters, gridFields, rowStart, length, showImgView); dataRows = composeDataTableExportRows(query, solrCoreName, json, rowStart, length, showImgView, solrFilters, request, legacyOnly, fqStr); } } writeOutputFile(response, dataRows, fileType, fileName, wb); } private int parseMaxRow(String solrParams) { String[] paramsList = solrParams.split("&"); int facetCount = 0; for (String str : paramsList) { if (str.startsWith("facetCount=")) { String[] vals = str.split("="); facetCount = Integer.parseInt(vals[1]); } } return facetCount; } public List<String> composeExperimentDataExportRows(String[] parameterStableId, String[] geneAccession, String allele[], String gender, ArrayList<Integer> phenotypingCenterIds, List<String> zygosity, String[] strain, String[] pipelines) throws SolrServerException, IOException, URISyntaxException, SQLException { List<String> rows = new ArrayList(); SexType sex = null; if (gender != null) { sex = SexType.valueOf(gender); } if (phenotypingCenterIds == null) { throw new RuntimeException("ERROR: phenotypingCenterIds is null. Expected non-null value."); } if (phenotypingCenterIds.isEmpty()) { phenotypingCenterIds.add(null); } if (strain == null || strain.length == 0) { strain = new String[1]; strain[0] = null; } if (allele == null || allele.length == 0) { allele = new String[1]; allele[0] = null; } ArrayList<Integer> pipelineIds = new ArrayList<>(); if (pipelines != null) { for (String pipe : pipelines) { pipelineIds.add(ppDAO.getPhenotypePipelineByStableId(pipe).getId()); } } if (pipelineIds.isEmpty()) { pipelineIds.add(null); } List<ExperimentDTO> experimentList; for (int k = 0; k < parameterStableId.length; k++) { for (int mgiI = 0; mgiI < geneAccession.length; mgiI++) { for (Integer pCenter : phenotypingCenterIds) { for (Integer pipelineId : pipelineIds) { for (int strainI = 0; strainI < strain.length; strainI++) { for (int alleleI = 0; alleleI < allele.length; alleleI++) { experimentList = experimentService.getExperimentDTO(parameterStableId[k], pipelineId, geneAccession[mgiI], sex, pCenter, zygosity, strain[strainI]); if (experimentList.size() > 0) { for (ExperimentDTO experiment : experimentList) { rows.addAll(experiment.getTabbedToString(ppDAO)); } } } } } } } } return rows; } public List<String> composeDataTableExportRows(String query, String solrCoreName, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String solrParams, HttpServletRequest request, boolean legacyOnly, String fqStr) throws IOException, URISyntaxException { List<String> rows = null; if (solrCoreName.equals("gene")) { rows = composeGeneDataTableRows(json, request, legacyOnly); } else if (solrCoreName.equals("mp")) { rows = composeMpDataTableRows(json, request); } else if (solrCoreName.equals("ma")) { rows = composeMaDataTableRows(json, request); } else if (solrCoreName.equals("pipeline")) { rows = composeProtocolDataTableRows(json, request); } else if (solrCoreName.equals("images")) { rows = composeImageDataTableRows(query, json, iDisplayStart, iDisplayLength, showImgView, solrParams, request); } else if (solrCoreName.equals("impc_images")) { rows = composeImpcImageDataTableRows(query, json, iDisplayStart, iDisplayLength, showImgView, fqStr, request); } else if (solrCoreName.equals("disease")) { rows = composeDiseaseDataTableRows(json, request); } return rows; } private List<String> composeProtocolDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String impressBaseUrl = request.getAttribute("drupalBaseUrl").toString().replace("https", "http") + "/impress/impress/displaySOP/"; // String impressBaseUrl = request.getAttribute("drupalBaseUrl") + // "/impress/impress/displaySOP/"; List<String> rowData = new ArrayList(); rowData.add("Parameter\tProcedure\tProcedure Impress link\tPipeline"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("parameter_name")); JSONArray procedures = doc.getJSONArray("procedure_name"); JSONArray procedure_stable_keys = doc.getJSONArray("procedure_stable_key"); List<String> procedureLinks = new ArrayList<String>(); for (int p = 0; p < procedures.size(); p++) { // String procedure = procedures.get(p).toString(); String procedure_stable_key = procedure_stable_keys.get(p).toString(); procedureLinks.add(impressBaseUrl + procedure_stable_key); } // String procedure = doc.getString("procedure_name"); // data.add(procedure); data.add(StringUtils.join(procedures, "|")); // String procedure_stable_key = // doc.getString("procedure_stable_key"); // String procedureLink = impressBaseUrl + procedure_stable_key; // data.add(procedureLink); data.add(StringUtils.join(procedureLinks, "|")); data.add(doc.getString("pipeline_name")); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeImageDataTableRows(String query, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String solrParams, HttpServletRequest request) { // System.out.println("query: "+ query + " -- "+ solrParams); String mediaBaseUrl = config.get("mediaBaseUrl").replace("https:", "http:"); List<String> rowData = new ArrayList(); String mpBaseUrl = request.getAttribute("baseUrl") + "/phenotypes/"; String maBaseUrl = request.getAttribute("baseUrl") + "/anatomy/"; String geneBaseUrl = request.getAttribute("baseUrl") + "/genes/"; if (showImgView) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); rowData.add("Annotation term\tAnnotation id\tAnnotation id link\tImage link"); // column // names for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); List<String> data = new ArrayList(); List<String> lists = new ArrayList(); List<String> termLists = new ArrayList(); List<String> link_lists = new ArrayList(); String[] fields = { "annotationTermId", "expName", "symbol_gene" }; for (String fld : fields) { if (doc.has(fld)) { JSONArray list = doc.getJSONArray(fld); if (fld.equals("annotationTermId")) { JSONArray termList = doc.containsKey("annotationTermName") ? doc.getJSONArray("annotationTermName") : new JSONArray(); for (int l = 0; l < list.size(); l++) { String value = list.getString(l); String termVal = termList.size() == 0 ? NO_INFO_MSG : termList.getString(l); if (value.startsWith("MP:")) { link_lists.add(hostName + mpBaseUrl + value); termLists.add("MP:" + termVal); } if (value.startsWith("MA:")) { link_lists.add(hostName + maBaseUrl + value); termLists.add("MA:" + termVal); } lists.add(value); // id } } else if (fld.equals("symbol_gene")) { // gene symbol and its link for (int l = 0; l < list.size(); l++) { String[] parts = list.getString(l).split("_"); String symbol = parts[0]; String mgiId = parts[1]; termLists.add("Gene:" + symbol); lists.add(mgiId); link_lists.add(hostName + geneBaseUrl + mgiId); } } else if (fld.equals("expName")) { for (int l = 0; l < list.size(); l++) { String value = list.getString(l); termLists.add("Procedure:" + value); lists.add(NO_INFO_MSG); link_lists.add(NO_INFO_MSG); } } } } data.add(termLists.size() == 0 ? NO_INFO_MSG : StringUtils.join(termLists, "|")); // term // names data.add(StringUtils.join(lists, "|")); data.add(StringUtils.join(link_lists, "|")); data.add(mediaBaseUrl + "/" + doc.getString("largeThumbnailFilePath")); rowData.add(StringUtils.join(data, "\t")); } } else { // System.out.println("MODE: annotview " + showImgView); // annotation view // annotation view: images group by annotationTerm per row rowData.add( "Annotation type\tAnnotation term\tAnnotation id\tAnnotation id link\tRelated image count\tImages link"); // column // names JSONObject facetFields = json.getJSONObject("facet_counts").getJSONObject("facet_fields"); JSONArray sumFacets = solrIndex.mergeFacets(facetFields); int numFacets = sumFacets.size(); int quotient = (numFacets / 2) / iDisplayLength - ((numFacets / 2) % iDisplayLength) / iDisplayLength; int remainder = (numFacets / 2) % iDisplayLength; int start = iDisplayStart * 2; // 2 elements(name, count), hence // multiply by 2 int end = iDisplayStart == quotient * iDisplayLength ? (iDisplayStart + remainder) * 2 : (iDisplayStart + iDisplayLength) * 2; for (int i = start; i < end; i = i + 2) { List<String> data = new ArrayList(); // array element is an alternate of facetField and facetCount String[] names = sumFacets.get(i).toString().split("_"); if (names.length == 2) { // only want facet value of xxx_yyy String annotName = names[0]; Map<String, String> hm = solrIndex.renderFacetField(names, request.getAttribute("mappedHostname").toString(), request.getAttribute("baseUrl").toString()); data.add(hm.get("label")); data.add(annotName); data.add(hm.get("id")); // System.out.println("annotname: "+ annotName); if (hm.get("fullLink") != null) { data.add(hm.get("fullLink").toString()); } else { data.add(NO_INFO_MSG); } String imgCount = sumFacets.get(i + 1).toString(); data.add(imgCount); String facetField = hm.get("field"); solrParams = solrParams.replaceAll("&q=.+&", "&q=" + query + " AND " + facetField + ":\"" + names[0] + "\"&"); String imgSubSetLink = hostName + request.getAttribute("baseUrl") + "/imagesb?" + solrParams; data.add(imgSubSetLink); rowData.add(StringUtils.join(data, "\t")); } } } return rowData; } private List<String> composeImpcImageDataTableRows(String query, JSONObject json, Integer iDisplayStart, Integer iDisplayLength, boolean showImgView, String fqStrOri, HttpServletRequest request) throws IOException, URISyntaxException { // currently just use the solr field value // String mediaBaseUrl = // config.get("impcMediaBaseUrl").replace("https:", "http:"); List<String> rowData = new ArrayList(); String baseUrl = request.getAttribute("baseUrl").toString(); String mpBaseUrl = baseUrl + "/phenotypes/"; String maBaseUrl = baseUrl + "/anatomy/"; String geneBaseUrl = baseUrl + "/genes/"; if (showImgView) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // rowData.add("Annotation term\tAnnotation id\tAnnotation id // link\tProcedure\tGene symbol\tGene symbol link\tImage link"); // // column names rowData.add("Procedure\tGene symbol\tGene symbol link\tMA term\tMA term link\tImage link"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); // String[] fields = {"annotationTermName", "annotationTermId", // "expName", "symbol_gene"}; String[] fields = { "procedure_name", "gene_symbol", "ma_term" }; for (String fld : fields) { if (doc.has(fld)) { List<String> lists = new ArrayList(); if (fld.equals("gene_symbol")) { data.add(doc.getString("gene_symbol")); data.add(hostName + geneBaseUrl + doc.getString("gene_accession_id")); } else if (fld.equals("procedure_name")) { data.add(doc.getString("procedure_name")); } else if (fld.equals("ma_term")) { JSONArray maTerms = doc.getJSONArray("ma_term"); JSONArray maIds = doc.getJSONArray("ma_id"); List<String> ma_Terms = new ArrayList<>(); List<String> ma_links = new ArrayList<>(); for (int m = 0; m < maTerms.size(); m++) { ma_Terms.add(maTerms.get(m).toString()); ma_links.add(hostName + maBaseUrl + maIds.get(m).toString()); } data.add(StringUtils.join(ma_Terms, "|")); data.add(StringUtils.join(ma_links, "|")); } } else { /* * if ( fld.equals("annotationTermId") ){ * data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); * data.add(NO_INFO_MSG); } else if ( * fld.equals("symbol_gene") ){ */ if (fld.equals("gene_symbol")) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } else if (fld.equals("procedure_name")) { data.add(NO_INFO_MSG); } else if (fld.equals("ma_term")) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } } } data.add(doc.containsKey("jpeg_url") ? doc.getString("jpeg_url") : NO_INFO_MSG); rowData.add(StringUtils.join(data, "\t")); } } else { // annotation view: images group by annotationTerm per row baseUrl = baseUrl.replace("https:", "http:"); String mediaBaseUrl = "http:" + config.get("impcMediaBaseUrl"); rowData.add( "Annotation type\tAnnotation term\tAnnotation id\tAnnotation id link\tRelated image count\tImages link"); // column // names String fqStr = query; String defaultQStr = "observation_type:image_record&qf=auto_suggest&defType=edismax"; if (query != "") { defaultQStr = "q=" + query + " AND " + defaultQStr; } else { defaultQStr = "q=" + defaultQStr; } String defaultFqStr = "fq=(biological_sample_group:experimental)"; JSONObject facetFields = json.getJSONObject("facet_counts").getJSONObject("facet_fields"); List<AnnotNameValCount> annots = solrIndex.mergeImpcFacets(json, baseUrl); int numFacets = annots.size(); int start = iDisplayStart; // 2 elements(name, count), hence // multiply by 2 int end = iDisplayStart + iDisplayLength; end = end > numFacets ? numFacets : end; for (int i = start; i < end; i++) { List<String> data = new ArrayList(); AnnotNameValCount annot = annots.get(i); String displayAnnotName = annot.name; data.add(displayAnnotName); String annotVal = annot.val; data.add(annotVal); if (annot.id != null) { data.add(annot.id); data.add(annot.link); } else { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } String thisFqStr = defaultFqStr + " AND " + annot.facet + ":\"" + annotVal + "\""; List pathAndImgCount = solrIndex.fetchImpcImagePathByAnnotName(query, thisFqStr); int imgCount = (int) pathAndImgCount.get(1); StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(imgCount); data.add(sb.toString()); String imgSubSetLink = mediaBaseUrl + "?" + thisFqStr; data.add(imgSubSetLink); rowData.add(StringUtils.join(data, "\t")); } } return rowData; } private List<String> composeMpDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/phenotypes/"; List<String> rowData = new ArrayList(); rowData.add( "Mammalian phenotype term\tMammalian phenotype id\tMammalian phenotype id link\tMammalian phenotype definition\tMammalian phenotype synonym\tMammalian phenotype top level term\tComputationally mapped human phenotype terms\tComputationally mapped human phenotype term Ids\tPostqc call(s)"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("mp_term")); String mpId = doc.getString("mp_id"); data.add(mpId); data.add(hostName + baseUrl + mpId); if (doc.has("mp_definition")) { data.add(doc.getString("mp_definition")); } else { data.add(NO_INFO_MSG); } if (doc.has("mp_term_synonym")) { List<String> syns = new ArrayList(); JSONArray syn = doc.getJSONArray("mp_term_synonym"); for (int t = 0; t < syn.size(); t++) { syns.add(syn.getString(t)); } data.add(StringUtils.join(syns, "|")); } else { data.add(NO_INFO_MSG); } if (doc.has("top_level_mp_term")) { List<String> tops = new ArrayList(); JSONArray top = doc.getJSONArray("top_level_mp_term"); for (int t = 0; t < top.size(); t++) { tops.add(top.getString(t)); } data.add(StringUtils.join(tops, "|")); } else { data.add(NO_INFO_MSG); } if (doc.has("hp_term")) { Set<SimpleOntoTerm> hpTerms = mpService.getComputationalHPTerms(doc); List<String> terms = new ArrayList<String>(); List<String> ids = new ArrayList<String>(); for (SimpleOntoTerm term : hpTerms) { ids.add(term.getTermId()); terms.add(term.getTermName().equals("") ? NO_INFO_MSG : term.getTermName()); } data.add(StringUtils.join(terms, "|")); data.add(StringUtils.join(ids, "|")); } else { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); } // number of genes annotated to this MP int numCalls = doc.containsKey("pheno_calls") ? doc.getInt("pheno_calls") : 0; data.add(Integer.toString(numCalls)); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeMaDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/anatomy/"; List<String> rowData = new ArrayList(); rowData.add( "Mouse adult gross anatomy term\tMouse adult gross anatomy id\tMouse adult gross anatomy id link\tMouse adult gross anatomy synonym"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("ma_term")); String maId = doc.getString("ma_id"); data.add(maId); data.add(hostName + baseUrl + maId); if (doc.has("ma_term_synonym")) { List<String> syns = new ArrayList(); JSONArray syn = doc.getJSONArray("ma_term_synonym"); for (int t = 0; t < syn.size(); t++) { syns.add(syn.getString(t)); } data.add(StringUtils.join(syns, "|")); } else { data.add(NO_INFO_MSG); } // will have these cols coming later /* * if(doc.has("mp_definition")) { * data.add(doc.getString("mp_definition")); } else { * data.add(NO_INFO_MSG); } * * if(doc.has("top_level_mp_term")) { List<String> tops = new * ArrayList<String>(); JSONArray top = * doc.getJSONArray("top_level_mp_term"); for(int t=0; * t<top.size();t++) { tops.add(top.getString(t)); } * data.add(StringUtils.join(tops, "|")); } else { * data.add(NO_INFO_MSG); } */ rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeGeneDataTableRows(JSONObject json, HttpServletRequest request, boolean legacyOnly) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); List<String> rowData = new ArrayList(); rowData.add( "Gene symbol\tHuman ortholog\tGene id\tGene name\tGene synonym\tProduction status\tPhenotype status\tPhenotype status link"); // column // names for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); data.add(doc.getString("marker_symbol")); if (doc.has("human_gene_symbol")) { List<String> hsynData = new ArrayList(); JSONArray hs = doc.getJSONArray("human_gene_symbol"); for (int s = 0; s < hs.size(); s++) { hsynData.add(hs.getString(s)); } data.add(StringUtils.join(hsynData, "|")); // use | as a // multiValue // separator in CSV // output } else { data.add(NO_INFO_MSG); } // MGI gene id data.add(doc.getString("mgi_accession_id")); // Sanger problem, they should have use string for marker_name and // not array // data.add(doc.getJSONArray("marker_name").getString(0)); // now corrected using httpdatasource in dataImportHandler if (doc.has("marker_name")) { data.add(doc.getString("marker_name")); } else { data.add(NO_INFO_MSG); } if (doc.has("marker_synonym")) { List<String> synData = new ArrayList(); JSONArray syn = doc.getJSONArray("marker_synonym"); for (int s = 0; s < syn.size(); s++) { synData.add(syn.getString(s)); } data.add(StringUtils.join(synData, "|")); // use | as a // multiValue // separator in CSV // output } else { data.add(NO_INFO_MSG); } // ES/Mice production status boolean toExport = true; String mgiId = doc.getString(GeneDTO.MGI_ACCESSION_ID); String genePageUrl = request.getAttribute("mappedHostname").toString() + request.getAttribute("baseUrl").toString() + "/genes/" + mgiId; String prodStatus = geneService.getProductionStatusForEsCellAndMice(doc, genePageUrl, toExport); data.add(prodStatus); String statusField = (doc.containsKey(GeneDTO.LATEST_PHENOTYPE_STATUS)) ? doc.getString(GeneDTO.LATEST_PHENOTYPE_STATUS) : null; Integer legacyPhenotypeStatus = (doc.containsKey(GeneDTO.LEGACY_PHENOTYPE_STATUS)) ? doc.getInt(GeneDTO.LEGACY_PHENOTYPE_STATUS) : null; Integer hasQc = (doc.containsKey(GeneDTO.HAS_QC)) ? doc.getInt(GeneDTO.HAS_QC) : null; String phenotypeStatus = geneService.getPhenotypingStatus(statusField, hasQc, legacyPhenotypeStatus, genePageUrl, toExport, legacyOnly); if (phenotypeStatus.isEmpty()) { data.add(NO_INFO_MSG); data.add(NO_INFO_MSG); // link column } else if (phenotypeStatus.contains("___")) { // multiple phenotyping statusses, eg, complete and legacy String[] phStatuses = phenotypeStatus.split("___"); List<String> labelList = new ArrayList<>(); List<String> urlList = new ArrayList<>(); for (int c = 0; c < phStatuses.length; c++) { String[] parts = phStatuses[c].split("\\|"); if (parts.length != 2) { System.out.println( "fileExport: '" + phStatuses[c] + "' --- Expeced length 2 but got " + parts.length); } else { String url = parts[0].replace("https", "http"); String label = parts[1]; labelList.add(label); urlList.add(url); } } data.add(StringUtils.join(labelList, "|")); data.add(StringUtils.join(urlList, "|")); } else if (phenotypeStatus.startsWith("http://") || phenotypeStatus.startsWith("https://")) { String[] parts = phenotypeStatus.split("\\|"); if (parts.length != 2) { System.out.println("fileExport: '" + phenotypeStatus + "' --- Expeced length 2 but got " + parts.length); } else { String url = parts[0].replace("https", "http"); String label = parts[1]; data.add(label); data.add(url); } } else { data.add(phenotypeStatus); } // put together as tab delimited rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeDiseaseDataTableRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); String baseUrl = request.getAttribute("baseUrl") + "/disease/"; List<String> rowData = new ArrayList(); // column names rowData.add("Disease id" + "\tDisease id link" + "\tDisease name" + "\tSource" + "\tCurated genes from human (OMIM, Orphanet)" + "\tCurated genes from mouse (MGI)" + "\tCurated genes from human data with IMPC prediction" + "\tCurated genes from human data with MGI prediction" + "\tCandidate genes by phenotype - IMPC data" + "\tCandidate genes by phenotype - Novel IMPC prediction in linkage locus" + "\tCandidate genes by phenotype - MGI data" + "\tCandidate genes by phenotype - Novel MGI prediction in linkage locus"); for (int i = 0; i < docs.size(); i++) { List<String> data = new ArrayList(); JSONObject doc = docs.getJSONObject(i); String omimId = doc.getString("disease_id"); data.add(omimId); data.add(hostName + baseUrl + omimId); data.add(doc.getString("disease_term")); data.add(doc.getString("disease_source")); data.add(doc.getString("human_curated")); data.add(doc.getString("mouse_curated")); data.add(doc.getString("impc_predicted_known_gene")); data.add(doc.getString("mgi_predicted_known_gene")); data.add(doc.getString("impc_predicted")); data.add(doc.getString("impc_novel_predicted_in_locus")); data.add(doc.getString("mgi_predicted")); data.add(doc.getString("mgi_novel_predicted_in_locus")); rowData.add(StringUtils.join(data, "\t")); } return rowData; } private List<String> composeDataRowGeneOrPhenPage(String id, String pageName, String filters, HttpServletRequest request) { List<String> res = new ArrayList<>(); List<PhenotypeCallSummary> phenotypeList = new ArrayList(); PhenotypeFacetResult phenoResult; String targetGraphUrl = (String) request.getAttribute("mappedHostname") + request.getAttribute("baseUrl"); if (pageName.equalsIgnoreCase("gene")) { try { phenoResult = phenoDAO.getPhenotypeCallByGeneAccessionAndFilter(id, filters); phenotypeList = phenoResult.getPhenotypeCallSummaries(); } catch (HibernateException | JSONException e) { log.error("ERROR GETTING PHENOTYPE LIST"); e.printStackTrace(); phenotypeList = new ArrayList(); } catch (Exception e) { e.printStackTrace(); } ArrayList<GenePageTableRow> phenotypes = new ArrayList(); for (PhenotypeCallSummary pcs : phenotypeList) { GenePageTableRow pr = new GenePageTableRow(pcs, targetGraphUrl, config); phenotypes.add(pr); } Collections.sort(phenotypes); // sort in same order as gene page. res.add("Phenotype\tAllele\tZygosity\tSex\tProcedure | Parameter\tPhenotyping Center\tSource\tP Value\tGraph"); for (DataTableRow pr : phenotypes) { res.add(pr.toTabbedString("gene")); } } else if (pageName.equalsIgnoreCase("phenotype")) { phenotypeList = new ArrayList(); try { phenoResult = phenoDAO.getPhenotypeCallByMPAccessionAndFilter(id.replaceAll("\"", ""), filters); phenotypeList = phenoResult.getPhenotypeCallSummaries(); } catch (HibernateException | JSONException e) { log.error("ERROR GETTING PHENOTYPE LIST"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } ArrayList<PhenotypePageTableRow> phenotypes = new ArrayList(); res.add("Gene\tAllele\tZygosity\tSex\tPhenotype\tProcedure | Parameter\tPhenotyping Center\tSource\tP Value\tGraph"); for (PhenotypeCallSummary pcs : phenotypeList) { PhenotypePageTableRow pr = new PhenotypePageTableRow(pcs, targetGraphUrl, config); if (pr.getParameter() != null && pr.getProcedure() != null) { phenotypes.add(pr); } } Collections.sort(phenotypes); // sort in same order as phenotype // page. for (DataTableRow pr : phenotypes) { res.add(pr.toTabbedString("phenotype")); } } return res; } private List<String> composeGene2PfamClansDataRows(JSONObject json, HttpServletRequest request) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // System.out.println(" GOT " + docs.size() + " docs"); String baseUrl = request.getAttribute("baseUrl") + "/genes/"; List<String> rowData = new ArrayList<>(); // column names // latest_phenotype_status,mgi_accession_id,marker_symbol,pfama_id,pfama_acc,clan_id,clan_acc,clan_desc String fields = "Gene Symbol" + "\tMGI gene link" + "\tPhenotyping status" + "\tPfam Id" + "\tClan Id" + "\tClan Acc" + "\tClan Description"; rowData.add(fields); String NOINFO = "no info available"; for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); String gId = doc.getString("mgi_accession_id"); String phenoStatus = doc.getString("latest_phenotype_status"); JSONArray _pfamaIds = doc.containsKey("pfama_id") ? doc.getJSONArray("pfama_id") : new JSONArray(); JSONArray _clanIds = doc.containsKey("clan_id") ? doc.getJSONArray("clan_id") : new JSONArray(); JSONArray _clanAccs = doc.containsKey("clan_acc") ? doc.getJSONArray("clan_acc") : new JSONArray(); JSONArray _clanDescs = doc.containsKey("clan_desc") ? doc.getJSONArray("clan_desc") : new JSONArray(); if (_pfamaIds.size() == 0) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); rowData.add(StringUtils.join(data, "\t")); } else { for (int j = 0; j < _clanIds.size(); j++) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(doc.containsKey("pfama_id") ? _pfamaIds.getString(j) : NOINFO); data.add(doc.containsKey("clan_id") ? _clanIds.getString(j) : NOINFO); data.add(doc.containsKey("clan_acc") ? _clanAccs.getString(j) : NOINFO); data.add(doc.containsKey("clan_desc") ? _clanDescs.getString(j) : NOINFO); rowData.add(StringUtils.join(data, "\t")); } } } return rowData; } private List<String> composeAlleleRefExportRows(int iDisplayLength, int iDisplayStart, String sSearch, String dumpMode) throws SQLException { List<String> rowData = new ArrayList<>(); rowData.add(referenceDAO.heading); List<ReferenceDTO> references = referenceDAO.getReferenceRows(sSearch); for (ReferenceDTO reference : references) { List<String> row = new ArrayList(); row.add(StringUtils.join(reference.getAlleleSymbols(), "|")); row.add(StringUtils.join(reference.getAlleleAccessionIds(), "|")); row.add(StringUtils.join(reference.getImpcGeneLinks(), "|")); row.add(StringUtils.join(reference.getMgiAlleleNames(), "|")); row.add(reference.getTitle()); row.add(reference.getJournal()); row.add(reference.getPmid()); row.add(reference.getDateOfPublication()); row.add(StringUtils.join(reference.getGrantIds(), "|")); row.add(StringUtils.join(reference.getGrantAgencies(), "|")); row.add(StringUtils.join(reference.getPaperUrls(), "|")); rowData.add(StringUtils.join(row, "\t")); } return rowData; } private List<String> composeAlleleRefEditExportRows(int iDisplayLength, int iDisplayStart, String sSearch, String dumpMode) throws SQLException { Connection conn = admintoolsDataSource.getConnection(); String like = "%" + sSearch + "%"; String query = null; if (!sSearch.isEmpty()) { query = "select * from allele_ref where " + " acc like ?" + " or symbol like ?" + " or pmid like ?" + " or date_of_publication like ?" + " or grant_id like ?" + " or agency like ?" + " or acronym like ?" + " order by reviewed desc" + " limit ?, ?"; } else { query = "select * from allele_ref order by reviewed desc limit ?,?"; } // System.out.println("query: "+ query); String mgiAlleleBaseUrl = "http://www.informatics.jax.org/allele/"; List<String> rowData = new ArrayList<>(); String fields = "Reviewed" + "\tMGI allele symbol" + "\tMGI allele id" + "\tMGI allele link" + "\tMGI allele name" + "\tPMID" + "\tDate of publication" + "\tGrant id" + "\tGrant agency" + "\tGrant acronym" + "\tPaper link"; rowData.add(fields); try (PreparedStatement p2 = conn.prepareStatement(query)) { if (!sSearch.isEmpty()) { for (int i = 1; i < 10; i++) { p2.setString(i, like); if (i == 8) { p2.setInt(i, iDisplayStart); } else if (i == 9) { p2.setInt(i, iDisplayLength); } } } else { p2.setInt(1, iDisplayStart); p2.setInt(2, iDisplayLength); } ResultSet resultSet = p2.executeQuery(); while (resultSet.next()) { List<String> data = new ArrayList<String>(); data.add(resultSet.getString("reviewed")); // rowData.add(resultSet.getString("acc")); String alleleSymbol = Tools.superscriptify(resultSet.getString("symbol")); data.add(alleleSymbol); String acc = resultSet.getString("acc"); String alLink = acc.equals("") ? "" : mgiAlleleBaseUrl + resultSet.getString("acc"); data.add(acc); data.add(alLink); data.add(resultSet.getString("name")); // rowData.add(resultSet.getString("name")); data.add(resultSet.getString("pmid")); data.add(resultSet.getString("date_of_publication")); data.add(resultSet.getString("grant_id")); data.add(resultSet.getString("agency")); data.add(resultSet.getString("acronym")); String url = resultSet.getString("paper_url"); if (url.equals("")) { data.add(url); } else { String[] urls = resultSet.getString("paper_url").split(","); List<String> links = new ArrayList<>(); for (int i = 0; i < urls.length; i++) { links.add(urls[i]); } data.add(StringUtils.join(links, "|")); } rowData.add(StringUtils.join(data, "\t")); } } catch (Exception e) { e.printStackTrace(); } conn.close(); // System.out.println("Rows returned: "+rowData.size()); return rowData; } private List<String> composeGene2GoAnnotationDataRows(JSONObject json, HttpServletRequest request, boolean hasgoterm, boolean gocollapse) { JSONArray docs = json.getJSONObject("response").getJSONArray("docs"); // System.out.println(" GOT " + docs.size() + " docs"); String baseUrl = request.getAttribute("baseUrl") + "/genes/"; // List<String> evidsList = new // ArrayList<String>(Arrays.asList(request.getParameter("goevids").split(","))); List<String> rowData = new ArrayList(); // column names String fields = null; if (gocollapse) { fields = "Gene Symbol" + "\tIMPC gene link" + "\tGO annotated" + "\tGO evidence Category"; } else { fields = "Gene Symbol" + "\tIMPC gene link" + "\tPhenotyping status" + "\tUniprot protein" + "\tGO Term Id" + "\tGO Term Name" + "\tGO Term Evidence" + "\tGO evidence Category" + "\tGO Term Domain"; } rowData.add(fields); // GO evidence code ranking mapping Map<String, Integer> codeRank = commonUtils.getGoCodeRank(); // GO evidence rank to category mapping Map<Integer, String> evidRankCat = SolrIndex.getGomapCategory(); String NOINFO = "no info available"; for (int i = 0; i < docs.size(); i++) { JSONObject doc = docs.getJSONObject(i); String gId = doc.getString("mgi_accession_id"); String phenoStatus = doc.containsKey("latest_phenotype_status") ? doc.getString("latest_phenotype_status") : NOINFO; if (!doc.containsKey("evidCodeRank")) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); data.add(NOINFO); rowData.add(StringUtils.join(data, "\t")); } else if (gocollapse) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(Integer.toString(doc.getInt("go_count"))); int evidCodeRank = doc.getInt("evidCodeRank"); data.add(evidRankCat.get(evidCodeRank)); rowData.add(StringUtils.join(data, "\t")); } else { int evidCodeRank = doc.getInt("evidCodeRank"); JSONArray _goTermIds = doc.containsKey("go_term_id") ? doc.getJSONArray("go_term_id") : new JSONArray(); JSONArray _goTermNames = doc.containsKey("go_term_name") ? doc.getJSONArray("go_term_name") : new JSONArray(); JSONArray _goTermEvids = doc.containsKey("go_term_evid") ? doc.getJSONArray("go_term_evid") : new JSONArray(); JSONArray _goTermDomains = doc.containsKey("go_term_domain") ? doc.getJSONArray("go_term_domain") : new JSONArray(); JSONArray _goUniprotAccs = doc.containsKey("go_uniprot") ? doc.getJSONArray("go_uniprot") : new JSONArray(); for (int j = 0; j < _goTermEvids.size(); j++) { String evid = _goTermEvids.get(j).toString(); if (codeRank.get(evid) == evidCodeRank) { List<String> data = new ArrayList(); data.add(doc.getString("marker_symbol")); data.add(hostName + baseUrl + gId); data.add(phenoStatus); String go2Uniprot = _goUniprotAccs.size() > 0 ? _goUniprotAccs.get(j).toString() : NOINFO; String uniprotAcc = go2Uniprot.replaceAll("[A-Z0-9:]+__", ""); data.add(uniprotAcc); data.add(_goTermIds.size() > 0 ? _goTermIds.get(j).toString() : NOINFO); data.add(_goTermNames.size() > 0 ? _goTermNames.get(j).toString() : NOINFO); data.add(_goTermEvids.size() > 0 ? _goTermEvids.get(j).toString() : NOINFO); data.add(evidRankCat.get(evidCodeRank)); data.add(_goTermDomains.size() > 0 ? _goTermDomains.get(j).toString() : NOINFO); rowData.add(StringUtils.join(data, "\t")); } } } } return rowData; } @RequestMapping(value = "/impc2gwasExport", method = RequestMethod.GET) public void exportImpc2GwasMappingAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "mgiGeneSymbol", required = true) String mgiGeneSymbol, @RequestParam(value = "gridFields", required = true) String gridFields, @RequestParam(value = "currentTraitName", required = false) String currentTraitName, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { List<String> dataRows = fetchImpc2GwasMappingData(request, mgiGeneSymbol, gridFields, currentTraitName); Workbook wb = null; String fileName = "impc_to_Gwas_mapping_dataset"; writeOutputFile(response, dataRows, fileType, fileName, wb); } private List<String> fetchImpc2GwasMappingData(HttpServletRequest request, String mgiGeneSymbol, String gridFields, String currentTraitName) throws SQLException { // GWAS Gene to IMPC gene mapping List<GwasDTO> gwasMappings = gwasDao.getGwasMappingRows("mgi_gene_symbol", mgiGeneSymbol.toUpperCase()); // System.out.println("FileExportController FOUND " + // gwasMappings.size() + " phenotype to gwas trait mappings"); List<String> rowData = new ArrayList(); rowData.add(gridFields); for (GwasDTO gw : gwasMappings) { String traitName = gw.getDiseaseTrait(); if (currentTraitName != null && !traitName.equals(currentTraitName)) { continue; } List<String> data = new ArrayList(); data.add(gw.getMgiGeneSymbol()); data.add(gw.getMgiGeneId()); data.add(gw.getMgiAlleleId()); data.add(gw.getMgiAlleleName()); data.add(gw.getMouseGender()); data.add(gw.getMpTermId()); data.add(gw.getMpTermName()); data.add(traitName); data.add(gw.getSnpId()); data.add(Float.toString(gw.getPvalue())); data.add(gw.getMappedGene()); data.add(gw.getReportedGene()); data.add(gw.getUpstreamGene()); data.add(gw.getDownstreamGene()); data.add(gw.getPhenoMappingCategory()); rowData.add(StringUtils.join(data, "\t")); } return rowData; } @RequestMapping(value = "/bqExport", method = RequestMethod.POST) public void exportBqTableAsExcelTsv( /* * ***************************************************************** * *** Please keep in mind that /export is used for ALL exports on * the website so be cautious about required parameters *******************************************************************/ @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "coreName", required = true) String dataTypeName, @RequestParam(value = "idList", required = true) String idlist, @RequestParam(value = "gridFields", required = true) String gridFields, HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { String dumpMode = "all"; List<String> queryIds = Arrays.asList(idlist.split(",")); Long time = System.currentTimeMillis(); List<String> mgiIds = new ArrayList<>(); List<GeneDTO> genes = new ArrayList<>(); List<QueryResponse> solrResponses = new ArrayList<>(); List<String> batchIdList = new ArrayList<>(); String batchIdListStr = null; int counter = 0; for (String id : queryIds) { counter++; // do the batch size if (counter % 500 == 0) { batchIdList.add(id); // batch solr query batchIdListStr = StringUtils.join(batchIdList, ","); // System.out.println(batchIdListStr); solrResponses.add(solrIndex.getBatchQueryJson(batchIdListStr, gridFields, dataTypeName)); batchIdList = new ArrayList<>(); } else { batchIdList.add(id); } } if (batchIdList.size() > 0) { // do the rest // batch solr query batchIdListStr = StringUtils.join(batchIdList, ","); solrResponses.add(solrIndex.getBatchQueryJson(batchIdListStr, gridFields, dataTypeName)); } List<String> dataRows = composeBatchQueryDataTableRows(solrResponses, dataTypeName, gridFields, request, queryIds); Workbook wb = null; String fileName = "batch_query_dataset"; writeOutputFile(response, dataRows, fileType, fileName, wb); } private List<String> composeBatchQueryDataTableRows(List<QueryResponse> solrResponses, String dataTypeName, String gridFields, HttpServletRequest request, List<String> queryIds) throws UnsupportedEncodingException { Set<String> foundIds = new HashSet<>(); System.out.println("Number of responses: " + solrResponses.size()); SolrDocumentList results = new SolrDocumentList(); for (QueryResponse solrResponse : solrResponses) { results.addAll(solrResponse.getResults()); } int totalDocs = results.size(); System.out.println("TOTAL DOCS FOUND: " + totalDocs); String hostName = request.getAttribute("mappedHostname").toString().replace("https:", "http:"); String baseUrl = request.getAttribute("baseUrl").toString(); String NA = "Info not available"; String imgBaseUrl = request.getAttribute("baseUrl") + "/impcImages/images?"; String oriDataTypeNAme = dataTypeName; if (dataTypeName.equals("ensembl") || dataTypeName.equals("marker_symbol")) { dataTypeName = "gene"; } Map<String, String> dataTypeId = new HashMap<>(); dataTypeId.put("gene", "mgi_accession_id"); dataTypeId.put("mp", "mp_id"); dataTypeId.put("ma", "ma_id"); dataTypeId.put("hp", "hp_id"); dataTypeId.put("disease", "disease_id"); Map<String, String> dataTypePath = new HashMap<>(); dataTypePath.put("gene", "genes"); dataTypePath.put("mp", "phenotypes"); dataTypePath.put("ma", "anatomy"); dataTypePath.put("hp", ""); dataTypePath.put("disease", "disease"); // column names // String idLinkColName = dataTypeId.get(dataType) + "_link"; String idLinkColName = "id_link"; gridFields = idLinkColName + "," + gridFields; // xx_id_link column only // for export, not // dataTable String[] cols = StringUtils.split(gridFields, ","); // List<String> foundIds = new ArrayList<>(); // swap cols cols[0] = dataTypeId.get(dataTypeName); cols[1] = idLinkColName; List<String> colList = new ArrayList<>(); for (int i = 0; i < cols.length; i++) { colList.add(cols[i]); } List<String> rowData = new ArrayList(); rowData.add(StringUtils.join(colList, "\t")); System.out.println("grid fields: " + colList); for (int i = 0; i < results.size(); i++) { SolrDocument doc = results.get(i); System.out.println("Working on document " + i + " of " + totalDocs); Map<String, Collection<Object>> docMap = doc.getFieldValuesMap(); // Note // getFieldValueMap() // returns // only // String // System.out.println("DOCMAP: "+docMap.toString()); List<String> orthologousDiseaseIdAssociations = new ArrayList<>(); List<String> orthologousDiseaseTermAssociations = new ArrayList<>(); List<String> phenotypicDiseaseIdAssociations = new ArrayList<>(); List<String> phenotypicDiseaseTermAssociations = new ArrayList<>(); if (docMap.get("mgi_accession_id") != null && !(dataTypeName.equals("ma") || dataTypeName.equals("disease"))) { Collection<Object> mgiGeneAccs = docMap.get("mgi_accession_id"); for (Object acc : mgiGeneAccs) { String mgi_gene_id = (String) acc; // System.out.println("mgi_gene_id: "+ mgi_gene_id); GeneIdentifier geneIdentifier = new GeneIdentifier(mgi_gene_id, mgi_gene_id); List<DiseaseAssociationSummary> diseaseAssociationSummarys = new ArrayList<>(); try { // log.info("{} - getting disease-gene associations // using cutoff {}", geneIdentifier, rawScoreCutoff); diseaseAssociationSummarys = phenoDigmDao.getGeneToDiseaseAssociationSummaries(geneIdentifier, rawScoreCutoff); //System.out.println("received " + diseaseAssociationSummarys.size() + " disease-gene associations"); // log.info("{} - received {} disease-gene // associations", geneIdentifier, // diseaseAssociationSummarys.size()); } catch (RuntimeException e) { log.error(ExceptionUtils.getFullStackTrace(e)); // log.error("Error retrieving disease data for {}", // geneIdentifier); } for (DiseaseAssociationSummary diseaseAssociationSummary : diseaseAssociationSummarys) { AssociationSummary associationSummary = diseaseAssociationSummary.getAssociationSummary(); if (associationSummary.isAssociatedInHuman()) { // System.out.println("DISEASE ID: " + // diseaseAssociationSummary.getDiseaseIdentifier().toString()); // System.out.println("DISEASE ID: " + // diseaseAssociationSummary.getDiseaseIdentifier().getDatabaseAcc()); // System.out.println("DISEASE TERM: " + // diseaseAssociationSummary.getDiseaseTerm()); orthologousDiseaseIdAssociations .add(diseaseAssociationSummary.getDiseaseIdentifier().toString()); orthologousDiseaseTermAssociations.add(diseaseAssociationSummary.getDiseaseTerm()); } else { phenotypicDiseaseIdAssociations .add(diseaseAssociationSummary.getDiseaseIdentifier().toString()); phenotypicDiseaseTermAssociations.add(diseaseAssociationSummary.getDiseaseTerm()); } } } } List<String> data = new ArrayList(); // for (String fieldName : doc.getFieldNames()) { for (int k = 0; k < cols.length; k++) { String fieldName = cols[k]; // System.out.println("DataTableController: "+ fieldName + " - // value: " + docMap.get(fieldName)); if (fieldName.equals("id_link")) { Collection<Object> accs = docMap.get(dataTypeId.get(dataTypeName)); String accStr = null; for (Object acc : accs) { accStr = (String) acc; } // System.out.println("idlink id: " + accStr); if (!oriDataTypeNAme.equals("ensembl") && !oriDataTypeNAme.equals("marker_symbol")) { System.out.println("idlink check: " + accStr); foundIds.add("\"" + accStr + "\""); } String link = null; if (dataTypePath.get(dataTypeName).isEmpty()) { link = ""; } else { link = hostName + baseUrl + "/" + dataTypePath.get(dataTypeName) + "/" + accStr; } // System.out.println("idlink: " + link); data.add(link); } else if (fieldName.equals("images_link")) { String impcImgBaseUrl = baseUrl + "/impcImages/images?"; String qryField = null; String imgQryField = null; if (dataTypeName.equals("gene")) { qryField = "mgi_accession_id"; imgQryField = "gene_accession_id"; } else if (dataTypeName.equals("ma")) { qryField = "ma_id"; imgQryField = "ma_id"; } Collection<Object> accs = docMap.get(qryField); String accStr = null; for (Object acc : accs) { accStr = imgQryField + ":\"" + (String) acc + "\""; } String imgLink = "<a target='_blank' href='" + hostName + impcImgBaseUrl + "q=" + accStr + " AND observation_type:image_record&fq=biological_sample_group:experimental" + "'>image url</a>"; data.add(imgLink); } else if (docMap.get(fieldName) == null) { String vals = NA; if (fieldName.equals("disease_id_by_gene_orthology")) { vals = orthologousDiseaseIdAssociations.size() == 0 ? NA : StringUtils.join(orthologousDiseaseIdAssociations, ", "); } else if (fieldName.equals("disease_term_by_gene_orthology")) { vals = orthologousDiseaseTermAssociations.size() == 0 ? NA : StringUtils.join(orthologousDiseaseTermAssociations, ", "); } else if (fieldName.equals("disease_id_by_phenotypic_similarity")) { vals = phenotypicDiseaseIdAssociations.size() == 0 ? NA : StringUtils.join(phenotypicDiseaseIdAssociations, ", "); } else if (fieldName.equals("disease_term_by_phenotypic_similarity")) { vals = phenotypicDiseaseTermAssociations.size() == 0 ? NA : StringUtils.join(phenotypicDiseaseTermAssociations, ", "); } data.add(vals); } else { try { String value = null; // System.out.println("TEST CLASS: "+ // docMap.get(fieldName).getClass()); try { Collection<Object> vals = docMap.get(fieldName); Set<Object> valSet = new HashSet<>(vals); if (oriDataTypeNAme.equals("ensembl") && fieldName.equals("ensembl_gene_id")) { for (Object val : valSet) { foundIds.add("\"" + val + "\""); } } if (oriDataTypeNAme.equals("marker_symbol") && fieldName.equals("marker_symbol")) { for (Object val : valSet) { foundIds.add("\"" + val.toString().toUpperCase() + "\""); } } else if (dataTypeName.equals("hp") && dataTypeId.get(dataTypeName).equals(fieldName)) { for (Object val : valSet) { foundIds.add("\"" + val + "\""); } } value = StringUtils.join(valSet, "|"); /* * if ( !dataTypeName.equals("hp") && * dataTypeId.get(dataTypeName).equals(fieldName) ){ * String coreName = * dataTypeName.equals("marker_symbol") || * dataTypeName.equals("ensembl") ? "gene" : * dataTypeName; foundIds.add("\"" + value + "\""); * * System.out.println("fieldname: " + fieldName + * " datatype: " + dataTypeName); //value = * "<a target='_blank' href='" + hostName + baseUrl * + "/" + dataTypePath.get(coreName) + "/" + value * + "'>" + value + "</a>"; } else if ( * dataTypeName.equals("hp") && * dataTypeId.get(dataTypeName).equals(fieldName) ){ * foundIds.add("\"" + value + "\""); } */ } catch (ClassCastException c) { value = docMap.get(fieldName).toString(); } // System.out.println("row " + i + ": field: " + k + " // -- " + fieldName + " - " + value); data.add(value); } catch (Exception e) { // e.printStackTrace(); if (e.getMessage().equals("java.lang.Integer cannot be cast to java.lang.String")) { Collection<Object> vals = docMap.get(fieldName); if (vals.size() > 0) { Iterator it = vals.iterator(); String value = (String) it.next(); // String value = Integer.toString(val); data.add(value); } } } } } // System.out.println("DATA: "+ StringUtils.join(data, "\t") ); rowData.add(StringUtils.join(data, "\t")); } // find the ids that are not found and displays them to users ArrayList nonFoundIds = (java.util.ArrayList) CollectionUtils.disjunction(queryIds, new ArrayList(foundIds)); // System.out.println("Query ids: "+ queryIds); // System.out.println("Found ids: "+ new ArrayList(foundIds)); System.out.println("non found ids: " + nonFoundIds.size()); for (int i = 0; i < nonFoundIds.size(); i++) { List<String> data = new ArrayList<String>(); for (int l = 0; l < cols.length; l++) { data.add(l == 0 ? nonFoundIds.get(i).toString().replaceAll("\"", "") : NA); } rowData.add(StringUtils.join(data, "\t")); } return rowData; } private void writeOutputFile(HttpServletResponse response, List<String> dataRows, String fileType, String fileName, Workbook wb) { response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); String outfile = fileName + "." + fileType; try { System.out.println("File to export: " + outfile); if (fileType.equals("tsv")) { response.setContentType("text/tsv; charset=utf-8"); response.setHeader("Content-disposition", "attachment; filename=" + outfile); // ServletOutputStream output = response.getOutputStream(); // ckc note: switch to use getWriter() so that we don't get // error like // java.io.CharConversionException: Not an ISO 8859-1 character // and if we do, the error will cause the dump to end // prematurely // and we may not get the full rows (depending on which row // causes error) PrintWriter output = response.getWriter(); for (String line : dataRows) { // System.out.println("line: " + line); line = line.replaceAll("\\t//", "\thttp://"); output.println(line); } output.flush(); output.close(); } else if (fileType.equals("xls")) { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + outfile); String sheetName = fileName; String[] titles = null; String[][] tableData = new String[0][0]; if (!dataRows.isEmpty()) { // titles = dataRows.remove(0).split("\t"); titles = dataRows.get(0).split("\t"); tableData = Tools.composeXlsTableData(dataRows); } wb = new ExcelWorkBook(titles, tableData, sheetName).fetchWorkBook(); ServletOutputStream output = response.getOutputStream(); try { wb.write(output); output.close(); } catch (IOException ioe) { log.error("ExcelWorkBook Error: " + ioe.getMessage()); ioe.printStackTrace(); } } } catch (Exception e) { log.error("Error: " + e.getMessage()); e.printStackTrace(); } } }
fixed path to multiple impg images
web/src/main/java/uk/ac/ebi/phenotype/web/controller/FileExportController.java
fixed path to multiple impg images
Java
apache-2.0
9c939b0d33834eadcee2499a2fa9d67e7ca637d7
0
relvaner/actor4j-core
/* * tools4j - Java Library * Copyright (c) 2008-2017, David A. Bauer * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package actor4j.core.di; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import actor4j.core.di.DIContainer; import actor4j.core.di.DIMapEntry; import actor4j.core.di.FactoryInjector; // Adapted for actor4j public class DIContainer<K> { protected Map<K, DIMapEntry> diMap; public DIContainer() { diMap = new ConcurrentHashMap<>(); } public void registerConstructorInjector(K key, Class<?> base, Object... params) { DIMapEntry entry = diMap.get(key); if (entry==null) entry = new DIMapEntry(); entry.setBase(base); entry.getConstructorInjector().setParams(params); diMap.put(key, entry); } public void registerFactoryInjector(K key, FactoryInjector<?> factoryInjector) { DIMapEntry entry = diMap.get(key); if (entry==null) entry = new DIMapEntry(); entry.setFactoryInjector(factoryInjector); diMap.put(key, entry); } protected Object buildInstance(Class<?> base, Object[] params) throws Exception { Object result = null; Class<?>[] types = new Class<?>[params.length]; for (int i=0; i<params.length; i++) types[i] = params[i].getClass(); Constructor<?> c2 = base.getConstructor(types); result = c2.newInstance(params); return result; } public Object getInstance(K key) throws Exception { Object result = null; DIMapEntry entry = diMap.get(key); if (entry!=null) { if (entry.getFactoryInjector()!=null) result = entry.getFactoryInjector().create(); else { if (entry.getConstructorInjector().getParams()!=null) result = buildInstance(entry.getBase(), entry.getConstructorInjector().getParams()); else result = entry.getBase().newInstance(); } } return result; } public DIMapEntry unregister(K key) { return diMap.remove(key); } public static <K> DIContainer<K> create() { return new DIContainer<>(); } }
src/main/java/actor4j/core/di/DIContainer.java
/* * tools4j - Java Library * Copyright (c) 2008-2017, David A. Bauer * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package actor4j.core.di; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import actor4j.core.di.DIContainer; import actor4j.core.di.DIMapEntry; import actor4j.core.di.FactoryInjector; // Adapted for actor4j public class DIContainer<K> { protected Map<K, DIMapEntry> diMap; public DIContainer() { diMap = new ConcurrentHashMap<>(); } public void registerConstructorInjector(K key, Class<?> base, Object... params) { DIMapEntry entry = diMap.get(key); if (entry==null) entry = new DIMapEntry(); entry.setBase(base); entry.getConstructorInjector().setParams(params); diMap.put(key, entry); } public void registerFactoryInjector(K key, FactoryInjector<?> factoryInjector) { DIMapEntry entry = diMap.get(key); if (entry==null) entry = new DIMapEntry(); entry.setFactoryInjector(factoryInjector); diMap.put(key, entry); } protected Object buildInstance(Class<?> base, Object[] params) throws Exception { Object result = null; Class<?>[] types = new Class<?>[params.length]; for (int i=0; i<params.length; i++) types[i] = params.getClass(); Constructor<?> c2 = base.getConstructor(types); result = c2.newInstance(params); return result; } public Object getInstance(K key) throws Exception { Object result = null; DIMapEntry entry = diMap.get(key); if (entry!=null) { if (entry.getFactoryInjector()!=null) result = entry.getFactoryInjector().create(); else { if (entry.getConstructorInjector().getParams()!=null) result = buildInstance(entry.getBase(), entry.getConstructorInjector().getParams()); else result = entry.getBase().newInstance(); } } return result; } public DIMapEntry unregister(K key) { return diMap.remove(key); } public static <K> DIContainer<K> create() { return new DIContainer<>(); } }
Bugfix in DIContainer
src/main/java/actor4j/core/di/DIContainer.java
Bugfix in DIContainer
Java
apache-2.0
74d0b7ff82821bb7be825179acf0bf66fa9e4957
0
hurzl/dmix,hurzl/dmix
/* * Copyright (C) 2010-2014 The MPDroid Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.namelessdev.mpdroid.library; import com.mobeta.android.dslv.DragSortController; import com.mobeta.android.dslv.DragSortListView; import com.namelessdev.mpdroid.MPDroidActivities; import com.namelessdev.mpdroid.R; import com.namelessdev.mpdroid.tools.Tools; import org.a0z.mpd.MPDPlaylist; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.exception.MPDException; import org.a0z.mpd.item.AbstractMusic; import org.a0z.mpd.item.Artist; import org.a0z.mpd.item.Music; import org.a0z.mpd.item.PlaylistFile; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; public class PlaylistEditActivity extends MPDroidActivities.MPDroidActivity implements StatusChangeListener, OnClickListener, AdapterView.OnItemClickListener { private static final String TAG = "PlaylistEditActivity"; private boolean mIsFirstRefresh = true; private boolean mIsPlayQueue = true; private ListView mListView; private PlaylistFile mPlaylist; private final DragSortListView.DropListener mDropListener = new DragSortListView.DropListener() { @Override public void drop(final int from, final int to) { if (from == to) { return; } final AbstractMap<String, Object> itemFrom = mSongList.get(from); final Integer songID = (Integer) itemFrom.get(AbstractMusic.RESPONSE_SONG_ID); if (mIsPlayQueue) { try { mApp.oMPDAsyncHelper.oMPD.getPlaylist().move(songID, to); } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to move a track on the queue.", e); } } else { try { mApp.oMPDAsyncHelper.oMPD.movePlaylistSong(mPlaylist, from, to); } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to rename a playlist.", e); } update(); } Tools.notifyUser("Updating ..."); } }; private ArrayList<HashMap<String, Object>> mSongList = new ArrayList<>(); @Override public void connectionStateChanged(final boolean connected, final boolean connectionLost) { } private List<Music> getMusic() { List<Music> musics; if (mIsPlayQueue) { final MPDPlaylist playlist = mApp.oMPDAsyncHelper.oMPD.getPlaylist(); musics = playlist.getMusicList(); } else { try { musics = mApp.oMPDAsyncHelper.oMPD.getPlaylistSongs(mPlaylist); } catch (final IOException | MPDException e) { Log.d(TAG, "Playlist update failure.", e); musics = Collections.emptyList(); } } return musics; } @Override public void libraryStateChanged(final boolean updating, final boolean dbChanged) { } @Override public void onClick(final View v) { if (v.getId() == R.id.Remove) { int count = 0; final Collection<HashMap<String, Object>> copy = new ArrayList<>(mSongList); final List<Integer> positions = new LinkedList<>(); for (final AbstractMap<String, Object> item : copy) { if (item.get("marked").equals(Boolean.TRUE)) { positions.add((Integer) item.get(AbstractMusic.RESPONSE_SONG_ID)); count++; } } try { if (mIsPlayQueue) { mApp.oMPDAsyncHelper.oMPD.getPlaylist().removeById(positions); } else { mApp.oMPDAsyncHelper.oMPD.removeFromPlaylist(mPlaylist, positions); } } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to remove.", e); } if (copy.size() != mSongList.size()) { ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged(); } Tools.notifyUser(R.string.removeCountSongs, count); update(); } } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPlaylist = getIntent().getParcelableExtra(PlaylistFile.EXTRA); if (null != mPlaylist) { mIsPlayQueue = false; } setContentView(R.layout.playlist_editlist_activity); mListView = (ListView) findViewById(android.R.id.list); mListView.setOnItemClickListener(this); if (mIsPlayQueue) { setTitle(R.string.nowPlaying); } else { setTitle(mPlaylist.getName()); } update(); mApp.oMPDAsyncHelper.addStatusChangeListener(this); final DragSortListView trackList = (DragSortListView) mListView; trackList.setOnCreateContextMenuListener(this); trackList.setDropListener(mDropListener); final DragSortController controller = new DragSortController(trackList); controller.setDragHandleId(R.id.icon); controller.setRemoveEnabled(false); controller.setSortEnabled(true); controller.setDragInitMode(1); trackList.setFloatViewManager(controller); trackList.setOnTouchListener(controller); trackList.setDragEnabled(true); trackList.setCacheColorHint(0); final Button button = (Button) findViewById(R.id.Remove); button.setOnClickListener(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void onDestroy() { mApp.oMPDAsyncHelper.removeStatusChangeListener(this); super.onDestroy(); } /** * Marks the selected item for deletion */ @Override public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, final long l) { final AbstractMap<String, Object> item = mSongList.get(i); item.get("marked"); if (item.get("marked").equals(true)) { item.put("marked", false); } else { item.put("marked", true); } ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Menu actions... switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return false; } } @Override protected void onStart() { super.onStart(); mApp.setActivity(this); } @Override protected void onStop() { super.onStop(); mApp.unsetActivity(this); } @Override public void playlistChanged(final MPDStatus mpdStatus, final int oldPlaylistVersion) { update(); } @Override public void randomChanged(final boolean random) { } @Override public void repeatChanged(final boolean repeating) { } @Override public void stateChanged(final MPDStatus mpdStatus, final int oldState) { } @Override public void stickerChanged(final MPDStatus mpdStatus) { } @Override public void trackChanged(final MPDStatus mpdStatus, final int oldTrack) { if (mIsPlayQueue) { // Mark running track... for (final AbstractMap<String, Object> song : mSongList) { final int songId = ((Integer) song.get(AbstractMusic.RESPONSE_SONG_ID)).intValue(); if (songId == mpdStatus.getSongId()) { song.put("play", android.R.drawable.ic_media_play); } else { song.put("play", 0); } } final SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter(); if (adapter != null) { adapter.notifyDataSetChanged(); } } } protected void update() { // TODO: Preserve position!!! mSongList = new ArrayList<>(); final int playingID = mApp.oMPDAsyncHelper.oMPD.getStatus().getSongId(); final int pos = null == mListView ? -1 : mListView.getFirstVisiblePosition(); final View view = null == mListView ? null : mListView.getChildAt(0); final int top = null == view ? -1 : view.getTop(); int listPlayingId = 0; int playlistPosition = 0; // Copy list to avoid concurrent exception for (final Music music : new ArrayList<>(getMusic())) { final HashMap<String, Object> item = new HashMap<>(); if (mIsPlayQueue) { item.put(AbstractMusic.RESPONSE_SONG_ID, music.getSongId()); } else { item.put(AbstractMusic.RESPONSE_SONG_ID, playlistPosition); } playlistPosition++; item.put(Artist.EXTRA, music.getArtist()); item.put(AbstractMusic.TAG_TITLE, music.getTitle()); item.put("marked", false); if (mIsPlayQueue && music.getSongId() == playingID) { item.put("play", android.R.drawable.ic_media_play); listPlayingId = mSongList.size() - 1; } else { item.put("play", 0); } final ListAdapter songs = new SimpleAdapter(this, mSongList, R.layout.playlist_editlist_item, new String[]{ "play", AbstractMusic.TAG_TITLE, AbstractMusic.TAG_ARTIST, "marked" }, new int[]{ R.id.picture, android.R.id.text1, android.R.id.text2, R.id.removeCBox }); if (mListView != null) { mListView.setAdapter(songs); if (mIsFirstRefresh) { mIsFirstRefresh = false; if (listPlayingId > 0) { mListView.setSelection(listPlayingId); } } else { if (-1 != pos && -1 != top) { mListView.setSelectionFromTop(pos, top); } } } } } @Override public void volumeChanged(final MPDStatus mpdStatus, final int oldVolume) { } }
MPDroid/src/main/java/com/namelessdev/mpdroid/library/PlaylistEditActivity.java
/* * Copyright (C) 2010-2014 The MPDroid Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.namelessdev.mpdroid.library; import com.mobeta.android.dslv.DragSortController; import com.mobeta.android.dslv.DragSortListView; import com.namelessdev.mpdroid.MPDroidActivities; import com.namelessdev.mpdroid.R; import com.namelessdev.mpdroid.tools.Tools; import org.a0z.mpd.MPDPlaylist; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.exception.MPDException; import org.a0z.mpd.item.AbstractMusic; import org.a0z.mpd.item.Artist; import org.a0z.mpd.item.Music; import org.a0z.mpd.item.PlaylistFile; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; public class PlaylistEditActivity extends MPDroidActivities.MPDroidActivity implements StatusChangeListener, OnClickListener, AdapterView.OnItemClickListener { private static final String TAG = "PlaylistEditActivity"; private boolean mIsFirstRefresh = true; private boolean mIsPlayQueue = true; private ListView mListView; private PlaylistFile mPlaylist; private final DragSortListView.DropListener mDropListener = new DragSortListView.DropListener() { @Override public void drop(final int from, final int to) { if (from == to) { return; } final AbstractMap<String, Object> itemFrom = mSongList.get(from); final Integer songID = (Integer) itemFrom.get(AbstractMusic.RESPONSE_SONG_ID); if (mIsPlayQueue) { try { mApp.oMPDAsyncHelper.oMPD.getPlaylist().move(songID, to); } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to move a track on the queue.", e); } } else { try { mApp.oMPDAsyncHelper.oMPD.movePlaylistSong(mPlaylist, from, to); } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to rename a playlist.", e); } update(); } Tools.notifyUser("Updating ..."); } }; private ArrayList<HashMap<String, Object>> mSongList = new ArrayList<>(); @Override public void connectionStateChanged(final boolean connected, final boolean connectionLost) { } @Override public void libraryStateChanged(final boolean updating, final boolean dbChanged) { } @Override public void onClick(final View v) { if (v.getId() == R.id.Remove) { int count = 0; final Collection<HashMap<String, Object>> copy = new ArrayList<>(mSongList); final List<Integer> positions = new LinkedList<>(); for (final AbstractMap<String, Object> item : copy) { if (item.get("marked").equals(Boolean.TRUE)) { positions.add((Integer) item.get(AbstractMusic.RESPONSE_SONG_ID)); count++; } } try { if (mIsPlayQueue) { mApp.oMPDAsyncHelper.oMPD.getPlaylist().removeById(positions); } else { mApp.oMPDAsyncHelper.oMPD.removeFromPlaylist(mPlaylist, positions); } } catch (final IOException | MPDException e) { Log.e(TAG, "Failed to remove.", e); } if (copy.size() != mSongList.size()) { ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged(); } Tools.notifyUser(R.string.removeCountSongs, count); update(); } } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPlaylist = getIntent().getParcelableExtra(PlaylistFile.EXTRA); if (null != mPlaylist) { mIsPlayQueue = false; } setContentView(R.layout.playlist_editlist_activity); mListView = (ListView) findViewById(android.R.id.list); mListView.setOnItemClickListener(this); if (mIsPlayQueue) { setTitle(R.string.nowPlaying); } else { setTitle(mPlaylist.getName()); } update(); mApp.oMPDAsyncHelper.addStatusChangeListener(this); final DragSortListView trackList = (DragSortListView) mListView; trackList.setOnCreateContextMenuListener(this); trackList.setDropListener(mDropListener); final DragSortController controller = new DragSortController(trackList); controller.setDragHandleId(R.id.icon); controller.setRemoveEnabled(false); controller.setSortEnabled(true); controller.setDragInitMode(1); trackList.setFloatViewManager(controller); trackList.setOnTouchListener(controller); trackList.setDragEnabled(true); trackList.setCacheColorHint(0); final Button button = (Button) findViewById(R.id.Remove); button.setOnClickListener(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void onDestroy() { mApp.oMPDAsyncHelper.removeStatusChangeListener(this); super.onDestroy(); } /** * Marks the selected item for deletion */ @Override public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, final long l) { final AbstractMap<String, Object> item = mSongList.get(i); item.get("marked"); if (item.get("marked").equals(true)) { item.put("marked", false); } else { item.put("marked", true); } ((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Menu actions... switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return false; } } @Override protected void onStart() { super.onStart(); mApp.setActivity(this); } @Override protected void onStop() { super.onStop(); mApp.unsetActivity(this); } @Override public void playlistChanged(final MPDStatus mpdStatus, final int oldPlaylistVersion) { update(); } @Override public void randomChanged(final boolean random) { } @Override public void repeatChanged(final boolean repeating) { } @Override public void stateChanged(final MPDStatus mpdStatus, final int oldState) { } @Override public void stickerChanged(final MPDStatus mpdStatus) { } @Override public void trackChanged(final MPDStatus mpdStatus, final int oldTrack) { if (mIsPlayQueue) { // Mark running track... for (final AbstractMap<String, Object> song : mSongList) { final int songId = ((Integer) song.get(AbstractMusic.RESPONSE_SONG_ID)).intValue(); if (songId == mpdStatus.getSongId()) { song.put("play", android.R.drawable.ic_media_play); } else { song.put("play", 0); } } final SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter(); if (adapter != null) { adapter.notifyDataSetChanged(); } } } protected void update() { // TODO: Preserve position!!! try { final List<Music> musics; if (mIsPlayQueue) { final MPDPlaylist playlist = mApp.oMPDAsyncHelper.oMPD.getPlaylist(); musics = playlist.getMusicList(); } else { musics = mApp.oMPDAsyncHelper.oMPD.getPlaylistSongs(mPlaylist); } mSongList = new ArrayList<>(); final int playingID = mApp.oMPDAsyncHelper.oMPD.getStatus().getSongId(); final int pos = null == mListView ? -1 : mListView.getFirstVisiblePosition(); final View view = null == mListView ? null : mListView.getChildAt(0); final int top = null == view ? -1 : view.getTop(); int listPlayingId = 0; int playlistPosition = 0; // Copy list to avoid concurrent exception for (final Music music : new ArrayList<>(musics)) { final HashMap<String, Object> item = new HashMap<>(); if (mIsPlayQueue) { item.put(AbstractMusic.RESPONSE_SONG_ID, music.getSongId()); } else { item.put(AbstractMusic.RESPONSE_SONG_ID, playlistPosition); } playlistPosition++; item.put(Artist.EXTRA, music.getArtist()); item.put(AbstractMusic.TAG_TITLE, music.getTitle()); item.put("marked", false); if (mIsPlayQueue && music.getSongId() == playingID) { item.put("play", android.R.drawable.ic_media_play); listPlayingId = mSongList.size() - 1; } else { item.put("play", 0); } mSongList.add(item); } final ListAdapter songs = new SimpleAdapter(this, mSongList, R.layout.playlist_editlist_item, new String[]{ "play", AbstractMusic.TAG_TITLE, AbstractMusic.TAG_ARTIST, "marked" }, new int[]{ R.id.picture, android.R.id.text1, android.R.id.text2, R.id.removeCBox }); if (mListView != null) { mListView.setAdapter(songs); if (mIsFirstRefresh) { mIsFirstRefresh = false; if (listPlayingId > 0) { mListView.setSelection(listPlayingId); } } else { if (-1 != pos && -1 != top) { mListView.setSelectionFromTop(pos, top); } } } } catch (final IOException | MPDException e) { Log.d(TAG, "Playlist update failure.", e); } } @Override public void volumeChanged(final MPDStatus mpdStatus, final int oldVolume) { } }
PlaylistEditActivity: Small cleanup for update(). Remove try/catch surrounding entire method, break out the method list retrieval to it's own method.
MPDroid/src/main/java/com/namelessdev/mpdroid/library/PlaylistEditActivity.java
PlaylistEditActivity: Small cleanup for update().
Java
apache-2.0
3bee7aca20ddde7137c874ab918d2dc603d3026e
0
jinmiao0601/okhttp,SunnyDayDev/okhttp,damien5314/okhttp,snodnipper/okhttp,zhupengGitHub/okhttp,adithyaphilip/okhttp,ijidan/okhttp,linyh1993/okhttp,felipecsl/okhttp,shashankvaibhav/okhttp,Gaantz/okhttp,309746069/okhttp,ptornhult/okhttp,huluhaziqi/okhttp,codelion/okhttp,jovezhougang/okhttp,lobo12/okhttp,qingsong-xu/okhttp,yukuoyuan/okhttp,huihui4045/okhttp,tiarebalbi/okhttp,JohnTsaiAndroid/okhttp,marenzo/okhttp,zmarkan/okhttp,jiekekeji/okhttp,b-cuts/okhttp,KENJU/okhttp,ruhaly/okhttp,apoorvmahajan/okhttp,VideoTec/okhttp,LittleApple2015/okhttp,ptornhult/okhttp,jfcalcerrada/okhttp,jiyiren/okhttp,sam-yr/okhttp,cnoldtree/okhttp,lobo12/okhttp,wanjingyan001/okhttp,sam-yr/okhttp,wlrhnh-David/okhttp,VioletLife/okhttp,zhupengGitHub/okhttp,qingsong-xu/okhttp,VideoTec/okhttp,ysjian/okhttp,joansmith/okhttp,airbnb/okhttp,VioletLife/okhttp,minakov/okhttp,xubuhang/okhttp,jovezhougang/okhttp,xph906/NewOKHttp,xubuhang/okhttp,jrodbx/okhttp,Synix/okhttp,NightlyNexus/okhttp,yangzilong1986/okhttp,StarRain/okhttp,SashiAsakura/okhttp,Eagles2F/okhttp,sunshinecoast/okhttp,jfcalcerrada/okhttp,junenn/okhttp,wfxiang08/okhttp,jinmiao0601/okhttp,VikingDen/okhttp,wfxiang08/okhttp,apoorvmahajan/okhttp,germanattanasio/okhttp,lockerfish/okhttp,danielgomezrico/okhttp,lockerfish/okhttp,bestwpw/okhttp,huihui4045/okhttp,Cryhelyxx/okhttp,yanqiangfire/okhttp,jfcalcerrada/okhttp,jinmiao/okhttp,ptornhult/okhttp,yanqiangfire/okhttp,artem-zinnatullin/okhttp,mgp/okhttp,Jinghualun/okhttp,jiekekeji/okhttp,jinmiao/okhttp,MichaelEvans/okhttp,KENJU/okhttp,allen0125/okhttp,SOFTPOWER1991/okhttp,idelpivnitskiy/okhttp,wendelas/okhttp,LB6264/okhttp,yakatak/okhttp,yuhuayi/okhttp,jinmiao0601/okhttp,b-cuts/okhttp,ruikong/okhttp,sunshinecoast/okhttp,yangshangwei/okhttp,sunshinecoast/okhttp,292388900/okhttp,NightlyNexus/okhttp,germanattanasio/okhttp,hanlonghxp/okhttp,ankit3005/okhttp,YlJava110/okhttp,LB6264/okhttp,amikey/okhttp,zmywly8866/okhttp,b-cuts/okhttp,ChanJLee/okhttp,idelpivnitskiy/okhttp,yakatak/okhttp,jokerzzzz/okhttp,teffy/okhttp,fjg1989/okhttp,mikandi/okhttp,xph906/NetProphet,shashankvaibhav/okhttp,tsdl2013/okhttp,elijah513/okhttp,ooon/okhttp,VioletLife/okhttp,damien5314/okhttp,cketti/okhttp,fjg1989/okhttp,lobo12/okhttp,VikingDen/okhttp,LittleApple2015/okhttp,ysjian/okhttp,Cryhelyxx/okhttp,hanlonghxp/okhttp,ankit3005/okhttp,lypdemo/okhttp,ChinaKim/okhttp,yangshangwei/okhttp,xph906/NewOKHttp,xph906/NewOKHttp,ze-pequeno/okhttp,xph906/NetProphet,qinxiandiqi/okhttp,Gaantz/okhttp,ZhQYuan/okhttp,ansman/okhttp,StarRain/okhttp,MichaelEvans/okhttp,qinxiandiqi/okhttp,hesy007/okhttp,nachocove/okhttp,germanattanasio/okhttp,zace-yuan/okhttp,309746069/okhttp,SashiAsakura/okhttp,SashiAsakura/okhttp,Synix/okhttp,ysjian/okhttp,amikey/okhttp,jokerzzzz/okhttp,mgp/okhttp,wfs3006/okhttp,hesy007/okhttp,yuhuayi/okhttp,nachocove/okhttp,Eagles2F/okhttp,ChanJLee/okhttp,elijah513/okhttp,DeathPluto/okhttp,apoorvmahajan/okhttp,snodnipper/okhttp,adithyaphilip/okhttp,ansman/okhttp,hisery/okhttp,joansmith/okhttp,zmarkan/okhttp,idelpivnitskiy/okhttp,yswheye/okhttp,airbnb/okhttp,xuIcream/okhttp,jovezhougang/okhttp,ruhaly/okhttp,AmberWhiteSky/okhttp,cmzy/okhttp,yschimke/okhttp,jiyiren/okhttp,yangzilong1986/okhttp,felipecsl/okhttp,danielgomezrico/okhttp,NerrickT/okhttp,huluhaziqi/okhttp,hgl888/okhttp,tsdl2013/okhttp,yukuoyuan/okhttp,hgl888/okhttp,marcelobns/okhttp,chaitanyajun12/okhttp,xph906/NetProphet,bestwpw/okhttp,ruikong/okhttp,ooon/okhttp,JohnTsaiAndroid/okhttp,jituo666/okhttp,jiyiren/okhttp,zheng1733/okhttp,yswheye/okhttp,nachocove/okhttp,zmarkan/okhttp,marcelobns/okhttp,ijidan/okhttp,bestwpw/okhttp,teffy/okhttp,wanjingyan001/okhttp,damien5314/okhttp,Gaantz/okhttp,cnoldtree/okhttp,ZhQYuan/okhttp,LittleApple2015/okhttp,square/okhttp,yakatak/okhttp,yukuoyuan/okhttp,Jinghualun/okhttp,wfxiang08/okhttp,jrodbx/okhttp,Jinghualun/okhttp,hanlonghxp/okhttp,icefoggy/okhttp,enlyn/okhttp,SOFTPOWER1991/okhttp,LB6264/okhttp,ansman/okhttp,DeathPluto/okhttp,Pannarrow/okhttp,Papuh/okhttp,huihui4045/okhttp,zace-yuan/okhttp,adithyaphilip/okhttp,292388900/okhttp,PatrickDattilio/okhttp,CharlieJiang/okhttp,lypdemo/okhttp,ooon/okhttp,PatrickDattilio/okhttp,PatrickDattilio/okhttp,shashankvaibhav/okhttp,nfuller/okhttp,SunnyDayDev/okhttp,HuangWenhuan0/okhttp,airbnb/okhttp,ChanJLee/okhttp,icefoggy/okhttp,jituo666/okhttp,NerrickT/okhttp,liqk2014/okhttp,linyh1993/okhttp,wfs3006/okhttp,square/okhttp,jiekekeji/okhttp,KENJU/okhttp,jinmiao/okhttp,Voxer/okhttp,zheng1733/okhttp,mjbenedict/okhttp,liqk2014/okhttp,yschimke/okhttp,mikandi/okhttp,qinxiandiqi/okhttp,Pannarrow/okhttp,zmywly8866/okhttp,liqk2014/okhttp,mjbenedict/okhttp,lockerfish/okhttp,309746069/okhttp,codelion/okhttp,yuhuayi/okhttp,CharlieJiang/okhttp,apoorvmahajan/okhttp,wfs3006/okhttp,jokerzzzz/okhttp,zheng1733/okhttp,minakov/okhttp,icefoggy/okhttp,JohnTsaiAndroid/okhttp,amikey/okhttp,cnoldtree/okhttp,chaitanyajun12/okhttp,NerrickT/okhttp,codelion/okhttp,tiarebalbi/okhttp,Voxer/okhttp,292388900/okhttp,yanqiangfire/okhttp,jituo666/okhttp,rschilling/okhttp,SunnyDayDev/okhttp,felipecsl/okhttp,nfuller/okhttp,ijidan/okhttp,HuangWenhuan0/okhttp,marenzo/okhttp,v7lin/okhttp,DeathPluto/okhttp,sam-yr/okhttp,enlyn/okhttp,joansmith/okhttp,zace-yuan/okhttp,wlrhnh-David/okhttp,YlJava110/okhttp,AmberWhiteSky/okhttp,fjg1989/okhttp,minakov/okhttp,NightlyNexus/okhttp,VideoTec/okhttp,Papuh/okhttp,VikingDen/okhttp,zmywly8866/okhttp,chaitanyajun12/okhttp,rschilling/okhttp,ChinaKim/okhttp,huluhaziqi/okhttp,hisery/okhttp,marcelobns/okhttp,Cryhelyxx/okhttp,qingsong-xu/okhttp,cmzy/okhttp,zhupengGitHub/okhttp,yschimke/okhttp,Papuh/okhttp,square/okhttp,jrodbx/okhttp,xuIcream/okhttp,lypdemo/okhttp,junenn/okhttp,Synix/okhttp,allen0125/okhttp,SOFTPOWER1991/okhttp,tiarebalbi/okhttp,junenn/okhttp,enlyn/okhttp,mikandi/okhttp,yswheye/okhttp,YlJava110/okhttp,linyh1993/okhttp,tsdl2013/okhttp,hisery/okhttp,artem-zinnatullin/okhttp,v7lin/okhttp,v7lin/okhttp,rschilling/okhttp,Voxer/okhttp,mgp/okhttp,wanjingyan001/okhttp,CharlieJiang/okhttp,artem-zinnatullin/okhttp,cketti/okhttp,Pannarrow/okhttp,yangzilong1986/okhttp,cketti/okhttp,teffy/okhttp,allen0125/okhttp,danielgomezrico/okhttp,hesy007/okhttp,ze-pequeno/okhttp,xubuhang/okhttp,StarRain/okhttp,elijah513/okhttp,MichaelEvans/okhttp,hgl888/okhttp,ruikong/okhttp,ze-pequeno/okhttp,wendelas/okhttp,wendelas/okhttp,wlrhnh-David/okhttp,mjbenedict/okhttp,Eagles2F/okhttp,ankit3005/okhttp,ruhaly/okhttp,nfuller/okhttp,ZhQYuan/okhttp,snodnipper/okhttp,marenzo/okhttp,HuangWenhuan0/okhttp,xuIcream/okhttp,ChinaKim/okhttp,AmberWhiteSky/okhttp,yangshangwei/okhttp
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.okhttp; import com.squareup.okhttp.internal.Internal; import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.internal.Util; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.File; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.ResponseCache; import java.net.URL; import java.security.Principal; import java.security.cert.Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.GzipSink; import okio.Okio; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static com.squareup.okhttp.mockwebserver.SocketPolicy.DISCONNECT_AT_END; 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.assertTrue; import static org.junit.Assert.fail; /** Test caching with {@link OkUrlFactory}. */ public final class CacheTest { private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; private static final SSLContext sslContext = SslContextBuilder.localhost(); @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); @Rule public MockWebServerRule serverRule = new MockWebServerRule(); @Rule public MockWebServerRule server2Rule = new MockWebServerRule(); private final OkHttpClient client = new OkHttpClient(); private MockWebServer server; private MockWebServer server2; private Cache cache; private final CookieManager cookieManager = new CookieManager(); @Before public void setUp() throws Exception { server = serverRule.get(); server.setProtocolNegotiationEnabled(false); server2 = server2Rule.get(); cache = new Cache(cacheRule.getRoot(), Integer.MAX_VALUE); client.setCache(cache); CookieHandler.setDefault(cookieManager); } @After public void tearDown() throws Exception { ResponseCache.setDefault(null); CookieHandler.setDefault(null); } /** * Test that response caching is consistent with the RI and the spec. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 */ @Test public void responseCachingByResponseCode() throws Exception { // Test each documented HTTP/1.1 code, plus the first unused value in each range. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // We can't test 100 because it's not really a response. // assertCached(false, 100); assertCached(false, 101); assertCached(false, 102); assertCached(true, 200); assertCached(false, 201); assertCached(false, 202); assertCached(true, 203); assertCached(true, 204); assertCached(false, 205); assertCached(false, 206); //Electing to not cache partial responses assertCached(false, 207); assertCached(true, 300); assertCached(true, 301); assertCached(true, 302); assertCached(false, 303); assertCached(false, 304); assertCached(false, 305); assertCached(false, 306); assertCached(true, 307); assertCached(true, 308); assertCached(false, 400); assertCached(false, 401); assertCached(false, 402); assertCached(false, 403); assertCached(true, 404); assertCached(true, 405); assertCached(false, 406); assertCached(false, 408); assertCached(false, 409); // the HTTP spec permits caching 410s, but the RI doesn't. assertCached(true, 410); assertCached(false, 411); assertCached(false, 412); assertCached(false, 413); assertCached(true, 414); assertCached(false, 415); assertCached(false, 416); assertCached(false, 417); assertCached(false, 418); assertCached(false, 500); assertCached(true, 501); assertCached(false, 502); assertCached(false, 503); assertCached(false, 504); assertCached(false, 505); assertCached(false, 506); } private void assertCached(boolean shouldPut, int responseCode) throws Exception { server = new MockWebServer(); MockResponse mockResponse = new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(responseCode) .setBody("ABCDE") .addHeader("WWW-Authenticate: challenge"); if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) { mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\""); } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\""); } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) { mockResponse.setBody(""); // We forbid bodies for 204 and 205. } server.enqueue(mockResponse); server.start(); Request request = new Request.Builder() .url(server.getUrl("/")) .build(); Response response = client.newCall(request).execute(); assertEquals(responseCode, response.code()); // Exhaust the content stream. response.body().string(); Response cached = cache.get(request); if (shouldPut) { assertNotNull(Integer.toString(responseCode), cached); cached.body().close(); } else { assertNull(Integer.toString(responseCode), cached); } server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers } @Test public void responseCachingAndInputStreamSkipWithFixedLength() throws IOException { testResponseCaching(TransferKind.FIXED_LENGTH); } @Test public void responseCachingAndInputStreamSkipWithChunkedEncoding() throws IOException { testResponseCaching(TransferKind.CHUNKED); } @Test public void responseCachingAndInputStreamSkipWithNoLengthHeaders() throws IOException { testResponseCaching(TransferKind.END_OF_STREAM); } /** * Skipping bytes in the input stream caused ResponseCache corruption. * http://code.google.com/p/android/issues/detail?id=8175 */ private void testResponseCaching(TransferKind transferKind) throws IOException { MockResponse mockResponse = new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setStatus("HTTP/1.1 200 Fantastic"); transferKind.setBody(mockResponse, "I love puppies but hate spiders", 1); server.enqueue(mockResponse); // Make sure that calling skip() doesn't omit bytes from the cache. Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in1 = response1.body().source(); assertEquals("I love ", in1.readUtf8("I love ".length())); in1.skip("puppies but hate ".length()); assertEquals("spiders", in1.readUtf8("spiders".length())); assertTrue(in1.exhausted()); in1.close(); assertEquals(1, cache.getWriteSuccessCount()); assertEquals(0, cache.getWriteAbortCount()); Response response2 = client.newCall(request).execute(); BufferedSource in2 = response2.body().source(); assertEquals("I love puppies but hate spiders", in2.readUtf8("I love puppies but hate spiders".length())); assertEquals(200, response2.code()); assertEquals("Fantastic", response2.message()); assertTrue(in2.exhausted()); in2.close(); assertEquals(1, cache.getWriteSuccessCount()); assertEquals(0, cache.getWriteAbortCount()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getHitCount()); } @Test public void secureResponseCaching() throws IOException { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in = response1.body().source(); assertEquals("ABC", in.readUtf8()); // OpenJDK 6 fails on this line, complaining that the connection isn't open yet String suite = response1.handshake().cipherSuite(); List<Certificate> localCerts = response1.handshake().localCertificates(); List<Certificate> serverCerts = response1.handshake().peerCertificates(); Principal peerPrincipal = response1.handshake().peerPrincipal(); Principal localPrincipal = response1.handshake().localPrincipal(); Response response2 = client.newCall(request).execute(); // Cached! assertEquals("ABC", response2.body().source().readUtf8()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(1, cache.getHitCount()); assertEquals(suite, response2.handshake().cipherSuite()); assertEquals(localCerts, response2.handshake().localCertificates()); assertEquals(serverCerts, response2.handshake().peerCertificates()); assertEquals(peerPrincipal, response2.handshake().peerPrincipal()); assertEquals(localPrincipal, response2.handshake().localPrincipal()); } @Test public void responseCachingAndRedirects() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server.enqueue(new MockResponse() .setBody("DEF")); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); assertEquals("ABC", response1.body().string()); Response response2 = client.newCall(request).execute(); // Cached! assertEquals("ABC", response2.body().string()); assertEquals(4, cache.getRequestCount()); // 2 requests + 2 redirects assertEquals(2, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void redirectToCachedResult() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("ABC")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .setBody("DEF")); Request request1 = new Request.Builder().url(server.getUrl("/foo")).build(); Response response1 = client.newCall(request1).execute(); assertEquals("ABC", response1.body().string()); RecordedRequest recordedRequest1 = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", recordedRequest1.getRequestLine()); assertEquals(0, recordedRequest1.getSequenceNumber()); Request request2 = new Request.Builder().url(server.getUrl("/bar")).build(); Response response2 = client.newCall(request2).execute(); assertEquals("ABC", response2.body().string()); RecordedRequest recordedRequest2 = server.takeRequest(); assertEquals("GET /bar HTTP/1.1", recordedRequest2.getRequestLine()); assertEquals(1, recordedRequest2.getSequenceNumber()); // an unrelated request should reuse the pooled connection Request request3 = new Request.Builder().url(server.getUrl("/baz")).build(); Response response3 = client.newCall(request3).execute(); assertEquals("DEF", response3.body().string()); RecordedRequest recordedRequest3 = server.takeRequest(); assertEquals("GET /baz HTTP/1.1", recordedRequest3.getRequestLine()); assertEquals(2, recordedRequest3.getSequenceNumber()); } @Test public void secureResponseCachingAndRedirects() throws IOException { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server.enqueue(new MockResponse() .setBody("DEF")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Response response1 = get(server.getUrl("/")); assertEquals("ABC", response1.body().string()); assertNotNull(response1.handshake().cipherSuite()); // Cached! Response response2 = get(server.getUrl("/")); assertEquals("ABC", response2.body().string()); assertNotNull(response2.handshake().cipherSuite()); assertEquals(4, cache.getRequestCount()); // 2 direct + 2 redirect = 4 assertEquals(2, cache.getHitCount()); assertEquals(response1.handshake().cipherSuite(), response2.handshake().cipherSuite()); } /** * We've had bugs where caching and cross-protocol redirects yield class * cast exceptions internal to the cache because we incorrectly assumed that * HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP; * in practice redirects mean that each can do either. * * https://github.com/square/okhttp/issues/214 */ @Test public void secureResponseCachingAndProtocolRedirects() throws IOException { server2.useHttps(sslContext.getSocketFactory(), false); server2.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server2.enqueue(new MockResponse() .setBody("DEF")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: " + server2.getUrl("/"))); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Response response1 = get(server.getUrl("/")); assertEquals("ABC", response1.body().string()); // Cached! Response response2 = get(server.getUrl("/")); assertEquals("ABC", response2.body().string()); assertEquals(4, cache.getRequestCount()); // 2 direct + 2 redirect = 4 assertEquals(2, cache.getHitCount()); } @Test public void foundCachedWithExpiresHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(302, "Expires", formatDate(1, TimeUnit.HOURS)); } @Test public void foundCachedWithCacheControlHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(302, "Cache-Control", "max-age=60"); } @Test public void temporaryRedirectCachedWithExpiresHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(307, "Expires", formatDate(1, TimeUnit.HOURS)); } @Test public void temporaryRedirectCachedWithCacheControlHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(307, "Cache-Control", "max-age=60"); } @Test public void foundNotCachedWithoutCacheHeader() throws Exception { temporaryRedirectNotCachedWithoutCachingHeader(302); } @Test public void temporaryRedirectNotCachedWithoutCacheHeader() throws Exception { temporaryRedirectNotCachedWithoutCachingHeader(307); } private void temporaryRedirectCachedWithCachingHeader( int responseCode, String headerName, String headerValue) throws Exception { server.enqueue(new MockResponse() .setResponseCode(responseCode) .addHeader(headerName, headerValue) .addHeader("Location", "/a")); server.enqueue(new MockResponse() .addHeader(headerName, headerValue) .setBody("a")); server.enqueue(new MockResponse() .setBody("b")); server.enqueue(new MockResponse() .setBody("c")); URL url = server.getUrl("/"); assertEquals("a", get(url).body().string()); assertEquals("a", get(url).body().string()); } private void temporaryRedirectNotCachedWithoutCachingHeader(int responseCode) throws Exception { server.enqueue(new MockResponse() .setResponseCode(responseCode) .addHeader("Location", "/a")); server.enqueue(new MockResponse() .setBody("a")); server.enqueue(new MockResponse() .setBody("b")); URL url = server.getUrl("/"); assertEquals("a", get(url).body().string()); assertEquals("b", get(url).body().string()); } @Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException { testServerPrematureDisconnect(TransferKind.FIXED_LENGTH); } @Test public void serverDisconnectsPrematurelyWithChunkedEncoding() throws IOException { testServerPrematureDisconnect(TransferKind.CHUNKED); } @Test public void serverDisconnectsPrematurelyWithNoLengthHeaders() throws IOException { // Intentionally empty. This case doesn't make sense because there's no // such thing as a premature disconnect when the disconnect itself // indicates the end of the data stream. } private void testServerPrematureDisconnect(TransferKind transferKind) throws IOException { MockResponse mockResponse = new MockResponse(); transferKind.setBody(mockResponse, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 16); server.enqueue(truncateViolently(mockResponse, 16)); server.enqueue(new MockResponse() .setBody("Request #2")); BufferedSource bodySource = get(server.getUrl("/")).body().source(); assertEquals("ABCDE", bodySource.readUtf8Line()); try { bodySource.readUtf8Line(); fail("This implementation silently ignored a truncated HTTP body."); } catch (IOException expected) { } finally { bodySource.close(); } assertEquals(1, cache.getWriteAbortCount()); assertEquals(0, cache.getWriteSuccessCount()); Response response = get(server.getUrl("/")); assertEquals("Request #2", response.body().string()); assertEquals(1, cache.getWriteAbortCount()); assertEquals(1, cache.getWriteSuccessCount()); } @Test public void clientPrematureDisconnectWithContentLengthHeader() throws IOException { testClientPrematureDisconnect(TransferKind.FIXED_LENGTH); } @Test public void clientPrematureDisconnectWithChunkedEncoding() throws IOException { testClientPrematureDisconnect(TransferKind.CHUNKED); } @Test public void clientPrematureDisconnectWithNoLengthHeaders() throws IOException { testClientPrematureDisconnect(TransferKind.END_OF_STREAM); } private void testClientPrematureDisconnect(TransferKind transferKind) throws IOException { // Setting a low transfer speed ensures that stream discarding will time out. MockResponse mockResponse = new MockResponse() .throttleBody(6, 1, TimeUnit.SECONDS); transferKind.setBody(mockResponse, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 1024); server.enqueue(mockResponse); server.enqueue(new MockResponse() .setBody("Request #2")); Response response1 = get(server.getUrl("/")); BufferedSource in = response1.body().source(); assertEquals("ABCDE", in.readUtf8(5)); in.close(); try { in.readByte(); fail("Expected an IllegalStateException because the source is closed."); } catch (IllegalStateException expected) { } assertEquals(1, cache.getWriteAbortCount()); assertEquals(0, cache.getWriteSuccessCount()); Response response2 = get(server.getUrl("/")); assertEquals("Request #2", response2.body().string()); assertEquals(1, cache.getWriteAbortCount()); assertEquals(1, cache.getWriteSuccessCount()); } @Test public void defaultExpirationDateFullyCachedForLessThan24Hours() throws Exception { // last modified: 105 seconds ago // served: 5 seconds ago // default lifetime: (105 - 5) / 10 = 10 seconds // expires: 10 seconds from served date = 5 seconds from now server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(-5, TimeUnit.SECONDS)) .setBody("A")); URL url = server.getUrl("/"); Response response1 = get(url); assertEquals("A", response1.body().string()); Response response2 = get(url); assertEquals("A", response2.body().string()); assertNull(response2.header("Warning")); } @Test public void defaultExpirationDateConditionallyCached() throws Exception { // last modified: 115 seconds ago // served: 15 seconds ago // default lifetime: (115 - 15) / 10 = 10 seconds // expires: 10 seconds from served date = 5 seconds ago String lastModifiedDate = formatDate(-115, TimeUnit.SECONDS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-15, TimeUnit.SECONDS))); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void defaultExpirationDateFullyCachedForMoreThan24Hours() throws Exception { // last modified: 105 days ago // served: 5 days ago // default lifetime: (105 - 5) / 10 = 10 days // expires: 10 days from served date = 5 days from now server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.DAYS)) .addHeader("Date: " + formatDate(-5, TimeUnit.DAYS)) .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); assertEquals("113 HttpURLConnection \"Heuristic expiration\"", response.header("Warning")); } @Test public void noDefaultExpirationForUrlsWithQueryString() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(-5, TimeUnit.SECONDS)) .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/?foo=bar"); assertEquals("A", get(url).body().string()); assertEquals("B", get(url).body().string()); } @Test public void expirationDateInThePastWithLastModifiedHeader() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void expirationDateInThePastWithNoLastModifiedHeader() throws Exception { assertNotCached(new MockResponse() .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); } @Test public void expirationDateInTheFuture() throws Exception { assertFullyCached(new MockResponse() .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } @Test public void maxAgePreferredWithMaxAgeAndExpires() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInThePastWithDateAndLastModifiedHeaders() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Cache-Control: max-age=60")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void maxAgeInThePastWithDateHeaderButNoLastModifiedHeader() throws Exception { // Chrome interprets max-age relative to the local clock. Both our cache // and Firefox both use the earlier of the local and server's clock. assertNotCached(new MockResponse() .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithDateHeader() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithNoDateHeader() throws Exception { assertFullyCached(new MockResponse() .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeWithLastModifiedButNoServedDate() throws Exception { assertFullyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithDateAndLastModifiedHeaders() throws Exception { assertFullyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgePreferredOverLowerSharedMaxAge() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: s-maxage=60") .addHeader("Cache-Control: max-age=180")); } @Test public void maxAgePreferredOverHigherMaxAge() throws Exception { assertNotCached(new MockResponse() .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: s-maxage=180") .addHeader("Cache-Control: max-age=60")); } @Test public void requestMethodOptionsIsNotCached() throws Exception { testRequestMethod("OPTIONS", false); } @Test public void requestMethodGetIsCached() throws Exception { testRequestMethod("GET", true); } @Test public void requestMethodHeadIsNotCached() throws Exception { // We could support this but choose not to for implementation simplicity testRequestMethod("HEAD", false); } @Test public void requestMethodPostIsNotCached() throws Exception { // We could support this but choose not to for implementation simplicity testRequestMethod("POST", false); } @Test public void requestMethodPutIsNotCached() throws Exception { testRequestMethod("PUT", false); } @Test public void requestMethodDeleteIsNotCached() throws Exception { testRequestMethod("DELETE", false); } @Test public void requestMethodTraceIsNotCached() throws Exception { testRequestMethod("TRACE", false); } private void testRequestMethod(String requestMethod, boolean expectCached) throws Exception { // 1. seed the cache (potentially) // 2. expect a cache hit or miss server.enqueue(new MockResponse() .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("X-Response-ID: 1")); server.enqueue(new MockResponse() .addHeader("X-Response-ID: 2")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .method(requestMethod, requestBodyOrNull(requestMethod)) .build(); Response response1 = client.newCall(request).execute(); response1.body().close(); assertEquals("1", response1.header("X-Response-ID")); Response response2 = get(url); response2.body().close(); if (expectCached) { assertEquals("1", response2.header("X-Response-ID")); } else { assertEquals("2", response2.header("X-Response-ID")); } } private RequestBody requestBodyOrNull(String requestMethod) { return (requestMethod.equals("POST") || requestMethod.equals("PUT")) ? RequestBody.create(MediaType.parse("text/plain"), "foo") : null; } @Test public void postInvalidatesCache() throws Exception { testMethodInvalidates("POST"); } @Test public void putInvalidatesCache() throws Exception { testMethodInvalidates("PUT"); } @Test public void deleteMethodInvalidatesCache() throws Exception { testMethodInvalidates("DELETE"); } private void testMethodInvalidates(String requestMethod) throws Exception { // 1. seed the cache // 2. invalidate it // 3. expect a cache miss server.enqueue(new MockResponse() .setBody("A") .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B")); server.enqueue(new MockResponse() .setBody("C")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .method(requestMethod, requestBodyOrNull(requestMethod)) .build(); Response invalidate = client.newCall(request).execute(); assertEquals("B", invalidate.body().string()); assertEquals("C", get(url).body().string()); } @Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception { // 1. seed the cache // 2. invalidate it with uncacheable response // 3. expect a cache miss server.enqueue(new MockResponse() .setBody("A") .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B") .setResponseCode(500)); server.enqueue(new MockResponse() .setBody("C")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .method("POST", requestBodyOrNull("POST")) .build(); Response invalidate = client.newCall(request).execute(); assertEquals("B", invalidate.body().string()); assertEquals("C", get(url).body().string()); } @Test public void etag() throws Exception { RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("ETag: v1")); assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); } /** If both If-Modified-Since and If-None-Match conditions apply, send only If-None-Match. */ @Test public void etagAndExpirationDateInThePast() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("ETag: v1") .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); assertNull(conditionalRequest.getHeader("If-Modified-Since")); } @Test public void etagAndExpirationDateInTheFuture() throws Exception { assertFullyCached(new MockResponse() .addHeader("ETag: v1") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } @Test public void cacheControlNoCache() throws Exception { assertNotCached(new MockResponse() .addHeader("Cache-Control: no-cache")); } @Test public void cacheControlNoCacheAndExpirationDateInTheFuture() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Cache-Control: no-cache")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void pragmaNoCache() throws Exception { assertNotCached(new MockResponse() .addHeader("Pragma: no-cache")); } @Test public void pragmaNoCacheAndExpirationDateInTheFuture() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Pragma: no-cache")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void cacheControlNoStore() throws Exception { assertNotCached(new MockResponse() .addHeader("Cache-Control: no-store")); } @Test public void cacheControlNoStoreAndExpirationDateInTheFuture() throws Exception { assertNotCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Cache-Control: no-store")); } @Test public void partialRangeResponsesDoNotCorruptCache() throws Exception { // 1. request a range // 2. request a full document, expecting a cache miss server.enqueue(new MockResponse() .setBody("AA") .setResponseCode(HttpURLConnection.HTTP_PARTIAL) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Content-Range: bytes 1000-1001/2000")); server.enqueue(new MockResponse() .setBody("BB")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Range", "bytes=1000-1001") .build(); Response range = client.newCall(request).execute(); assertEquals("AA", range.body().string()); assertEquals("BB", get(url).body().string()); } @Test public void serverReturnsDocumentOlderThanCache() throws Exception { server.enqueue(new MockResponse() .setBody("A") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B") .addHeader("Last-Modified: " + formatDate(-4, TimeUnit.HOURS))); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("A", get(url).body().string()); } @Test public void clientSideNoStore() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("B")); Request request1 = new Request.Builder() .url(server.getUrl("/")) .cacheControl(new CacheControl.Builder().noStore().build()) .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(server.getUrl("/")) .build(); Response response2 = client.newCall(request2).execute(); assertEquals("B", response2.body().string()); } @Test public void nonIdentityEncodingAndConditionalCache() throws Exception { assertNonIdentityEncodingCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); } @Test public void nonIdentityEncodingAndFullCache() throws Exception { assertNonIdentityEncodingCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } private void assertNonIdentityEncodingCached(MockResponse response) throws Exception { server.enqueue(response .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // At least three request/response pairs are required because after the first request is cached // a different execution path might be taken. Thus modifications to the cache applied during // the second request might not be visible until another request is performed. assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); } @Test public void notModifiedSpecifiesEncoding() throws Exception { server.enqueue(new MockResponse() .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED) .addHeader("Content-Encoding: gzip")); server.enqueue(new MockResponse() .setBody("DEFDEFDEF")); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("DEFDEFDEF", get(server.getUrl("/")).body().string()); } /** https://github.com/square/okhttp/issues/947 */ @Test public void gzipAndVaryOnAcceptEncoding() throws Exception { server.enqueue(new MockResponse() .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip") .addHeader("Vary: Accept-Encoding") .addHeader("Cache-Control: max-age=60")); server.enqueue(new MockResponse() .setBody("FAIL")); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); } @Test public void conditionalCacheHitIsNotDoublePooled() throws Exception { server.enqueue(new MockResponse() .addHeader("ETag: v1") .setBody("A")); server.enqueue(new MockResponse() .clearHeaders() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); ConnectionPool pool = ConnectionPool.getDefault(); pool.evictAll(); client.setConnectionPool(pool); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, client.getConnectionPool().getConnectionCount()); } @Test public void expiresDateBeforeModifiedDate() throws Exception { assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-2, TimeUnit.HOURS))); } @Test public void requestMaxAge() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-age=30") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestMinFresh() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=60") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "min-fresh=120") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestMaxStale() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); } @Test public void requestMaxStaleDirectiveWithNoValue() throws IOException { // Add a stale response to the cache. server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); // With max-stale, we'll return that stale response. Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); } @Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120, must-revalidate") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestOnlyIfCachedWithNoResponseCached() throws IOException { // (no responses enqueued) Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(1, cache.getRequestCount()); assertEquals(0, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithFullResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(1, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithConditionalResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithUnhelpfulResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestCacheControlNoCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header("Cache-Control", "no-cache") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestPragmaNoCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header("Pragma", "no-cache") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void clientSuppliedIfModifiedSinceWithCachedResult() throws Exception { MockResponse response = new MockResponse() .addHeader("ETag: v3") .addHeader("Cache-Control: max-age=0"); String ifModifiedSinceDate = formatDate(-24, TimeUnit.HOURS); RecordedRequest request = assertClientSuppliedCondition(response, "If-Modified-Since", ifModifiedSinceDate); assertEquals(ifModifiedSinceDate, request.getHeader("If-Modified-Since")); assertNull(request.getHeader("If-None-Match")); } @Test public void clientSuppliedIfNoneMatchSinceWithCachedResult() throws Exception { String lastModifiedDate = formatDate(-3, TimeUnit.MINUTES); MockResponse response = new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: max-age=0"); RecordedRequest request = assertClientSuppliedCondition(response, "If-None-Match", "v1"); assertEquals("v1", request.getHeader("If-None-Match")); assertNull(request.getHeader("If-Modified-Since")); } private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String conditionName, String conditionValue) throws Exception { server.enqueue(seed.setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header(conditionName, conditionValue) .build(); Response response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); assertEquals("", response.body().string()); server.takeRequest(); // seed return server.takeRequest(); } /** * For Last-Modified and Date headers, we should echo the date back in the * exact format we were served. */ @Test public void retainServedDateFormat() throws Exception { // Serve a response with a non-standard date format that OkHttp supports. Date lastModifiedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-1)); Date servedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-2)); DateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("EDT")); String lastModifiedString = dateFormat.format(lastModifiedDate); String servedString = dateFormat.format(servedDate); // This response should be conditionally cached. server.enqueue(new MockResponse() .addHeader("Last-Modified: " + lastModifiedString) .addHeader("Expires: " + servedString) .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); // The first request has no conditions. RecordedRequest request1 = server.takeRequest(); assertNull(request1.getHeader("If-Modified-Since")); // The 2nd request uses the server's date format. RecordedRequest request2 = server.takeRequest(); assertEquals(lastModifiedString, request2.getHeader("If-Modified-Since")); } @Test public void clientSuppliedConditionWithoutCachedResult() throws Exception { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Request request = new Request.Builder() .url(server.getUrl("/")) .header("If-Modified-Since", formatDate(-24, TimeUnit.HOURS)) .build(); Response response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); assertEquals("", response.body().string()); } @Test public void authorizationRequestFullyCached() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Authorization", "password") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("A", get(url).body().string()); } @Test public void contentLocationDoesNotPopulateCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Content-Location: /bar") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/foo")).body().string()); assertEquals("B", get(server.getUrl("/bar")).body().string()); } @Test public void connectionIsReturnedToPoolAfterConditionalSuccess() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/a")).body().string()); assertEquals("A", get(server.getUrl("/a")).body().string()); assertEquals("B", get(server.getUrl("/b")).body().string()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); assertEquals(2, server.takeRequest().getSequenceNumber()); } @Test public void statisticsConditionalCacheMiss() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); server.enqueue(new MockResponse() .setBody("C")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("B", get(server.getUrl("/")).body().string()); assertEquals("C", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(3, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void statisticsConditionalCacheHit() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(3, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void statisticsFullCacheHit() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void varyMatchesChangedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request frRequest = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response frResponse = client.newCall(frRequest).execute(); assertEquals("A", frResponse.body().string()); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response enResponse = client.newCall(enRequest).execute(); assertEquals("B", enResponse.body().string()); } @Test public void varyMatchesUnchangedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMatchesAbsentRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); } @Test public void varyMatchesAddedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Foo", "bar") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void varyMatchesRemovedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Foo", "bar") .build(); Response fooresponse = client.newCall(request).execute(); assertEquals("A", fooresponse.body().string()); assertEquals("B", get(server.getUrl("/")).body().string()); } @Test public void varyFieldsAreCaseInsensitive() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: ACCEPT-LANGUAGE") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("accept-language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldsWithMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language, Accept-Charset") .addHeader("Vary: Accept-Encoding") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldsWithNoMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language, Accept-Charset") .addHeader("Vary: Accept-Encoding") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request frRequest = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response frResponse = client.newCall(frRequest).execute(); assertEquals("A", frResponse.body().string()); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response enResponse = client.newCall(enRequest).execute(); assertEquals("B", enResponse.body().string()); } @Test public void varyMultipleFieldValuesWithMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldValuesWithNoMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA") .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("B", response2.body().string()); } @Test public void varyAsterisk() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: *") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("B", get(server.getUrl("/")).body().string()); } @Test public void varyAndHttps() throws Exception { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("A", response2.body().string()); } @Test public void cachePlusCookies() throws Exception { server.enqueue(new MockResponse() .addHeader("Set-Cookie: a=FIRST; domain=" + server.getCookieDomain() + ";") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Set-Cookie: a=SECOND; domain=" + server.getCookieDomain() + ";") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertCookies(url, "a=FIRST"); assertEquals("A", get(url).body().string()); assertCookies(url, "a=SECOND"); } @Test public void getHeadersReturnsNetworkEndToEndHeaders() throws Exception { server.enqueue(new MockResponse() .addHeader("Allow: GET, HEAD") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Allow: GET, HEAD, PUT") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("GET, HEAD", response1.header("Allow")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("GET, HEAD, PUT", response2.header("Allow")); } @Test public void getHeadersReturnsCachedHopByHopHeaders() throws Exception { server.enqueue(new MockResponse() .addHeader("Transfer-Encoding: identity") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Transfer-Encoding: none") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("identity", response1.header("Transfer-Encoding")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("identity", response2.header("Transfer-Encoding")); } @Test public void getHeadersDeletesCached100LevelWarnings() throws Exception { server.enqueue(new MockResponse() .addHeader("Warning: 199 test danger") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("199 test danger", response1.header("Warning")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals(null, response2.header("Warning")); } @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { server.enqueue(new MockResponse() .addHeader("Warning: 299 test danger") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("299 test danger", response1.header("Warning")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("299 test danger", response2.header("Warning")); } public void assertCookies(URL url, String... expectedCookies) throws Exception { List<String> actualCookies = new ArrayList<>(); for (HttpCookie cookie : cookieManager.getCookieStore().get(url.toURI())) { actualCookies.add(cookie.toString()); } assertEquals(Arrays.asList(expectedCookies), actualCookies); } @Test public void doNotCachePartialResponse() throws Exception { assertNotCached(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_PARTIAL) .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Content-Range: bytes 100-100/200") .addHeader("Cache-Control: max-age=60")); } @Test public void conditionalHitUpdatesCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=30") .addHeader("Allow: GET, HEAD") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); // cache miss; seed the cache Response response1 = get(server.getUrl("/a")); assertEquals("A", response1.body().string()); assertEquals(null, response1.header("Allow")); // conditional cache hit; update the cache Response response2 = get(server.getUrl("/a")); assertEquals(HttpURLConnection.HTTP_OK, response2.code()); assertEquals("A", response2.body().string()); assertEquals("GET, HEAD", response2.header("Allow")); // full cache hit Response response3 = get(server.getUrl("/a")); assertEquals("A", response3.body().string()); assertEquals("GET, HEAD", response3.header("Allow")); assertEquals(2, server.getRequestCount()); } @Test public void responseSourceHeaderCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); } @Test public void responseSourceHeaderConditionalCacheFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(-31, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("B", response.body().string()); } @Test public void responseSourceHeaderConditionalCacheNotFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=0") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setResponseCode(304)); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); } @Test public void responseSourceHeaderFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A")); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); } @Test public void emptyResponseHeaderNameFromCacheIsLenient() throws Exception { Headers.Builder headers = new Headers.Builder() .add("Cache-Control: max-age=120"); Internal.instance.addLenient(headers, ": A"); server.enqueue(new MockResponse() .setHeaders(headers.build()) .setBody("body")); Response response = get(server.getUrl("/")); assertEquals("A", response.header("")); } /** * Old implementations of OkHttp's response cache wrote header fields like * ":status: 200 OK". This broke our cached response parser because it split * on the first colon. This regression test exists to help us read these old * bad cache entries. * * https://github.com/square/okhttp/issues/227 */ @Test public void testGoldenCacheResponse() throws Exception { cache.close(); server.enqueue(new MockResponse() .clearHeaders() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); String urlKey = Util.md5Hex(url.toString()); String entryMetadata = "" + "" + url + "\n" + "GET\n" + "0\n" + "HTTP/1.1 200 OK\n" + "7\n" + ":status: 200 OK\n" + ":version: HTTP/1.1\n" + "etag: foo\n" + "content-length: 3\n" + "OkHttp-Received-Millis: " + System.currentTimeMillis() + "\n" + "X-Android-Response-Source: NETWORK 200\n" + "OkHttp-Sent-Millis: " + System.currentTimeMillis() + "\n" + "\n" + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n" + "1\n" + "MIIBpDCCAQ2gAwIBAgIBATANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDEw1qd2lsc29uLmxvY2FsMB4XDTEzMDgy" + "OTA1MDE1OVoXDTEzMDgzMDA1MDE1OVowGDEWMBQGA1UEAxMNandpbHNvbi5sb2NhbDCBnzANBgkqhkiG9w0BAQEF" + "AAOBjQAwgYkCgYEAlFW+rGo/YikCcRghOyKkJanmVmJSce/p2/jH1QvNIFKizZdh8AKNwojt3ywRWaDULA/RlCUc" + "ltF3HGNsCyjQI/+Lf40x7JpxXF8oim1E6EtDoYtGWAseelawus3IQ13nmo6nWzfyCA55KhAWf4VipelEy8DjcuFK" + "v6L0xwXnI0ECAwEAATANBgkqhkiG9w0BAQsFAAOBgQAuluNyPo1HksU3+Mr/PyRQIQS4BI7pRXN8mcejXmqyscdP" + "7S6J21FBFeRR8/XNjVOp4HT9uSc2hrRtTEHEZCmpyoxixbnM706ikTmC7SN/GgM+SmcoJ1ipJcNcl8N0X6zym4dm" + "yFfXKHu2PkTo7QFdpOJFvP3lIigcSZXozfmEDg==\n" + "-1\n"; String entryBody = "abc"; String journalBody = "" + "libcore.io.DiskLruCache\n" + "1\n" + "201105\n" + "2\n" + "\n" + "CLEAN " + urlKey + " " + entryMetadata.length() + " " + entryBody.length() + "\n"; writeFile(cache.getDirectory(), urlKey + ".0", entryMetadata); writeFile(cache.getDirectory(), urlKey + ".1", entryBody); writeFile(cache.getDirectory(), "journal", journalBody); cache = new Cache(cache.getDirectory(), Integer.MAX_VALUE); client.setCache(cache); Response response = get(url); assertEquals(entryBody, response.body().string()); assertEquals("3", response.header("Content-Length")); assertEquals("foo", response.header("etag")); } @Test public void evictAll() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); client.getCache().evictAll(); assertEquals(0, client.getCache().getSize()); assertEquals("B", get(url).body().string()); } @Test public void networkInterceptorInvokedForConditionalGet() throws Exception { server.enqueue(new MockResponse() .addHeader("ETag: v1") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // Seed the cache. URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); final AtomicReference<String> ifNoneMatch = new AtomicReference<>(); client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match")); return chain.proceed(chain.request()); } }); // Confirm the value is cached and intercepted. assertEquals("A", get(url).body().string()); assertEquals("v1", ifNoneMatch.get()); } @Test public void networkInterceptorNotInvokedForFullyCached() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); // Seed the cache. URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); // Confirm the interceptor isn't exercised. client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { throw new AssertionError(); } }); assertEquals("A", get(url).body().string()); } @Test public void iterateCache() throws Exception { // Put some responses in the cache. server.enqueue(new MockResponse() .setBody("a")); URL urlA = server.getUrl("/a"); assertEquals("a", get(urlA).body().string()); server.enqueue(new MockResponse() .setBody("b")); URL urlB = server.getUrl("/b"); assertEquals("b", get(urlB).body().string()); server.enqueue(new MockResponse() .setBody("c")); URL urlC = server.getUrl("/c"); assertEquals("c", get(urlC).body().string()); // Confirm the iterator returns those responses... Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); assertEquals(urlA.toString(), i.next()); assertTrue(i.hasNext()); assertEquals(urlB.toString(), i.next()); assertTrue(i.hasNext()); assertEquals(urlC.toString(), i.next()); // ... and nothing else. assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } @Test public void iteratorRemoveFromCache() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); // Remove it with iteration. Iterator<String> i = cache.urls(); assertEquals(url.toString(), i.next()); i.remove(); // Confirm that subsequent requests suffer a cache miss. server.enqueue(new MockResponse() .setBody("b")); assertEquals("b", get(url).body().string()); } @Test public void iteratorRemoveWithoutNextThrows() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); try { i.remove(); fail(); } catch (IllegalStateException expected) { } } @Test public void iteratorRemoveOncePerCallToNext() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); assertEquals(url.toString(), i.next()); i.remove(); // Too many calls to remove(). try { i.remove(); fail(); } catch (IllegalStateException expected) { } } @Test public void elementEvictedBetweenHasNextAndNext() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); // The URL will remain available if hasNext() returned true... Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); // ...so even when we evict the element, we still get something back. cache.evictAll(); assertEquals(url.toString(), i.next()); // Remove does nothing. But most importantly, it doesn't throw! i.remove(); } @Test public void elementEvictedBeforeHasNextIsOmitted() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); cache.evictAll(); // The URL was evicted before hasNext() made any promises. assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } /** Test https://github.com/square/okhttp/issues/1712. */ @Test public void conditionalMissUpdatesCache() throws Exception { server.enqueue(new MockResponse() .addHeader("ETag: v1") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .addHeader("ETag: v2") .setBody("B")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("A", get(url).body().string()); assertEquals("B", get(url).body().string()); assertEquals("B", get(url).body().string()); assertEquals(null, server.takeRequest().getHeader("If-None-Match")); assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); assertEquals("v2", server.takeRequest().getHeader("If-None-Match")); } private Response get(URL url) throws IOException { Request request = new Request.Builder() .url(url) .build(); return client.newCall(request).execute(); } private void writeFile(File directory, String file, String content) throws IOException { BufferedSink sink = Okio.buffer(Okio.sink(new File(directory, file))); sink.writeUtf8(content); sink.close(); } /** * @param delta the offset from the current date to use. Negative * values yield dates in the past; positive values yield dates in the * future. */ private String formatDate(long delta, TimeUnit timeUnit) { return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta))); } private String formatDate(Date date) { DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123.format(date); } private void assertNotCached(MockResponse response) throws Exception { server.enqueue(response.setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("B", get(url).body().string()); } /** @return the request with the conditional get headers. */ private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception { // scenario 1: condition succeeds server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // scenario 2: condition fails server.enqueue(response.setBody("B") .setStatus("HTTP/1.1 200 B-OK")); server.enqueue(new MockResponse() .setStatus("HTTP/1.1 200 C-OK") .setBody("C")); URL valid = server.getUrl("/valid"); Response response1 = get(valid); assertEquals("A", response1.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response1.code()); assertEquals("A-OK", response1.message()); Response response2 = get(valid); assertEquals("A", response2.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response2.code()); assertEquals("A-OK", response2.message()); URL invalid = server.getUrl("/invalid"); Response response3 = get(invalid); assertEquals("B", response3.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response3.code()); assertEquals("B-OK", response3.message()); Response response4 = get(invalid); assertEquals("C", response4.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response4.code()); assertEquals("C-OK", response4.message()); server.takeRequest(); // regular get return server.takeRequest(); // conditional get } private void assertFullyCached(MockResponse response) throws Exception { server.enqueue(response.setBody("A")); server.enqueue(response.setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("A", get(url).body().string()); } /** * Shortens the body of {@code response} but not the corresponding headers. * Only useful to test how clients respond to the premature conclusion of * the HTTP body. */ private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) { response.setSocketPolicy(DISCONNECT_AT_END); Headers headers = response.getHeaders(); Buffer truncatedBody = new Buffer(); truncatedBody.write(response.getBody(), numBytesToKeep); response.setBody(truncatedBody); response.setHeaders(headers); return response; } enum TransferKind { CHUNKED() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) throws IOException { response.setChunkedBody(content, chunkSize); } }, FIXED_LENGTH() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) { response.setBody(content); } }, END_OF_STREAM() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) { response.setBody(content); response.setSocketPolicy(DISCONNECT_AT_END); response.removeHeader("Content-Length"); } }; abstract void setBody(MockResponse response, Buffer content, int chunkSize) throws IOException; void setBody(MockResponse response, String content, int chunkSize) throws IOException { setBody(response, new Buffer().writeUtf8(content), chunkSize); } } /** Returns a gzipped copy of {@code bytes}. */ public Buffer gzip(String data) throws IOException { Buffer result = new Buffer(); BufferedSink sink = Okio.buffer(new GzipSink(result)); sink.writeUtf8(data); sink.close(); return result; } }
okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.okhttp; import com.squareup.okhttp.internal.Internal; import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.internal.Util; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.File; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.ResponseCache; import java.net.URL; import java.security.Principal; import java.security.cert.Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.GzipSink; import okio.Okio; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static com.squareup.okhttp.mockwebserver.SocketPolicy.DISCONNECT_AT_END; 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.assertTrue; import static org.junit.Assert.fail; /** Test caching with {@link OkUrlFactory}. */ public final class CacheTest { private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; private static final SSLContext sslContext = SslContextBuilder.localhost(); @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); @Rule public MockWebServerRule serverRule = new MockWebServerRule(); @Rule public MockWebServerRule server2Rule = new MockWebServerRule(); private final OkHttpClient client = new OkHttpClient(); private MockWebServer server; private MockWebServer server2; private Cache cache; private final CookieManager cookieManager = new CookieManager(); @Before public void setUp() throws Exception { server = serverRule.get(); server.setProtocolNegotiationEnabled(false); server2 = server2Rule.get(); cache = new Cache(cacheRule.getRoot(), Integer.MAX_VALUE); client.setCache(cache); CookieHandler.setDefault(cookieManager); } @After public void tearDown() throws Exception { ResponseCache.setDefault(null); CookieHandler.setDefault(null); } /** * Test that response caching is consistent with the RI and the spec. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 */ @Test public void responseCachingByResponseCode() throws Exception { // Test each documented HTTP/1.1 code, plus the first unused value in each range. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // We can't test 100 because it's not really a response. // assertCached(false, 100); assertCached(false, 101); assertCached(false, 102); assertCached(true, 200); assertCached(false, 201); assertCached(false, 202); assertCached(true, 203); assertCached(true, 204); assertCached(false, 205); assertCached(false, 206); //Electing to not cache partial responses assertCached(false, 207); assertCached(true, 300); assertCached(true, 301); assertCached(true, 302); assertCached(false, 303); assertCached(false, 304); assertCached(false, 305); assertCached(false, 306); assertCached(true, 307); assertCached(true, 308); assertCached(false, 400); assertCached(false, 401); assertCached(false, 402); assertCached(false, 403); assertCached(true, 404); assertCached(true, 405); assertCached(false, 406); assertCached(false, 408); assertCached(false, 409); // the HTTP spec permits caching 410s, but the RI doesn't. assertCached(true, 410); assertCached(false, 411); assertCached(false, 412); assertCached(false, 413); assertCached(true, 414); assertCached(false, 415); assertCached(false, 416); assertCached(false, 417); assertCached(false, 418); assertCached(false, 500); assertCached(true, 501); assertCached(false, 502); assertCached(false, 503); assertCached(false, 504); assertCached(false, 505); assertCached(false, 506); } private void assertCached(boolean shouldPut, int responseCode) throws Exception { server = new MockWebServer(); MockResponse mockResponse = new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(responseCode) .setBody("ABCDE") .addHeader("WWW-Authenticate: challenge"); if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) { mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\""); } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\""); } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_RESET) { mockResponse.setBody(""); // We forbid bodies for 204 and 205. } server.enqueue(mockResponse); server.start(); Request request = new Request.Builder() .url(server.getUrl("/")) .build(); Response response = client.newCall(request).execute(); assertEquals(responseCode, response.code()); // Exhaust the content stream. response.body().string(); Response cached = cache.get(request); if (shouldPut) { assertNotNull(Integer.toString(responseCode), cached); cached.body().close(); } else { assertNull(Integer.toString(responseCode), cached); } server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers } @Test public void responseCachingAndInputStreamSkipWithFixedLength() throws IOException { testResponseCaching(TransferKind.FIXED_LENGTH); } @Test public void responseCachingAndInputStreamSkipWithChunkedEncoding() throws IOException { testResponseCaching(TransferKind.CHUNKED); } @Test public void responseCachingAndInputStreamSkipWithNoLengthHeaders() throws IOException { testResponseCaching(TransferKind.END_OF_STREAM); } /** * Skipping bytes in the input stream caused ResponseCache corruption. * http://code.google.com/p/android/issues/detail?id=8175 */ private void testResponseCaching(TransferKind transferKind) throws IOException { MockResponse mockResponse = new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setStatus("HTTP/1.1 200 Fantastic"); transferKind.setBody(mockResponse, "I love puppies but hate spiders", 1); server.enqueue(mockResponse); // Make sure that calling skip() doesn't omit bytes from the cache. Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in1 = response1.body().source(); assertEquals("I love ", in1.readUtf8("I love ".length())); in1.skip("puppies but hate ".length()); assertEquals("spiders", in1.readUtf8("spiders".length())); assertTrue(in1.exhausted()); in1.close(); assertEquals(1, cache.getWriteSuccessCount()); assertEquals(0, cache.getWriteAbortCount()); Response response2 = client.newCall(request).execute(); BufferedSource in2 = response2.body().source(); assertEquals("I love puppies but hate spiders", in2.readUtf8("I love puppies but hate spiders".length())); assertEquals(200, response2.code()); assertEquals("Fantastic", response2.message()); assertTrue(in2.exhausted()); in2.close(); assertEquals(1, cache.getWriteSuccessCount()); assertEquals(0, cache.getWriteAbortCount()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getHitCount()); } @Test public void secureResponseCaching() throws IOException { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in = response1.body().source(); assertEquals("ABC", in.readUtf8()); // OpenJDK 6 fails on this line, complaining that the connection isn't open yet String suite = response1.handshake().cipherSuite(); List<Certificate> localCerts = response1.handshake().localCertificates(); List<Certificate> serverCerts = response1.handshake().peerCertificates(); Principal peerPrincipal = response1.handshake().peerPrincipal(); Principal localPrincipal = response1.handshake().localPrincipal(); Response response2 = client.newCall(request).execute(); // Cached! assertEquals("ABC", response2.body().source().readUtf8()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(1, cache.getHitCount()); assertEquals(suite, response2.handshake().cipherSuite()); assertEquals(localCerts, response2.handshake().localCertificates()); assertEquals(serverCerts, response2.handshake().peerCertificates()); assertEquals(peerPrincipal, response2.handshake().peerPrincipal()); assertEquals(localPrincipal, response2.handshake().localPrincipal()); } @Test public void responseCachingAndRedirects() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server.enqueue(new MockResponse() .setBody("DEF")); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request).execute(); assertEquals("ABC", response1.body().string()); Response response2 = client.newCall(request).execute(); // Cached! assertEquals("ABC", response2.body().string()); assertEquals(4, cache.getRequestCount()); // 2 requests + 2 redirects assertEquals(2, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void redirectToCachedResult() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("ABC")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .setBody("DEF")); Request request1 = new Request.Builder().url(server.getUrl("/foo")).build(); Response response1 = client.newCall(request1).execute(); assertEquals("ABC", response1.body().string()); RecordedRequest recordedRequest1 = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", recordedRequest1.getRequestLine()); assertEquals(0, recordedRequest1.getSequenceNumber()); Request request2 = new Request.Builder().url(server.getUrl("/bar")).build(); Response response2 = client.newCall(request2).execute(); assertEquals("ABC", response2.body().string()); RecordedRequest recordedRequest2 = server.takeRequest(); assertEquals("GET /bar HTTP/1.1", recordedRequest2.getRequestLine()); assertEquals(1, recordedRequest2.getSequenceNumber()); // an unrelated request should reuse the pooled connection Request request3 = new Request.Builder().url(server.getUrl("/baz")).build(); Response response3 = client.newCall(request3).execute(); assertEquals("DEF", response3.body().string()); RecordedRequest recordedRequest3 = server.takeRequest(); assertEquals("GET /baz HTTP/1.1", recordedRequest3.getRequestLine()); assertEquals(2, recordedRequest3.getSequenceNumber()); } @Test public void secureResponseCachingAndRedirects() throws IOException { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: /foo")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server.enqueue(new MockResponse() .setBody("DEF")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Response response1 = get(server.getUrl("/")); assertEquals("ABC", response1.body().string()); assertNotNull(response1.handshake().cipherSuite()); // Cached! Response response2 = get(server.getUrl("/")); assertEquals("ABC", response2.body().string()); assertNotNull(response2.handshake().cipherSuite()); assertEquals(4, cache.getRequestCount()); // 2 direct + 2 redirect = 4 assertEquals(2, cache.getHitCount()); assertEquals(response1.handshake().cipherSuite(), response2.handshake().cipherSuite()); } /** * We've had bugs where caching and cross-protocol redirects yield class * cast exceptions internal to the cache because we incorrectly assumed that * HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP; * in practice redirects mean that each can do either. * * https://github.com/square/okhttp/issues/214 */ @Test public void secureResponseCachingAndProtocolRedirects() throws IOException { server2.useHttps(sslContext.getSocketFactory(), false); server2.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); server2.enqueue(new MockResponse() .setBody("DEF")); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM) .addHeader("Location: " + server2.getUrl("/"))); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); Response response1 = get(server.getUrl("/")); assertEquals("ABC", response1.body().string()); // Cached! Response response2 = get(server.getUrl("/")); assertEquals("ABC", response2.body().string()); assertEquals(4, cache.getRequestCount()); // 2 direct + 2 redirect = 4 assertEquals(2, cache.getHitCount()); } @Test public void foundCachedWithExpiresHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(302, "Expires", formatDate(1, TimeUnit.HOURS)); } @Test public void foundCachedWithCacheControlHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(302, "Cache-Control", "max-age=60"); } @Test public void temporaryRedirectCachedWithExpiresHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(307, "Expires", formatDate(1, TimeUnit.HOURS)); } @Test public void temporaryRedirectCachedWithCacheControlHeader() throws Exception { temporaryRedirectCachedWithCachingHeader(307, "Cache-Control", "max-age=60"); } @Test public void foundNotCachedWithoutCacheHeader() throws Exception { temporaryRedirectNotCachedWithoutCachingHeader(302); } @Test public void temporaryRedirectNotCachedWithoutCacheHeader() throws Exception { temporaryRedirectNotCachedWithoutCachingHeader(307); } private void temporaryRedirectCachedWithCachingHeader( int responseCode, String headerName, String headerValue) throws Exception { server.enqueue(new MockResponse() .setResponseCode(responseCode) .addHeader(headerName, headerValue) .addHeader("Location", "/a")); server.enqueue(new MockResponse() .addHeader(headerName, headerValue) .setBody("a")); server.enqueue(new MockResponse() .setBody("b")); server.enqueue(new MockResponse() .setBody("c")); URL url = server.getUrl("/"); assertEquals("a", get(url).body().string()); assertEquals("a", get(url).body().string()); } private void temporaryRedirectNotCachedWithoutCachingHeader(int responseCode) throws Exception { server.enqueue(new MockResponse() .setResponseCode(responseCode) .addHeader("Location", "/a")); server.enqueue(new MockResponse() .setBody("a")); server.enqueue(new MockResponse() .setBody("b")); URL url = server.getUrl("/"); assertEquals("a", get(url).body().string()); assertEquals("b", get(url).body().string()); } @Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException { testServerPrematureDisconnect(TransferKind.FIXED_LENGTH); } @Test public void serverDisconnectsPrematurelyWithChunkedEncoding() throws IOException { testServerPrematureDisconnect(TransferKind.CHUNKED); } @Test public void serverDisconnectsPrematurelyWithNoLengthHeaders() throws IOException { // Intentionally empty. This case doesn't make sense because there's no // such thing as a premature disconnect when the disconnect itself // indicates the end of the data stream. } private void testServerPrematureDisconnect(TransferKind transferKind) throws IOException { MockResponse mockResponse = new MockResponse(); transferKind.setBody(mockResponse, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 16); server.enqueue(truncateViolently(mockResponse, 16)); server.enqueue(new MockResponse() .setBody("Request #2")); BufferedSource bodySource = get(server.getUrl("/")).body().source(); assertEquals("ABCDE", bodySource.readUtf8Line()); try { bodySource.readUtf8Line(); fail("This implementation silently ignored a truncated HTTP body."); } catch (IOException expected) { } finally { bodySource.close(); } assertEquals(1, cache.getWriteAbortCount()); assertEquals(0, cache.getWriteSuccessCount()); Response response = get(server.getUrl("/")); assertEquals("Request #2", response.body().string()); assertEquals(1, cache.getWriteAbortCount()); assertEquals(1, cache.getWriteSuccessCount()); } @Test public void clientPrematureDisconnectWithContentLengthHeader() throws IOException { testClientPrematureDisconnect(TransferKind.FIXED_LENGTH); } @Test public void clientPrematureDisconnectWithChunkedEncoding() throws IOException { testClientPrematureDisconnect(TransferKind.CHUNKED); } @Test public void clientPrematureDisconnectWithNoLengthHeaders() throws IOException { testClientPrematureDisconnect(TransferKind.END_OF_STREAM); } private void testClientPrematureDisconnect(TransferKind transferKind) throws IOException { // Setting a low transfer speed ensures that stream discarding will time out. MockResponse mockResponse = new MockResponse() .throttleBody(6, 1, TimeUnit.SECONDS); transferKind.setBody(mockResponse, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 1024); server.enqueue(mockResponse); server.enqueue(new MockResponse() .setBody("Request #2")); Response response1 = get(server.getUrl("/")); BufferedSource in = response1.body().source(); assertEquals("ABCDE", in.readUtf8(5)); in.close(); try { in.readByte(); fail("Expected an IllegalStateException because the source is closed."); } catch (IllegalStateException expected) { } assertEquals(1, cache.getWriteAbortCount()); assertEquals(0, cache.getWriteSuccessCount()); Response response2 = get(server.getUrl("/")); assertEquals("Request #2", response2.body().string()); assertEquals(1, cache.getWriteAbortCount()); assertEquals(1, cache.getWriteSuccessCount()); } @Test public void defaultExpirationDateFullyCachedForLessThan24Hours() throws Exception { // last modified: 105 seconds ago // served: 5 seconds ago // default lifetime: (105 - 5) / 10 = 10 seconds // expires: 10 seconds from served date = 5 seconds from now server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(-5, TimeUnit.SECONDS)) .setBody("A")); URL url = server.getUrl("/"); Response response1 = get(url); assertEquals("A", response1.body().string()); Response response2 = get(url); assertEquals("A", response2.body().string()); assertNull(response2.header("Warning")); } @Test public void defaultExpirationDateConditionallyCached() throws Exception { // last modified: 115 seconds ago // served: 15 seconds ago // default lifetime: (115 - 15) / 10 = 10 seconds // expires: 10 seconds from served date = 5 seconds ago String lastModifiedDate = formatDate(-115, TimeUnit.SECONDS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-15, TimeUnit.SECONDS))); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void defaultExpirationDateFullyCachedForMoreThan24Hours() throws Exception { // last modified: 105 days ago // served: 5 days ago // default lifetime: (105 - 5) / 10 = 10 days // expires: 10 days from served date = 5 days from now server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.DAYS)) .addHeader("Date: " + formatDate(-5, TimeUnit.DAYS)) .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); assertEquals("113 HttpURLConnection \"Heuristic expiration\"", response.header("Warning")); } @Test public void noDefaultExpirationForUrlsWithQueryString() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-105, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(-5, TimeUnit.SECONDS)) .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/?foo=bar"); assertEquals("A", get(url).body().string()); assertEquals("B", get(url).body().string()); } @Test public void expirationDateInThePastWithLastModifiedHeader() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void expirationDateInThePastWithNoLastModifiedHeader() throws Exception { assertNotCached(new MockResponse() .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); } @Test public void expirationDateInTheFuture() throws Exception { assertFullyCached(new MockResponse() .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } @Test public void maxAgePreferredWithMaxAgeAndExpires() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInThePastWithDateAndLastModifiedHeaders() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Cache-Control: max-age=60")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void maxAgeInThePastWithDateHeaderButNoLastModifiedHeader() throws Exception { // Chrome interprets max-age relative to the local clock. Both our cache // and Firefox both use the earlier of the local and server's clock. assertNotCached(new MockResponse() .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithDateHeader() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithNoDateHeader() throws Exception { assertFullyCached(new MockResponse() .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeWithLastModifiedButNoServedDate() throws Exception { assertFullyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgeInTheFutureWithDateAndLastModifiedHeaders() throws Exception { assertFullyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60")); } @Test public void maxAgePreferredOverLowerSharedMaxAge() throws Exception { assertFullyCached(new MockResponse() .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: s-maxage=60") .addHeader("Cache-Control: max-age=180")); } @Test public void maxAgePreferredOverHigherMaxAge() throws Exception { assertNotCached(new MockResponse() .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: s-maxage=180") .addHeader("Cache-Control: max-age=60")); } @Test public void requestMethodOptionsIsNotCached() throws Exception { testRequestMethod("OPTIONS", false); } @Test public void requestMethodGetIsCached() throws Exception { testRequestMethod("GET", true); } @Test public void requestMethodHeadIsNotCached() throws Exception { // We could support this but choose not to for implementation simplicity testRequestMethod("HEAD", false); } @Test public void requestMethodPostIsNotCached() throws Exception { // We could support this but choose not to for implementation simplicity testRequestMethod("POST", false); } @Test public void requestMethodPutIsNotCached() throws Exception { testRequestMethod("PUT", false); } @Test public void requestMethodDeleteIsNotCached() throws Exception { testRequestMethod("DELETE", false); } @Test public void requestMethodTraceIsNotCached() throws Exception { testRequestMethod("TRACE", false); } private void testRequestMethod(String requestMethod, boolean expectCached) throws Exception { // 1. seed the cache (potentially) // 2. expect a cache hit or miss server.enqueue(new MockResponse() .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("X-Response-ID: 1")); server.enqueue(new MockResponse() .addHeader("X-Response-ID: 2")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .method(requestMethod, requestBodyOrNull(requestMethod)) .build(); Response response1 = client.newCall(request).execute(); response1.body().close(); assertEquals("1", response1.header("X-Response-ID")); Response response2 = get(url); response2.body().close(); if (expectCached) { assertEquals("1", response2.header("X-Response-ID")); } else { assertEquals("2", response2.header("X-Response-ID")); } } private RequestBody requestBodyOrNull(String requestMethod) { return (requestMethod.equals("POST") || requestMethod.equals("PUT")) ? RequestBody.create(MediaType.parse("text/plain"), "foo") : null; } @Test public void postInvalidatesCache() throws Exception { testMethodInvalidates("POST"); } @Test public void putInvalidatesCache() throws Exception { testMethodInvalidates("PUT"); } @Test public void deleteMethodInvalidatesCache() throws Exception { testMethodInvalidates("DELETE"); } private void testMethodInvalidates(String requestMethod) throws Exception { // 1. seed the cache // 2. invalidate it // 3. expect a cache miss server.enqueue(new MockResponse() .setBody("A") .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B")); server.enqueue(new MockResponse() .setBody("C")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .method(requestMethod, requestBodyOrNull(requestMethod)) .build(); Response invalidate = client.newCall(request).execute(); assertEquals("B", invalidate.body().string()); assertEquals("C", get(url).body().string()); } @Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception { // 1. seed the cache // 2. invalidate it with uncacheable response // 3. expect a cache miss server.enqueue(new MockResponse() .setBody("A") .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B") .setResponseCode(500)); server.enqueue(new MockResponse() .setBody("C")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .method("POST", requestBodyOrNull("POST")) .build(); Response invalidate = client.newCall(request).execute(); assertEquals("B", invalidate.body().string()); assertEquals("C", get(url).body().string()); } @Test public void etag() throws Exception { RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("ETag: v1")); assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); } /** If both If-Modified-Since and If-None-Match conditions apply, send only If-None-Match. */ @Test public void etagAndExpirationDateInThePast() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("ETag: v1") .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); assertEquals("v1", conditionalRequest.getHeader("If-None-Match")); assertNull(conditionalRequest.getHeader("If-Modified-Since")); } @Test public void etagAndExpirationDateInTheFuture() throws Exception { assertFullyCached(new MockResponse() .addHeader("ETag: v1") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } @Test public void cacheControlNoCache() throws Exception { assertNotCached(new MockResponse() .addHeader("Cache-Control: no-cache")); } @Test public void cacheControlNoCacheAndExpirationDateInTheFuture() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Cache-Control: no-cache")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void pragmaNoCache() throws Exception { assertNotCached(new MockResponse() .addHeader("Pragma: no-cache")); } @Test public void pragmaNoCacheAndExpirationDateInTheFuture() throws Exception { String lastModifiedDate = formatDate(-2, TimeUnit.HOURS); RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Pragma: no-cache")); assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since")); } @Test public void cacheControlNoStore() throws Exception { assertNotCached(new MockResponse() .addHeader("Cache-Control: no-store")); } @Test public void cacheControlNoStoreAndExpirationDateInTheFuture() throws Exception { assertNotCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Cache-Control: no-store")); } @Test public void partialRangeResponsesDoNotCorruptCache() throws Exception { // 1. request a range // 2. request a full document, expecting a cache miss server.enqueue(new MockResponse() .setBody("AA") .setResponseCode(HttpURLConnection.HTTP_PARTIAL) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .addHeader("Content-Range: bytes 1000-1001/2000")); server.enqueue(new MockResponse() .setBody("BB")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Range", "bytes=1000-1001") .build(); Response range = client.newCall(request).execute(); assertEquals("AA", range.body().string()); assertEquals("BB", get(url).body().string()); } @Test public void serverReturnsDocumentOlderThanCache() throws Exception { server.enqueue(new MockResponse() .setBody("A") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B") .addHeader("Last-Modified: " + formatDate(-4, TimeUnit.HOURS))); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("A", get(url).body().string()); } @Test public void clientSideNoStore() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("B")); Request request1 = new Request.Builder() .url(server.getUrl("/")) .cacheControl(new CacheControl.Builder().noStore().build()) .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(server.getUrl("/")) .build(); Response response2 = client.newCall(request2).execute(); assertEquals("B", response2.body().string()); } @Test public void nonIdentityEncodingAndConditionalCache() throws Exception { assertNonIdentityEncodingCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); } @Test public void nonIdentityEncodingAndFullCache() throws Exception { assertNonIdentityEncodingCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); } private void assertNonIdentityEncodingCached(MockResponse response) throws Exception { server.enqueue(response .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // At least three request/response pairs are required because after the first request is cached // a different execution path might be taken. Thus modifications to the cache applied during // the second request might not be visible until another request is performed. assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); } @Test public void notModifiedSpecifiesEncoding() throws Exception { server.enqueue(new MockResponse() .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED) .addHeader("Content-Encoding: gzip")); server.enqueue(new MockResponse() .setBody("DEFDEFDEF")); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("DEFDEFDEF", get(server.getUrl("/")).body().string()); } /** https://github.com/square/okhttp/issues/947 */ @Test public void gzipAndVaryOnAcceptEncoding() throws Exception { server.enqueue(new MockResponse() .setBody(gzip("ABCABCABC")) .addHeader("Content-Encoding: gzip") .addHeader("Vary: Accept-Encoding") .addHeader("Cache-Control: max-age=60")); server.enqueue(new MockResponse() .setBody("FAIL")); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); assertEquals("ABCABCABC", get(server.getUrl("/")).body().string()); } @Test public void conditionalCacheHitIsNotDoublePooled() throws Exception { server.enqueue(new MockResponse() .addHeader("ETag: v1") .setBody("A")); server.enqueue(new MockResponse() .clearHeaders() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); ConnectionPool pool = ConnectionPool.getDefault(); pool.evictAll(); client.setConnectionPool(pool); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, client.getConnectionPool().getConnectionCount()); } @Test public void expiresDateBeforeModifiedDate() throws Exception { assertConditionallyCached(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(-2, TimeUnit.HOURS))); } @Test public void requestMaxAge() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Last-Modified: " + formatDate(-2, TimeUnit.HOURS)) .addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-age=30") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestMinFresh() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=60") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "min-fresh=120") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestMaxStale() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); } @Test public void requestMaxStaleDirectiveWithNoValue() throws IOException { // Add a stale response to the cache. server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); // With max-stale, we'll return that stale response. Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("110 HttpURLConnection \"Response is stale\"", response.header("Warning")); } @Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120, must-revalidate") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "max-stale=180") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestOnlyIfCachedWithNoResponseCached() throws IOException { // (no responses enqueued) Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(1, cache.getRequestCount()); assertEquals(0, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithFullResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(1, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithConditionalResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(-1, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestOnlyIfCachedWithUnhelpfulResponseCached() throws IOException { server.enqueue(new MockResponse() .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertTrue(response.body().source().exhausted()); assertEquals(504, response.code()); assertEquals(2, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void requestCacheControlNoCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header("Cache-Control", "no-cache") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void requestPragmaNoCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS)) .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header("Pragma", "no-cache") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void clientSuppliedIfModifiedSinceWithCachedResult() throws Exception { MockResponse response = new MockResponse() .addHeader("ETag: v3") .addHeader("Cache-Control: max-age=0"); String ifModifiedSinceDate = formatDate(-24, TimeUnit.HOURS); RecordedRequest request = assertClientSuppliedCondition(response, "If-Modified-Since", ifModifiedSinceDate); assertEquals(ifModifiedSinceDate, request.getHeader("If-Modified-Since")); assertNull(request.getHeader("If-None-Match")); } @Test public void clientSuppliedIfNoneMatchSinceWithCachedResult() throws Exception { String lastModifiedDate = formatDate(-3, TimeUnit.MINUTES); MockResponse response = new MockResponse() .addHeader("Last-Modified: " + lastModifiedDate) .addHeader("Date: " + formatDate(-2, TimeUnit.MINUTES)) .addHeader("Cache-Control: max-age=0"); RecordedRequest request = assertClientSuppliedCondition(response, "If-None-Match", "v1"); assertEquals("v1", request.getHeader("If-None-Match")); assertNull(request.getHeader("If-Modified-Since")); } private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String conditionName, String conditionValue) throws Exception { server.enqueue(seed.setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); Request request = new Request.Builder() .url(url) .header(conditionName, conditionValue) .build(); Response response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); assertEquals("", response.body().string()); server.takeRequest(); // seed return server.takeRequest(); } /** * For Last-Modified and Date headers, we should echo the date back in the * exact format we were served. */ @Test public void retainServedDateFormat() throws Exception { // Serve a response with a non-standard date format that OkHttp supports. Date lastModifiedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-1)); Date servedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-2)); DateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("EDT")); String lastModifiedString = dateFormat.format(lastModifiedDate); String servedString = dateFormat.format(servedDate); // This response should be conditionally cached. server.enqueue(new MockResponse() .addHeader("Last-Modified: " + lastModifiedString) .addHeader("Expires: " + servedString) .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); // The first request has no conditions. RecordedRequest request1 = server.takeRequest(); assertNull(request1.getHeader("If-Modified-Since")); // The 2nd request uses the server's date format. RecordedRequest request2 = server.takeRequest(); assertEquals(lastModifiedString, request2.getHeader("If-Modified-Since")); } @Test public void clientSuppliedConditionWithoutCachedResult() throws Exception { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Request request = new Request.Builder() .url(server.getUrl("/")) .header("If-Modified-Since", formatDate(-24, TimeUnit.HOURS)) .build(); Response response = client.newCall(request).execute(); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, response.code()); assertEquals("", response.body().string()); } @Test public void authorizationRequestFullyCached() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Authorization", "password") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); assertEquals("A", get(url).body().string()); } @Test public void contentLocationDoesNotPopulateCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Content-Location: /bar") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/foo")).body().string()); assertEquals("B", get(server.getUrl("/bar")).body().string()); } @Test public void connectionIsReturnedToPoolAfterConditionalSuccess() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/a")).body().string()); assertEquals("A", get(server.getUrl("/a")).body().string()); assertEquals("B", get(server.getUrl("/b")).body().string()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); assertEquals(2, server.takeRequest().getSequenceNumber()); } @Test public void statisticsConditionalCacheMiss() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); server.enqueue(new MockResponse() .setBody("C")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("B", get(server.getUrl("/")).body().string()); assertEquals("C", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(3, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); } @Test public void statisticsConditionalCacheHit() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(3, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void statisticsFullCacheHit() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(1, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(0, cache.getHitCount()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals(3, cache.getRequestCount()); assertEquals(1, cache.getNetworkCount()); assertEquals(2, cache.getHitCount()); } @Test public void varyMatchesChangedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request frRequest = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response frResponse = client.newCall(frRequest).execute(); assertEquals("A", frResponse.body().string()); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response enResponse = client.newCall(enRequest).execute(); assertEquals("B", enResponse.body().string()); } @Test public void varyMatchesUnchangedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMatchesAbsentRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("A", get(server.getUrl("/")).body().string()); } @Test public void varyMatchesAddedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Foo", "bar") .build(); Response response = client.newCall(request).execute(); assertEquals("B", response.body().string()); } @Test public void varyMatchesRemovedRequestHeaderField() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Foo") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Foo", "bar") .build(); Response fooresponse = client.newCall(request).execute(); assertEquals("A", fooresponse.body().string()); assertEquals("B", get(server.getUrl("/")).body().string()); } @Test public void varyFieldsAreCaseInsensitive() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: ACCEPT-LANGUAGE") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("accept-language", "fr-CA") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldsWithMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language, Accept-Charset") .addHeader("Vary: Accept-Encoding") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response response1 = client.newCall(request).execute(); assertEquals("A", response1.body().string()); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response response2 = client.newCall(request1).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldsWithNoMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language, Accept-Charset") .addHeader("Vary: Accept-Encoding") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request frRequest = new Request.Builder() .url(url) .header("Accept-Language", "fr-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response frResponse = client.newCall(frRequest).execute(); assertEquals("A", frResponse.body().string()); Request enRequest = new Request.Builder() .url(url) .header("Accept-Language", "en-CA") .header("Accept-Charset", "UTF-8") .header("Accept-Encoding", "identity") .build(); Response enResponse = client.newCall(enRequest).execute(); assertEquals("B", enResponse.body().string()); } @Test public void varyMultipleFieldValuesWithMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("A", response2.body().string()); } @Test public void varyMultipleFieldValuesWithNoMatch() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA, fr-FR") .addHeader("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .addHeader("Accept-Language", "fr-CA") .addHeader("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("B", response2.body().string()); } @Test public void varyAsterisk() throws Exception { server.enqueue( new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: *") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", get(server.getUrl("/")).body().string()); assertEquals("B", get(server.getUrl("/")).body().string()); } @Test public void varyAndHttps() throws Exception { server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .addHeader("Vary: Accept-Language") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); URL url = server.getUrl("/"); Request request1 = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response response1 = client.newCall(request1).execute(); assertEquals("A", response1.body().string()); Request request2 = new Request.Builder() .url(url) .header("Accept-Language", "en-US") .build(); Response response2 = client.newCall(request2).execute(); assertEquals("A", response2.body().string()); } @Test public void cachePlusCookies() throws Exception { server.enqueue(new MockResponse() .addHeader("Set-Cookie: a=FIRST; domain=" + server.getCookieDomain() + ";") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Set-Cookie: a=SECOND; domain=" + server.getCookieDomain() + ";") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertCookies(url, "a=FIRST"); assertEquals("A", get(url).body().string()); assertCookies(url, "a=SECOND"); } @Test public void getHeadersReturnsNetworkEndToEndHeaders() throws Exception { server.enqueue(new MockResponse() .addHeader("Allow: GET, HEAD") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Allow: GET, HEAD, PUT") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("GET, HEAD", response1.header("Allow")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("GET, HEAD, PUT", response2.header("Allow")); } @Test public void getHeadersReturnsCachedHopByHopHeaders() throws Exception { server.enqueue(new MockResponse() .addHeader("Transfer-Encoding: identity") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Transfer-Encoding: none") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("identity", response1.header("Transfer-Encoding")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("identity", response2.header("Transfer-Encoding")); } @Test public void getHeadersDeletesCached100LevelWarnings() throws Exception { server.enqueue(new MockResponse() .addHeader("Warning: 199 test danger") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("199 test danger", response1.header("Warning")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals(null, response2.header("Warning")); } @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { server.enqueue(new MockResponse() .addHeader("Warning: 299 test danger") .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); Response response1 = get(server.getUrl("/")); assertEquals("A", response1.body().string()); assertEquals("299 test danger", response1.header("Warning")); Response response2 = get(server.getUrl("/")); assertEquals("A", response2.body().string()); assertEquals("299 test danger", response2.header("Warning")); } public void assertCookies(URL url, String... expectedCookies) throws Exception { List<String> actualCookies = new ArrayList<>(); for (HttpCookie cookie : cookieManager.getCookieStore().get(url.toURI())) { actualCookies.add(cookie.toString()); } assertEquals(Arrays.asList(expectedCookies), actualCookies); } @Test public void doNotCachePartialResponse() throws Exception { assertNotCached(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_PARTIAL) .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) .addHeader("Content-Range: bytes 100-100/200") .addHeader("Cache-Control: max-age=60")); } @Test public void conditionalHitUpdatesCache() throws Exception { server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS)) .addHeader("Cache-Control: max-age=0") .setBody("A")); server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=30") .addHeader("Allow: GET, HEAD") .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); server.enqueue(new MockResponse() .setBody("B")); // cache miss; seed the cache Response response1 = get(server.getUrl("/a")); assertEquals("A", response1.body().string()); assertEquals(null, response1.header("Allow")); // conditional cache hit; update the cache Response response2 = get(server.getUrl("/a")); assertEquals(HttpURLConnection.HTTP_OK, response2.code()); assertEquals("A", response2.body().string()); assertEquals("GET, HEAD", response2.header("Allow")); // full cache hit Response response3 = get(server.getUrl("/a")); assertEquals("A", response3.body().string()); assertEquals("GET, HEAD", response3.header("Allow")); assertEquals(2, server.getRequestCount()); } @Test public void responseSourceHeaderCached() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Request request = new Request.Builder() .url(server.getUrl("/")) .header("Cache-Control", "only-if-cached") .build(); Response response = client.newCall(request).execute(); assertEquals("A", response.body().string()); } @Test public void responseSourceHeaderConditionalCacheFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(-31, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B") .addHeader("Cache-Control: max-age=30") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("B", response.body().string()); } @Test public void responseSourceHeaderConditionalCacheNotFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=0") .addHeader("Date: " + formatDate(0, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setResponseCode(304)); assertEquals("A", get(server.getUrl("/")).body().string()); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); } @Test public void responseSourceHeaderFetched() throws IOException { server.enqueue(new MockResponse() .setBody("A")); Response response = get(server.getUrl("/")); assertEquals("A", response.body().string()); } @Test public void emptyResponseHeaderNameFromCacheIsLenient() throws Exception { Headers.Builder headers = new Headers.Builder() .add("Cache-Control: max-age=120"); Internal.instance.addLenient(headers, ": A"); server.enqueue(new MockResponse() .setHeaders(headers.build()) .setBody("body")); Response response = get(server.getUrl("/")); assertEquals("A", response.header("")); } /** * Old implementations of OkHttp's response cache wrote header fields like * ":status: 200 OK". This broke our cached response parser because it split * on the first colon. This regression test exists to help us read these old * bad cache entries. * * https://github.com/square/okhttp/issues/227 */ @Test public void testGoldenCacheResponse() throws Exception { cache.close(); server.enqueue(new MockResponse() .clearHeaders() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); URL url = server.getUrl("/"); String urlKey = Util.md5Hex(url.toString()); String entryMetadata = "" + "" + url + "\n" + "GET\n" + "0\n" + "HTTP/1.1 200 OK\n" + "7\n" + ":status: 200 OK\n" + ":version: HTTP/1.1\n" + "etag: foo\n" + "content-length: 3\n" + "OkHttp-Received-Millis: " + System.currentTimeMillis() + "\n" + "X-Android-Response-Source: NETWORK 200\n" + "OkHttp-Sent-Millis: " + System.currentTimeMillis() + "\n" + "\n" + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n" + "1\n" + "MIIBpDCCAQ2gAwIBAgIBATANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDEw1qd2lsc29uLmxvY2FsMB4XDTEzMDgy" + "OTA1MDE1OVoXDTEzMDgzMDA1MDE1OVowGDEWMBQGA1UEAxMNandpbHNvbi5sb2NhbDCBnzANBgkqhkiG9w0BAQEF" + "AAOBjQAwgYkCgYEAlFW+rGo/YikCcRghOyKkJanmVmJSce/p2/jH1QvNIFKizZdh8AKNwojt3ywRWaDULA/RlCUc" + "ltF3HGNsCyjQI/+Lf40x7JpxXF8oim1E6EtDoYtGWAseelawus3IQ13nmo6nWzfyCA55KhAWf4VipelEy8DjcuFK" + "v6L0xwXnI0ECAwEAATANBgkqhkiG9w0BAQsFAAOBgQAuluNyPo1HksU3+Mr/PyRQIQS4BI7pRXN8mcejXmqyscdP" + "7S6J21FBFeRR8/XNjVOp4HT9uSc2hrRtTEHEZCmpyoxixbnM706ikTmC7SN/GgM+SmcoJ1ipJcNcl8N0X6zym4dm" + "yFfXKHu2PkTo7QFdpOJFvP3lIigcSZXozfmEDg==\n" + "-1\n"; String entryBody = "abc"; String journalBody = "" + "libcore.io.DiskLruCache\n" + "1\n" + "201105\n" + "2\n" + "\n" + "CLEAN " + urlKey + " " + entryMetadata.length() + " " + entryBody.length() + "\n"; writeFile(cache.getDirectory(), urlKey + ".0", entryMetadata); writeFile(cache.getDirectory(), urlKey + ".1", entryBody); writeFile(cache.getDirectory(), "journal", journalBody); cache = new Cache(cache.getDirectory(), Integer.MAX_VALUE); client.setCache(cache); Response response = get(url); assertEquals(entryBody, response.body().string()); assertEquals("3", response.header("Content-Length")); assertEquals("foo", response.header("etag")); } @Test public void evictAll() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); client.getCache().evictAll(); assertEquals(0, client.getCache().getSize()); assertEquals("B", get(url).body().string()); } @Test public void networkInterceptorInvokedForConditionalGet() throws Exception { server.enqueue(new MockResponse() .addHeader("ETag: v1") .setBody("A")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // Seed the cache. URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); final AtomicReference<String> ifNoneMatch = new AtomicReference<>(); client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match")); return chain.proceed(chain.request()); } }); // Confirm the value is cached and intercepted. assertEquals("A", get(url).body().string()); assertEquals("v1", ifNoneMatch.get()); } @Test public void networkInterceptorNotInvokedForFullyCached() throws Exception { server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("A")); // Seed the cache. URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); // Confirm the interceptor isn't exercised. client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { throw new AssertionError(); } }); assertEquals("A", get(url).body().string()); } @Test public void iterateCache() throws Exception { // Put some responses in the cache. server.enqueue(new MockResponse() .setBody("a")); URL urlA = server.getUrl("/a"); assertEquals("a", get(urlA).body().string()); server.enqueue(new MockResponse() .setBody("b")); URL urlB = server.getUrl("/b"); assertEquals("b", get(urlB).body().string()); server.enqueue(new MockResponse() .setBody("c")); URL urlC = server.getUrl("/c"); assertEquals("c", get(urlC).body().string()); // Confirm the iterator returns those responses... Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); assertEquals(urlA.toString(), i.next()); assertTrue(i.hasNext()); assertEquals(urlB.toString(), i.next()); assertTrue(i.hasNext()); assertEquals(urlC.toString(), i.next()); // ... and nothing else. assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } @Test public void iteratorRemoveFromCache() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .addHeader("Cache-Control: max-age=60") .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); // Remove it with iteration. Iterator<String> i = cache.urls(); assertEquals(url.toString(), i.next()); i.remove(); // Confirm that subsequent requests suffer a cache miss. server.enqueue(new MockResponse() .setBody("b")); assertEquals("b", get(url).body().string()); } @Test public void iteratorRemoveWithoutNextThrows() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); try { i.remove(); fail(); } catch (IllegalStateException expected) { } } @Test public void iteratorRemoveOncePerCallToNext() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); assertEquals(url.toString(), i.next()); i.remove(); // Too many calls to remove(). try { i.remove(); fail(); } catch (IllegalStateException expected) { } } @Test public void elementEvictedBetweenHasNextAndNext() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); // The URL will remain available if hasNext() returned true... Iterator<String> i = cache.urls(); assertTrue(i.hasNext()); // ...so even when we evict the element, we still get something back. cache.evictAll(); assertEquals(url.toString(), i.next()); // Remove does nothing. But most importantly, it doesn't throw! i.remove(); } @Test public void elementEvictedBeforeHasNextIsOmitted() throws Exception { // Put a response in the cache. server.enqueue(new MockResponse() .setBody("a")); URL url = server.getUrl("/a"); assertEquals("a", get(url).body().string()); Iterator<String> i = cache.urls(); cache.evictAll(); // The URL was evicted before hasNext() made any promises. assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } private Response get(URL url) throws IOException { Request request = new Request.Builder() .url(url) .build(); return client.newCall(request).execute(); } private void writeFile(File directory, String file, String content) throws IOException { BufferedSink sink = Okio.buffer(Okio.sink(new File(directory, file))); sink.writeUtf8(content); sink.close(); } /** * @param delta the offset from the current date to use. Negative * values yield dates in the past; positive values yield dates in the * future. */ private String formatDate(long delta, TimeUnit timeUnit) { return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta))); } private String formatDate(Date date) { DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123.format(date); } private void assertNotCached(MockResponse response) throws Exception { server.enqueue(response.setBody("A")); server.enqueue(new MockResponse() .setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("B", get(url).body().string()); } /** @return the request with the conditional get headers. */ private RecordedRequest assertConditionallyCached(MockResponse response) throws Exception { // scenario 1: condition succeeds server.enqueue(response.setBody("A").setStatus("HTTP/1.1 200 A-OK")); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)); // scenario 2: condition fails server.enqueue(response.setBody("B") .setStatus("HTTP/1.1 200 B-OK")); server.enqueue(new MockResponse() .setStatus("HTTP/1.1 200 C-OK") .setBody("C")); URL valid = server.getUrl("/valid"); Response response1 = get(valid); assertEquals("A", response1.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response1.code()); assertEquals("A-OK", response1.message()); Response response2 = get(valid); assertEquals("A", response2.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response2.code()); assertEquals("A-OK", response2.message()); URL invalid = server.getUrl("/invalid"); Response response3 = get(invalid); assertEquals("B", response3.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response3.code()); assertEquals("B-OK", response3.message()); Response response4 = get(invalid); assertEquals("C", response4.body().string()); assertEquals(HttpURLConnection.HTTP_OK, response4.code()); assertEquals("C-OK", response4.message()); server.takeRequest(); // regular get return server.takeRequest(); // conditional get } private void assertFullyCached(MockResponse response) throws Exception { server.enqueue(response.setBody("A")); server.enqueue(response.setBody("B")); URL url = server.getUrl("/"); assertEquals("A", get(url).body().string()); assertEquals("A", get(url).body().string()); } /** * Shortens the body of {@code response} but not the corresponding headers. * Only useful to test how clients respond to the premature conclusion of * the HTTP body. */ private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) { response.setSocketPolicy(DISCONNECT_AT_END); Headers headers = response.getHeaders(); Buffer truncatedBody = new Buffer(); truncatedBody.write(response.getBody(), numBytesToKeep); response.setBody(truncatedBody); response.setHeaders(headers); return response; } enum TransferKind { CHUNKED() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) throws IOException { response.setChunkedBody(content, chunkSize); } }, FIXED_LENGTH() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) { response.setBody(content); } }, END_OF_STREAM() { @Override void setBody(MockResponse response, Buffer content, int chunkSize) { response.setBody(content); response.setSocketPolicy(DISCONNECT_AT_END); response.removeHeader("Content-Length"); } }; abstract void setBody(MockResponse response, Buffer content, int chunkSize) throws IOException; void setBody(MockResponse response, String content, int chunkSize) throws IOException { setBody(response, new Buffer().writeUtf8(content), chunkSize); } } /** Returns a gzipped copy of {@code bytes}. */ public Buffer gzip(String data) throws IOException { Buffer result = new Buffer(); BufferedSink sink = Okio.buffer(new GzipSink(result)); sink.writeUtf8(data); sink.close(); return result; } }
Test that conditional misses update the cache. Closes https://github.com/square/okhttp/issues/1712
okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
Test that conditional misses update the cache.
Java
apache-2.0
252b789a952c101ece3d551344a5196a0301df4e
0
cbmeeks/viritin,viritin/viritin,qwasli/maddon,viritin/viritin,pbaris/viritin,pbaris/viritin
package org.vaadin.maddon.fields; import java.util.Collection; import com.vaadin.data.Container; import com.vaadin.data.Property; import com.vaadin.data.Validator; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Field; import com.vaadin.ui.ListSelect; import com.vaadin.ui.NativeSelect; import com.vaadin.ui.OptionGroup; import com.vaadin.ui.TwinColSelect; import java.util.Arrays; import org.vaadin.maddon.ListContainer; /** * A select implementation with better typed API than in core Vaadin. * * By default the options toString is used to generate the caption for option. * To override this behavior, use setCaptionGenerator or override getCaption(T) * to provide your own strategy. * <p> * Behind the scenes uses Vaadin cores NativeSelect (default) or other cores * AbstractSelect implementation, type provided in constructor. Tree and Table * are not supported, see MTable. * <p> * Note, that this select is always in single select mode. See CollectionSelect * for "multiselect". * * @author mstahv * @param <T> the type of selects value */ public class TypedSelect<T> extends CustomComponent implements Field<T> { private CaptionGenerator<T> captionGenerator; private AbstractSelect select; private ListContainer<T> bic; private Class<T> fieldType; public TypedSelect(Class<T> type) { this.fieldType = type; bic = new ListContainer<T>(type); } /** * Note, that with this constructor, you cannot override the select type. * @param options options to select from */ public TypedSelect(T... options) { setOptions(options); } public TypedSelect(String caption) { setCaption(caption); } /** * Note, that with this constructor, you cannot override the select type. */ public TypedSelect(String caption, Collection<T> listAllStyles) { this(caption); setOptions(listAllStyles); } public TypedSelect<T> withCaption(String caption) { setCaption(caption); return this; } public TypedSelect<T> withSelectType(Class<? extends AbstractSelect> selectType) { if (selectType == ListSelect.class) { select = new ListSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == OptionGroup.class) { select = new OptionGroup() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == ComboBox.class) { select = new ComboBox() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == TwinColSelect.class) { select = new TwinColSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else /*if (selectType == null || selectType == NativeSelect.class)*/ { select = new NativeSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } return this; } protected final AbstractSelect getSelect() { if (select == null) { withSelectType(null); if (bic != null) { select.setContainerDataSource(bic); } } return select; } protected String getCaption(T option) { if (captionGenerator != null) { return captionGenerator.getCaption(option); } return option.toString(); } @SuppressWarnings("unchecked") @Override public T getValue() { return (T) getSelect().getValue(); } @Override public void focus() { getSelect().focus(); } public final TypedSelect<T> setOptions(T... values) { return setOptions(Arrays.asList(values)); } @SuppressWarnings("unchecked") @Override public Class<T> getType() { if (fieldType == null) { try { fieldType = (Class<T>) ((Container.Sortable) select .getContainerDataSource()).firstItemId().getClass(); } catch (Exception e) { } } return fieldType; } public TypedSelect setType(Class<T> type) { this.fieldType = type; return this; } @Override public boolean isInvalidCommitted() { return getSelect().isInvalidCommitted(); } @Override public void setInvalidCommitted(boolean isCommitted) { getSelect().setInvalidCommitted(isCommitted); } @Override public void commit() throws SourceException, InvalidValueException { getSelect().commit(); } @Override public void discard() throws SourceException { getSelect().discard(); } @Override public void setBuffered(boolean buffered) { getSelect().setBuffered(buffered); } @Override public boolean isBuffered() { return getSelect().isBuffered(); } @Override public boolean isModified() { return getSelect().isModified(); } @Override public void addValidator(Validator validator) { getSelect().addValidator(validator); } @Override public void removeValidator(Validator validator) { getSelect().removeValidator(validator); } @Override public void removeAllValidators() { getSelect().removeAllValidators(); } @Override public Collection<Validator> getValidators() { return getSelect().getValidators(); } @Override public boolean isValid() { return getSelect().isValid(); } @Override public void validate() throws InvalidValueException { getSelect().validate(); } @Override public boolean isInvalidAllowed() { return getSelect().isInvalidAllowed(); } @Override public void setInvalidAllowed(boolean invalidValueAllowed) throws UnsupportedOperationException { getSelect().setInvalidAllowed(invalidValueAllowed); } @Override public void setValue(T newValue) throws ReadOnlyException { getSelect().setValue(newValue); } @Override public void addValueChangeListener(ValueChangeListener listener) { getSelect().addValueChangeListener(listener); } @Override public void addListener(ValueChangeListener listener) { getSelect().addValueChangeListener(listener); } @Override public void removeValueChangeListener(ValueChangeListener listener) { getSelect().removeValueChangeListener(listener); } @Override public void removeListener(ValueChangeListener listener) { getSelect().removeValueChangeListener(listener); } @Override public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { getSelect().valueChange(event); } @Override public void setPropertyDataSource(Property newDataSource) { getSelect().setPropertyDataSource(newDataSource); } @Override public Property getPropertyDataSource() { return getSelect().getPropertyDataSource(); } @Override public int getTabIndex() { return getSelect().getTabIndex(); } @Override public void setTabIndex(int tabIndex) { getSelect().setTabIndex(tabIndex); } @Override public boolean isRequired() { return getSelect().isRequired(); } @Override public void setRequired(boolean required) { getSelect().setRequired(required); } @Override public void setRequiredError(String requiredMessage) { getSelect().setRequiredError(requiredMessage); } @Override public String getRequiredError() { return getSelect().getRequiredError(); } public CaptionGenerator<T> getCaptionGenerator() { return captionGenerator; } public TypedSelect<T> setCaptionGenerator(CaptionGenerator<T> captionGenerator) { this.captionGenerator = captionGenerator; return this; } public final TypedSelect<T> setOptions(Collection<T> options) { if (bic != null) { bic.setCollection(options); } else { bic = new ListContainer<T>(options); getSelect().setContainerDataSource(bic); } return this; } public TypedSelect<T> setBeans(Collection<T> options) { return setOptions(options); } @Override public void attach() { if (getCompositionRoot() == null) { setCompositionRoot(getSelect()); if (bic != null && getSelect().getContainerDataSource() != bic) { getSelect().setContainerDataSource(bic); } } super.attach(); } }
src/main/java/org/vaadin/maddon/fields/TypedSelect.java
package org.vaadin.maddon.fields; import java.util.Collection; import com.vaadin.data.Container; import com.vaadin.data.Property; import com.vaadin.data.Validator; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.data.util.IndexedContainer; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Field; import com.vaadin.ui.ListSelect; import com.vaadin.ui.NativeSelect; import com.vaadin.ui.OptionGroup; import com.vaadin.ui.TwinColSelect; import java.util.Arrays; import org.vaadin.maddon.ListContainer; /** * A select implementation with better typed API than in core Vaadin. * * By default the options toString is used to generate the caption for option. * To override this behavior, use setCaptionGenerator or override getCaption(T) * to provide your own strategy. * <p> * Behind the scenes uses Vaadin cores NativeSelect (default) or other cores * AbstractSelect implementation, type provided in constructor. Tree and Table * are not supported, see MTable. * <p> * Note, that this select is always in single select mode. See CollectionSelect * for "multiselect". * * @author mstahv * @param <T> the type of selects value */ public class TypedSelect<T> extends CustomComponent implements Field<T> { private CaptionGenerator<T> captionGenerator; private AbstractSelect select; private ListContainer<T> bic; private Class<T> fieldType; public TypedSelect(Class<T> type) { this.fieldType = type; bic = new ListContainer<T>(type); } /** * Note, that with this constructor, you cannot override the select type. * @param options options to select from */ public TypedSelect(T... options) { setOptions(options); } public TypedSelect(String caption) { setCaption(caption); } /** * Note, that with this constructor, you cannot override the select type. */ public TypedSelect(String caption, Collection<T> listAllStyles) { this(caption); setOptions(listAllStyles); } public TypedSelect<T> withCaption(String caption) { setCaption(caption); return this; } public TypedSelect<T> withSelectType(Class<? extends AbstractSelect> selectType) { if (selectType == ListSelect.class) { select = new ListSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == OptionGroup.class) { select = new OptionGroup() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == ComboBox.class) { select = new ComboBox() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else if (selectType == TwinColSelect.class) { select = new TwinColSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } else /*if (selectType == null || selectType == NativeSelect.class)*/ { select = new NativeSelect() { @SuppressWarnings("unchecked") @Override public String getItemCaption(Object itemId) { return TypedSelect.this.getCaption((T) itemId); } }; } return this; } protected final AbstractSelect getSelect() { if (select == null) { withSelectType(null); if (bic != null) { select.setContainerDataSource(bic); } } return select; } protected String getCaption(T option) { if (captionGenerator != null) { return captionGenerator.getCaption(option); } return option.toString(); } @SuppressWarnings("unchecked") @Override public T getValue() { return (T) getSelect().getValue(); } @Override public void focus() { getSelect().focus(); } public final TypedSelect<T> setOptions(T... values) { return setOptions(Arrays.asList(values)); } @SuppressWarnings("unchecked") @Override public Class<T> getType() { if (fieldType == null) { try { fieldType = (Class<T>) ((Container.Sortable) select .getContainerDataSource()).firstItemId().getClass(); } catch (Exception e) { } } return fieldType; } public TypedSelect setType(Class<T> type) { this.fieldType = type; return this; } @Override public boolean isInvalidCommitted() { return getSelect().isInvalidCommitted(); } @Override public void setInvalidCommitted(boolean isCommitted) { getSelect().setInvalidCommitted(isCommitted); } @Override public void commit() throws SourceException, InvalidValueException { getSelect().commit(); } @Override public void discard() throws SourceException { getSelect().discard(); } @Override public void setBuffered(boolean buffered) { getSelect().setBuffered(buffered); } @Override public boolean isBuffered() { return getSelect().isBuffered(); } @Override public boolean isModified() { return getSelect().isModified(); } @Override public void addValidator(Validator validator) { getSelect().addValidator(validator); } @Override public void removeValidator(Validator validator) { getSelect().removeValidator(validator); } @Override public void removeAllValidators() { getSelect().removeAllValidators(); } @Override public Collection<Validator> getValidators() { return getSelect().getValidators(); } @Override public boolean isValid() { return getSelect().isValid(); } @Override public void validate() throws InvalidValueException { getSelect().validate(); } @Override public boolean isInvalidAllowed() { return getSelect().isInvalidAllowed(); } @Override public void setInvalidAllowed(boolean invalidValueAllowed) throws UnsupportedOperationException { getSelect().setInvalidAllowed(invalidValueAllowed); } @Override public void setValue(T newValue) throws ReadOnlyException { getSelect().setValue(newValue); } @Override public void addValueChangeListener(ValueChangeListener listener) { getSelect().addValueChangeListener(listener); } @Override public void addListener(ValueChangeListener listener) { getSelect().addValueChangeListener(listener); } @Override public void removeValueChangeListener(ValueChangeListener listener) { getSelect().removeValueChangeListener(listener); } @Override public void removeListener(ValueChangeListener listener) { getSelect().removeValueChangeListener(listener); } @Override public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { getSelect().valueChange(event); } @Override public void setPropertyDataSource(Property newDataSource) { getSelect().setPropertyDataSource(newDataSource); } @Override public Property getPropertyDataSource() { return getSelect().getPropertyDataSource(); } @Override public int getTabIndex() { return getSelect().getTabIndex(); } @Override public void setTabIndex(int tabIndex) { getSelect().setTabIndex(tabIndex); } @Override public boolean isRequired() { return getSelect().isRequired(); } @Override public void setRequired(boolean required) { getSelect().setRequired(required); } @Override public void setRequiredError(String requiredMessage) { getSelect().setRequiredError(requiredMessage); } @Override public String getRequiredError() { return getSelect().getRequiredError(); } public CaptionGenerator<T> getCaptionGenerator() { return captionGenerator; } public TypedSelect<T> setCaptionGenerator(CaptionGenerator<T> captionGenerator) { this.captionGenerator = captionGenerator; return this; } public final TypedSelect<T> setOptions(Collection<T> options) { if (bic != null) { bic.setCollection(options); } else { bic = new ListContainer<T>(options); getSelect().setContainerDataSource(bic); } return this; } public TypedSelect<T> setBeans(Collection<T> options) { return setOptions(options); } @Override public void attach() { if (getCompositionRoot() == null) { setCompositionRoot(getSelect()); if (bic != null && getSelect().getContainerDataSource() != bic) { getSelect().setContainerDataSource(bic); } } super.attach(); } }
Removed obsolete import
src/main/java/org/vaadin/maddon/fields/TypedSelect.java
Removed obsolete import
Java
apache-2.0
8f37c2a3ffaaaed73c17c97d6374d2d00b464274
0
protyposis/MediaPlayer-Extended,protyposis/MediaPlayer-Extended
/* * Copyright 2014 Mario Guggenberger <mg@protyposis.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.protyposis.android.mediaplayer; import android.content.Context; import android.media.AudioManager; import android.media.MediaCodec; import android.media.MediaFormat; import android.net.Uri; import android.os.*; import android.os.Process; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import java.io.IOException; import java.util.Map; import java.util.concurrent.CountDownLatch; /** * Created by maguggen on 04.06.2014. */ public class MediaPlayer { private static final String TAG = MediaPlayer.class.getSimpleName(); private static final long BUFFER_LOW_WATER_MARK_US = 2000000; // 2 seconds; NOTE: make sure this is below DashMediaExtractor's mMinBufferTimeUs /** * Pass as track index to tell the player that no track should be selected. */ public static final int TRACK_INDEX_NONE = -1; /** * Pass as track index to tell the player to automatically select the first fitting track. */ public static final int TRACK_INDEX_AUTO = -2; public enum SeekMode { /** * Seeks to the previous sync point. * This mode exists for backwards compatibility and is the same as {@link #FAST_TO_PREVIOUS_SYNC}. */ @Deprecated FAST(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Seeks to the previous sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_PREVIOUS_SYNC}. */ FAST_TO_PREVIOUS_SYNC(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Seeks to the next sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_NEXT_SYNC}. */ FAST_TO_NEXT_SYNC(MediaExtractor.SEEK_TO_NEXT_SYNC), /** * Seeks to to the closest sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_CLOSEST_SYNC}. */ FAST_TO_CLOSEST_SYNC(MediaExtractor.SEEK_TO_CLOSEST_SYNC), /** * Seeks to the exact frame if the seek time equals the frame time, else * to the following frame; this means that it will often seek one frame too far. */ PRECISE(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Default mode. * Always seeks to the exact frame. Can cost maximally twice the time than the PRECISE mode. */ EXACT(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Always seeks to the exact frame by skipping the decoding of all frames between the sync * and target frame, because of which it can result in block artifacts. */ FAST_EXACT(MediaExtractor.SEEK_TO_PREVIOUS_SYNC); private int baseSeekMode = MediaExtractor.SEEK_TO_PREVIOUS_SYNC; SeekMode(int baseSeekMode) { this.baseSeekMode = baseSeekMode; } public int getBaseSeekMode() { return baseSeekMode; } } /** * The mode of how to delay rendering of video frames until their target PTS. */ enum VideoRenderTimingMode { /** * Automatically chooses {@link VideoRenderTimingMode#SLEEP} for API < 21 and * {@link VideoRenderTimingMode#SURFACEVIEW_TIMESTAMP_API21} for API >= 21. */ AUTO, /** * Defers rendering by putting the playback thread to sleep until the PTS is reached and renders * frames through {@link MediaCodec#releaseOutputBuffer(int, boolean)}. */ SLEEP, /** * Defers rendering through {@link MediaCodec#releaseOutputBuffer(int, long)} which blocks * until the PTS is reached. Supported on API 21+. */ SURFACEVIEW_TIMESTAMP_API21; public boolean isRenderModeApi21() { switch (this) { case AUTO: return Build.VERSION.SDK_INT >= 21; case SLEEP: return false; case SURFACEVIEW_TIMESTAMP_API21: return true; } return false; } } private enum State { IDLE, INITIALIZED, PREPARING, PREPARED, STOPPED, RELEASING, RELEASED, ERROR } private SeekMode mSeekMode = SeekMode.EXACT; private Surface mSurface; private SurfaceHolder mSurfaceHolder; private MediaExtractor mVideoExtractor; private MediaExtractor mAudioExtractor; private int mVideoTrackIndex; private MediaFormat mVideoFormat; private long mVideoMinPTS; private int mAudioTrackIndex; private MediaFormat mAudioFormat; private long mAudioMinPTS; private int mAudioSessionId; private int mAudioStreamType; private float mVolumeLeft = 1, mVolumeRight = 1; private PlaybackThread mPlaybackThread; private long mCurrentPosition; private long mSeekTargetTime; private boolean mSeeking; private int mBufferPercentage; private TimeBase mTimeBase; private EventHandler mEventHandler; private OnPreparedListener mOnPreparedListener; private OnCompletionListener mOnCompletionListener; private OnSeekListener mOnSeekListener; private OnSeekCompleteListener mOnSeekCompleteListener; private OnErrorListener mOnErrorListener; private OnInfoListener mOnInfoListener; private OnVideoSizeChangedListener mOnVideoSizeChangedListener; private OnBufferingUpdateListener mOnBufferingUpdateListener; private PowerManager.WakeLock mWakeLock = null; private boolean mScreenOnWhilePlaying; private boolean mStayAwake; private boolean mLooping; private AudioPlayback mAudioPlayback; private Decoders mDecoders; private boolean mBuffering; private VideoRenderTimingMode mVideoRenderTimingMode; private State mCurrentState; /** * A lock to sync release() with the actual releasing on the playback thread. This lock makes * sure that release() waits until everything has been released before returning to the caller, * and thus makes the async release look synchronized to an API caller. */ private Object mReleaseSyncLock; public MediaPlayer() { mPlaybackThread = null; mEventHandler = new EventHandler(); mTimeBase = new TimeBase(); mVideoRenderTimingMode = VideoRenderTimingMode.AUTO; mCurrentState = State.IDLE; mAudioSessionId = 0; // AudioSystem.AUDIO_SESSION_ALLOCATE; mAudioStreamType = AudioManager.STREAM_MUSIC; } /** * Sets the media source and track indices. The track indices can either be actual track indices * that have been determined externally, {@link #TRACK_INDEX_AUTO} to automatically select * the first fitting track index, or {@link #TRACK_INDEX_NONE} to not select any track. * * @param source the media source * @param videoTrackIndex a video track index or one of the TACK_INDEX_* constants * @param audioTrackIndex an audio track index or one of the TACK_INDEX_* constants * @throws IOException * @throws IllegalStateException */ public void setDataSource(MediaSource source, int videoTrackIndex, int audioTrackIndex) throws IOException, IllegalStateException { if(mCurrentState != State.IDLE) { throw new IllegalStateException(); } mVideoExtractor = source.getVideoExtractor(); mAudioExtractor = source.getAudioExtractor(); if(mVideoExtractor != null && mAudioExtractor == null) { mAudioExtractor = mVideoExtractor; } switch (videoTrackIndex) { case TRACK_INDEX_AUTO: mVideoTrackIndex = getTrackIndex(mVideoExtractor, "video/"); break; case TRACK_INDEX_NONE: mVideoTrackIndex = MediaCodecDecoder.INDEX_NONE; break; default: mVideoTrackIndex = videoTrackIndex; } switch (audioTrackIndex) { case TRACK_INDEX_AUTO: mAudioTrackIndex = getTrackIndex(mAudioExtractor, "audio/"); break; case TRACK_INDEX_NONE: mAudioTrackIndex = MediaCodecDecoder.INDEX_NONE; break; default: mAudioTrackIndex = audioTrackIndex; } // Select video track if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE) { mVideoExtractor.selectTrack(mVideoTrackIndex); mVideoFormat = mVideoExtractor.getTrackFormat(mVideoTrackIndex); mVideoMinPTS = mVideoExtractor.getSampleTime(); Log.d(TAG, "selected video track #" + mVideoTrackIndex + " " + mVideoFormat.toString()); } // Select audio track if(mAudioTrackIndex != MediaCodecDecoder.INDEX_NONE) { mAudioExtractor.selectTrack(mAudioTrackIndex); mAudioFormat = mAudioExtractor.getTrackFormat(mAudioTrackIndex); mAudioMinPTS = mAudioExtractor.getSampleTime(); Log.d(TAG, "selected audio track #" + mAudioTrackIndex + " " + mAudioFormat.toString()); } if(mVideoTrackIndex == MediaCodecDecoder.INDEX_NONE) { mVideoExtractor = null; } if(mVideoTrackIndex == MediaCodecDecoder.INDEX_NONE && mAudioTrackIndex == MediaCodecDecoder.INDEX_NONE) { throw new IOException("invalid data source, no supported stream found"); } if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE && mPlaybackThread == null && mSurface == null) { Log.i(TAG, "no video output surface specified"); } mCurrentState = State.INITIALIZED; } /** * Sets the media source and automatically selects fitting tracks. * * @param source the media source * @throws IOException * @throws IllegalStateException */ public void setDataSource(MediaSource source) throws IOException, IllegalStateException { setDataSource(source, TRACK_INDEX_AUTO, TRACK_INDEX_AUTO); } private int getTrackIndex(MediaExtractor mediaExtractor, String mimeType) { if(mediaExtractor == null) { return MediaCodecDecoder.INDEX_NONE; } for (int i = 0; i < mediaExtractor.getTrackCount(); ++i) { MediaFormat format = mediaExtractor.getTrackFormat(i); Log.d(TAG, format.toString()); String mime = format.getString(MediaFormat.KEY_MIME); if (mime.startsWith(mimeType)) { return i; } } return MediaCodecDecoder.INDEX_NONE; } /** * @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri, java.util.Map) * @deprecated only for compatibility with Android API */ @Deprecated public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException { setDataSource(new UriSource(context, uri, headers)); } /** * @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri) * @deprecated only for compatibility with Android API */ @Deprecated public void setDataSource(Context context, Uri uri) throws IOException { setDataSource(context, uri, null); } private void prepareInternal() throws IOException, IllegalStateException { MediaCodecDecoder.OnDecoderEventListener decoderEventListener = new MediaCodecDecoder.OnDecoderEventListener() { @Override public void onBuffering(MediaCodecDecoder decoder) { // Enter buffering mode (playback pause) if cached amount is below water mark // Do not enter buffering mode is player is already paused (buffering mode will be // entered when playback is started and buffer is too empty). if(mPlaybackThread != null && !mPlaybackThread.isPaused() && !mBuffering && mDecoders.getCachedDuration() < BUFFER_LOW_WATER_MARK_US && !mDecoders.hasCacheReachedEndOfStream()) { mBuffering = true; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0)); } } }; if(mCurrentState == State.RELEASING) { // release() has already been called, drop out of prepareAsync() (can only happen with async prepare) return; } mDecoders = new Decoders(); if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE) { try { MediaCodecDecoder vd = new MediaCodecVideoDecoder(mVideoExtractor, false, mVideoTrackIndex, decoderEventListener, mSurface, mVideoRenderTimingMode.isRenderModeApi21()); mDecoders.addDecoder(vd); } catch (Exception e) { Log.e(TAG, "cannot create video decoder: " + e.getMessage()); } } if(mAudioTrackIndex != MediaCodecDecoder.INDEX_NONE) { mAudioPlayback = new AudioPlayback(); // Initialize settings in case they have already been set before the preparation mAudioPlayback.setAudioSessionId(mAudioSessionId); setVolume(mVolumeLeft, mVolumeRight); // sets the volume on mAudioPlayback try { boolean passive = (mAudioExtractor == mVideoExtractor || mAudioExtractor == null); MediaCodecDecoder ad = new MediaCodecAudioDecoder(mAudioExtractor != null ? mAudioExtractor : mVideoExtractor, passive, mAudioTrackIndex, decoderEventListener, mAudioPlayback); mDecoders.addDecoder(ad); } catch (Exception e) { Log.e(TAG, "cannot create audio decoder: " + e.getMessage()); mAudioPlayback = null; } } // If no decoder could be initialized, there is nothing to play back, so we throw an exception if(mDecoders.getDecoders().isEmpty()) { throw new IOException("cannot decode any stream"); } if (mAudioPlayback != null) { mAudioSessionId = mAudioPlayback.getAudioSessionId(); mAudioStreamType = mAudioPlayback.getAudioStreamType(); } // After the decoder is initialized, we know the video size if(mDecoders.getVideoDecoder() != null) { int width = mDecoders.getVideoDecoder().getVideoWidth(); int height = mDecoders.getVideoDecoder().getVideoHeight(); int rotation = mDecoders.getVideoDecoder().getVideoRotation(); // Swap width/height to report correct dimensions of rotated portrait video (rotated by 90 or 270 degrees) if(rotation > 0 && rotation != 180) { int temp = width; width = height; height = temp; } mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE, width, height)); } if(mCurrentState == State.RELEASING) { // release() has already been called, drop out of prepareAsync() return; } // Decode the first frame to initialize the decoder, and seek back to the start // This is necessary on some platforms, else a seek directly after initialization will fail, // or the decoder goes into a state where it does not accept any input and does not deliver // any output, locking up playback (observed on N4 API22). // N4 API22 Test: disable this code open video, seek to end, press play to start from beginning // -> results in infinite decoding loop without output if(true) { if(mDecoders.getVideoDecoder() != null) { MediaCodecDecoder.FrameInfo vfi = mDecoders.decodeFrame(true); mDecoders.getVideoDecoder().releaseFrame(vfi); } else { mDecoders.decodeFrame(false); } if (mAudioPlayback != null) mAudioPlayback.pause(true); mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); } } /** * @see android.media.MediaPlayer#prepare() */ public void prepare() throws IOException, IllegalStateException { if(mCurrentState != State.INITIALIZED && mCurrentState != State.STOPPED) { throw new IllegalStateException(); } mCurrentState = State.PREPARING; // Prepare synchronously on caller thread prepareInternal(); // Create the playback loop handler thread mPlaybackThread = new PlaybackThread(); mPlaybackThread.start(); mCurrentState = State.PREPARED; } /** * @see android.media.MediaPlayer#prepareAsync() */ public void prepareAsync() throws IllegalStateException { if(mCurrentState != State.INITIALIZED && mCurrentState != State.STOPPED) { throw new IllegalStateException(); } mCurrentState = State.PREPARING; // Create the playback loop handler thread mPlaybackThread = new PlaybackThread(); mPlaybackThread.start(); // Execute prepare asynchronously on playback thread mPlaybackThread.prepare(); } /** * @see android.media.MediaPlayer#setDisplay(android.view.SurfaceHolder) */ public void setDisplay(SurfaceHolder sh) { mSurfaceHolder = sh; if (sh != null) { mSurface = sh.getSurface(); } else { mSurface = null; } if(mDecoders != null && mDecoders.getVideoDecoder() != null) { //mDecoders.getVideoDecoder().updateSurface(mSurface); } if(mPlaybackThread == null) { // Player not prepared yet, so we can set the timing mode setVideoRenderTimingMode(VideoRenderTimingMode.AUTO); updateSurfaceScreenOn(); } else { // Player is already prepared, just change the surface mPlaybackThread.setSurface(mSurface); } } /** * @see android.media.MediaPlayer#setSurface(android.view.Surface) */ public void setSurface(Surface surface) { mSurface = surface; if (mScreenOnWhilePlaying && surface != null) { Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface"); } mSurfaceHolder = null; if(mPlaybackThread == null) { // Player not prepared yet, so we can set the timing mode setVideoRenderTimingMode(VideoRenderTimingMode.SLEEP); // the surface could be a GL texture, so we switch to sleep timing mode updateSurfaceScreenOn(); } else { // Player is already prepared, just change the surface mPlaybackThread.setSurface(mSurface); } } public void start() { if(mCurrentState != State.PREPARED) { mCurrentState = State.ERROR; throw new IllegalStateException(); } mPlaybackThread.play(); stayAwake(true); } public void pause() { if(mCurrentState != State.PREPARED) { mCurrentState = State.ERROR; throw new IllegalStateException(); } mPlaybackThread.pause(); stayAwake(false); } public SeekMode getSeekMode() { return mSeekMode; } public void setSeekMode(SeekMode seekMode) { this.mSeekMode = seekMode; } public void seekTo(long usec) { if(mCurrentState.ordinal() < State.PREPARED.ordinal() && mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } /* A seek needs to be performed in the decoding thread to execute commands in the correct * order. Otherwise it can happen that, after a seek in the media decoder, seeking procedure * starts, then a frame is decoded, and then the codec is flushed; the PTS of the decoded frame * then interferes the seeking procedure, the seek stops prematurely and a wrong waiting time * gets calculated. */ Log.d(TAG, "seekTo " + usec + " with video sample offset " + mVideoMinPTS); if (mOnSeekListener != null) { mOnSeekListener.onSeek(MediaPlayer.this); } mSeeking = true; // The passed in target time is always aligned to a zero start time, while the actual video // can have an offset and must not necessarily start at zero. The offset can e.g. come from // the CTTS box SampleOffset field, and is only reported on Android 5+. In Android 4, the // offset is handled by the framework, not reported, and videos always start at zero. // By adding the offset to the seek target time, we always seek to a zero-reference time in // the stream. mSeekTargetTime = mVideoMinPTS + usec; mPlaybackThread.seekTo(mSeekTargetTime); } public void seekTo(int msec) { seekTo(msec * 1000L); } /** * Sets the playback speed. Can be used for fast forward and slow motion. * The speed must not be negative. * * speed 0.5 = half speed / slow motion * speed 2.0 = double speed / fast forward * speed 0.0 equals to pause * * @param speed the playback speed to set * @throws IllegalArgumentException if the speed is negative */ public void setPlaybackSpeed(float speed) { if(speed < 0) { throw new IllegalArgumentException("speed cannot be negative"); } mTimeBase.setSpeed(speed); mTimeBase.startAt(mCurrentPosition); } /** * Gets the current playback speed. See {@link #setPlaybackSpeed(float)} for details. * @return the current playback speed */ public float getPlaybackSpeed() { return (float)mTimeBase.getSpeed(); } public boolean isPlaying() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mPlaybackThread != null && !mPlaybackThread.isPaused(); } /** * @see android.media.MediaPlayer#setLooping(boolean) */ public void setLooping(boolean looping) { mLooping = looping; } /** * @see android.media.MediaPlayer#isLooping() */ public boolean isLooping() { return mLooping; } public void stop() { release(); mCurrentState = State.STOPPED; } public void release() { if(mCurrentState == State.RELEASING || mCurrentState == State.RELEASED) { return; } mCurrentState = State.RELEASING; if(mPlaybackThread != null) { // Create a new lock object for this release cycle mReleaseSyncLock = new Object(); synchronized (mReleaseSyncLock) { try { // Schedule release on the playback thread mPlaybackThread.release(); mPlaybackThread = null; // Wait for the release on the playback thread to finish mReleaseSyncLock.wait(); } catch (InterruptedException e) { // nothing to do here } } mReleaseSyncLock = null; } stayAwake(false); mCurrentState = State.RELEASED; } public void reset() { stop(); mCurrentState = State.IDLE; } /** * @see android.media.MediaPlayer#setWakeMode(android.content.Context, int) */ public void setWakeMode(Context context, int mode) { boolean washeld = false; if (mWakeLock != null) { if (mWakeLock.isHeld()) { washeld = true; mWakeLock.release(); } mWakeLock = null; } PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName()); mWakeLock.setReferenceCounted(false); if (washeld) { mWakeLock.acquire(); } } /** * @see android.media.MediaPlayer#setScreenOnWhilePlaying(boolean) */ public void setScreenOnWhilePlaying(boolean screenOn) { if (mScreenOnWhilePlaying != screenOn) { if (screenOn && mSurfaceHolder == null) { Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder"); } mScreenOnWhilePlaying = screenOn; updateSurfaceScreenOn(); } } private void stayAwake(boolean awake) { if (mWakeLock != null) { if (awake && !mWakeLock.isHeld()) { mWakeLock.acquire(); } else if (!awake && mWakeLock.isHeld()) { mWakeLock.release(); } } mStayAwake = awake; updateSurfaceScreenOn(); } private void updateSurfaceScreenOn() { if (mSurfaceHolder != null) { mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); } } public int getDuration() { if(mCurrentState.ordinal() <= State.PREPARING.ordinal() && mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? (int)(mVideoFormat.getLong(MediaFormat.KEY_DURATION)/1000) : mAudioFormat != null && mAudioFormat.containsKey(MediaFormat.KEY_DURATION) ? (int)(mAudioFormat.getLong(MediaFormat.KEY_DURATION)/1000) : 0; } public int getCurrentPosition() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } /* During a seek, return the temporary seek target time; otherwise a seek bar doesn't * update to the selected seek position until the seek is finished (which can take a * while in exact mode). */ return (int)((mSeeking ? mSeekTargetTime : mCurrentPosition)/1000); } public int getBufferPercentage() { return mBufferPercentage; } public int getVideoWidth() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? (int)(mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) * mVideoFormat.getFloat(MediaExtractor.MEDIA_FORMAT_EXTENSION_KEY_DAR)) : 0; } public int getVideoHeight() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) : 0; } /** * @see android.media.MediaPlayer#setVolume(float, float) */ public void setVolume(float leftVolume, float rightVolume) { mVolumeLeft = leftVolume; mVolumeRight = rightVolume; if(mAudioPlayback != null) { mAudioPlayback.setStereoVolume(leftVolume, rightVolume); } } /** * This API method in the Android MediaPlayer is hidden, but may be unhidden in the future. Here * it can already be used. * see android.media.MediaPlayer#setVolume(float) */ public void setVolume(float volume) { setVolume(volume, volume); } /** * @see android.media.MediaPlayer#setAudioSessionId(int) */ public void setAudioSessionId(int sessionId) { if(mCurrentState != State.IDLE) { throw new IllegalStateException(); } mAudioSessionId = sessionId; } /** * @see android.media.MediaPlayer#getAudioSessionId() */ public int getAudioSessionId() { return mAudioSessionId; } public void setAudioStreamType(int streamType) { // Can be set any time, no IllegalStateException is thrown, but value will be ignored if audio is already initialized mAudioStreamType = streamType; } /** * Gets the stream type of the audio playback session. * @return the stream type */ public int getAudioStreamType() { return mAudioStreamType; } /** * Sets the timing mode for video frame rendering. * This only works before the calling {@link #prepare()} or {@link #prepareAsync()}. * * This method is only needed for the special case of rendering the video to a GL surface texture, * where {@link MediaCodec#releaseOutputBuffer(int, long)} does not defer the frame rendering * and thus does not block until the PTS is reached. This only seems to work correctly on a * {@link android.view.SurfaceView}. It is therefore required to manually set the * {@link VideoRenderTimingMode#SLEEP} mode on API 21+ platforms to get timed frame rendering. * * TODO find out how to get deferred/blocking rendering to work with a surface texture * * @see VideoRenderTimingMode * @param mode the desired timing mode * @throws IllegalStateException */ void setVideoRenderTimingMode(VideoRenderTimingMode mode) { if(mPlaybackThread != null) { throw new IllegalStateException("called after prepare/prepareAsync"); } if(mode == VideoRenderTimingMode.SURFACEVIEW_TIMESTAMP_API21 && Build.VERSION.SDK_INT < 21) { throw new IllegalArgumentException("this mode needs min API 21"); } Log.d(TAG, "setVideoRenderTimingMode " + mode); mVideoRenderTimingMode = mode; } private class PlaybackThread extends HandlerThread implements Handler.Callback { private static final int PLAYBACK_PREPARE = 1; private static final int PLAYBACK_PLAY = 2; private static final int PLAYBACK_PAUSE = 3; private static final int PLAYBACK_LOOP = 4; private static final int PLAYBACK_SEEK = 5; private static final int PLAYBACK_RELEASE = 6; private static final int PLAYBACK_PAUSE_AUDIO = 7; static final int DECODER_SET_SURFACE = 100; private Handler mHandler; private boolean mPaused; private boolean mReleasing; private MediaCodecDecoder.FrameInfo mVideoFrameInfo; private boolean mRenderModeApi21; // Usage of timed outputBufferRelease on API 21+ private boolean mRenderingStarted; // Flag to know if decoding the first frame private double mPlaybackSpeed; private boolean mAVLocked; public PlaybackThread() { // Give this thread a high priority for more precise event timing super(TAG + "#" + PlaybackThread.class.getSimpleName(), Process.THREAD_PRIORITY_AUDIO); // Init fields mPaused = true; mReleasing = false; mRenderModeApi21 = mVideoRenderTimingMode.isRenderModeApi21(); mRenderingStarted = true; mAVLocked = false; } @Override public synchronized void start() { super.start(); // Create the handler that will process the messages on the handler thread mHandler = new Handler(this.getLooper(), this); Log.d(TAG, "PlaybackThread started"); } public void prepare() { mHandler.sendEmptyMessage(PLAYBACK_PREPARE); } public void play() { mPaused = false; mHandler.sendEmptyMessage(PLAYBACK_PLAY); } public void pause() { mPaused = true; mHandler.sendEmptyMessage(PLAYBACK_PAUSE); } public boolean isPaused() { return mPaused; } public void seekTo(long usec) { // When multiple seek requests come in, e.g. when a user slides the finger on a // seek bar in the UI, we don't want to process all of them and can therefore remove // all requests from the queue and only keep the most recent one. mHandler.removeMessages(PLAYBACK_SEEK); // remove any previous requests mHandler.obtainMessage(PLAYBACK_SEEK, usec).sendToTarget(); } public void setSurface(Surface surface) { mHandler.sendMessage(mHandler.obtainMessage(PlaybackThread.DECODER_SET_SURFACE, surface)); } private void release() { if(!isAlive()) { return; } mPaused = true; // Set this flag so the loop does not schedule next loop iteration mReleasing = true; // Call actual release method // Actually it does not matter what we schedule here, we just need to schedule // something so {@link #handleMessage} gets called on the handler thread, read the // mReleasing flag, and call {@link #releaseInternal}. mHandler.sendEmptyMessage(PLAYBACK_RELEASE); } @Override public boolean handleMessage(Message msg) { try { if(mReleasing) { // When the releasing flag is set, just release without processing any more messages releaseInternal(); return true; } switch (msg.what) { case PLAYBACK_PREPARE: prepareInternal(); return true; case PLAYBACK_PLAY: playInternal(); return true; case PLAYBACK_PAUSE: pauseInternal(); return true; case PLAYBACK_PAUSE_AUDIO: pauseInternalAudio(); return true; case PLAYBACK_LOOP: loopInternal(); return true; case PLAYBACK_SEEK: seekInternal((Long) msg.obj); return true; case PLAYBACK_RELEASE: releaseInternal(); return true; case DECODER_SET_SURFACE: setVideoSurface((Surface) msg.obj); return true; default: Log.d(TAG, "unknown/invalid message"); return false; } } catch (InterruptedException e) { Log.d(TAG, "decoder interrupted", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); } catch (IllegalStateException e) { Log.e(TAG, "decoder error, too many instances?", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); } catch (IOException e) { Log.e(TAG, "decoder error, codec can not be created", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO)); } // Release after an exception releaseInternal(); return true; } private void prepareInternal() { try { MediaPlayer.this.prepareInternal(); mCurrentState = MediaPlayer.State.PREPARED; // This event is only triggered after a successful async prepare (not after the sync prepare!) mEventHandler.sendEmptyMessage(MEDIA_PREPARED); } catch (IOException e) { Log.e(TAG, "prepareAsync() failed: cannot decode stream(s)", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO)); releaseInternal(); } catch (IllegalStateException e) { Log.e(TAG, "prepareAsync() failed: something is in a wrong state", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); releaseInternal(); } catch (IllegalArgumentException e) { Log.e(TAG, "prepareAsync() failed: surface might be gone", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); releaseInternal(); } } private void playInternal() throws IOException, InterruptedException { if(mDecoders.isEOS()) { mCurrentPosition = 0; mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); } // reset time (otherwise playback tries to "catch up" time after a pause) mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); if(mAudioPlayback != null) { mHandler.removeMessages(PLAYBACK_PAUSE_AUDIO); mAudioPlayback.play(); } mPlaybackSpeed = mTimeBase.getSpeed(); // Sync audio playback speed to playback speed (to account for speed changes during pause) if (mAudioPlayback != null) { mAudioPlayback.setPlaybackSpeed((float) mPlaybackSpeed); } mHandler.removeMessages(PLAYBACK_LOOP); loopInternal(); } private void pauseInternal(boolean drainAudioPlayback) { // When playback is paused in timed API21 render mode, the remaining cached frames will // still be rendered, resulting in a short but noticeable pausing lag. This can be avoided // by switching to the old render timing mode. mHandler.removeMessages(PLAYBACK_LOOP); // removes remaining loop requests (required when EOS is reached) if (mAudioPlayback != null) { if(drainAudioPlayback) { // Defer pausing the audio playback for the length of the playback buffer, to // make sure that all audio samples have been played out. mHandler.sendEmptyMessageDelayed(PLAYBACK_PAUSE_AUDIO, (mAudioPlayback.getQueueBufferTimeUs() + mAudioPlayback.getPlaybackBufferTimeUs()) / 1000 + 1); } else { mAudioPlayback.pause(false); } } } private void pauseInternal() { pauseInternal(false); } private void pauseInternalAudio() { if (mAudioPlayback != null) { mAudioPlayback.pause(); } } private void loopInternal() throws IOException, InterruptedException { // If this is an online stream, notify the client of the buffer fill level. long cachedDuration = mDecoders.getCachedDuration(); if(cachedDuration != -1) { // The cached duration from the MediaExtractor returns the cached time from // the current position onwards, but the Android MediaPlayer returns the // total time consisting of the current playback point and the length of // the prefetched data. // This comes before the buffering pause to update the clients buffering info // also during a buffering playback pause. mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_BUFFERING_UPDATE, (int) (100d / (getDuration() * 1000) * (mCurrentPosition + cachedDuration)), 0)); } // If we are in buffering mode, check if the buffer has been filled until the low water // mark or the end of the stream has been reached, and pause playback if it isn't filled // high enough yet. if(mBuffering && cachedDuration > -1 && cachedDuration < BUFFER_LOW_WATER_MARK_US && !mDecoders.hasCacheReachedEndOfStream()) { //Log.d(TAG, "buffering... " + mDecoders.getCachedDuration() + " / " + BUFFER_LOW_WATER_MARK_US); // To pause playback for buffering, we simply skip this loop and call it again later mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 100); return; } if(mDecoders.getVideoDecoder() != null && mVideoFrameInfo == null) { // This method needs a video frame to operate on. If there is no frame, we need // to decode one first. mVideoFrameInfo = mDecoders.decodeFrame(false); if(mVideoFrameInfo == null && !mDecoders.isEOS()) { // If the decoder didn't return a frame, we need to give it some processing time // and come back later... mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 10); return; } } long startTime = SystemClock.elapsedRealtime(); // When we are in buffering mode, and a frame has been decoded, the buffer is // obviously refilled so we can send the buffering end message and exit buffering mode. if(mBuffering) { mBuffering = false; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0)); // Reset timebase so player does not try to catch up time lost while caching mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); } // When the waiting time to the next frame is too long, we defer rendering through // the handler here instead of relying on releaseOutputBuffer(buffer, renderTimestampNs), // which does not work well with long waiting times and many frames in the queue. // On API < 21 the frame rendering is timed with a sleep() and this is not really necessary, // but still shifts some waiting time from the sleep() to here. if(mVideoFrameInfo != null && mTimeBase.getOffsetFrom(mVideoFrameInfo.presentationTimeUs) > 60000) { mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 50); return; } // Update the current position of the player mCurrentPosition = mDecoders.getCurrentDecodingPTS(); if(mDecoders.getVideoDecoder() != null && mVideoFrameInfo != null) { renderVideoFrame(mVideoFrameInfo); mVideoFrameInfo = null; // When the first frame is rendered, video rendering has started and the event triggered if (mRenderingStarted) { mRenderingStarted = false; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_VIDEO_RENDERING_START, 0)); } } if (mAudioPlayback != null) { // Sync audio playback speed to playback speed (to account for speed changes during playback) // Change the speed on the audio playback object only if it has really changed, to avoid runtime overhead if(mPlaybackSpeed != mTimeBase.getSpeed()) { mPlaybackSpeed = mTimeBase.getSpeed(); mAudioPlayback.setPlaybackSpeed((float) mPlaybackSpeed); } // Sync timebase to audio timebase when there is audio data available long currentAudioPTS = mAudioPlayback.getCurrentPresentationTimeUs(); if(currentAudioPTS > AudioPlayback.PTS_NOT_SET) { mTimeBase.startAt(currentAudioPTS); } } // Handle EOS if (mDecoders.isEOS()) { mEventHandler.sendEmptyMessage(MEDIA_PLAYBACK_COMPLETE); // If looping is on, seek back to the start... if(mLooping) { if(mAudioPlayback != null) { // Flush audio buffer to reset audio PTS mAudioPlayback.flush(); } mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); mDecoders.renderFrames(); } // ... else just pause playback and wait for next command else { mPaused = true; pauseInternal(true); // pause but play remaining buffered audio } } else { // Get next frame mVideoFrameInfo = mDecoders.decodeFrame(false); } if(!mPaused) { // Static delay time until the next call of the playback loop long delay = 10; // Scale delay by playback speed to avoid limiting framerate delay = (long)(delay / mTimeBase.getSpeed()); // Calculate the duration taken for the current call long duration = (SystemClock.elapsedRealtime() - startTime); // Adjust the delay by the time taken delay = delay - duration; if(delay > 0) { // Sleep for some time and then continue processing the loop // This replaces the very unreliable and jittery Thread.sleep in the old decoder thread mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, delay); } else { // The current call took too much time; there is no time left for delaying, call instantly mHandler.sendEmptyMessage(PLAYBACK_LOOP); } } } private void seekInternal(long usec) throws IOException, InterruptedException { if(mVideoFrameInfo != null) { // A decoded video frame is waiting to be rendered, dismiss it mDecoders.getVideoDecoder().dismissFrame(mVideoFrameInfo); mVideoFrameInfo = null; } // Clear the audio cache if(mAudioPlayback != null) mAudioPlayback.pause(true); // Seek to the target time mDecoders.seekTo(mSeekMode, usec); // Reset time to keep frame rate constant // (otherwise it's too fast on back seeks and waits for the PTS time on fw seeks) mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); // Check if another seek has been issued in the meantime boolean newSeekWaiting = mHandler.hasMessages(PLAYBACK_SEEK); // Render seek target frame (if no new seek is waiting to be processed) if(newSeekWaiting) { mDecoders.dismissFrames(); } else { mDecoders.renderFrames(); } // When there are no more seek requests in the queue, notify of finished seek operation if(!newSeekWaiting) { // Set the final seek position as the current position // (the final seek position may be off the initial target seek position) mCurrentPosition = mDecoders.getCurrentDecodingPTS(); mSeeking = false; mAVLocked = false; mEventHandler.sendEmptyMessage(MEDIA_SEEK_COMPLETE); if(!mPaused) { playInternal(); } } } private void releaseInternal() { // post interrupt to avoid all further execution of messages/events in the queue interrupt(); // quit message processing and exit thread quit(); if(mDecoders != null) { if(mVideoFrameInfo != null) { mDecoders.getVideoDecoder().releaseFrame(mVideoFrameInfo); mVideoFrameInfo = null; } } if(mDecoders != null) { mDecoders.release(); } if(mAudioPlayback != null) mAudioPlayback.stopAndRelease(); if(mAudioExtractor != null & mAudioExtractor != mVideoExtractor) { mAudioExtractor.release(); } if(mVideoExtractor != null) mVideoExtractor.release(); Log.d(TAG, "PlaybackThread destroyed"); // Notify #release() that it can now continue because #releaseInternal is finished if(mReleaseSyncLock != null) { synchronized(mReleaseSyncLock) { mReleaseSyncLock.notify(); mReleaseSyncLock = null; } } } private void renderVideoFrame(MediaCodecDecoder.FrameInfo videoFrameInfo) throws InterruptedException { if(videoFrameInfo.endOfStream) { // The EOS frame does not contain a video frame, so we dismiss it mDecoders.getVideoDecoder().dismissFrame(videoFrameInfo); return; } // Calculate waiting time until the next frame's PTS // The waiting time might be much higher that a frame's duration because timed API21 // rendering caches multiple released output frames before actually rendering them. long waitingTime = mTimeBase.getOffsetFrom(videoFrameInfo.presentationTimeUs); // Log.d(TAG, "VPTS " + mCurrentPosition // + " APTS " + mAudioPlayback.getCurrentPresentationTimeUs() // + " waitingTime " + waitingTime); if (waitingTime < -1000) { // we need to catch up time by skipping rendering of this frame // this doesn't gain enough time if playback speed is too high and decoder at full load // TODO improve fast forward mode Log.d(TAG, "LAGGING " + waitingTime); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_VIDEO_TRACK_LAGGING, 0)); } // Defer the video size changed message until the first frame of the new size is being rendered if (videoFrameInfo.representationChanged) { mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE, mDecoders.getVideoDecoder().getVideoWidth(), mDecoders.getVideoDecoder().getVideoHeight())); } // Slow down playback, if necessary, to keep frame rate if(!mRenderModeApi21 && waitingTime > 5000) { // Sleep until it's time to render the next frame // This is not v-synced to the display. Not required any more on API 21+. Thread.sleep(waitingTime / 1000); } // Release the current frame and render it to the surface mDecoders.getVideoDecoder().renderFrame(videoFrameInfo, waitingTime); } private void setVideoSurface(Surface surface) { if(mDecoders != null && mDecoders.getVideoDecoder() != null) { if(mVideoFrameInfo != null) { // Dismiss queued video frame // After updating the surface, which re-initializes the codec, // the frame buffer will not be valid any more and trying to decode // it would result in an error; so we throw it away. mDecoders.getVideoDecoder().dismissFrame(mVideoFrameInfo); mVideoFrameInfo = null; } mDecoders.getVideoDecoder().updateSurface(surface); } } } /** * Interface definition for a callback to be invoked when the media * source is ready for playback. */ public interface OnPreparedListener { /** * Called when the media file is ready for playback. * @param mp the MediaPlayer that is ready for playback */ void onPrepared(MediaPlayer mp); } /** * Register a callback to be invoked when the media source is ready * for playback. * * @param listener the callback that will be run */ public void setOnPreparedListener(OnPreparedListener listener) { mOnPreparedListener = listener; } /** * Interface definition for a callback to be invoked when playback of * a media source has completed. */ public interface OnCompletionListener { /** * Called when the end of a media source is reached during playback. * @param mp the MediaPlayer that reached the end of the file */ void onCompletion(MediaPlayer mp); } /** * Register a callback to be invoked when the end of a media source * has been reached during playback. * * @param listener the callback that will be run */ public void setOnCompletionListener(OnCompletionListener listener) { mOnCompletionListener = listener; } /** * Interface definition of a callback to be invoked when a seek * is issued. */ public interface OnSeekListener { /** * Called to indicate that a seek operation has been started. * @param mp the mediaPlayer that the seek was called on */ public void onSeek(MediaPlayer mp); } /** * Register a calback to be invoked when a seek operation has been started. * @param listener the callback that will be run */ public void setOnSeekListener(OnSeekListener listener) { mOnSeekListener = listener; } /** * Interface definition of a callback to be invoked indicating * the completion of a seek operation. */ public interface OnSeekCompleteListener { /** * Called to indicate the completion of a seek operation. * @param mp the MediaPlayer that issued the seek operation */ public void onSeekComplete(MediaPlayer mp); } /** * Register a callback to be invoked when a seek operation has been * completed. * * @param listener the callback that will be run */ public void setOnSeekCompleteListener(OnSeekCompleteListener listener) { mOnSeekCompleteListener = listener; } /** * Interface definition of a callback to be invoked when the * video size is first known or updated */ public interface OnVideoSizeChangedListener { /** * Called to indicate the video size * * The video size (width and height) could be 0 if there was no video, * no display surface was set, or the value was not determined yet. * * @param mp the MediaPlayer associated with this callback * @param width the width of the video * @param height the height of the video */ public void onVideoSizeChanged(MediaPlayer mp, int width, int height); } /** * Register a callback to be invoked when the video size is * known or updated. * * @param listener the callback that will be run */ public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) { mOnVideoSizeChangedListener = listener; } /** * Interface definition of a callback to be invoked indicating buffering * status of a media resource being streamed over the network. */ public interface OnBufferingUpdateListener { /** * Called to update status in buffering a media stream received through * progressive HTTP download. The received buffering percentage * indicates how much of the content has been buffered or played. * For example a buffering update of 80 percent when half the content * has already been played indicates that the next 30 percent of the * content to play has been buffered. * * @param mp the MediaPlayer the update pertains to * @param percent the percentage (0-100) of the content * that has been buffered or played thus far */ void onBufferingUpdate(MediaPlayer mp, int percent); } /** * Register a callback to be invoked when the status of a network * stream's buffer has changed. * * @param listener the callback that will be run. */ public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) { mOnBufferingUpdateListener = listener; } /** Unspecified media player error. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_UNKNOWN = 1; /** Media server died. In this case, the application must release the * MediaPlayer object and instantiate a new one. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_SERVER_DIED = 100; /** The video is streamed and its container is not valid for progressive * playback i.e the video's index (e.g moov atom) is not at the start of the * file. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; /** File or network related operation errors. */ public static final int MEDIA_ERROR_IO = -1004; /** Bitstream is not conforming to the related coding standard or file spec. */ public static final int MEDIA_ERROR_MALFORMED = -1007; /** Bitstream is conforming to the related coding standard or file spec, but * the media framework does not support the feature. */ public static final int MEDIA_ERROR_UNSUPPORTED = -1010; /** Some operation takes too long to complete, usually more than 3-5 seconds. */ public static final int MEDIA_ERROR_TIMED_OUT = -110; /** * Interface definition of a callback to be invoked when there * has been an error during an asynchronous operation (other errors * will throw exceptions at method call time). */ public interface OnErrorListener { /** * Called to indicate an error. * * @param mp the MediaPlayer the error pertains to * @param what the type of error that has occurred: * <ul> * <li>{@link #MEDIA_ERROR_UNKNOWN} * <li>{@link #MEDIA_ERROR_SERVER_DIED} * </ul> * @param extra an extra code, specific to the error. Typically * implementation dependent. * <ul> * <li>{@link #MEDIA_ERROR_IO} * <li>{@link #MEDIA_ERROR_MALFORMED} * <li>{@link #MEDIA_ERROR_UNSUPPORTED} * <li>{@link #MEDIA_ERROR_TIMED_OUT} * </ul> * @return True if the method handled the error, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the OnCompletionListener to be called. */ boolean onError(MediaPlayer mp, int what, int extra); } /** * Register a callback to be invoked when an error has happened * during an asynchronous operation. * * @param listener the callback that will be run */ public void setOnErrorListener(OnErrorListener listener) { mOnErrorListener = listener; } /** The player just pushed the very first video frame for rendering. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; /** The video is too complex for the decoder: it can't decode frames fast * enough. Possibly only the audio plays fine at this stage. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; /** MediaPlayer is temporarily pausing playback internally in order to * buffer more data. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_BUFFERING_START = 701; /** MediaPlayer is resuming playback after filling buffers. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_BUFFERING_END = 702; /** * Interface definition of a callback to be invoked to communicate some * info and/or warning about the media or its playback. */ public interface OnInfoListener { /** * Called to indicate an info or a warning. * * @param mp the MediaPlayer the info pertains to. * @param what the type of info or warning. * <ul> * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START} * <li>{@link #MEDIA_INFO_BUFFERING_START} * <li>{@link #MEDIA_INFO_BUFFERING_END} * </ul> * @param extra an extra code, specific to the info. Typically * implementation dependent. * @return True if the method handled the info, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the info to be discarded. */ boolean onInfo(MediaPlayer mp, int what, int extra); } /** * Register a callback to be invoked when an info/warning is available. * @param listener the callback that will be run */ public void setOnInfoListener(OnInfoListener listener) { mOnInfoListener = listener; } private static final int MEDIA_PREPARED = 1; private static final int MEDIA_PLAYBACK_COMPLETE = 2; private static final int MEDIA_BUFFERING_UPDATE = 3; private static final int MEDIA_SEEK_COMPLETE = 4; private static final int MEDIA_SET_VIDEO_SIZE = 5; private static final int MEDIA_ERROR = 100; private static final int MEDIA_INFO = 200; private class EventHandler extends Handler { @Override public void handleMessage(Message msg) { switch(msg.what) { case MEDIA_PREPARED: Log.d(TAG, "onPrepared"); if(mOnPreparedListener != null) { mOnPreparedListener.onPrepared(MediaPlayer.this); } return; case MEDIA_SEEK_COMPLETE: Log.d(TAG, "onSeekComplete"); if (mOnSeekCompleteListener != null) { mOnSeekCompleteListener.onSeekComplete(MediaPlayer.this); } return; case MEDIA_PLAYBACK_COMPLETE: Log.d(TAG, "onPlaybackComplete"); if(mOnCompletionListener != null) { mOnCompletionListener.onCompletion(MediaPlayer.this); } stayAwake(false); return; case MEDIA_SET_VIDEO_SIZE: Log.d(TAG, "onVideoSizeChanged"); if(mOnVideoSizeChangedListener != null) { mOnVideoSizeChangedListener.onVideoSizeChanged(MediaPlayer.this, msg.arg1, msg.arg2); } return; case MEDIA_ERROR: Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); boolean error_was_handled = false; if (mOnErrorListener != null) { error_was_handled = mOnErrorListener.onError(MediaPlayer.this, msg.arg1, msg.arg2); } if (mOnCompletionListener != null && !error_was_handled) { mOnCompletionListener.onCompletion(MediaPlayer.this); } stayAwake(false); return; case MEDIA_INFO: Log.d(TAG, "onInfo"); if(mOnInfoListener != null) { mOnInfoListener.onInfo(MediaPlayer.this, msg.arg1, msg.arg2); } return; case MEDIA_BUFFERING_UPDATE: //Log.d(TAG, "onBufferingUpdate"); if (mOnBufferingUpdateListener != null) mOnBufferingUpdateListener.onBufferingUpdate(MediaPlayer.this, msg.arg1); mBufferPercentage = msg.arg1; return; default: // nothing } } } }
MediaPlayer/src/main/java/net/protyposis/android/mediaplayer/MediaPlayer.java
/* * Copyright 2014 Mario Guggenberger <mg@protyposis.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.protyposis.android.mediaplayer; import android.content.Context; import android.media.AudioManager; import android.media.MediaCodec; import android.media.MediaFormat; import android.net.Uri; import android.os.*; import android.os.Process; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import java.io.IOException; import java.util.Map; import java.util.concurrent.CountDownLatch; /** * Created by maguggen on 04.06.2014. */ public class MediaPlayer { private static final String TAG = MediaPlayer.class.getSimpleName(); private static final long BUFFER_LOW_WATER_MARK_US = 2000000; // 2 seconds; NOTE: make sure this is below DashMediaExtractor's mMinBufferTimeUs /** * Pass as track index to tell the player that no track should be selected. */ public static final int TRACK_INDEX_NONE = -1; /** * Pass as track index to tell the player to automatically select the first fitting track. */ public static final int TRACK_INDEX_AUTO = -2; public enum SeekMode { /** * Seeks to the previous sync point. * This mode exists for backwards compatibility and is the same as {@link #FAST_TO_PREVIOUS_SYNC}. */ @Deprecated FAST(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Seeks to the previous sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_PREVIOUS_SYNC}. */ FAST_TO_PREVIOUS_SYNC(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Seeks to the next sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_NEXT_SYNC}. */ FAST_TO_NEXT_SYNC(MediaExtractor.SEEK_TO_NEXT_SYNC), /** * Seeks to to the closest sync point. * This seek mode equals Android MediaExtractor's {@link android.media.MediaExtractor#SEEK_TO_CLOSEST_SYNC}. */ FAST_TO_CLOSEST_SYNC(MediaExtractor.SEEK_TO_CLOSEST_SYNC), /** * Seeks to the exact frame if the seek time equals the frame time, else * to the following frame; this means that it will often seek one frame too far. */ PRECISE(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Default mode. * Always seeks to the exact frame. Can cost maximally twice the time than the PRECISE mode. */ EXACT(MediaExtractor.SEEK_TO_PREVIOUS_SYNC), /** * Always seeks to the exact frame by skipping the decoding of all frames between the sync * and target frame, because of which it can result in block artifacts. */ FAST_EXACT(MediaExtractor.SEEK_TO_PREVIOUS_SYNC); private int baseSeekMode = MediaExtractor.SEEK_TO_PREVIOUS_SYNC; SeekMode(int baseSeekMode) { this.baseSeekMode = baseSeekMode; } public int getBaseSeekMode() { return baseSeekMode; } } /** * The mode of how to delay rendering of video frames until their target PTS. */ enum VideoRenderTimingMode { /** * Automatically chooses {@link VideoRenderTimingMode#SLEEP} for API < 21 and * {@link VideoRenderTimingMode#SURFACEVIEW_TIMESTAMP_API21} for API >= 21. */ AUTO, /** * Defers rendering by putting the playback thread to sleep until the PTS is reached and renders * frames through {@link MediaCodec#releaseOutputBuffer(int, boolean)}. */ SLEEP, /** * Defers rendering through {@link MediaCodec#releaseOutputBuffer(int, long)} which blocks * until the PTS is reached. Supported on API 21+. */ SURFACEVIEW_TIMESTAMP_API21; public boolean isRenderModeApi21() { switch (this) { case AUTO: return Build.VERSION.SDK_INT >= 21; case SLEEP: return false; case SURFACEVIEW_TIMESTAMP_API21: return true; } return false; } } private enum State { IDLE, INITIALIZED, PREPARING, PREPARED, STOPPED, RELEASING, RELEASED, ERROR } private SeekMode mSeekMode = SeekMode.EXACT; private Surface mSurface; private SurfaceHolder mSurfaceHolder; private MediaExtractor mVideoExtractor; private MediaExtractor mAudioExtractor; private int mVideoTrackIndex; private MediaFormat mVideoFormat; private long mVideoMinPTS; private int mAudioTrackIndex; private MediaFormat mAudioFormat; private long mAudioMinPTS; private int mAudioSessionId; private int mAudioStreamType; private float mVolumeLeft = 1, mVolumeRight = 1; private PlaybackThread mPlaybackThread; private long mCurrentPosition; private long mSeekTargetTime; private boolean mSeeking; private int mBufferPercentage; private TimeBase mTimeBase; private EventHandler mEventHandler; private OnPreparedListener mOnPreparedListener; private OnCompletionListener mOnCompletionListener; private OnSeekListener mOnSeekListener; private OnSeekCompleteListener mOnSeekCompleteListener; private OnErrorListener mOnErrorListener; private OnInfoListener mOnInfoListener; private OnVideoSizeChangedListener mOnVideoSizeChangedListener; private OnBufferingUpdateListener mOnBufferingUpdateListener; private PowerManager.WakeLock mWakeLock = null; private boolean mScreenOnWhilePlaying; private boolean mStayAwake; private boolean mLooping; private AudioPlayback mAudioPlayback; private Decoders mDecoders; private boolean mBuffering; private VideoRenderTimingMode mVideoRenderTimingMode; private State mCurrentState; /** * A lock to sync release() with the actual releasing on the playback thread. This lock makes * sure that release() waits until everything has been released before returning to the caller, * and thus makes the async release look synchronized to an API caller. */ private Object mReleaseSyncLock; public MediaPlayer() { mPlaybackThread = null; mEventHandler = new EventHandler(); mTimeBase = new TimeBase(); mVideoRenderTimingMode = VideoRenderTimingMode.AUTO; mCurrentState = State.IDLE; mAudioSessionId = 0; // AudioSystem.AUDIO_SESSION_ALLOCATE; mAudioStreamType = AudioManager.STREAM_MUSIC; } /** * Sets the media source and track indices. The track indices can either be actual track indices * that have been determined externally, {@link #TRACK_INDEX_AUTO} to automatically select * the first fitting track index, or {@link #TRACK_INDEX_NONE} to not select any track. * * @param source the media source * @param videoTrackIndex a video track index or one of the TACK_INDEX_* constants * @param audioTrackIndex an audio track index or one of the TACK_INDEX_* constants * @throws IOException * @throws IllegalStateException */ public void setDataSource(MediaSource source, int videoTrackIndex, int audioTrackIndex) throws IOException, IllegalStateException { if(mCurrentState != State.IDLE) { throw new IllegalStateException(); } mVideoExtractor = source.getVideoExtractor(); mAudioExtractor = source.getAudioExtractor(); if(mVideoExtractor != null && mAudioExtractor == null) { mAudioExtractor = mVideoExtractor; } switch (videoTrackIndex) { case TRACK_INDEX_AUTO: mVideoTrackIndex = getTrackIndex(mVideoExtractor, "video/"); break; case TRACK_INDEX_NONE: mVideoTrackIndex = MediaCodecDecoder.INDEX_NONE; break; default: mVideoTrackIndex = videoTrackIndex; } switch (audioTrackIndex) { case TRACK_INDEX_AUTO: mAudioTrackIndex = getTrackIndex(mAudioExtractor, "audio/"); break; case TRACK_INDEX_NONE: mAudioTrackIndex = MediaCodecDecoder.INDEX_NONE; break; default: mAudioTrackIndex = audioTrackIndex; } // Select video track if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE) { mVideoExtractor.selectTrack(mVideoTrackIndex); mVideoFormat = mVideoExtractor.getTrackFormat(mVideoTrackIndex); mVideoMinPTS = mVideoExtractor.getSampleTime(); } // Select audio track if(mAudioTrackIndex != MediaCodecDecoder.INDEX_NONE) { mAudioExtractor.selectTrack(mAudioTrackIndex); mAudioFormat = mAudioExtractor.getTrackFormat(mAudioTrackIndex); mAudioMinPTS = mAudioExtractor.getSampleTime(); } if(mVideoTrackIndex == MediaCodecDecoder.INDEX_NONE) { mVideoExtractor = null; } if(mVideoTrackIndex == MediaCodecDecoder.INDEX_NONE && mAudioTrackIndex == MediaCodecDecoder.INDEX_NONE) { throw new IOException("invalid data source, no supported stream found"); } if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE && mPlaybackThread == null && mSurface == null) { Log.i(TAG, "no video output surface specified"); } mCurrentState = State.INITIALIZED; } /** * Sets the media source and automatically selects fitting tracks. * * @param source the media source * @throws IOException * @throws IllegalStateException */ public void setDataSource(MediaSource source) throws IOException, IllegalStateException { setDataSource(source, TRACK_INDEX_AUTO, TRACK_INDEX_AUTO); } private int getTrackIndex(MediaExtractor mediaExtractor, String mimeType) { if(mediaExtractor == null) { return MediaCodecDecoder.INDEX_NONE; } for (int i = 0; i < mediaExtractor.getTrackCount(); ++i) { MediaFormat format = mediaExtractor.getTrackFormat(i); Log.d(TAG, format.toString()); String mime = format.getString(MediaFormat.KEY_MIME); if (mime.startsWith(mimeType)) { return i; } } return MediaCodecDecoder.INDEX_NONE; } /** * @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri, java.util.Map) * @deprecated only for compatibility with Android API */ @Deprecated public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException { setDataSource(new UriSource(context, uri, headers)); } /** * @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri) * @deprecated only for compatibility with Android API */ @Deprecated public void setDataSource(Context context, Uri uri) throws IOException { setDataSource(context, uri, null); } private void prepareInternal() throws IOException, IllegalStateException { MediaCodecDecoder.OnDecoderEventListener decoderEventListener = new MediaCodecDecoder.OnDecoderEventListener() { @Override public void onBuffering(MediaCodecDecoder decoder) { // Enter buffering mode (playback pause) if cached amount is below water mark // Do not enter buffering mode is player is already paused (buffering mode will be // entered when playback is started and buffer is too empty). if(mPlaybackThread != null && !mPlaybackThread.isPaused() && !mBuffering && mDecoders.getCachedDuration() < BUFFER_LOW_WATER_MARK_US && !mDecoders.hasCacheReachedEndOfStream()) { mBuffering = true; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0)); } } }; if(mCurrentState == State.RELEASING) { // release() has already been called, drop out of prepareAsync() (can only happen with async prepare) return; } mDecoders = new Decoders(); if(mVideoTrackIndex != MediaCodecDecoder.INDEX_NONE) { try { MediaCodecDecoder vd = new MediaCodecVideoDecoder(mVideoExtractor, false, mVideoTrackIndex, decoderEventListener, mSurface, mVideoRenderTimingMode.isRenderModeApi21()); mDecoders.addDecoder(vd); } catch (Exception e) { Log.e(TAG, "cannot create video decoder: " + e.getMessage()); } } if(mAudioTrackIndex != MediaCodecDecoder.INDEX_NONE) { mAudioPlayback = new AudioPlayback(); // Initialize settings in case they have already been set before the preparation mAudioPlayback.setAudioSessionId(mAudioSessionId); setVolume(mVolumeLeft, mVolumeRight); // sets the volume on mAudioPlayback try { boolean passive = (mAudioExtractor == mVideoExtractor || mAudioExtractor == null); MediaCodecDecoder ad = new MediaCodecAudioDecoder(mAudioExtractor != null ? mAudioExtractor : mVideoExtractor, passive, mAudioTrackIndex, decoderEventListener, mAudioPlayback); mDecoders.addDecoder(ad); } catch (Exception e) { Log.e(TAG, "cannot create audio decoder: " + e.getMessage()); mAudioPlayback = null; } } // If no decoder could be initialized, there is nothing to play back, so we throw an exception if(mDecoders.getDecoders().isEmpty()) { throw new IOException("cannot decode any stream"); } if (mAudioPlayback != null) { mAudioSessionId = mAudioPlayback.getAudioSessionId(); mAudioStreamType = mAudioPlayback.getAudioStreamType(); } // After the decoder is initialized, we know the video size if(mDecoders.getVideoDecoder() != null) { int width = mDecoders.getVideoDecoder().getVideoWidth(); int height = mDecoders.getVideoDecoder().getVideoHeight(); int rotation = mDecoders.getVideoDecoder().getVideoRotation(); // Swap width/height to report correct dimensions of rotated portrait video (rotated by 90 or 270 degrees) if(rotation > 0 && rotation != 180) { int temp = width; width = height; height = temp; } mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE, width, height)); } if(mCurrentState == State.RELEASING) { // release() has already been called, drop out of prepareAsync() return; } // Decode the first frame to initialize the decoder, and seek back to the start // This is necessary on some platforms, else a seek directly after initialization will fail, // or the decoder goes into a state where it does not accept any input and does not deliver // any output, locking up playback (observed on N4 API22). // N4 API22 Test: disable this code open video, seek to end, press play to start from beginning // -> results in infinite decoding loop without output if(true) { if(mDecoders.getVideoDecoder() != null) { MediaCodecDecoder.FrameInfo vfi = mDecoders.decodeFrame(true); mDecoders.getVideoDecoder().releaseFrame(vfi); } else { mDecoders.decodeFrame(false); } if (mAudioPlayback != null) mAudioPlayback.pause(true); mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); } } /** * @see android.media.MediaPlayer#prepare() */ public void prepare() throws IOException, IllegalStateException { if(mCurrentState != State.INITIALIZED && mCurrentState != State.STOPPED) { throw new IllegalStateException(); } mCurrentState = State.PREPARING; // Prepare synchronously on caller thread prepareInternal(); // Create the playback loop handler thread mPlaybackThread = new PlaybackThread(); mPlaybackThread.start(); mCurrentState = State.PREPARED; } /** * @see android.media.MediaPlayer#prepareAsync() */ public void prepareAsync() throws IllegalStateException { if(mCurrentState != State.INITIALIZED && mCurrentState != State.STOPPED) { throw new IllegalStateException(); } mCurrentState = State.PREPARING; // Create the playback loop handler thread mPlaybackThread = new PlaybackThread(); mPlaybackThread.start(); // Execute prepare asynchronously on playback thread mPlaybackThread.prepare(); } /** * @see android.media.MediaPlayer#setDisplay(android.view.SurfaceHolder) */ public void setDisplay(SurfaceHolder sh) { mSurfaceHolder = sh; if (sh != null) { mSurface = sh.getSurface(); } else { mSurface = null; } if(mDecoders != null && mDecoders.getVideoDecoder() != null) { //mDecoders.getVideoDecoder().updateSurface(mSurface); } if(mPlaybackThread == null) { // Player not prepared yet, so we can set the timing mode setVideoRenderTimingMode(VideoRenderTimingMode.AUTO); updateSurfaceScreenOn(); } else { // Player is already prepared, just change the surface mPlaybackThread.setSurface(mSurface); } } /** * @see android.media.MediaPlayer#setSurface(android.view.Surface) */ public void setSurface(Surface surface) { mSurface = surface; if (mScreenOnWhilePlaying && surface != null) { Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface"); } mSurfaceHolder = null; if(mPlaybackThread == null) { // Player not prepared yet, so we can set the timing mode setVideoRenderTimingMode(VideoRenderTimingMode.SLEEP); // the surface could be a GL texture, so we switch to sleep timing mode updateSurfaceScreenOn(); } else { // Player is already prepared, just change the surface mPlaybackThread.setSurface(mSurface); } } public void start() { if(mCurrentState != State.PREPARED) { mCurrentState = State.ERROR; throw new IllegalStateException(); } mPlaybackThread.play(); stayAwake(true); } public void pause() { if(mCurrentState != State.PREPARED) { mCurrentState = State.ERROR; throw new IllegalStateException(); } mPlaybackThread.pause(); stayAwake(false); } public SeekMode getSeekMode() { return mSeekMode; } public void setSeekMode(SeekMode seekMode) { this.mSeekMode = seekMode; } public void seekTo(long usec) { if(mCurrentState.ordinal() < State.PREPARED.ordinal() && mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } /* A seek needs to be performed in the decoding thread to execute commands in the correct * order. Otherwise it can happen that, after a seek in the media decoder, seeking procedure * starts, then a frame is decoded, and then the codec is flushed; the PTS of the decoded frame * then interferes the seeking procedure, the seek stops prematurely and a wrong waiting time * gets calculated. */ Log.d(TAG, "seekTo " + usec + " with video sample offset " + mVideoMinPTS); if (mOnSeekListener != null) { mOnSeekListener.onSeek(MediaPlayer.this); } mSeeking = true; // The passed in target time is always aligned to a zero start time, while the actual video // can have an offset and must not necessarily start at zero. The offset can e.g. come from // the CTTS box SampleOffset field, and is only reported on Android 5+. In Android 4, the // offset is handled by the framework, not reported, and videos always start at zero. // By adding the offset to the seek target time, we always seek to a zero-reference time in // the stream. mSeekTargetTime = mVideoMinPTS + usec; mPlaybackThread.seekTo(mSeekTargetTime); } public void seekTo(int msec) { seekTo(msec * 1000L); } /** * Sets the playback speed. Can be used for fast forward and slow motion. * The speed must not be negative. * * speed 0.5 = half speed / slow motion * speed 2.0 = double speed / fast forward * speed 0.0 equals to pause * * @param speed the playback speed to set * @throws IllegalArgumentException if the speed is negative */ public void setPlaybackSpeed(float speed) { if(speed < 0) { throw new IllegalArgumentException("speed cannot be negative"); } mTimeBase.setSpeed(speed); mTimeBase.startAt(mCurrentPosition); } /** * Gets the current playback speed. See {@link #setPlaybackSpeed(float)} for details. * @return the current playback speed */ public float getPlaybackSpeed() { return (float)mTimeBase.getSpeed(); } public boolean isPlaying() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mPlaybackThread != null && !mPlaybackThread.isPaused(); } /** * @see android.media.MediaPlayer#setLooping(boolean) */ public void setLooping(boolean looping) { mLooping = looping; } /** * @see android.media.MediaPlayer#isLooping() */ public boolean isLooping() { return mLooping; } public void stop() { release(); mCurrentState = State.STOPPED; } public void release() { if(mCurrentState == State.RELEASING || mCurrentState == State.RELEASED) { return; } mCurrentState = State.RELEASING; if(mPlaybackThread != null) { // Create a new lock object for this release cycle mReleaseSyncLock = new Object(); synchronized (mReleaseSyncLock) { try { // Schedule release on the playback thread mPlaybackThread.release(); mPlaybackThread = null; // Wait for the release on the playback thread to finish mReleaseSyncLock.wait(); } catch (InterruptedException e) { // nothing to do here } } mReleaseSyncLock = null; } stayAwake(false); mCurrentState = State.RELEASED; } public void reset() { stop(); mCurrentState = State.IDLE; } /** * @see android.media.MediaPlayer#setWakeMode(android.content.Context, int) */ public void setWakeMode(Context context, int mode) { boolean washeld = false; if (mWakeLock != null) { if (mWakeLock.isHeld()) { washeld = true; mWakeLock.release(); } mWakeLock = null; } PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName()); mWakeLock.setReferenceCounted(false); if (washeld) { mWakeLock.acquire(); } } /** * @see android.media.MediaPlayer#setScreenOnWhilePlaying(boolean) */ public void setScreenOnWhilePlaying(boolean screenOn) { if (mScreenOnWhilePlaying != screenOn) { if (screenOn && mSurfaceHolder == null) { Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder"); } mScreenOnWhilePlaying = screenOn; updateSurfaceScreenOn(); } } private void stayAwake(boolean awake) { if (mWakeLock != null) { if (awake && !mWakeLock.isHeld()) { mWakeLock.acquire(); } else if (!awake && mWakeLock.isHeld()) { mWakeLock.release(); } } mStayAwake = awake; updateSurfaceScreenOn(); } private void updateSurfaceScreenOn() { if (mSurfaceHolder != null) { mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); } } public int getDuration() { if(mCurrentState.ordinal() <= State.PREPARING.ordinal() && mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? (int)(mVideoFormat.getLong(MediaFormat.KEY_DURATION)/1000) : mAudioFormat != null && mAudioFormat.containsKey(MediaFormat.KEY_DURATION) ? (int)(mAudioFormat.getLong(MediaFormat.KEY_DURATION)/1000) : 0; } public int getCurrentPosition() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } /* During a seek, return the temporary seek target time; otherwise a seek bar doesn't * update to the selected seek position until the seek is finished (which can take a * while in exact mode). */ return (int)((mSeeking ? mSeekTargetTime : mCurrentPosition)/1000); } public int getBufferPercentage() { return mBufferPercentage; } public int getVideoWidth() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? (int)(mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) * mVideoFormat.getFloat(MediaExtractor.MEDIA_FORMAT_EXTENSION_KEY_DAR)) : 0; } public int getVideoHeight() { if(mCurrentState.ordinal() >= State.RELEASING.ordinal()) { mCurrentState = State.ERROR; throw new IllegalStateException(); } return mVideoFormat != null ? mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) : 0; } /** * @see android.media.MediaPlayer#setVolume(float, float) */ public void setVolume(float leftVolume, float rightVolume) { mVolumeLeft = leftVolume; mVolumeRight = rightVolume; if(mAudioPlayback != null) { mAudioPlayback.setStereoVolume(leftVolume, rightVolume); } } /** * This API method in the Android MediaPlayer is hidden, but may be unhidden in the future. Here * it can already be used. * see android.media.MediaPlayer#setVolume(float) */ public void setVolume(float volume) { setVolume(volume, volume); } /** * @see android.media.MediaPlayer#setAudioSessionId(int) */ public void setAudioSessionId(int sessionId) { if(mCurrentState != State.IDLE) { throw new IllegalStateException(); } mAudioSessionId = sessionId; } /** * @see android.media.MediaPlayer#getAudioSessionId() */ public int getAudioSessionId() { return mAudioSessionId; } public void setAudioStreamType(int streamType) { // Can be set any time, no IllegalStateException is thrown, but value will be ignored if audio is already initialized mAudioStreamType = streamType; } /** * Gets the stream type of the audio playback session. * @return the stream type */ public int getAudioStreamType() { return mAudioStreamType; } /** * Sets the timing mode for video frame rendering. * This only works before the calling {@link #prepare()} or {@link #prepareAsync()}. * * This method is only needed for the special case of rendering the video to a GL surface texture, * where {@link MediaCodec#releaseOutputBuffer(int, long)} does not defer the frame rendering * and thus does not block until the PTS is reached. This only seems to work correctly on a * {@link android.view.SurfaceView}. It is therefore required to manually set the * {@link VideoRenderTimingMode#SLEEP} mode on API 21+ platforms to get timed frame rendering. * * TODO find out how to get deferred/blocking rendering to work with a surface texture * * @see VideoRenderTimingMode * @param mode the desired timing mode * @throws IllegalStateException */ void setVideoRenderTimingMode(VideoRenderTimingMode mode) { if(mPlaybackThread != null) { throw new IllegalStateException("called after prepare/prepareAsync"); } if(mode == VideoRenderTimingMode.SURFACEVIEW_TIMESTAMP_API21 && Build.VERSION.SDK_INT < 21) { throw new IllegalArgumentException("this mode needs min API 21"); } Log.d(TAG, "setVideoRenderTimingMode " + mode); mVideoRenderTimingMode = mode; } private class PlaybackThread extends HandlerThread implements Handler.Callback { private static final int PLAYBACK_PREPARE = 1; private static final int PLAYBACK_PLAY = 2; private static final int PLAYBACK_PAUSE = 3; private static final int PLAYBACK_LOOP = 4; private static final int PLAYBACK_SEEK = 5; private static final int PLAYBACK_RELEASE = 6; private static final int PLAYBACK_PAUSE_AUDIO = 7; static final int DECODER_SET_SURFACE = 100; private Handler mHandler; private boolean mPaused; private boolean mReleasing; private MediaCodecDecoder.FrameInfo mVideoFrameInfo; private boolean mRenderModeApi21; // Usage of timed outputBufferRelease on API 21+ private boolean mRenderingStarted; // Flag to know if decoding the first frame private double mPlaybackSpeed; private boolean mAVLocked; public PlaybackThread() { // Give this thread a high priority for more precise event timing super(TAG + "#" + PlaybackThread.class.getSimpleName(), Process.THREAD_PRIORITY_AUDIO); // Init fields mPaused = true; mReleasing = false; mRenderModeApi21 = mVideoRenderTimingMode.isRenderModeApi21(); mRenderingStarted = true; mAVLocked = false; } @Override public synchronized void start() { super.start(); // Create the handler that will process the messages on the handler thread mHandler = new Handler(this.getLooper(), this); Log.d(TAG, "PlaybackThread started"); } public void prepare() { mHandler.sendEmptyMessage(PLAYBACK_PREPARE); } public void play() { mPaused = false; mHandler.sendEmptyMessage(PLAYBACK_PLAY); } public void pause() { mPaused = true; mHandler.sendEmptyMessage(PLAYBACK_PAUSE); } public boolean isPaused() { return mPaused; } public void seekTo(long usec) { // When multiple seek requests come in, e.g. when a user slides the finger on a // seek bar in the UI, we don't want to process all of them and can therefore remove // all requests from the queue and only keep the most recent one. mHandler.removeMessages(PLAYBACK_SEEK); // remove any previous requests mHandler.obtainMessage(PLAYBACK_SEEK, usec).sendToTarget(); } public void setSurface(Surface surface) { mHandler.sendMessage(mHandler.obtainMessage(PlaybackThread.DECODER_SET_SURFACE, surface)); } private void release() { if(!isAlive()) { return; } mPaused = true; // Set this flag so the loop does not schedule next loop iteration mReleasing = true; // Call actual release method // Actually it does not matter what we schedule here, we just need to schedule // something so {@link #handleMessage} gets called on the handler thread, read the // mReleasing flag, and call {@link #releaseInternal}. mHandler.sendEmptyMessage(PLAYBACK_RELEASE); } @Override public boolean handleMessage(Message msg) { try { if(mReleasing) { // When the releasing flag is set, just release without processing any more messages releaseInternal(); return true; } switch (msg.what) { case PLAYBACK_PREPARE: prepareInternal(); return true; case PLAYBACK_PLAY: playInternal(); return true; case PLAYBACK_PAUSE: pauseInternal(); return true; case PLAYBACK_PAUSE_AUDIO: pauseInternalAudio(); return true; case PLAYBACK_LOOP: loopInternal(); return true; case PLAYBACK_SEEK: seekInternal((Long) msg.obj); return true; case PLAYBACK_RELEASE: releaseInternal(); return true; case DECODER_SET_SURFACE: setVideoSurface((Surface) msg.obj); return true; default: Log.d(TAG, "unknown/invalid message"); return false; } } catch (InterruptedException e) { Log.d(TAG, "decoder interrupted", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); } catch (IllegalStateException e) { Log.e(TAG, "decoder error, too many instances?", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); } catch (IOException e) { Log.e(TAG, "decoder error, codec can not be created", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO)); } // Release after an exception releaseInternal(); return true; } private void prepareInternal() { try { MediaPlayer.this.prepareInternal(); mCurrentState = MediaPlayer.State.PREPARED; // This event is only triggered after a successful async prepare (not after the sync prepare!) mEventHandler.sendEmptyMessage(MEDIA_PREPARED); } catch (IOException e) { Log.e(TAG, "prepareAsync() failed: cannot decode stream(s)", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO)); releaseInternal(); } catch (IllegalStateException e) { Log.e(TAG, "prepareAsync() failed: something is in a wrong state", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); releaseInternal(); } catch (IllegalArgumentException e) { Log.e(TAG, "prepareAsync() failed: surface might be gone", e); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0)); releaseInternal(); } } private void playInternal() throws IOException, InterruptedException { if(mDecoders.isEOS()) { mCurrentPosition = 0; mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); } // reset time (otherwise playback tries to "catch up" time after a pause) mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); if(mAudioPlayback != null) { mHandler.removeMessages(PLAYBACK_PAUSE_AUDIO); mAudioPlayback.play(); } mPlaybackSpeed = mTimeBase.getSpeed(); // Sync audio playback speed to playback speed (to account for speed changes during pause) if (mAudioPlayback != null) { mAudioPlayback.setPlaybackSpeed((float) mPlaybackSpeed); } mHandler.removeMessages(PLAYBACK_LOOP); loopInternal(); } private void pauseInternal(boolean drainAudioPlayback) { // When playback is paused in timed API21 render mode, the remaining cached frames will // still be rendered, resulting in a short but noticeable pausing lag. This can be avoided // by switching to the old render timing mode. mHandler.removeMessages(PLAYBACK_LOOP); // removes remaining loop requests (required when EOS is reached) if (mAudioPlayback != null) { if(drainAudioPlayback) { // Defer pausing the audio playback for the length of the playback buffer, to // make sure that all audio samples have been played out. mHandler.sendEmptyMessageDelayed(PLAYBACK_PAUSE_AUDIO, (mAudioPlayback.getQueueBufferTimeUs() + mAudioPlayback.getPlaybackBufferTimeUs()) / 1000 + 1); } else { mAudioPlayback.pause(false); } } } private void pauseInternal() { pauseInternal(false); } private void pauseInternalAudio() { if (mAudioPlayback != null) { mAudioPlayback.pause(); } } private void loopInternal() throws IOException, InterruptedException { // If this is an online stream, notify the client of the buffer fill level. long cachedDuration = mDecoders.getCachedDuration(); if(cachedDuration != -1) { // The cached duration from the MediaExtractor returns the cached time from // the current position onwards, but the Android MediaPlayer returns the // total time consisting of the current playback point and the length of // the prefetched data. // This comes before the buffering pause to update the clients buffering info // also during a buffering playback pause. mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_BUFFERING_UPDATE, (int) (100d / (getDuration() * 1000) * (mCurrentPosition + cachedDuration)), 0)); } // If we are in buffering mode, check if the buffer has been filled until the low water // mark or the end of the stream has been reached, and pause playback if it isn't filled // high enough yet. if(mBuffering && cachedDuration > -1 && cachedDuration < BUFFER_LOW_WATER_MARK_US && !mDecoders.hasCacheReachedEndOfStream()) { //Log.d(TAG, "buffering... " + mDecoders.getCachedDuration() + " / " + BUFFER_LOW_WATER_MARK_US); // To pause playback for buffering, we simply skip this loop and call it again later mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 100); return; } if(mDecoders.getVideoDecoder() != null && mVideoFrameInfo == null) { // This method needs a video frame to operate on. If there is no frame, we need // to decode one first. mVideoFrameInfo = mDecoders.decodeFrame(false); if(mVideoFrameInfo == null && !mDecoders.isEOS()) { // If the decoder didn't return a frame, we need to give it some processing time // and come back later... mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 10); return; } } long startTime = SystemClock.elapsedRealtime(); // When we are in buffering mode, and a frame has been decoded, the buffer is // obviously refilled so we can send the buffering end message and exit buffering mode. if(mBuffering) { mBuffering = false; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0)); // Reset timebase so player does not try to catch up time lost while caching mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); } // When the waiting time to the next frame is too long, we defer rendering through // the handler here instead of relying on releaseOutputBuffer(buffer, renderTimestampNs), // which does not work well with long waiting times and many frames in the queue. // On API < 21 the frame rendering is timed with a sleep() and this is not really necessary, // but still shifts some waiting time from the sleep() to here. if(mVideoFrameInfo != null && mTimeBase.getOffsetFrom(mVideoFrameInfo.presentationTimeUs) > 60000) { mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, 50); return; } // Update the current position of the player mCurrentPosition = mDecoders.getCurrentDecodingPTS(); if(mDecoders.getVideoDecoder() != null && mVideoFrameInfo != null) { renderVideoFrame(mVideoFrameInfo); mVideoFrameInfo = null; // When the first frame is rendered, video rendering has started and the event triggered if (mRenderingStarted) { mRenderingStarted = false; mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_VIDEO_RENDERING_START, 0)); } } if (mAudioPlayback != null) { // Sync audio playback speed to playback speed (to account for speed changes during playback) // Change the speed on the audio playback object only if it has really changed, to avoid runtime overhead if(mPlaybackSpeed != mTimeBase.getSpeed()) { mPlaybackSpeed = mTimeBase.getSpeed(); mAudioPlayback.setPlaybackSpeed((float) mPlaybackSpeed); } // Sync timebase to audio timebase when there is audio data available long currentAudioPTS = mAudioPlayback.getCurrentPresentationTimeUs(); if(currentAudioPTS > AudioPlayback.PTS_NOT_SET) { mTimeBase.startAt(currentAudioPTS); } } // Handle EOS if (mDecoders.isEOS()) { mEventHandler.sendEmptyMessage(MEDIA_PLAYBACK_COMPLETE); // If looping is on, seek back to the start... if(mLooping) { if(mAudioPlayback != null) { // Flush audio buffer to reset audio PTS mAudioPlayback.flush(); } mDecoders.seekTo(SeekMode.FAST_TO_PREVIOUS_SYNC, 0); mDecoders.renderFrames(); } // ... else just pause playback and wait for next command else { mPaused = true; pauseInternal(true); // pause but play remaining buffered audio } } else { // Get next frame mVideoFrameInfo = mDecoders.decodeFrame(false); } if(!mPaused) { // Static delay time until the next call of the playback loop long delay = 10; // Scale delay by playback speed to avoid limiting framerate delay = (long)(delay / mTimeBase.getSpeed()); // Calculate the duration taken for the current call long duration = (SystemClock.elapsedRealtime() - startTime); // Adjust the delay by the time taken delay = delay - duration; if(delay > 0) { // Sleep for some time and then continue processing the loop // This replaces the very unreliable and jittery Thread.sleep in the old decoder thread mHandler.sendEmptyMessageDelayed(PLAYBACK_LOOP, delay); } else { // The current call took too much time; there is no time left for delaying, call instantly mHandler.sendEmptyMessage(PLAYBACK_LOOP); } } } private void seekInternal(long usec) throws IOException, InterruptedException { if(mVideoFrameInfo != null) { // A decoded video frame is waiting to be rendered, dismiss it mDecoders.getVideoDecoder().dismissFrame(mVideoFrameInfo); mVideoFrameInfo = null; } // Clear the audio cache if(mAudioPlayback != null) mAudioPlayback.pause(true); // Seek to the target time mDecoders.seekTo(mSeekMode, usec); // Reset time to keep frame rate constant // (otherwise it's too fast on back seeks and waits for the PTS time on fw seeks) mTimeBase.startAt(mDecoders.getCurrentDecodingPTS()); // Check if another seek has been issued in the meantime boolean newSeekWaiting = mHandler.hasMessages(PLAYBACK_SEEK); // Render seek target frame (if no new seek is waiting to be processed) if(newSeekWaiting) { mDecoders.dismissFrames(); } else { mDecoders.renderFrames(); } // When there are no more seek requests in the queue, notify of finished seek operation if(!newSeekWaiting) { // Set the final seek position as the current position // (the final seek position may be off the initial target seek position) mCurrentPosition = mDecoders.getCurrentDecodingPTS(); mSeeking = false; mAVLocked = false; mEventHandler.sendEmptyMessage(MEDIA_SEEK_COMPLETE); if(!mPaused) { playInternal(); } } } private void releaseInternal() { // post interrupt to avoid all further execution of messages/events in the queue interrupt(); // quit message processing and exit thread quit(); if(mDecoders != null) { if(mVideoFrameInfo != null) { mDecoders.getVideoDecoder().releaseFrame(mVideoFrameInfo); mVideoFrameInfo = null; } } if(mDecoders != null) { mDecoders.release(); } if(mAudioPlayback != null) mAudioPlayback.stopAndRelease(); if(mAudioExtractor != null & mAudioExtractor != mVideoExtractor) { mAudioExtractor.release(); } if(mVideoExtractor != null) mVideoExtractor.release(); Log.d(TAG, "PlaybackThread destroyed"); // Notify #release() that it can now continue because #releaseInternal is finished if(mReleaseSyncLock != null) { synchronized(mReleaseSyncLock) { mReleaseSyncLock.notify(); mReleaseSyncLock = null; } } } private void renderVideoFrame(MediaCodecDecoder.FrameInfo videoFrameInfo) throws InterruptedException { if(videoFrameInfo.endOfStream) { // The EOS frame does not contain a video frame, so we dismiss it mDecoders.getVideoDecoder().dismissFrame(videoFrameInfo); return; } // Calculate waiting time until the next frame's PTS // The waiting time might be much higher that a frame's duration because timed API21 // rendering caches multiple released output frames before actually rendering them. long waitingTime = mTimeBase.getOffsetFrom(videoFrameInfo.presentationTimeUs); // Log.d(TAG, "VPTS " + mCurrentPosition // + " APTS " + mAudioPlayback.getCurrentPresentationTimeUs() // + " waitingTime " + waitingTime); if (waitingTime < -1000) { // we need to catch up time by skipping rendering of this frame // this doesn't gain enough time if playback speed is too high and decoder at full load // TODO improve fast forward mode Log.d(TAG, "LAGGING " + waitingTime); mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO, MEDIA_INFO_VIDEO_TRACK_LAGGING, 0)); } // Defer the video size changed message until the first frame of the new size is being rendered if (videoFrameInfo.representationChanged) { mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE, mDecoders.getVideoDecoder().getVideoWidth(), mDecoders.getVideoDecoder().getVideoHeight())); } // Slow down playback, if necessary, to keep frame rate if(!mRenderModeApi21 && waitingTime > 5000) { // Sleep until it's time to render the next frame // This is not v-synced to the display. Not required any more on API 21+. Thread.sleep(waitingTime / 1000); } // Release the current frame and render it to the surface mDecoders.getVideoDecoder().renderFrame(videoFrameInfo, waitingTime); } private void setVideoSurface(Surface surface) { if(mDecoders != null && mDecoders.getVideoDecoder() != null) { if(mVideoFrameInfo != null) { // Dismiss queued video frame // After updating the surface, which re-initializes the codec, // the frame buffer will not be valid any more and trying to decode // it would result in an error; so we throw it away. mDecoders.getVideoDecoder().dismissFrame(mVideoFrameInfo); mVideoFrameInfo = null; } mDecoders.getVideoDecoder().updateSurface(surface); } } } /** * Interface definition for a callback to be invoked when the media * source is ready for playback. */ public interface OnPreparedListener { /** * Called when the media file is ready for playback. * @param mp the MediaPlayer that is ready for playback */ void onPrepared(MediaPlayer mp); } /** * Register a callback to be invoked when the media source is ready * for playback. * * @param listener the callback that will be run */ public void setOnPreparedListener(OnPreparedListener listener) { mOnPreparedListener = listener; } /** * Interface definition for a callback to be invoked when playback of * a media source has completed. */ public interface OnCompletionListener { /** * Called when the end of a media source is reached during playback. * @param mp the MediaPlayer that reached the end of the file */ void onCompletion(MediaPlayer mp); } /** * Register a callback to be invoked when the end of a media source * has been reached during playback. * * @param listener the callback that will be run */ public void setOnCompletionListener(OnCompletionListener listener) { mOnCompletionListener = listener; } /** * Interface definition of a callback to be invoked when a seek * is issued. */ public interface OnSeekListener { /** * Called to indicate that a seek operation has been started. * @param mp the mediaPlayer that the seek was called on */ public void onSeek(MediaPlayer mp); } /** * Register a calback to be invoked when a seek operation has been started. * @param listener the callback that will be run */ public void setOnSeekListener(OnSeekListener listener) { mOnSeekListener = listener; } /** * Interface definition of a callback to be invoked indicating * the completion of a seek operation. */ public interface OnSeekCompleteListener { /** * Called to indicate the completion of a seek operation. * @param mp the MediaPlayer that issued the seek operation */ public void onSeekComplete(MediaPlayer mp); } /** * Register a callback to be invoked when a seek operation has been * completed. * * @param listener the callback that will be run */ public void setOnSeekCompleteListener(OnSeekCompleteListener listener) { mOnSeekCompleteListener = listener; } /** * Interface definition of a callback to be invoked when the * video size is first known or updated */ public interface OnVideoSizeChangedListener { /** * Called to indicate the video size * * The video size (width and height) could be 0 if there was no video, * no display surface was set, or the value was not determined yet. * * @param mp the MediaPlayer associated with this callback * @param width the width of the video * @param height the height of the video */ public void onVideoSizeChanged(MediaPlayer mp, int width, int height); } /** * Register a callback to be invoked when the video size is * known or updated. * * @param listener the callback that will be run */ public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) { mOnVideoSizeChangedListener = listener; } /** * Interface definition of a callback to be invoked indicating buffering * status of a media resource being streamed over the network. */ public interface OnBufferingUpdateListener { /** * Called to update status in buffering a media stream received through * progressive HTTP download. The received buffering percentage * indicates how much of the content has been buffered or played. * For example a buffering update of 80 percent when half the content * has already been played indicates that the next 30 percent of the * content to play has been buffered. * * @param mp the MediaPlayer the update pertains to * @param percent the percentage (0-100) of the content * that has been buffered or played thus far */ void onBufferingUpdate(MediaPlayer mp, int percent); } /** * Register a callback to be invoked when the status of a network * stream's buffer has changed. * * @param listener the callback that will be run. */ public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) { mOnBufferingUpdateListener = listener; } /** Unspecified media player error. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_UNKNOWN = 1; /** Media server died. In this case, the application must release the * MediaPlayer object and instantiate a new one. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_SERVER_DIED = 100; /** The video is streamed and its container is not valid for progressive * playback i.e the video's index (e.g moov atom) is not at the start of the * file. * @see MediaPlayer.OnErrorListener */ public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; /** File or network related operation errors. */ public static final int MEDIA_ERROR_IO = -1004; /** Bitstream is not conforming to the related coding standard or file spec. */ public static final int MEDIA_ERROR_MALFORMED = -1007; /** Bitstream is conforming to the related coding standard or file spec, but * the media framework does not support the feature. */ public static final int MEDIA_ERROR_UNSUPPORTED = -1010; /** Some operation takes too long to complete, usually more than 3-5 seconds. */ public static final int MEDIA_ERROR_TIMED_OUT = -110; /** * Interface definition of a callback to be invoked when there * has been an error during an asynchronous operation (other errors * will throw exceptions at method call time). */ public interface OnErrorListener { /** * Called to indicate an error. * * @param mp the MediaPlayer the error pertains to * @param what the type of error that has occurred: * <ul> * <li>{@link #MEDIA_ERROR_UNKNOWN} * <li>{@link #MEDIA_ERROR_SERVER_DIED} * </ul> * @param extra an extra code, specific to the error. Typically * implementation dependent. * <ul> * <li>{@link #MEDIA_ERROR_IO} * <li>{@link #MEDIA_ERROR_MALFORMED} * <li>{@link #MEDIA_ERROR_UNSUPPORTED} * <li>{@link #MEDIA_ERROR_TIMED_OUT} * </ul> * @return True if the method handled the error, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the OnCompletionListener to be called. */ boolean onError(MediaPlayer mp, int what, int extra); } /** * Register a callback to be invoked when an error has happened * during an asynchronous operation. * * @param listener the callback that will be run */ public void setOnErrorListener(OnErrorListener listener) { mOnErrorListener = listener; } /** The player just pushed the very first video frame for rendering. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; /** The video is too complex for the decoder: it can't decode frames fast * enough. Possibly only the audio plays fine at this stage. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; /** MediaPlayer is temporarily pausing playback internally in order to * buffer more data. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_BUFFERING_START = 701; /** MediaPlayer is resuming playback after filling buffers. * @see MediaPlayer.OnInfoListener */ public static final int MEDIA_INFO_BUFFERING_END = 702; /** * Interface definition of a callback to be invoked to communicate some * info and/or warning about the media or its playback. */ public interface OnInfoListener { /** * Called to indicate an info or a warning. * * @param mp the MediaPlayer the info pertains to. * @param what the type of info or warning. * <ul> * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START} * <li>{@link #MEDIA_INFO_BUFFERING_START} * <li>{@link #MEDIA_INFO_BUFFERING_END} * </ul> * @param extra an extra code, specific to the info. Typically * implementation dependent. * @return True if the method handled the info, false if it didn't. * Returning false, or not having an OnErrorListener at all, will * cause the info to be discarded. */ boolean onInfo(MediaPlayer mp, int what, int extra); } /** * Register a callback to be invoked when an info/warning is available. * @param listener the callback that will be run */ public void setOnInfoListener(OnInfoListener listener) { mOnInfoListener = listener; } private static final int MEDIA_PREPARED = 1; private static final int MEDIA_PLAYBACK_COMPLETE = 2; private static final int MEDIA_BUFFERING_UPDATE = 3; private static final int MEDIA_SEEK_COMPLETE = 4; private static final int MEDIA_SET_VIDEO_SIZE = 5; private static final int MEDIA_ERROR = 100; private static final int MEDIA_INFO = 200; private class EventHandler extends Handler { @Override public void handleMessage(Message msg) { switch(msg.what) { case MEDIA_PREPARED: Log.d(TAG, "onPrepared"); if(mOnPreparedListener != null) { mOnPreparedListener.onPrepared(MediaPlayer.this); } return; case MEDIA_SEEK_COMPLETE: Log.d(TAG, "onSeekComplete"); if (mOnSeekCompleteListener != null) { mOnSeekCompleteListener.onSeekComplete(MediaPlayer.this); } return; case MEDIA_PLAYBACK_COMPLETE: Log.d(TAG, "onPlaybackComplete"); if(mOnCompletionListener != null) { mOnCompletionListener.onCompletion(MediaPlayer.this); } stayAwake(false); return; case MEDIA_SET_VIDEO_SIZE: Log.d(TAG, "onVideoSizeChanged"); if(mOnVideoSizeChangedListener != null) { mOnVideoSizeChangedListener.onVideoSizeChanged(MediaPlayer.this, msg.arg1, msg.arg2); } return; case MEDIA_ERROR: Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); boolean error_was_handled = false; if (mOnErrorListener != null) { error_was_handled = mOnErrorListener.onError(MediaPlayer.this, msg.arg1, msg.arg2); } if (mOnCompletionListener != null && !error_was_handled) { mOnCompletionListener.onCompletion(MediaPlayer.this); } stayAwake(false); return; case MEDIA_INFO: Log.d(TAG, "onInfo"); if(mOnInfoListener != null) { mOnInfoListener.onInfo(MediaPlayer.this, msg.arg1, msg.arg2); } return; case MEDIA_BUFFERING_UPDATE: //Log.d(TAG, "onBufferingUpdate"); if (mOnBufferingUpdateListener != null) mOnBufferingUpdateListener.onBufferingUpdate(MediaPlayer.this, msg.arg1); mBufferPercentage = msg.arg1; return; default: // nothing } } } }
Add debug logging for selected tracks
MediaPlayer/src/main/java/net/protyposis/android/mediaplayer/MediaPlayer.java
Add debug logging for selected tracks
Java
apache-2.0
b0785ba3aa19071b42b78b8bef9f512b1a91e049
0
codders/k2-sling-fork,JEBailey/sling,vladbailescu/sling,SylvesterAbreu/sling,tmaret/sling,tteofili/sling,trekawek/sling,plutext/sling,ffromm/sling,wimsymons/sling,ist-dresden/sling,headwirecom/sling,SylvesterAbreu/sling,ffromm/sling,labertasch/sling,cleliameneghin/sling,ist-dresden/sling,tteofili/sling,nleite/sling,klcodanr/sling,trekawek/sling,vladbailescu/sling,vladbailescu/sling,tyge68/sling,Nimco/sling,ffromm/sling,mikibrv/sling,roele/sling,nleite/sling,labertasch/sling,Nimco/sling,ist-dresden/sling,gutsy/sling,Nimco/sling,cleliameneghin/sling,roele/sling,JEBailey/sling,Nimco/sling,codders/k2-sling-fork,nleite/sling,sdmcraft/sling,klcodanr/sling,wimsymons/sling,mikibrv/sling,sdmcraft/sling,cleliameneghin/sling,plutext/sling,JEBailey/sling,ieb/sling,awadheshv/sling,ist-dresden/sling,nleite/sling,sdmcraft/sling,tmaret/sling,anchela/sling,klcodanr/sling,wimsymons/sling,anchela/sling,SylvesterAbreu/sling,headwirecom/sling,ist-dresden/sling,tyge68/sling,dulvac/sling,tyge68/sling,ieb/sling,ieb/sling,klcodanr/sling,mcdan/sling,dulvac/sling,Sivaramvt/sling,klcodanr/sling,codders/k2-sling-fork,mcdan/sling,SylvesterAbreu/sling,gutsy/sling,Nimco/sling,gutsy/sling,mmanski/sling,vladbailescu/sling,mikibrv/sling,labertasch/sling,awadheshv/sling,mmanski/sling,plutext/sling,tmaret/sling,SylvesterAbreu/sling,gutsy/sling,tmaret/sling,tteofili/sling,dulvac/sling,plutext/sling,plutext/sling,dulvac/sling,anchela/sling,klcodanr/sling,cleliameneghin/sling,mmanski/sling,awadheshv/sling,gutsy/sling,mmanski/sling,tmaret/sling,tteofili/sling,tyge68/sling,tteofili/sling,wimsymons/sling,dulvac/sling,ffromm/sling,ffromm/sling,mikibrv/sling,Sivaramvt/sling,gutsy/sling,sdmcraft/sling,sdmcraft/sling,anchela/sling,Sivaramvt/sling,sdmcraft/sling,mmanski/sling,mcdan/sling,trekawek/sling,ieb/sling,headwirecom/sling,Sivaramvt/sling,trekawek/sling,JEBailey/sling,roele/sling,awadheshv/sling,Nimco/sling,labertasch/sling,mikibrv/sling,awadheshv/sling,wimsymons/sling,labertasch/sling,tyge68/sling,ffromm/sling,ieb/sling,roele/sling,Sivaramvt/sling,tteofili/sling,ieb/sling,mcdan/sling,dulvac/sling,plutext/sling,headwirecom/sling,JEBailey/sling,tyge68/sling,SylvesterAbreu/sling,trekawek/sling,roele/sling,headwirecom/sling,trekawek/sling,awadheshv/sling,Sivaramvt/sling,nleite/sling,mcdan/sling,wimsymons/sling,vladbailescu/sling,nleite/sling,anchela/sling,cleliameneghin/sling,mmanski/sling,mikibrv/sling,mcdan/sling
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launcher.webapp; import static org.apache.felix.framework.util.FelixConstants.*; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.GenericServlet; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServletResponse; import org.apache.felix.framework.Logger; import org.apache.sling.launcher.app.ResourceProvider; import org.apache.sling.launcher.app.Sling; import org.apache.sling.osgi.log.LogbackManager; import org.eclipse.equinox.http.servlet.HttpServiceServlet; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; /** * The <code>SlingServlet</code> serves as a basic servlet for Project Sling. * The tasks of this servlet are as follows: * <ul> * <li>The {@link #init()} method launches Apache <code>Felix</code> as the * OSGi framework implementation we use. * <li>Registers as a service listener interested for services of type * <code>javax.servlet.Servlet</code>. * <li>Handles requests by delegating to a servlet which is expected to be * registered with the framework as a service of type * <code>javax.servlet.Servlet</code>. If no delegatee servlet has been * registered request handlings results in a temporary unavailability of the * servlet. * </ul> * <p> * <b>Request Handling</b> * <p> * This servlet handles request by forwarding to a delegatee servlet. The * delegatee servlet is automatically retrieved from the service registry by the * {@link #getDelegatee()}. This method also makes sure, the such a servlet * actually exits by throwing an <code>UnvailableException</code> if not and * also makes sure the servlet is initialized. * <p> * <b>Launch Configuration</b> * <p> * The Apache <code>Felix</code> framework requires configuration parameters * to be specified for startup. This servlet builds the list of parameters from * three locations: * <ol> * <li>The <code>com/day/osgi/servlet/SlingServlet.properties</code> is read * from the servlet class path. This properties file contains default settings.</li> * <li>Extensions of this servlet may provide additional properties to be * loaded overwriting the {@link #loadConfigProperties()} method. * <li>Finally, web application init parameters are added to the properties and * may overwrite existing properties of the same name(s). * </ol> * <p> * After loading all properties, variable substitution takes place on the * property values. A variable is indicated as <code>${&lt;prop-name&gt;}</code> * where <code>&lt;prop-name&gt;</code> is the name of a system or * configuration property (configuration properties override system properties). * Variables may be nested and are resolved from inner-most to outer-most. For * example, the property value <code>${outer-${inner}}</code> is resolved by * first resolving <code>${inner}</code> and then resolving the property whose * name is the catenation of <code>outer-</code> and the result of resolving * <code>${inner}</code>. * <p> * <b>Logging</b> * <p> * This servlet logs through the servlet container logging mechanism by calling * the <code>GenericServlet.log</code> methods. Bundles launched within the * framework provided by this servlet may use whatever logging mechanism they * choose to use. The Day Commons OSGI Log Bundle provides an OSGi Log Service * implementation, which also provides access to Apache Commons Logging, SLF4J * and Log4J logging. It is recommended that this bundle is used to setup and * configure logging for systems based on this servlet. */ public class SlingServlet extends GenericServlet { /** Pseduo class version ID to keep the IDE quite. */ private static final long serialVersionUID = 1L; /** Mapping between log level numbers and names */ private static final String[] logLevels = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG" }; /** The Sling configuration property name setting the initial log level */ private static final String PROP_LOG_LEVEL = LogbackManager.LOG_LEVEL; /** * The name of the configuration property defining the obr repository. */ private static final String OBR_REPOSITORY_URL = "obr.repository.url"; /** * The <code>Felix</code> instance loaded on {@link #init()} and stopped * on {@link #destroy()}. */ private SlingBridge sling; /** * The map of delegatee servlets to which requests are delegated. This map * is managed through the * {@link #serviceChanged(ServiceEvent) service listener} based on servlets * registered. * * @see #getDelegatee() * @see #ungetDelegatee(Object) */ private Servlet delegatee; /** * Initializes this servlet by loading the framework configuration * properties, starting the OSGi framework (Apache Felix) and exposing the * system bundle context and the <code>Felix</code> instance as servlet * context attributes. * * @throws ServletException if the framework cannot be initialized. */ public final void init() throws ServletException { super.init(); // read the default parameters Map<String, String> props = loadConfigProperties(); try { Logger logger = new ServletContextLogger(getServletContext()); ResourceProvider rp = new ServletContextResourceProvider( getServletContext()); sling = new SlingBridge(logger, rp, props); } catch (Exception ex) { log("Cannot start the OSGi framework", ex); throw new UnavailableException("Cannot start the OSGi Framework: " + ex); } // set up the OSGi HttpService proxy servlet delegatee = new HttpServiceServlet(); delegatee.init(getServletConfig()); log("Servlet " + getServletName() + " initialized"); } /** * Services the request by delegating to the delegatee servlet. If no * delegatee servlet is available, a <code>UnavailableException</code> is * thrown. * * @param req the <code>ServletRequest</code> object that contains the * client's request * @param res the <code>ServletResponse</code> object that will contain * the servlet's response * @throws UnavailableException if the no delegatee servlet is currently * available * @throws ServletException if an exception occurs that interferes with the * servlet's normal operation occurred * @throws IOException if an input or output exception occurs */ public final void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // delegate the request to the registered delegatee servlet Servlet delegatee = getDelegatee(); if (delegatee == null) { ((HttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND); } else { delegatee.service(req, res); } } /** * Destroys this servlet by shutting down the OSGi framework and hence the * delegatee servlet if one is set at all. */ public final void destroy() { // destroy the delegatee if (delegatee != null) { delegatee.destroy(); delegatee = null; } // shutdown the Felix container if (sling != null) { sling.destroy(); sling = null; } // finally call the base class destroy method super.destroy(); } Servlet getDelegatee() { return delegatee; } // ---------- Configuration Loading ---------------------------------------- /** * Loads the configuration properties in the configuration property file * associated with the framework installation; these properties are * accessible to the framework and to bundles and are intended for * configuration purposes. By default, the configuration property file is * located in the <tt>conf/</tt> directory of the Felix installation * directory and is called "<tt>config.properties</tt>". The * installation directory of Felix is assumed to be the parent directory of * the <tt>felix.jar</tt> file as found on the system class path property. * The precise file from which to load configuration properties can be set * by initializing the "<tt>felix.config.properties</tt>" system * property to an arbitrary URL. * * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was * an error. */ private Map<String, String> loadConfigProperties() { // The config properties file is either specified by a system // property or it is in the same directory as the Felix JAR file. // Try to load it from one of these places. Map<String, String> props = new HashMap<String, String>(); // The following property must start with a comma! final String servletVersion = getServletContext().getMajorVersion() + "." + getServletContext().getMinorVersion(); props.put( Sling.PROP_SYSTEM_PACKAGES, ",javax.servlet;javax.servlet.http;javax.servlet.resources; version=" + servletVersion); // prevent system properties from being considered props.put(Sling.SLING_IGNORE_SYSTEM_PROPERTIES, "true"); // add optional boot delegation for JCR and Jackrabbit API props.put("sling.include.jcr-client", "jcr-client.properties"); // copy context init parameters @SuppressWarnings("unchecked") Enumeration<String> pe = getServletContext().getInitParameterNames(); while (pe.hasMoreElements()) { String name = pe.nextElement(); props.put(name, getServletContext().getInitParameter(name)); } // copy servlet init parameters pe = getInitParameterNames(); while (pe.hasMoreElements()) { String name = pe.nextElement(); props.put(name, getInitParameter(name)); } // ensure the Felix Logger loglevel matches the Sling log level checkLogSettings(props); // if the specified obr location is not a url and starts with a '/', we // assume that this location is inside the webapp and create the correct // full url final String repoLocation = props.get(OBR_REPOSITORY_URL); if (repoLocation != null && repoLocation.indexOf(":/") < 1 && repoLocation.startsWith("/")) { try { final URL url = getServletContext().getResource(repoLocation); // only if we get back a resource url, we update it if (url != null) { props.put(OBR_REPOSITORY_URL, url.toExternalForm()); } } catch (MalformedURLException e) { // if an exception occurs, we ignore it } } return props; } private void checkLogSettings(Map<String, String> props) { String logLevelString = props.get(PROP_LOG_LEVEL); if (logLevelString != null) { int logLevel = 1; try { logLevel = Integer.parseInt(logLevelString); } catch (NumberFormatException nfe) { // might be a loglevel name for (int i=0; i < logLevels.length; i++) { if (logLevels[i].equalsIgnoreCase(logLevelString)) { logLevel = i; break; } } } props.put(LOG_LEVEL_PROP, String.valueOf(logLevel)); } } private static class ServletContextLogger extends Logger { private ServletContext servletContext; private ServletContextLogger(ServletContext servletContext) { this.servletContext = servletContext; } @Override protected void doLog(ServiceReference sr, int level, String msg, Throwable throwable) { // unwind throwable if it is a BundleException if ((throwable instanceof BundleException) && (((BundleException) throwable).getNestedException() != null)) { throwable = ((BundleException) throwable).getNestedException(); } String s = (sr == null) ? null : "SvcRef " + sr; s = (s == null) ? msg : s + " " + msg; s = (throwable == null) ? s : s + " (" + throwable + ")"; switch (level) { case LOG_DEBUG: servletContext.log("DEBUG: " + s); break; case LOG_ERROR: servletContext.log("ERROR: " + s, throwable); break; case LOG_INFO: servletContext.log("INFO: " + s); break; case LOG_WARNING: servletContext.log("WARNING: " + s); break; default: servletContext.log("UNKNOWN[" + level + "]: " + s); } } } private static class ServletContextResourceProvider extends ResourceProvider { /** * The root folder for internal web application files (value is * "/WEB-INF/"). */ private static final String WEB_INF = "/WEB-INF"; private ServletContext servletContext; private ServletContextResourceProvider(ServletContext servletContext) { this.servletContext = servletContext; } @SuppressWarnings("unchecked") @Override public Iterator<String> getChildren(String path) { // ensure leading slash if (path.charAt(0) != '/') { path = "/" + path; } Set resources = servletContext.getResourcePaths(path); // unchecked if (resources == null || resources.isEmpty()) { resources = servletContext.getResourcePaths(WEB_INF + path); // unchecked } if ( resources == null ) { return Collections.EMPTY_LIST.iterator(); } return resources.iterator(); // unchecked } public URL getResource(String path) { // nothing for empty or null path if (path == null || path.length() == 0) { return null; } // ensure leading slash if (path.charAt(0) != '/') { path = "/" + path; } try { // try direct path URL resource = servletContext.getResource(path); if (resource != null) { return resource; } // otherwise try WEB-INF location return servletContext.getResource(WEB_INF + path); } catch (MalformedURLException mue) { servletContext.log("Failure to get resource " + path, mue); } // fall back to no resource found return null; } } }
launcher/webapp/src/main/java/org/apache/sling/launcher/webapp/SlingServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launcher.webapp; import static org.apache.felix.framework.util.FelixConstants.*; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.GenericServlet; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServletResponse; import org.apache.felix.framework.Logger; import org.apache.sling.launcher.app.ResourceProvider; import org.apache.sling.launcher.app.Sling; import org.apache.sling.osgi.log.LogbackManager; import org.eclipse.equinox.http.servlet.HttpServiceServlet; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; /** * The <code>SlingServlet</code> serves as a basic servlet for Project Sling. * The tasks of this servlet are as follows: * <ul> * <li>The {@link #init()} method launches Apache <code>Felix</code> as the * OSGi framework implementation we use. * <li>Registers as a service listener interested for services of type * <code>javax.servlet.Servlet</code>. * <li>Handles requests by delegating to a servlet which is expected to be * registered with the framework as a service of type * <code>javax.servlet.Servlet</code>. If no delegatee servlet has been * registered request handlings results in a temporary unavailability of the * servlet. * </ul> * <p> * <b>Request Handling</b> * <p> * This servlet handles request by forwarding to a delegatee servlet. The * delegatee servlet is automatically retrieved from the service registry by the * {@link #getDelegatee()}. This method also makes sure, the such a servlet * actually exits by throwing an <code>UnvailableException</code> if not and * also makes sure the servlet is initialized. * <p> * <b>Launch Configuration</b> * <p> * The Apache <code>Felix</code> framework requires configuration parameters * to be specified for startup. This servlet builds the list of parameters from * three locations: * <ol> * <li>The <code>com/day/osgi/servlet/SlingServlet.properties</code> is read * from the servlet class path. This properties file contains default settings.</li> * <li>Extensions of this servlet may provide additional properties to be * loaded overwriting the {@link #loadConfigProperties()} method. * <li>Finally, web application init parameters are added to the properties and * may overwrite existing properties of the same name(s). * </ol> * <p> * After loading all properties, variable substitution takes place on the * property values. A variable is indicated as <code>${&lt;prop-name&gt;}</code> * where <code>&lt;prop-name&gt;</code> is the name of a system or * configuration property (configuration properties override system properties). * Variables may be nested and are resolved from inner-most to outer-most. For * example, the property value <code>${outer-${inner}}</code> is resolved by * first resolving <code>${inner}</code> and then resolving the property whose * name is the catenation of <code>outer-</code> and the result of resolving * <code>${inner}</code>. * <p> * <b>Logging</b> * <p> * This servlet logs through the servlet container logging mechanism by calling * the <code>GenericServlet.log</code> methods. Bundles launched within the * framework provided by this servlet may use whatever logging mechanism they * choose to use. The Day Commons OSGI Log Bundle provides an OSGi Log Service * implementation, which also provides access to Apache Commons Logging, SLF4J * and Log4J logging. It is recommended that this bundle is used to setup and * configure logging for systems based on this servlet. */ public class SlingServlet extends GenericServlet { /** Pseduo class version ID to keep the IDE quite. */ private static final long serialVersionUID = 1L; /** Mapping between log level numbers and names */ private static final String[] logLevels = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG" }; /** The Sling configuration property name setting the initial log level */ private static final String PROP_LOG_LEVEL = LogbackManager.LOG_LEVEL; /** * The name of the configuration property defining the obr repository. */ private static final String OBR_REPOSITORY_URL = "obr.repository.url"; /** * The <code>Felix</code> instance loaded on {@link #init()} and stopped * on {@link #destroy()}. */ private SlingBridge sling; /** * The map of delegatee servlets to which requests are delegated. This map * is managed through the * {@link #serviceChanged(ServiceEvent) service listener} based on servlets * registered. * * @see #getDelegatee() * @see #ungetDelegatee(Object) */ private Servlet delegatee; /** * Initializes this servlet by loading the framework configuration * properties, starting the OSGi framework (Apache Felix) and exposing the * system bundle context and the <code>Felix</code> instance as servlet * context attributes. * * @throws ServletException if the framework cannot be initialized. */ public final void init() throws ServletException { super.init(); // read the default parameters Map<String, String> props = loadConfigProperties(); try { Logger logger = new ServletContextLogger(getServletContext()); ResourceProvider rp = new ServletContextResourceProvider( getServletContext()); sling = new SlingBridge(logger, rp, props); } catch (Exception ex) { log("Cannot start the OSGi framework", ex); throw new UnavailableException("Cannot start the OSGi Framework: " + ex); } // set up the OSGi HttpService proxy servlet delegatee = new HttpServiceServlet(); delegatee.init(getServletConfig()); log("Servlet " + getServletName() + " initialized"); } /** * Services the request by delegating to the delegatee servlet. If no * delegatee servlet is available, a <code>UnavailableException</code> is * thrown. * * @param req the <code>ServletRequest</code> object that contains the * client's request * @param res the <code>ServletResponse</code> object that will contain * the servlet's response * @throws UnavailableException if the no delegatee servlet is currently * available * @throws ServletException if an exception occurs that interferes with the * servlet's normal operation occurred * @throws IOException if an input or output exception occurs */ public final void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // delegate the request to the registered delegatee servlet Servlet delegatee = getDelegatee(); if (delegatee == null) { ((HttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND); } else { delegatee.service(req, res); } } /** * Destroys this servlet by shutting down the OSGi framework and hence the * delegatee servlet if one is set at all. */ public final void destroy() { // destroy the delegatee if (delegatee != null) { delegatee.destroy(); delegatee = null; } // shutdown the Felix container if (sling != null) { sling.destroy(); sling = null; } // finally call the base class destroy method super.destroy(); } Servlet getDelegatee() { return delegatee; } // ---------- Configuration Loading ---------------------------------------- /** * Loads the configuration properties in the configuration property file * associated with the framework installation; these properties are * accessible to the framework and to bundles and are intended for * configuration purposes. By default, the configuration property file is * located in the <tt>conf/</tt> directory of the Felix installation * directory and is called "<tt>config.properties</tt>". The * installation directory of Felix is assumed to be the parent directory of * the <tt>felix.jar</tt> file as found on the system class path property. * The precise file from which to load configuration properties can be set * by initializing the "<tt>felix.config.properties</tt>" system * property to an arbitrary URL. * * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was * an error. */ private Map<String, String> loadConfigProperties() { // The config properties file is either specified by a system // property or it is in the same directory as the Felix JAR file. // Try to load it from one of these places. Map<String, String> props = new HashMap<String, String>(); // The following property must start with a comma! final String servletVersion = getServletContext().getMajorVersion() + "." + getServletContext().getMinorVersion(); props.put( Sling.PROP_SYSTEM_PACKAGES, ",javax.servlet;javax.servlet.http;javax.servlet.resources; version=" + servletVersion); // prevent system properties from being considered props.put(Sling.SLING_IGNORE_SYSTEM_PROPERTIES, "true"); // add optional boot delegation for JCR and Jackrabbit API props.put("sling.include.jcr-client", "jcr-client.properties"); // copy context init parameters @SuppressWarnings("unchecked") Enumeration<String> pe = getServletContext().getInitParameterNames(); while (pe.hasMoreElements()) { String name = pe.nextElement(); props.put(name, getServletContext().getInitParameter(name)); } // copy servlet init parameters pe = getInitParameterNames(); while (pe.hasMoreElements()) { String name = pe.nextElement(); props.put(name, getInitParameter(name)); } // ensure the Felix Logger loglevel matches the Sling log level checkLogSettings(props); // if the specified obr location is not a url and starts with a '/', we // assume that this location is inside the webapp and create the correct // full url final String repoLocation = props.get(OBR_REPOSITORY_URL); if (repoLocation != null && repoLocation.indexOf(":/") < 1 && repoLocation.startsWith("/")) { try { final URL url = getServletContext().getResource(repoLocation); // only if we get back a resource url, we update it if (url != null) { props.put(OBR_REPOSITORY_URL, url.toExternalForm()); } } catch (MalformedURLException e) { // if an exception occurs, we ignore it } } return props; } private void checkLogSettings(Map<String, String> props) { String logLevelString = props.get(PROP_LOG_LEVEL); if (logLevelString != null) { int logLevel = 1; try { logLevel = Integer.parseInt(logLevelString); } catch (NumberFormatException nfe) { // might be a loglevel name for (int i=0; i < logLevels.length; i++) { if (logLevels[i].equalsIgnoreCase(logLevelString)) { logLevel = i; break; } } } props.put(LOG_LEVEL_PROP, String.valueOf(logLevel)); } } private static class ServletContextLogger extends Logger { private ServletContext servletContext; private ServletContextLogger(ServletContext servletContext) { this.servletContext = servletContext; } @Override protected void doLog(ServiceReference sr, int level, String msg, Throwable throwable) { // unwind throwable if it is a BundleException if ((throwable instanceof BundleException) && (((BundleException) throwable).getNestedException() != null)) { throwable = ((BundleException) throwable).getNestedException(); } String s = (sr == null) ? null : "SvcRef " + sr; s = (s == null) ? msg : s + " " + msg; s = (throwable == null) ? s : s + " (" + throwable + ")"; switch (level) { case LOG_DEBUG: servletContext.log("DEBUG: " + s); break; case LOG_ERROR: servletContext.log("ERROR: " + s, throwable); break; case LOG_INFO: servletContext.log("INFO: " + s); break; case LOG_WARNING: servletContext.log("WARNING: " + s); break; default: servletContext.log("UNKNOWN[" + level + "]: " + s); } } } private static class ServletContextResourceProvider extends ResourceProvider { /** * The root folder for internal web application files (value is * "/WEB-INF/"). */ private static final String WEB_INF = "/WEB-INF"; private ServletContext servletContext; private ServletContextResourceProvider(ServletContext servletContext) { this.servletContext = servletContext; } @SuppressWarnings("unchecked") @Override public Iterator<String> getChildren(String path) { // ensure leading slash if (path.charAt(0) != '/') { path = "/" + path; } Set resources = servletContext.getResourcePaths(path); // unchecked if (resources.isEmpty()) { resources = servletContext.getResourcePaths(WEB_INF + path); // unchecked } return resources.iterator(); // unchecked } public URL getResource(String path) { // nothing for empty or null path if (path == null || path.length() == 0) { return null; } // ensure leading slash if (path.charAt(0) != '/') { path = "/" + path; } try { // try direct path URL resource = servletContext.getResource(path); if (resource != null) { return resource; } // otherwise try WEB-INF location return servletContext.getResource(WEB_INF + path); } catch (MalformedURLException mue) { servletContext.log("Failure to get resource " + path, mue); } // fall back to no resource found return null; } } }
getResourcePaths might return null. git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@607061 13f79535-47bb-0310-9956-ffa450edef68
launcher/webapp/src/main/java/org/apache/sling/launcher/webapp/SlingServlet.java
getResourcePaths might return null.
Java
bsd-3-clause
9a95d4fab8a9ed02aa22438a77e8a2784a061b21
0
NCIP/catissue-advanced-query,NCIP/catissue-advanced-query
package edu.wustl.query.util.global; import java.awt.Color; /** * * @author baljeet_dhindhwal * @version 1.0 * */ public class Constants extends edu.wustl.common.util.global.Constants { //Shopping cart related /** Constant for QUERY_SHOPPING_CART */ public static final String QUERY_SHOPPING_CART = "queryShoppingCart"; /** Constant for */ public static final String CHECK_ALL_ACROSS_ALL_PAGES = "isCheckAllAcrossAllChecked"; /** Constant for */ public static final String CHECK_ALL_PAGES = "checkAllPages"; /** Constant for */ public static final String SELECTED_COLUMN_META_DATA = "selectedColumnMetaData"; /** Constant for */ public static final String DELETE = "delete"; /** Constant for */ public static final String VALIDATION_MESSAGE_FOR_ORDERING = "validationMessageForOrdering"; /** Constant for */ public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule"; /** Constant for */ public static final String IS_LIST_EMPTY = "isListEmpty"; /** Constant for */ public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; /** Constant for */ public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; /** Constant for */ public static final String PAGINATION_DATA_LIST = "paginationDataList"; /** Constant for */ public static final String LABEL_TREE_NODE = "Label"; /** Constant for */ public static final String HAS_CONDITION_ON_IDENTIFIED_FIELD = "hasConditionOnIdentifiedField"; /** Constant for */ public static final String NODE_SEPARATOR = "::"; /** Constant for */ public static final String UNDERSCORE = "_"; /** Constant for */ public static final String ADD_TO_ORDER_LIST = "addToOrderList"; /** Constant for */ public static final String REQUEST_TO_ORDER = "requestToOrder"; /** Constant for */ public static final String EDIT_QUERY = "editQuery"; /** Constant for */ public static final String BULK_TRANSFERS = "bulkTransfers"; /** Constant for */ public static final String BULK_DISPOSALS = "bulkDisposals"; /** Constant for */ public static final String OUTPUT_TERMS_COLUMNS = "outputTermsColumns"; /** Constant for */ public static final String SUCCESS = "success"; /** Constant for */ public static final String ATTRIBUTE_SEPARATOR = "|"; /** Constant for */ public static final String KEY_SEPARATOR = "*&*"; /** Constant for */ public static final String KEY_CODE = "key"; /** Constant for */ public static final String EXPORT_DATA_LIST = "exportDataList"; /** Constant for */ public static final String ENTITY_IDS_MAP = "entityIdsMap"; /** Constant for */ public static final String FINISH = "finish"; /** Constant for */ public static final String QUERY_REASUL_OBJECT_DATA_MAP = "queryReasultObjectDataMap"; /** Constant for */ public static final String DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP = "defineViewQueryReasultObjectDataMap"; /** Constant for */ public static final String CONTAINTMENT_ASSOCIATION = "CONTAINTMENT"; /** Constant for */ public static final String MAIN_ENTITY_MAP = "mainEntityMap"; /** Constant for */ public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute"; /** Constant for */ public static final String PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP = "pageOfSpecimenCollectionRequirementGroup"; /** Constant for */ public static final String NO_MAIN_OBJECT_IN_QUERY = "noMainObjectInQuery"; /** Constant for */ public static final String QUERY_ALREADY_DELETED = "queryAlreadyDeleted"; /** Constant for */ public static final String BACK = "back"; /** Constant for */ public static final String RESTORE = "restore"; /** Constant for */ public static final String SELECTED_COLUMN_NAME_VALUE_BEAN_LIST = "selectedColumnNameValueBeanList"; /** Constant for */ public static final String TREE_DATA = "treeData"; /** Constant for */ public static final String ID_NODES_MAP = "idNodesMap"; /** Constant for */ public static final String DEFINE_RESULTS_VIEW = "DefineResultsView"; /** Constant for */ public static final String CURRENT_PAGE = "currentPage"; /** Constant for */ public static final String ADD_LIMITS = "AddLimits"; /** Constant for */ public static final int QUERY_INTERFACE_BIZLOGIC_ID = 67; /** Constant for */ public static final String SQL = "SQL"; /** Constant for */ public static final String ID_COLUMN_ID = "ID_COLUMN_ID"; /** Constant for */ public static final String ID = "id"; /** Constant for */ public static final String SAVE_TREE_NODE_LIST = "rootOutputTreeNodeList"; /** Constant for */ public static final String ATTRIBUTE_COLUMN_NAME_MAP = "attributeColumnNameMap"; /** Constant for */ public static final String IS_SAVED_QUERY = "isSavedQuery"; /** Constant for */ public static final String TREE_ROOTS = "treeRoots"; /** Constant for */ public static final String NO_OF_TREES = "noOfTrees"; /** Constant for */ public static final String TREE_NODE_LIMIT_EXCEEDED_RECORDS = "treeNodeLimitExceededRecords"; /** Constant for */ public static final String VIEW_LIMITED_RECORDS = "viewLimitedRecords"; /** Constant for */ public static final String SAVE_GENERATED_SQL = "sql"; /** Constant for */ public static final String TREENO_ZERO = "zero"; /** Constant for */ public static final String COLUMN_NAMES = "columnNames"; /** Constant for */ public static final String INDEX = "index"; /** Constant for */ public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = {"firstName", "lastName", "title", "name", "label", "shorttitle"}; /** Constant for */ public static final String COLUMN_NAME = "Column"; /** Constant for */ public static final String ON = " ON "; /** Constant for */ public static final String OFF = "off"; /** Constant for */ public static final String PAGE_OF_QUERY_MODULE = "pageOfQueryModule"; /** Constant for */ public static final String PAGE_OF_QUERY_RESULTS = "pageOfQueryResults"; /** Constant for */ public static final String RANDOM_NUMBER = "randomNumber"; /** Constant for */ public static final String IS_NOT_NULL = "is not null"; /** Constant for */ public static final String IS_NULL = "is null"; /** Constant for */ public static final String IN = "in"; /** Constant for Join 'ON' clause */ public static final String JOIN_ON_CLAUSE = " ON "; /** Constant for */ public static final String Not_In = "Not In"; /** Constant for */ public static final String Equals = "Equals"; /** Constant for */ public static final String Not_Equals = "Not Equals"; /** Constant for */ public static final String Between = "Between"; /** Constant for */ public static final String Less_Than = "Less than"; /** Constant for */ public static final String Less_Than_Or_Equals = "Less than or Equal to"; /** Constant for */ public static final String Greater_Than = "Greater than"; /** Constant for */ public static final String Greater_Than_Or_Equals = "Greater than or Equal to"; /** Constant for */ public static final String Contains = "Contains"; /** Constant for */ public static final String STRATS_WITH = "Starts With"; /** Constant for */ public static final String ENDS_WITH = "Ends With"; /** Constant for */ public static final String NOT_BETWEEN = "Not Between"; /** Constant for */ public static final String INVALID_CONDITION_VALUES = "InvalidValues"; /** Constant for */ public static final String SAVE_QUERY_PAGE = "Save Query Page"; /** Constant for */ public static final String EXECUTE_QUERY_PAGE = "Execute Query Page"; /** Constant for */ public static final String FETCH_QUERY_ACTION = "FetchQuery.do"; /** Constant for */ public static final String EXECUTE_QUERY_ACTION = "ExecuteQueryAction.do"; /** Constant for */ public static final String EXECUTE_QUERY = "executeQuery"; /** Constant for */ public static final String SHOPPING_CART_FILE_NAME = "MyList.csv"; /** Constant for */ public static final String APPLICATION_DOWNLOAD = "application/download"; /** Constant for */ public static final String DOT_CSV = ".csv"; /** Constant for */ public static final String HTML_CONTENTS = "HTMLContents"; /** Constant for */ public static final String INPUT_APPLET_DATA = "inputAppletData"; /** Constant for */ public static final String SHOW_ALL = "showall"; /** Constant for */ public static final String SHOW_ALL_ATTRIBUTE = "Show all attributes"; /** Constant for */ public static final String SHOW_SELECTED_ATTRIBUTE = "Show selected attributes"; /** Constant for */ public static final String ADD_EDIT_PAGE = "Add Edit Page"; /** Constant for */ public static final String IS_QUERY_SAVED = "isQuerySaved"; /** Constant for */ public static final String CONDITIONLIST = "conditionList"; /** Constant for */ public static final String QUERY_SAVED = "querySaved"; public static final String Query_Type="queryType"; /** Constant for */ public static final String DISPLAY_NAME_FOR_CONDITION = "_displayName"; /** Constant for */ public static final String SHOW_ALL_LINK = "showAllLink"; /** Constant for */ public static final String VIEW_ALL_RECORDS = "viewAllRecords"; /** Constant for */ public static final String POPUP_MESSAGE = "popupMessage"; /** Constant for */ public static final String ID_COLUMNS_MAP = "idColumnsMap"; /** Constant for */ public static final String TREE_NODE_ID = "nodeId"; /** Constant for */ public static final String HASHED_NODE_ID = "-1"; /** Constant for */ public static final String BUTTON_CLICKED = "buttonClicked"; /** Constant for */ public static final String UPDATE_SESSION_DATA = "updateSessionData"; /** Constant for */ public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; /** Constant for */ public static final String VIEW = "view"; /** Constant for */ public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL"; /** Constant for */ public static final String TEMP_OUPUT_TREE_TABLE_NAME = "TEMP_OUTPUTTREE"; /** Constant for */ public static final String CREATE_TABLE = "Create table "; /** Constant for */ public static final String AS = "as"; /** Constant for */ public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>"; /** Constant for */ public static final String TREE_NODE_FONT_CLOSE = "</i></font>"; /** Constant for */ public static final String ZERO_ID = "0"; /** Constant for */ public static final String NULL_ID = "NULL"; /** Constant for */ public static final String UNIQUE_ID_SEPARATOR = "UQ"; /** Constant for */ public static final String SELECT_DISTINCT = "select distinct "; /** Constant for */ public static final String SELECT = "SELECT "; /** Constant for */ public static final String FILE_TYPE = "file"; /** Constant for */ public static final String FROM = " from "; /** Constant for */ public static final String WHERE = " where "; /** Constant for */ public static final String LIKE = " LIKE "; /** Constant for */ public static final String LEFT_JOIN = " LEFT JOIN "; /** Constant for */ public static final String INNER_JOIN = " INNER JOIN "; /** Constant for GROUP_BY Clause */ public static final String GROUP_BY_CLAUSE = " GROUP BY "; /** Constant for */ public static final String HASHED_OUT = "####"; /** Constant for */ public static final String DYNAMIC_UI_XML = "dynamicUI.xml"; /** Constant for */ public static final String DATE = "date"; /** Constant for */ public static final String DATE_FORMAT = "MM-dd-yyyy"; /** Constant for */ public static final String DEFINE_SEARCH_RULES = "Define Limits For"; /** Constant for */ public static final String CLASSES_PRESENT_IN_QUERY = "Classes Present In Query"; /** Constant for */ public static final String CLASS = "class"; /** Constant for */ public static final String ATTRIBUTE = "attribute"; /** Constant for */ public static final String FILE = "file"; /** Constant for */ public static final String MISSING_TWO_VALUES = "missingTwoValues"; /** Constant for */ public static final String METHOD_NAME = "method"; /** Constant for */ public static final String categorySearchForm = "categorySearchForm"; /** Constant for */ public static final int ADVANCE_QUERY_TABLES = 2; /** Constant for */ public static final String DATE_TYPE = "Date"; /** Constant for */ public static final String INTEGER_TYPE = "Integer"; /** Constant for */ public static final String FLOAT_TYPE = "Float"; /** Constant for */ public static final String DOUBLE_TYPE = "Double"; /** Constant for */ public static final String LONG_TYPE = "Long"; /** Constant for */ public static final String SHORT_TYPE = "Short"; /** Constant for */ public static final String FIRST_NODE_ATTRIBUTES = "firstDropDown"; /** Constant for */ public static final String ARITHMETIC_OPERATORS = "secondDropDown"; /** Constant for */ public static final String SECOND_NODE_ATTRIBUTES = "thirdDropDown"; /** Constant for */ public static final String RELATIONAL_OPERATORS = "fourthDropDown"; /** Constant for */ public static final String TIME_INTERVALS_LIST = "timeIntervals"; /** Constant for */ public static final String ENTITY_LABEL_LIST = "entityList"; /** Constant for */ public static final String DefineSearchResultsViewAction = "/DefineSearchResultsView.do"; /** Constant for */ public static final Color BG_COLOR = new Color(0xf4f4f5); // Dagviewapplet constants /** Constant for */ public static final String QUERY_OBJECT = "queryObject"; /** Constant for */ public static final String SESSION_ID = "session_id"; /** Constant for */ public static final String STR_TO_CREATE_QUERY_OBJ = "strToCreateQueryObject"; /** Constant for */ public static final String ENTITY_NAME = "entityName"; /** Constant for */ public static final String INIT_DATA = "initData"; /** Constant for */ public static final String ATTRIBUTES = "Attributes"; /** Constant for */ public static final String ATTRIBUTE_OPERATORS = "AttributeOperators"; /** Constant for */ public static final String FIRST_ATTR_VALUES = "FirstAttributeValues"; /** Constant for */ public static final String SECOND_ATTR_VALUES = "SecondAttributeValues"; /** Constant for */ public static final String SHOW_ENTITY_INFO = "showEntityInformation"; /** Constant for */ public static final String SRC_ENTITY = "srcEntity"; /** Constant for */ public static final String PATHS = "paths"; /** Constant for */ public static final String DEST_ENTITY = "destEntity"; /** Constant for */ public static final String ERROR_MESSAGE = "errorMessage"; /** Constant for */ public static final String SHOW_VALIDATION_MESSAGES = "showValidationMessages"; /** Constant for */ public static final String SHOW_RESULTS_PAGE = "showViewSearchResultsJsp"; /** Constant for */ public static final String ATTR_VALUES = "AttributeValues"; /** Constant for */ public static final String SHOW_ERROR_PAGE = "showErrorPage"; /** Constant for */ public static final String GET_DATA = "getData"; /** Constant for */ public static final String SET_DATA = "setData"; /** Constant for */ public static final String EMPTY_LIMIT_ERROR_MESSAGE = "<font color='red'>Please enter at least one condition to add a limit to limit set.</font>"; /** Constant for */ public static final String CANNOT_DELETE_NODE="Cannot delete an object in the edit mode. However, you can edit the conditions or attributes for the selected object."; /** Constant for */ public static final String REMOVE_SELECTED_ATTRIBUTES="Clear the attributes on the Define Result View page for the selected object, and then try deleting the object."; /** Constant for */ public static final String EMPTY_DAG_ERROR_MESSAGE = "<font color='red'>Limit set should contain at least one limit.</font>"; /** Constant for */ public static final String MULTIPLE_ROOTS_EXCEPTION = "<font color='red'>Expression graph should be a connected graph.</font>"; /** Constant for */ public static final String EDIT_LIMITS = "<font color='blue'>Limit succesfully edited.</font>"; /** Constant for */ public static final String EDIT_MODE = "Edit"; /** Constant for */ public static final String DELETE_LIMITS = "<font color='blue'>Limit succesfully deleted.</font>"; /** Constant for */ public static final String MAXIMUM_TREE_NODE_LIMIT = "resultView.maximumTreeNodeLimit"; //public static final String ATTRIBUTES = "Attributes"; /** Constant for */ public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime"; /** Constant for */ public static final String SearchCategory = "SearchCategory.do"; /** Constant for */ public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do"; /** Constant for */ public static final String NAME = "name"; /** Constant for */ public static final String TREE_VIEW_FRAME = "treeViewFrame"; /** Constant for */ public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do"; /** Constant for */ public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do"; /** Constant for */ public static final String GRID_DATA_VIEW_FRAME = "gridFrame"; /** Constant for */ public static final String PAGE_NUMBER = "pageNum"; /** Constant for */ public static final String TOTAL_RESULTS = "totalResults"; /** Constant for */ public static final String RESULTS_PER_PAGE = "numResultsPerPage"; /** Constant for */ public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList"; /** Constant for */ public static final String PAGE_OF = "pageOf"; /** Constant for */ public static final String PAGE_OF_GET_DATA ="pageOfGetData"; /** Constant for */ public static final String PAGE_OF_GET_COUNT ="pageOfGetCount"; /** Constant for */ public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; /** Constant for */ public static final int[] RESULT_PERPAGE_OPTIONS = {10, 50, 100, 500, 1000}; /** Constant for */ public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery"; /** Constant for */ public static final String CONFIGURE_GRID_VIEW_ACTION = "ConfigureGridView.do"; /** Constant for */ public static final String SAVE_QUERY_ACTION = "SaveQueryAction.do"; /** Constant for */ public static final int CHARACTERS_IN_ONE_LINE = 110; /** Constant for */ public static final String SINGLE_QUOTE_ESCAPE_SEQUENCE = "&#096;"; /** Constant for */ public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do"; /** Constant for */ public static final String QUERY_IDENTIFIER_NOT_VALID = "Query identifier is not valid."; /** Constant for */ public static final String NO_RESULT_FOUND = "No result found."; /** Constant for */ public static final String QUERY_ID = "queryId"; /** Constant for */ public static final String QUERY_COLUMN_NAME = "Column"; /** Constant for */ public static final String QUERY_OPENING_PARENTHESIS = "("; /** Constant for */ public static final String QUERY_CLOSING_PARENTHESIS = ")"; /** Constant for */ public static final String QUERY_DOT = "."; /** Constant for */ public static final String QUERY_UNDERSCORE = "_"; /** Constant for */ public static final String QUERY_COMMA = " ,"; /** Constant for */ public static final String QUERY_EQUALS = " = "; /** Constant for */ public static final String QUERY_FILE = "file"; /** Constant for */ public static final String STR_TO_DATE = "STR_TO_DATE"; /** Constant for */ public static final String QUERY_FROM_XMLTABLE = " from xmltable"; /** Constant for */ public static final String QUERY_FOR = " for "; /** Constant for */ public static final String QUERY_LET = " let "; /** Constant for */ public static final String QUERY_ORDER_BY = " order by "; /** Constant for */ public static final String QUERY_RETURN = " return "; /** Constant for */ public static final char QUERY_DOLLAR = '$'; /** Constant for */ public static final String QUERY_XMLCOLUMN = "db2-fn:xmlcolumn"; /** Constant for */ public static final String QUERY_XMLDATA = "XMLDATA"; /** Constant for */ public static final String QUERY_AND = " and "; /** Constant for OR Clause */ public static final String QUERY_OR = " OR "; /** Constant for */ public static final String QUERY_TEMPORAL_CONDITION = "TEMPORAL_CONDITION"; /** Constant for */ public static final String TRUE = "true"; /** Constant for */ public static final String FALSE = "false"; /** Constant for */ public static final String Is_PAGING = "isPaging"; /** Constant for */ public static final String CONTENT_TYPE_TEXT = "text/html"; /** * * @param s * @return */ public static final String getOracleTermString(String s) { return "day-from-dateTime(" + s + ") * 86400" + "hours-from-dateTime(" + s + ") * 3600" + "minutes-from-dateTime(" + s + ") * 60" + "seconds-from-dateTime(" + s + ")"; } /** * * @param s * @return the actual time in seconds */ public static final String getDB2TermString(String s) { return "extract(day from " + s + ")*86400 + extract(hour from " + s + ")*3600 + extract(minute from " + s + ")*60 + extract(second from " + s + ")"; } public static final String VERSION = "VERSION"; //Constants related to Export functionality /** Constant for */ public static final String SEARCH_RESULT = "SearchResult.csv"; /** Constant for */ public static final String ZIP_FILE_EXTENTION = ".zip"; /** Constant for */ public static final String CSV_FILE_EXTENTION = ".csv"; /** Constant for */ public static final String EXPORT_ZIP_NAME = "SearchResult.zip"; /** Constant for */ public static final String PRIMARY_KEY_TAG_NAME = "PRIMARY_KEY"; /** Constant for */ public static final String ID_COLUMN_NAME = "ID_COLUMN_NAME"; /** Constant for */ public static final String PRIMARY_KEY_ATTRIBUTE_SEPARATOR = "!~!~!"; //Taraben Khoiwala /** Constant for */ public static final String PERMISSIBLEVALUEFILTER = "PV_FILTER"; /** Constant for */ public static final int ADVANCE_QUERY_INTERFACE_ID = 24; /** Constant for */ public static final String PUBLIC_QUERY_PROTECTION_GROUP = "Public_Query_Protection_Group"; /** Constant for */ public static final String MY_QUERIES = "MyQueries"; public static final String SAHRED_QUERIES = "sharedQueries"; /** Constant for */ public static final String[] NUMBER = {"long", "double", "short", "integer", "float"}; /** Constant for */ public static final String NEWLINE = "\n"; /** Constant for */ public static final String DATATYPE_BOOLEAN = "boolean"; /** Constant for */ public static final String DATATYPE_NUMBER = "number"; /** Constant for */ public static final int MAX_PV_SIZE = 500; /** Constant for */ public static final int MAX_SIZE = 500; /** Constant for */ public static final int WORKFLOW_BIZLOGIC_ID = 101; /** Constant for */ public static final String MY_QUERIES_FOR_WORKFLOW = "myQueriesForWorkFlow"; public static final String SAHRED_QUERIES_FOR_WORKFLOW = "sharedQueriesForWorkFlow"; public static final String MY_QUERIES_FOR_MAIN_MENU = "myQueriesForMainMenu"; public static final String SHARED_QUERIES_FOR_MAIN_MENU = "sharedQueriesForMainMenu"; /** Constant for */ public static final String PUBLIC_QUERIES_FOR_WORKFLOW = "publicQueryForWorkFlow"; /** Constant for */ public static final String DISPLAY_QUERIES_IN_POPUP = "displayQueriesInPopup"; /** Constant for */ public static final String PAGE_OF_MY_QUERIES = "MyQueries"; /** Constant for */ public static final int WORKFLOW_FORM_ID = 101; /** Constant for */ public static final String ELEMENT_ENTITY_GROUP = "entity-group"; /** Constant for */ public static final String ELEMENT_ENTITY = "entity"; /** Constant for */ public static final String ELEMENT_NAME = "name"; /** Constant for */ public static final String ELEMENT_ATTRIBUTE = "attribute"; /** Constant for */ public static final String ELEMENT_TAG = "tag"; /** Constant for */ public static final String ELEMENT_TAG_NAME = "tag-name"; /** Constant for */ public static final String ELEMENT_TAG_VALUE = "tag-value"; /** Constant for */ public static final String TAGGED_VALUE_NOT_SEARCHABLE = "NOT_SEARCHABLE"; /** Constant for */ public static final String TAGGED_VALUE_NOT_VIEWABLE = "NOT_VIEWABLE"; /** Constant for */ public static final String VI_IGNORE_PREDICATE = "VI_IGNORE_PREDICATE"; /** Constant for default condition tagged value**/ public static final String TAGGED_VALUE_DEFAULT_CONDITION = "DEFAULT_CONDITION"; /** Constant for default condition tagged value**/ public static final String DEFAULT_CONDITION_DATA = "DEFAULT_CONDITION_DATA"; /** Constant for */ public static final String TAGGED_VALUE_PRIMARY_KEY = "PRIMARY_KEY"; /** Constant for */ public static final String TAGGED_VALUE_PV_FILTER = "PV_FILTER"; /** Constant for */ public static final String TAGGED_VALUE_VI_HIDDEN = "VI_HIDDEN"; /** Constant for */ public static final String CONTAINMENT_OBJECTS_MAP = "containmentObjectMap"; /** Constant for */ public static final String ENTITY_EXPRESSION_ID_MAP = "entityExpressionIdMap"; //added by amit_doshi /** Constant for */ public static final String PV_TREE_VECTOR = "PermissibleValueTreeVector"; /** Constant for */ public static final String PROPERTIESFILENAME = "vocab.properties"; /** Constant for */ public static final int SEARCH_PV_FROM_VOCAB_BILOGIC_ID = 12; /** Constant for */ public static final String ATTRIBUTE_INTERFACE = "AttributeInterface"; /** Constant for */ public static final String ENTITY_INTERFACE = "EntityInterface"; /** Constant for */ public static final String VOCABULIRES = "Vocabulries"; /** Constant for */ public static final String ENUMRATED_ATTRIBUTE = "EnumratedAttribute"; /** Constant for */ public static final String COMPONENT_ID = "componentId"; /** Constant for */ public static final String NO_RESULT = "No results found"; /** Constant for */ public static final String PV_HTML = "PVHTML"; /** Constant for */ public static final String DEFINE_VIEW_MSG = "DefineView"; /** Constant for */ public static final String ENTITY_NOT_PRESENT = "not present"; /** Constant for */ public static final String ENTITY_PRESENT = "present"; /** Constant for */ public static final String MAIN_ENTITY_MSG = "Main Entity"; /** Constant for */ public static final String NOT_PRESENT_MSG = " Is Not Present In DAG"; /** Constant for */ public static final String MAIN_ENTITY_LIST = "mainEntityList"; /** Constant for */ public static final String SELECTED_CONCEPT_LIST = "SELECTED_CONCEPT_LIST"; /** Constant for */ public static final String TAGGED_VALUE_MAIN_ENTIY = "MAIN_ENTITY"; /** Constant for */ public static final String BASE_MAIN_ENTITY = "BASE_MAIN_ENTITY"; /** Constant for */ public static final String QUERY_NO_ROOTEXPRESSION="query.noRootExpression.message"; /** Constant for */ public static final String ENTITY_LIST = "entityList"; /** Constant for */ public static final String MAIN_ENTITY_EXPRESSIONS_MAP = "mainEntityExpressionsMap"; /** Constant for */ public static final String MAIN_EXPRESSION_TO_ADD_CONTAINMENTS = "expressionsToAddContainments"; /** Constant for */ public static final String ALL_ADD_LIMIT_EXPRESSIONS = "allLimitExpressionIds"; /** Constant for */ public static final String MAIN_EXPRESSIONS_ENTITY_EXP_ID_MAP = "mainExpEntityExpressionIdMap"; /** Constant for */ public static final String MAIN_ENTITY_ID= "entityId"; /** Constant for */ public static final String XML_FILE_NAME = "fileName"; public static final String PERMISSIBLEVALUEVIEW = "PV_VIEW"; public static final String VI_INFO_MESSAGE1 = "This entity contains more than "; public static final String VI_INFO_MESSAGE2 = " Permissible values.Please search for the specific term "; //Start : Added for changes in Query Design for CIDER Query public static final String PROJECT_ID = "projectId"; //End : Added for changes in Query Design for CIDER Query /** Constant for Advanced Query 'JNDI' name **/ public static final String JNDI_NAME_QUERY = "java:/query"; /** Constant for CIDER 'JNDI' name **/ public static final String JNDI_NAME_CIDER = "java:/cider"; // CONSTANTS for columns in table 'QUERY_EXECUTION_LOG' /** Constant for CREATIONTIME **/ public static final String CREATIONTIME = "CREATIONTIME"; /** Constant for USER_ID **/ public static final String USER_ID = "USER_ID"; /** Constant for STATUS **/ public static final String QUERY_STATUS = "QUERY_STATUS"; /** Constant for PROJECT_ID **/ public static final String PRJCT_ID = "PROJECT_ID"; /** Constant for WORKFLOW_ID **/ public static final String COL_WORKFLOW_ID = "WORKFLOW_ID"; /** Constant for QUERY_EXECUTION_ID **/ public static final String QUERY_EXECUTION_ID = "QUERY_EXECUTION_ID"; /** Constant for QUERY_EXECUTION_ID **/ public static final String COUNT_QUERY_EXECUTION_ID = "COUNT_QUERY_EXECUTION_ID"; public static final String COUNT_QUERY_UPI = "UPI"; public static final String COUNT_QUERY_DOB = "DATE_OF_BIRTH"; /** Constant for QUERY_EXECUTION_ID **/ public static final String DATA_QUERY_EXECUTION_ID = "DATA_QUERY_EXECUTION_ID"; /** Constant for QUERY_ID **/ public static final String QRY_ID = "QUERY_ID"; /** Constant for GENERATING_QUERY **/ public static final String GENERATING_QUERY = "Generating Query"; /** Constant for QUERY_IN_PROGRESS **/ public static final String QUERY_IN_PROGRESS = "In Progress"; /** Constant for QUERY_COMPLETED **/ public static final String QUERY_COMPLETED = "Completed"; /** Constant for QUERY_CANCELLED **/ public static final String QUERY_CANCELLED = "Cancelled"; /** Constant for XQUERY_FAILED **/ public static final String QUERY_FAILED = "Query Failed"; /** Constant for separator used in tag values for default conditions **/ public static final String DEFAULT_CONDITIONS_SEPARATOR="!=!"; /** Constant for default conditions current date **/ public static final String DEFAULT_CONDITION_CURRENT_DATE="CURRENT_DATE"; /** Constant for default conditions facility id **/ public static final String DEFAULT_CONDITION_FACILITY_ID="FACILITY_ID"; /** Constant for default conditions project rule research opt out **/ public static final String DEFAULT_CONDITION_RULES_OPT_OUT="RULES_OPT_OUT"; /** Constant for default conditions project rule minors **/ public static final String DEFAULT_CONDITION_RULES_MINOR="RULES_MINOR"; /** Constant for secure condition for Age **/ public static final String SECURE_CONDITION_AGE="AGE"; /** Constant for space **/ public static final String SPACE=" "; public static final String SHOW_LAST = "showLast"; public static final String EXECUTION_LOG_ID = "executionLogId"; public static final int SHOW_LAST_COUNT = 25; public static final String TOTAL_PAGES = "totalPages"; public static final String RESULTS_PER_PAGE_OPTIONS = "resultsPerPageOptions"; public static final String RECENT_QUERIES_BEAN_LIST = "recentQueriesBeanList"; public static final int PER_PAGE_RESULTS = 10; public static final String RESULT_OBJECT = "resultObject"; public static final String QUERY_COUNT = "queryCount"; public static final String GET_COUNT_STATUS = "status"; public static final String EXECUTION_ID = "executionId"; public static final String QUERY_TYPE_GET_COUNT="Count"; public static final String QUERY_TYPE_GET_DATA="Data"; public static final int[] SHOW_LAST_OPTION = {25, 50, 100, 200}; //Constants for Get Count /** Constant for abortExecution*/ public static final String ABORT_EXECUTION="abortExecution"; /** Constant for query_exec_id*/ public static final String QUERY_EXEC_ID="query_exec_id"; /** Constant for isNewQuery*/ public static final String IS_NEW_QUERY="isNewQuery"; /** Constant for selectedProject */ public static final String SELECTED_PROJECT="selectedProject"; /** Constant for Query Exception */ public static final String QUERY_EXCEPTION="queryException"; /** Constant for Wait */ public static final String WAIT="wait"; /** Constant for Query Title */ public static final String QUERY_TITLE="queryTitle"; public static final String MY_QUERIESFOR_DASHBOARD = "myQueriesforDashboard"; public static final String WORKFLOW_NAME = "worflowName"; public static final String WORKFLOW_ID = "worflowId"; public static final String IS_WORKFLOW="isWorkflow"; public static final String PAGE_OF_WORKFLOW="workflow"; public static final String FORWARD_TO_HASHMAP = "forwardToHashMap"; public static final String NEXT_PAGE_OF = "nextPageOf"; public static final String QUERYWIZARD = "queryWizard"; public static final String DATA_QUERY_ID = "dataQueryId "; public static final String COUNT_QUERY_ID = "countQueryId "; public static final String PROJECT_NAME_VALUE_BEAN = "projectsNameValueBeanList"; /** Constant for WORFLOW_ID */ public static final String WORFLOW_ID = "workflowId"; /** Constant for WORFLOW_NAME */ public static final String WORFLOW_NAME = "worflowName"; /** constants for VI*/ public static final String SRC_VOCAB_MESSAGE = "SourceVocabMessage"; public static final Object ABORT = "abort"; public static final String SELECTED_BOX = "selectedCheckBox"; public static final String OPERATION = "operation"; public static final String SEARCH_TERM = "searchTerm"; public static final String MED_MAPPED_N_VALID_PVCONCEPT = "Normal_Bold_Enabled"; public static final String MED_MAPPED_N_NOT_VALIED_PVCONCEPT = "Bold_Italic_Disabled"; public static final String NOT_MED_MAPPED_PVCONCEPT = "Normal_Italic_Disabled"; public static final String NOT_MED_VALED_PVCONCEPT = "Normal_Disabled"; public static final String ID_DEL = "ID_DEL"; public static final String MSG_DEL = "@MSG@"; // if you change its value,kindly change in queryModule.js its hard coded there public static final String NOT_AVAILABLE = "Not Available"; public static final String SEARCH_CRITERIA = "searchCriteria"; public static final String ANY_WORD = "ANY_WORD"; public static final String TARGET_VOCABS = "targetVocabsForSearchTerm"; /** * Query ITABLE */ public static final String ITABLE = "QUERY_ITABLE"; /** * COUNT QUERY EXECUTION LOG TABLE */ public static final String COUNT_QUERY_EXECUTION_LOG = "COUNT_QUERY_EXECUTION_LOG"; /** * DATA QUERY EXECUTION LOG TABLE */ public static final String DATA_QUERY_EXECUTION_LOG = "DATA_QUERY_EXECUTION_LOG"; /** * QUERY EXECUTION LOG TABLE */ public static final String QUERY_EXECUTION_LOG = "QUERY_EXECUTION_LOG"; /** * QUERY SECURITY LOG TABLE */ public static final String QUERY_SECURITY_LOG = "QUERY_SECURITY_LOG"; /** Constant for DATE_OF_BIRTH **/ public static final String DATE_OF_BIRTH = "DATE_OF_BIRTH"; /** Constant for VIEW_FLAG **/ public static final String VIEW_FLAG = "VIEW_FLAG"; /** Constant for XQUERY_STRING **/ public static final String XQUERY_STRING = "XQUERY_STRING"; /** Constant for QUERY_TYPE **/ public static final String QUERY_TYPE = "QUERY_TYPE"; /** Constant for IP_ADDRESS **/ public static final String IP_ADDRESS = "IP_ADDRESS"; /** Constant for QUERY_COUNT **/ public static final String QRY_COUNT = "QUERY_COUNT"; /** Constant for DEID_SEQUENCE **/ public static final String DEID_SEQUENCE = "DEID_SEQUENCE"; /** Constant for PARAMETRIZED_ATTRIBUTE **/ public static final String PARAMETERIZED = "PARAMETERIZED"; /** Constant for ITABLE_ATTRIBUTES**/ public static final String TAGGED_VALUE_ITABLE_ATTRIBUTES = "ITABLE_ATTRIBUTES"; /** Constant for SECURE CONDITION **/ public static final String TAGGED_VALUE_SECURE_CONDITION = "SECURE_CONDITION"; public static final int AGE = 89; public static final int MINOR = 18; /** * constant for PATIENT_DATA_QUERY */ public static final String PATIENT_DATA_QUERY = "patientDataQuery"; public static final String PATIENT_QUERY_ROOT_OUT_PUT_NODE_LIST = "patientDataRootOutPutList"; /** Constant for Equal to operator */ public static final String EQUALS = " = "; /** Constant for... */ public static final String EXECUTION_ID_OF_QUERY = "queryExecutionId"; /** Constant for AbstractQuery */ public static final String ABSTRACT_QUERY = "abstractQuery"; /** * Constant for request attribute for 'execution type'. */ public static final String REQ_ATTRIB_EXECUTION_TYPE = "executeType"; /** * Constant to denoted execution type as 'Workflow'. */ public static final String EXECUTION_TYPE_WORKFLOW = "executeWorkFlow"; /** Constant for presenatation property name for med concept name**/ public static final String MED_CONECPT_NAME = "med_concept_name"; public static final String MED_ENTITY_NAME = "MedicalEntityDictionary"; /** * for shared queries Count */ public static final String SHARED_QUERIES_COUNT = "sharedQueriesCount"; /** * for my queries Count */ public static final String MY_QUERIES_COUNT = "myQueriesCount"; public static final String PATIENT_DEID = "PATIENT_DEID"; /** Constant for result view tag */ public static final String TAGGED_VALUE_RESULTVIEW = "resultview"; /** Constant for result order tag */ public static final String TAGGED_VALUE_RESULTORDER = "resultorder"; /** * StrutsConfigReader related constants */ public static final String WEB_INF_FOLDER_NAME = "WEB-INF"; public static final String AQ_STRUTS_CONFIG_FILE_NAME = "advancequery-struts-config.xml"; public static final String AQ_STRUTS_CONFIG_DTD_FILE_NAME = "struts-config_1_1.dtd"; public static final String STRUTS_NODE_ACTION = "action"; public static final String NODE_ACTION_ATTRIBUTE_PATH = "path"; /** * for setting project of last executed query on work flow page */ public static final String EXECUTED_FOR_PROJECT= "executedForProject"; public static final String HAS_SECURE_PRIVILEGE = "hasSecurePrivilege"; }
WEB-INF/src/edu/wustl/query/util/global/Constants.java
package edu.wustl.query.util.global; import java.awt.Color; /** * * @author baljeet_dhindhwal * @version 1.0 * */ public class Constants extends edu.wustl.common.util.global.Constants { //Shopping cart related /** Constant for QUERY_SHOPPING_CART */ public static final String QUERY_SHOPPING_CART = "queryShoppingCart"; /** Constant for */ public static final String CHECK_ALL_ACROSS_ALL_PAGES = "isCheckAllAcrossAllChecked"; /** Constant for */ public static final String CHECK_ALL_PAGES = "checkAllPages"; /** Constant for */ public static final String SELECTED_COLUMN_META_DATA = "selectedColumnMetaData"; /** Constant for */ public static final String DELETE = "delete"; /** Constant for */ public static final String VALIDATION_MESSAGE_FOR_ORDERING = "validationMessageForOrdering"; /** Constant for */ public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule"; /** Constant for */ public static final String IS_LIST_EMPTY = "isListEmpty"; /** Constant for */ public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; /** Constant for */ public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; /** Constant for */ public static final String PAGINATION_DATA_LIST = "paginationDataList"; /** Constant for */ public static final String LABEL_TREE_NODE = "Label"; /** Constant for */ public static final String HAS_CONDITION_ON_IDENTIFIED_FIELD = "hasConditionOnIdentifiedField"; /** Constant for */ public static final String NODE_SEPARATOR = "::"; /** Constant for */ public static final String UNDERSCORE = "_"; /** Constant for */ public static final String ADD_TO_ORDER_LIST = "addToOrderList"; /** Constant for */ public static final String REQUEST_TO_ORDER = "requestToOrder"; /** Constant for */ public static final String EDIT_QUERY = "editQuery"; /** Constant for */ public static final String BULK_TRANSFERS = "bulkTransfers"; /** Constant for */ public static final String BULK_DISPOSALS = "bulkDisposals"; /** Constant for */ public static final String OUTPUT_TERMS_COLUMNS = "outputTermsColumns"; /** Constant for */ public static final String SUCCESS = "success"; /** Constant for */ public static final String ENTITY_SEPARATOR = ";"; /** Constant for */ public static final String ATTRIBUTE_SEPARATOR = "|"; /** Constant for */ public static final String KEY_SEPARATOR = "*&*"; /** Constant for */ public static final String KEY_CODE = "key"; /** Constant for */ public static final String EXPORT_DATA_LIST = "exportDataList"; /** Constant for */ public static final String ENTITY_IDS_MAP = "entityIdsMap"; /** Constant for */ public static final String FINISH = "finish"; /** Constant for */ public static final String QUERY_REASUL_OBJECT_DATA_MAP = "queryReasultObjectDataMap"; /** Constant for */ public static final String DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP = "defineViewQueryReasultObjectDataMap"; /** Constant for */ public static final String CONTAINTMENT_ASSOCIATION = "CONTAINTMENT"; /** Constant for */ public static final String MAIN_ENTITY_MAP = "mainEntityMap"; /** Constant for */ public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute"; /** Constant for */ public static final String PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP = "pageOfSpecimenCollectionRequirementGroup"; /** Constant for */ public static final String NO_MAIN_OBJECT_IN_QUERY = "noMainObjectInQuery"; /** Constant for */ public static final String QUERY_ALREADY_DELETED = "queryAlreadyDeleted"; /** Constant for */ public static final String BACK = "back"; /** Constant for */ public static final String RESTORE = "restore"; /** Constant for */ public static final String SELECTED_COLUMN_NAME_VALUE_BEAN_LIST = "selectedColumnNameValueBeanList"; /** Constant for */ public static final String TREE_DATA = "treeData"; /** Constant for */ public static final String ID_NODES_MAP = "idNodesMap"; /** Constant for */ public static final String DEFINE_RESULTS_VIEW = "DefineResultsView"; /** Constant for */ public static final String CURRENT_PAGE = "currentPage"; /** Constant for */ public static final String ADD_LIMITS = "AddLimits"; /** Constant for */ public static final int QUERY_INTERFACE_BIZLOGIC_ID = 67; /** Constant for */ public static final String SQL = "SQL"; /** Constant for */ public static final String ID_COLUMN_ID = "ID_COLUMN_ID"; /** Constant for */ public static final String ID = "id"; /** Constant for */ public static final String SAVE_TREE_NODE_LIST = "rootOutputTreeNodeList"; /** Constant for */ public static final String ATTRIBUTE_COLUMN_NAME_MAP = "attributeColumnNameMap"; /** Constant for */ public static final String IS_SAVED_QUERY = "isSavedQuery"; /** Constant for */ public static final String TREE_ROOTS = "treeRoots"; /** Constant for */ public static final String NO_OF_TREES = "noOfTrees"; /** Constant for */ public static final String TREE_NODE_LIMIT_EXCEEDED_RECORDS = "treeNodeLimitExceededRecords"; /** Constant for */ public static final String VIEW_LIMITED_RECORDS = "viewLimitedRecords"; /** Constant for */ public static final String SAVE_GENERATED_SQL = "sql"; /** Constant for */ public static final String TREENO_ZERO = "zero"; /** Constant for */ public static final String COLUMN_NAMES = "columnNames"; /** Constant for */ public static final String INDEX = "index"; /** Constant for */ public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = {"firstName", "lastName", "title", "name", "label", "shorttitle"}; /** Constant for */ public static final String COLUMN_NAME = "Column"; /** Constant for */ public static final String ON = " ON "; /** Constant for */ public static final String OFF = "off"; /** Constant for */ public static final String PAGE_OF_QUERY_MODULE = "pageOfQueryModule"; /** Constant for */ public static final String PAGE_OF_QUERY_RESULTS = "pageOfQueryResults"; /** Constant for */ public static final String RANDOM_NUMBER = "randomNumber"; /** Constant for */ public static final String IS_NOT_NULL = "is not null"; /** Constant for */ public static final String IS_NULL = "is null"; /** Constant for */ public static final String IN = "in"; /** Constant for Join 'ON' clause */ public static final String JOIN_ON_CLAUSE = " ON "; /** Constant for */ public static final String Not_In = "Not In"; /** Constant for */ public static final String Equals = "Equals"; /** Constant for */ public static final String Not_Equals = "Not Equals"; /** Constant for */ public static final String Between = "Between"; /** Constant for */ public static final String Less_Than = "Less than"; /** Constant for */ public static final String Less_Than_Or_Equals = "Less than or Equal to"; /** Constant for */ public static final String Greater_Than = "Greater than"; /** Constant for */ public static final String Greater_Than_Or_Equals = "Greater than or Equal to"; /** Constant for */ public static final String Contains = "Contains"; /** Constant for */ public static final String STRATS_WITH = "Starts With"; /** Constant for */ public static final String ENDS_WITH = "Ends With"; /** Constant for */ public static final String NOT_BETWEEN = "Not Between"; /** Constant for */ public static final String INVALID_CONDITION_VALUES = "InvalidValues"; /** Constant for */ public static final String SAVE_QUERY_PAGE = "Save Query Page"; /** Constant for */ public static final String EXECUTE_QUERY_PAGE = "Execute Query Page"; /** Constant for */ public static final String FETCH_QUERY_ACTION = "FetchQuery.do"; /** Constant for */ public static final String EXECUTE_QUERY_ACTION = "ExecuteQueryAction.do"; /** Constant for */ public static final String EXECUTE_QUERY = "executeQuery"; /** Constant for */ public static final String SHOPPING_CART_FILE_NAME = "MyList.csv"; /** Constant for */ public static final String APPLICATION_DOWNLOAD = "application/download"; /** Constant for */ public static final String DOT_CSV = ".csv"; /** Constant for */ public static final String HTML_CONTENTS = "HTMLContents"; /** Constant for */ public static final String INPUT_APPLET_DATA = "inputAppletData"; /** Constant for */ public static final String SHOW_ALL = "showall"; /** Constant for */ public static final String SHOW_ALL_ATTRIBUTE = "Show all attributes"; /** Constant for */ public static final String SHOW_SELECTED_ATTRIBUTE = "Show selected attributes"; /** Constant for */ public static final String ADD_EDIT_PAGE = "Add Edit Page"; /** Constant for */ public static final String IS_QUERY_SAVED = "isQuerySaved"; /** Constant for */ public static final String CONDITIONLIST = "conditionList"; /** Constant for */ public static final String QUERY_SAVED = "querySaved"; public static final String Query_Type="queryType"; /** Constant for */ public static final String DISPLAY_NAME_FOR_CONDITION = "_displayName"; /** Constant for */ public static final String SHOW_ALL_LINK = "showAllLink"; /** Constant for */ public static final String VIEW_ALL_RECORDS = "viewAllRecords"; /** Constant for */ public static final String POPUP_MESSAGE = "popupMessage"; /** Constant for */ public static final String ID_COLUMNS_MAP = "idColumnsMap"; /** Constant for */ public static final String TREE_NODE_ID = "nodeId"; /** Constant for */ public static final String HASHED_NODE_ID = "-1"; /** Constant for */ public static final String BUTTON_CLICKED = "buttonClicked"; /** Constant for */ public static final String UPDATE_SESSION_DATA = "updateSessionData"; /** Constant for */ public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; /** Constant for */ public static final String VIEW = "view"; /** Constant for */ public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL"; /** Constant for */ public static final String TEMP_OUPUT_TREE_TABLE_NAME = "TEMP_OUTPUTTREE"; /** Constant for */ public static final String CREATE_TABLE = "Create table "; /** Constant for */ public static final String AS = "as"; /** Constant for */ public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>"; /** Constant for */ public static final String TREE_NODE_FONT_CLOSE = "</i></font>"; /** Constant for */ public static final String ZERO_ID = "0"; /** Constant for */ public static final String NULL_ID = "NULL"; /** Constant for */ public static final String UNIQUE_ID_SEPARATOR = "UQ"; /** Constant for */ public static final String SELECT_DISTINCT = "select distinct "; /** Constant for */ public static final String SELECT = "SELECT "; /** Constant for */ public static final String FILE_TYPE = "file"; /** Constant for */ public static final String FROM = " from "; /** Constant for */ public static final String WHERE = " where "; /** Constant for */ public static final String LIKE = " LIKE "; /** Constant for */ public static final String LEFT_JOIN = " LEFT JOIN "; /** Constant for */ public static final String INNER_JOIN = " INNER JOIN "; /** Constant for GROUP_BY Clause */ public static final String GROUP_BY_CLAUSE = " GROUP BY "; /** Constant for */ public static final String HASHED_OUT = "####"; /** Constant for */ public static final String DYNAMIC_UI_XML = "dynamicUI.xml"; /** Constant for */ public static final String DATE = "date"; /** Constant for */ public static final String DATE_FORMAT = "MM-dd-yyyy"; /** Constant for */ public static final String DEFINE_SEARCH_RULES = "Define Limits For"; /** Constant for */ public static final String CLASSES_PRESENT_IN_QUERY = "Classes Present In Query"; /** Constant for */ public static final String CLASS = "class"; /** Constant for */ public static final String ATTRIBUTE = "attribute"; /** Constant for */ public static final String FILE = "file"; /** Constant for */ public static final String MISSING_TWO_VALUES = "missingTwoValues"; /** Constant for */ public static final String METHOD_NAME = "method"; /** Constant for */ public static final String categorySearchForm = "categorySearchForm"; /** Constant for */ public static final int ADVANCE_QUERY_TABLES = 2; /** Constant for */ public static final String DATE_TYPE = "Date"; /** Constant for */ public static final String INTEGER_TYPE = "Integer"; /** Constant for */ public static final String FLOAT_TYPE = "Float"; /** Constant for */ public static final String DOUBLE_TYPE = "Double"; /** Constant for */ public static final String LONG_TYPE = "Long"; /** Constant for */ public static final String SHORT_TYPE = "Short"; /** Constant for */ public static final String FIRST_NODE_ATTRIBUTES = "firstDropDown"; /** Constant for */ public static final String ARITHMETIC_OPERATORS = "secondDropDown"; /** Constant for */ public static final String SECOND_NODE_ATTRIBUTES = "thirdDropDown"; /** Constant for */ public static final String RELATIONAL_OPERATORS = "fourthDropDown"; /** Constant for */ public static final String TIME_INTERVALS_LIST = "timeIntervals"; /** Constant for */ public static final String ENTITY_LABEL_LIST = "entityList"; /** Constant for */ public static final String DefineSearchResultsViewAction = "/DefineSearchResultsView.do"; /** Constant for */ public static final Color BG_COLOR = new Color(0xf4f4f5); // Dagviewapplet constants /** Constant for */ public static final String QUERY_OBJECT = "queryObject"; /** Constant for */ public static final String SESSION_ID = "session_id"; /** Constant for */ public static final String STR_TO_CREATE_QUERY_OBJ = "strToCreateQueryObject"; /** Constant for */ public static final String ENTITY_NAME = "entityName"; /** Constant for */ public static final String INIT_DATA = "initData"; /** Constant for */ public static final String ATTRIBUTES = "Attributes"; /** Constant for */ public static final String ATTRIBUTE_OPERATORS = "AttributeOperators"; /** Constant for */ public static final String FIRST_ATTR_VALUES = "FirstAttributeValues"; /** Constant for */ public static final String SECOND_ATTR_VALUES = "SecondAttributeValues"; /** Constant for */ public static final String SHOW_ENTITY_INFO = "showEntityInformation"; /** Constant for */ public static final String SRC_ENTITY = "srcEntity"; /** Constant for */ public static final String PATHS = "paths"; /** Constant for */ public static final String DEST_ENTITY = "destEntity"; /** Constant for */ public static final String ERROR_MESSAGE = "errorMessage"; /** Constant for */ public static final String SHOW_VALIDATION_MESSAGES = "showValidationMessages"; /** Constant for */ public static final String SHOW_RESULTS_PAGE = "showViewSearchResultsJsp"; /** Constant for */ public static final String ATTR_VALUES = "AttributeValues"; /** Constant for */ public static final String SHOW_ERROR_PAGE = "showErrorPage"; /** Constant for */ public static final String GET_DATA = "getData"; /** Constant for */ public static final String SET_DATA = "setData"; /** Constant for */ public static final String EMPTY_LIMIT_ERROR_MESSAGE = "<font color='red'>Please enter at least one condition to add a limit to limit set.</font>"; /** Constant for */ public static final String CANNOT_DELETE_NODE="Cannot delete an object in the edit mode. However, you can edit the conditions or attributes for the selected object."; /** Constant for */ public static final String REMOVE_SELECTED_ATTRIBUTES="Clear the attributes on the Define Result View page for the selected object, and then try deleting the object."; /** Constant for */ public static final String EMPTY_DAG_ERROR_MESSAGE = "<font color='red'>Limit set should contain at least one limit.</font>"; /** Constant for */ public static final String MULTIPLE_ROOTS_EXCEPTION = "<font color='red'>Expression graph should be a connected graph.</font>"; /** Constant for */ public static final String EDIT_LIMITS = "<font color='blue'>Limit succesfully edited.</font>"; /** Constant for */ public static final String EDIT_MODE = "Edit"; /** Constant for */ public static final String DELETE_LIMITS = "<font color='blue'>Limit succesfully deleted.</font>"; /** Constant for */ public static final String MAXIMUM_TREE_NODE_LIMIT = "resultView.maximumTreeNodeLimit"; //public static final String ATTRIBUTES = "Attributes"; /** Constant for */ public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime"; /** Constant for */ public static final String SearchCategory = "SearchCategory.do"; /** Constant for */ public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do"; /** Constant for */ public static final String NAME = "name"; /** Constant for */ public static final String TREE_VIEW_FRAME = "treeViewFrame"; /** Constant for */ public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do"; /** Constant for */ public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do"; /** Constant for */ public static final String GRID_DATA_VIEW_FRAME = "gridFrame"; /** Constant for */ public static final String PAGE_NUMBER = "pageNum"; /** Constant for */ public static final String TOTAL_RESULTS = "totalResults"; /** Constant for */ public static final String RESULTS_PER_PAGE = "numResultsPerPage"; /** Constant for */ public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList"; /** Constant for */ public static final String PAGE_OF = "pageOf"; /** Constant for */ public static final String PAGE_OF_GET_DATA ="pageOfGetData"; /** Constant for */ public static final String PAGE_OF_GET_COUNT ="pageOfGetCount"; /** Constant for */ public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; /** Constant for */ public static final int[] RESULT_PERPAGE_OPTIONS = {10, 50, 100, 500, 1000}; /** Constant for */ public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery"; /** Constant for */ public static final String CONFIGURE_GRID_VIEW_ACTION = "ConfigureGridView.do"; /** Constant for */ public static final String SAVE_QUERY_ACTION = "SaveQueryAction.do"; /** Constant for */ public static final int CHARACTERS_IN_ONE_LINE = 110; /** Constant for */ public static final String SINGLE_QUOTE_ESCAPE_SEQUENCE = "&#096;"; /** Constant for */ public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do"; /** Constant for */ public static final String QUERY_IDENTIFIER_NOT_VALID = "Query identifier is not valid."; /** Constant for */ public static final String NO_RESULT_FOUND = "No result found."; /** Constant for */ public static final String QUERY_ID = "queryId"; /** Constant for */ public static final String QUERY_COLUMN_NAME = "Column"; /** Constant for */ public static final String QUERY_OPENING_PARENTHESIS = "("; /** Constant for */ public static final String QUERY_CLOSING_PARENTHESIS = ")"; /** Constant for */ public static final String QUERY_DOT = "."; /** Constant for */ public static final String QUERY_UNDERSCORE = "_"; /** Constant for */ public static final String QUERY_COMMA = " ,"; /** Constant for */ public static final String QUERY_EQUALS = " = "; /** Constant for */ public static final String QUERY_FILE = "file"; /** Constant for */ public static final String STR_TO_DATE = "STR_TO_DATE"; /** Constant for */ public static final String QUERY_FROM_XMLTABLE = " from xmltable"; /** Constant for */ public static final String QUERY_FOR = " for "; /** Constant for */ public static final String QUERY_LET = " let "; /** Constant for */ public static final String QUERY_ORDER_BY = " order by "; /** Constant for */ public static final String QUERY_RETURN = " return "; /** Constant for */ public static final char QUERY_DOLLAR = '$'; /** Constant for */ public static final String QUERY_XMLCOLUMN = "db2-fn:xmlcolumn"; /** Constant for */ public static final String QUERY_XMLDATA = "XMLDATA"; /** Constant for */ public static final String QUERY_AND = " and "; /** Constant for OR Clause */ public static final String QUERY_OR = " OR "; /** Constant for */ public static final String QUERY_TEMPORAL_CONDITION = "TEMPORAL_CONDITION"; /** Constant for */ public static final String TRUE = "true"; /** Constant for */ public static final String FALSE = "false"; /** Constant for */ public static final String Is_PAGING = "isPaging"; /** Constant for */ public static final String CONTENT_TYPE_TEXT = "text/html"; /** * * @param s * @return */ public static final String getOracleTermString(String s) { return "day-from-dateTime(" + s + ") * 86400" + "hours-from-dateTime(" + s + ") * 3600" + "minutes-from-dateTime(" + s + ") * 60" + "seconds-from-dateTime(" + s + ")"; } /** * * @param s * @return the actual time in seconds */ public static final String getDB2TermString(String s) { return "extract(day from " + s + ")*86400 + extract(hour from " + s + ")*3600 + extract(minute from " + s + ")*60 + extract(second from " + s + ")"; } public static final String VERSION = "VERSION"; //Constants related to Export functionality /** Constant for */ public static final String SEARCH_RESULT = "SearchResult.csv"; /** Constant for */ public static final String ZIP_FILE_EXTENTION = ".zip"; /** Constant for */ public static final String CSV_FILE_EXTENTION = ".csv"; /** Constant for */ public static final String EXPORT_ZIP_NAME = "SearchResult.zip"; /** Constant for */ public static final String PRIMARY_KEY_TAG_NAME = "PRIMARY_KEY"; /** Constant for */ public static final String ID_COLUMN_NAME = "ID_COLUMN_NAME"; /** Constant for */ public static final String PRIMARY_KEY_ATTRIBUTE_SEPARATOR = "!~!~!"; //Taraben Khoiwala /** Constant for */ public static final String PERMISSIBLEVALUEFILTER = "PV_FILTER"; /** Constant for */ public static final int ADVANCE_QUERY_INTERFACE_ID = 24; /** Constant for */ public static final String PUBLIC_QUERY_PROTECTION_GROUP = "Public_Query_Protection_Group"; /** Constant for */ public static final String MY_QUERIES = "MyQueries"; public static final String SAHRED_QUERIES = "sharedQueries"; /** Constant for */ public static final String[] NUMBER = {"long", "double", "short", "integer", "float"}; /** Constant for */ public static final String NEWLINE = "\n"; /** Constant for */ public static final String DATATYPE_BOOLEAN = "boolean"; /** Constant for */ public static final String DATATYPE_NUMBER = "number"; /** Constant for */ public static final int MAX_PV_SIZE = 500; /** Constant for */ public static final int MAX_SIZE = 500; /** Constant for */ public static final int WORKFLOW_BIZLOGIC_ID = 101; /** Constant for */ public static final String MY_QUERIES_FOR_WORKFLOW = "myQueriesForWorkFlow"; public static final String SAHRED_QUERIES_FOR_WORKFLOW = "sharedQueriesForWorkFlow"; public static final String MY_QUERIES_FOR_MAIN_MENU = "myQueriesForMainMenu"; public static final String SHARED_QUERIES_FOR_MAIN_MENU = "sharedQueriesForMainMenu"; /** Constant for */ public static final String PUBLIC_QUERIES_FOR_WORKFLOW = "publicQueryForWorkFlow"; /** Constant for */ public static final String DISPLAY_QUERIES_IN_POPUP = "displayQueriesInPopup"; /** Constant for */ public static final String PAGE_OF_MY_QUERIES = "MyQueries"; /** Constant for */ public static final int WORKFLOW_FORM_ID = 101; /** Constant for */ public static final String ELEMENT_ENTITY_GROUP = "entity-group"; /** Constant for */ public static final String ELEMENT_ENTITY = "entity"; /** Constant for */ public static final String ELEMENT_NAME = "name"; /** Constant for */ public static final String ELEMENT_ATTRIBUTE = "attribute"; /** Constant for */ public static final String ELEMENT_TAG = "tag"; /** Constant for */ public static final String ELEMENT_TAG_NAME = "tag-name"; /** Constant for */ public static final String ELEMENT_TAG_VALUE = "tag-value"; /** Constant for */ public static final String TAGGED_VALUE_NOT_SEARCHABLE = "NOT_SEARCHABLE"; /** Constant for */ public static final String TAGGED_VALUE_NOT_VIEWABLE = "NOT_VIEWABLE"; /** Constant for */ public static final String VI_IGNORE_PREDICATE = "VI_IGNORE_PREDICATE"; /** Constant for default condition tagged value**/ public static final String TAGGED_VALUE_DEFAULT_CONDITION = "DEFAULT_CONDITION"; /** Constant for default condition tagged value**/ public static final String DEFAULT_CONDITION_DATA = "DEFAULT_CONDITION_DATA"; /** Constant for */ public static final String TAGGED_VALUE_PRIMARY_KEY = "PRIMARY_KEY"; /** Constant for */ public static final String TAGGED_VALUE_PV_FILTER = "PV_FILTER"; /** Constant for */ public static final String TAGGED_VALUE_VI_HIDDEN = "VI_HIDDEN"; /** Constant for */ public static final String CONTAINMENT_OBJECTS_MAP = "containmentObjectMap"; /** Constant for */ public static final String ENTITY_EXPRESSION_ID_MAP = "entityExpressionIdMap"; //added by amit_doshi /** Constant for */ public static final String PV_TREE_VECTOR = "PermissibleValueTreeVector"; /** Constant for */ public static final String PROPERTIESFILENAME = "vocab.properties"; /** Constant for */ public static final int SEARCH_PV_FROM_VOCAB_BILOGIC_ID = 12; /** Constant for */ public static final String ATTRIBUTE_INTERFACE = "AttributeInterface"; /** Constant for */ public static final String ENTITY_INTERFACE = "EntityInterface"; /** Constant for */ public static final String VOCABULIRES = "Vocabulries"; /** Constant for */ public static final String ENUMRATED_ATTRIBUTE = "EnumratedAttribute"; /** Constant for */ public static final String COMPONENT_ID = "componentId"; /** Constant for */ public static final String NO_RESULT = "No results found"; /** Constant for */ public static final String PV_HTML = "PVHTML"; /** Constant for */ public static final String DEFINE_VIEW_MSG = "DefineView"; /** Constant for */ public static final String ENTITY_NOT_PRESENT = "not present"; /** Constant for */ public static final String ENTITY_PRESENT = "present"; /** Constant for */ public static final String MAIN_ENTITY_MSG = "Main Entity"; /** Constant for */ public static final String NOT_PRESENT_MSG = " Is Not Present In DAG"; /** Constant for */ public static final String MAIN_ENTITY_LIST = "mainEntityList"; /** Constant for */ public static final String SELECTED_CONCEPT_LIST = "SELECTED_CONCEPT_LIST"; /** Constant for */ public static final String TAGGED_VALUE_MAIN_ENTIY = "MAIN_ENTITY"; /** Constant for */ public static final String BASE_MAIN_ENTITY = "BASE_MAIN_ENTITY"; /** Constant for */ public static final String QUERY_NO_ROOTEXPRESSION="query.noRootExpression.message"; /** Constant for */ public static final String ENTITY_LIST = "entityList"; /** Constant for */ public static final String MAIN_ENTITY_EXPRESSIONS_MAP = "mainEntityExpressionsMap"; /** Constant for */ public static final String MAIN_EXPRESSION_TO_ADD_CONTAINMENTS = "expressionsToAddContainments"; /** Constant for */ public static final String ALL_ADD_LIMIT_EXPRESSIONS = "allLimitExpressionIds"; /** Constant for */ public static final String MAIN_EXPRESSIONS_ENTITY_EXP_ID_MAP = "mainExpEntityExpressionIdMap"; /** Constant for */ public static final String MAIN_ENTITY_ID= "entityId"; /** Constant for */ public static final String XML_FILE_NAME = "fileName"; public static final String PERMISSIBLEVALUEVIEW = "PV_VIEW"; public static final String VI_INFO_MESSAGE1 = "This entity contains more than "; public static final String VI_INFO_MESSAGE2 = " Permissible values.Please search for the specific term "; //Start : Added for changes in Query Design for CIDER Query public static final String PROJECT_ID = "projectId"; //End : Added for changes in Query Design for CIDER Query /** Constant for Advanced Query 'JNDI' name **/ public static final String JNDI_NAME_QUERY = "java:/query"; /** Constant for CIDER 'JNDI' name **/ public static final String JNDI_NAME_CIDER = "java:/cider"; // CONSTANTS for columns in table 'QUERY_EXECUTION_LOG' /** Constant for CREATIONTIME **/ public static final String CREATIONTIME = "CREATIONTIME"; /** Constant for USER_ID **/ public static final String USER_ID = "USER_ID"; /** Constant for STATUS **/ public static final String QUERY_STATUS = "QUERY_STATUS"; /** Constant for PROJECT_ID **/ public static final String PRJCT_ID = "PROJECT_ID"; /** Constant for WORKFLOW_ID **/ public static final String COL_WORKFLOW_ID = "WORKFLOW_ID"; /** Constant for QUERY_EXECUTION_ID **/ public static final String QUERY_EXECUTION_ID = "QUERY_EXECUTION_ID"; /** Constant for QUERY_EXECUTION_ID **/ public static final String COUNT_QUERY_EXECUTION_ID = "COUNT_QUERY_EXECUTION_ID"; public static final String COUNT_QUERY_UPI = "UPI"; public static final String COUNT_QUERY_DOB = "DATE_OF_BIRTH"; /** Constant for QUERY_EXECUTION_ID **/ public static final String DATA_QUERY_EXECUTION_ID = "DATA_QUERY_EXECUTION_ID"; /** Constant for QUERY_ID **/ public static final String QRY_ID = "QUERY_ID"; /** Constant for GENERATING_QUERY **/ public static final String GENERATING_QUERY = "Generating Query"; /** Constant for QUERY_IN_PROGRESS **/ public static final String QUERY_IN_PROGRESS = "In Progress"; /** Constant for QUERY_COMPLETED **/ public static final String QUERY_COMPLETED = "Completed"; /** Constant for QUERY_CANCELLED **/ public static final String QUERY_CANCELLED = "Cancelled"; /** Constant for XQUERY_FAILED **/ public static final String QUERY_FAILED = "Query Failed"; /** Constant for separator used in tag values for default conditions **/ public static final String DEFAULT_CONDITIONS_SEPARATOR="!=!"; /** Constant for default conditions current date **/ public static final String DEFAULT_CONDITION_CURRENT_DATE="CURRENT_DATE"; /** Constant for default conditions facility id **/ public static final String DEFAULT_CONDITION_FACILITY_ID="FACILITY_ID"; /** Constant for default conditions project rule research opt out **/ public static final String DEFAULT_CONDITION_RULES_OPT_OUT="RULES_OPT_OUT"; /** Constant for default conditions project rule minors **/ public static final String DEFAULT_CONDITION_RULES_MINOR="RULES_MINOR"; /** Constant for secure condition for Age **/ public static final String SECURE_CONDITION_AGE="AGE"; /** Constant for space **/ public static final String SPACE=" "; public static final String SHOW_LAST = "showLast"; public static final String EXECUTION_LOG_ID = "executionLogId"; public static final int SHOW_LAST_COUNT = 25; public static final String TOTAL_PAGES = "totalPages"; public static final String RESULTS_PER_PAGE_OPTIONS = "resultsPerPageOptions"; public static final String RECENT_QUERIES_BEAN_LIST = "recentQueriesBeanList"; public static final int PER_PAGE_RESULTS = 10; public static final String RESULT_OBJECT = "resultObject"; public static final String QUERY_COUNT = "queryCount"; public static final String GET_COUNT_STATUS = "status"; public static final String EXECUTION_ID = "executionId"; public static final String QUERY_TYPE_GET_COUNT="Count"; public static final String QUERY_TYPE_GET_DATA="Data"; public static final int[] SHOW_LAST_OPTION = {25, 50, 100, 200}; //Constants for Get Count /** Constant for abortExecution*/ public static final String ABORT_EXECUTION="abortExecution"; /** Constant for query_exec_id*/ public static final String QUERY_EXEC_ID="query_exec_id"; /** Constant for isNewQuery*/ public static final String IS_NEW_QUERY="isNewQuery"; /** Constant for selectedProject */ public static final String SELECTED_PROJECT="selectedProject"; /** Constant for Query Exception */ public static final String QUERY_EXCEPTION="queryException"; /** Constant for Wait */ public static final String WAIT="wait"; /** Constant for Query Title */ public static final String QUERY_TITLE="queryTitle"; public static final String MY_QUERIESFOR_DASHBOARD = "myQueriesforDashboard"; public static final String WORKFLOW_NAME = "worflowName"; public static final String WORKFLOW_ID = "worflowId"; public static final String IS_WORKFLOW="isWorkflow"; public static final String PAGE_OF_WORKFLOW="workflow"; public static final String FORWARD_TO_HASHMAP = "forwardToHashMap"; public static final String NEXT_PAGE_OF = "nextPageOf"; public static final String QUERYWIZARD = "queryWizard"; public static final String DATA_QUERY_ID = "dataQueryId "; public static final String COUNT_QUERY_ID = "countQueryId "; public static final String PROJECT_NAME_VALUE_BEAN = "projectsNameValueBeanList"; /** Constant for WORFLOW_ID */ public static final String WORFLOW_ID = "workflowId"; /** Constant for WORFLOW_NAME */ public static final String WORFLOW_NAME = "worflowName"; /** constants for VI*/ public static final String SRC_VOCAB_MESSAGE = "SourceVocabMessage"; public static final Object ABORT = "abort"; public static final String SELECTED_BOX = "selectedCheckBox"; public static final String OPERATION = "operation"; public static final String SEARCH_TERM = "searchTerm"; public static final String MED_MAPPED_N_VALID_PVCONCEPT = "Normal_Bold_Enabled"; public static final String MED_MAPPED_N_NOT_VALIED_PVCONCEPT = "Bold_Italic_Disabled"; public static final String NOT_MED_MAPPED_PVCONCEPT = "Normal_Italic_Disabled"; public static final String NOT_MED_VALED_PVCONCEPT = "Normal_Disabled"; public static final String ID_DEL = "ID_DEL"; public static final String MSG_DEL = "@MSG@"; // if you change its value,kindly change in queryModule.js its hard coded there public static final String NOT_AVAILABLE = "Not Available"; public static final String SEARCH_CRITERIA = "searchCriteria"; public static final String ANY_WORD = "ANY_WORD"; public static final String TARGET_VOCABS = "targetVocabsForSearchTerm"; /** * Query ITABLE */ public static final String ITABLE = "QUERY_ITABLE"; /** * COUNT QUERY EXECUTION LOG TABLE */ public static final String COUNT_QUERY_EXECUTION_LOG = "COUNT_QUERY_EXECUTION_LOG"; /** * DATA QUERY EXECUTION LOG TABLE */ public static final String DATA_QUERY_EXECUTION_LOG = "DATA_QUERY_EXECUTION_LOG"; /** * QUERY EXECUTION LOG TABLE */ public static final String QUERY_EXECUTION_LOG = "QUERY_EXECUTION_LOG"; /** * QUERY SECURITY LOG TABLE */ public static final String QUERY_SECURITY_LOG = "QUERY_SECURITY_LOG"; /** Constant for DATE_OF_BIRTH **/ public static final String DATE_OF_BIRTH = "DATE_OF_BIRTH"; /** Constant for VIEW_FLAG **/ public static final String VIEW_FLAG = "VIEW_FLAG"; /** Constant for XQUERY_STRING **/ public static final String XQUERY_STRING = "XQUERY_STRING"; /** Constant for QUERY_TYPE **/ public static final String QUERY_TYPE = "QUERY_TYPE"; /** Constant for IP_ADDRESS **/ public static final String IP_ADDRESS = "IP_ADDRESS"; /** Constant for QUERY_COUNT **/ public static final String QRY_COUNT = "QUERY_COUNT"; /** Constant for DEID_SEQUENCE **/ public static final String DEID_SEQUENCE = "DEID_SEQUENCE"; /** Constant for PARAMETRIZED_ATTRIBUTE **/ public static final String PARAMETERIZED = "PARAMETERIZED"; /** Constant for ITABLE_ATTRIBUTES**/ public static final String TAGGED_VALUE_ITABLE_ATTRIBUTES = "ITABLE_ATTRIBUTES"; /** Constant for SECURE CONDITION **/ public static final String TAGGED_VALUE_SECURE_CONDITION = "SECURE_CONDITION"; public static final int AGE = 89; public static final int MINOR = 18; /** * constant for PATIENT_DATA_QUERY */ public static final String PATIENT_DATA_QUERY = "patientDataQuery"; public static final String PATIENT_QUERY_ROOT_OUT_PUT_NODE_LIST = "patientDataRootOutPutList"; /** Constant for Equal to operator */ public static final String EQUALS = " = "; /** Constant for... */ public static final String EXECUTION_ID_OF_QUERY = "queryExecutionId"; /** Constant for AbstractQuery */ public static final String ABSTRACT_QUERY = "abstractQuery"; /** * Constant for request attribute for 'execution type'. */ public static final String REQ_ATTRIB_EXECUTION_TYPE = "executeType"; /** * Constant to denoted execution type as 'Workflow'. */ public static final String EXECUTION_TYPE_WORKFLOW = "executeWorkFlow"; /** Constant for presenatation property name for med concept name**/ public static final String MED_CONECPT_NAME = "med_concept_name"; public static final String MED_ENTITY_NAME = "MedicalEntityDictionary"; /** * for shared queries Count */ public static final String SHARED_QUERIES_COUNT = "sharedQueriesCount"; /** * for my queries Count */ public static final String MY_QUERIES_COUNT = "myQueriesCount"; public static final String PATIENT_DEID = "PATIENT_DEID"; /** Constant for result view tag */ public static final String TAGGED_VALUE_RESULTVIEW = "resultview"; /** Constant for result order tag */ public static final String TAGGED_VALUE_RESULTORDER = "resultorder"; /** * StrutsConfigReader related constants */ public static final String WEB_INF_FOLDER_NAME = "WEB-INF"; public static final String AQ_STRUTS_CONFIG_FILE_NAME = "advancequery-struts-config.xml"; public static final String AQ_STRUTS_CONFIG_DTD_FILE_NAME = "struts-config_1_1.dtd"; public static final String STRUTS_NODE_ACTION = "action"; public static final String NODE_ACTION_ATTRIBUTE_PATH = "path"; /** * for setting project of last executed query on work flow page */ public static final String EXECUTED_FOR_PROJECT= "executedForProject"; public static final String HAS_SECURE_PRIVILEGE = "hasSecurePrivilege"; }
removed Entity separator(;). SVN-Revision: 6427
WEB-INF/src/edu/wustl/query/util/global/Constants.java
removed Entity separator(;).
Java
bsd-3-clause
068c9faa4986e29713ffd2ae1f0900b3cc9e86e6
0
davidpicard/jkernelmachines,davidpicard/jkernelmachines,davidpicard/jkernelmachines
/** This file is part of JkernelMachines. JkernelMachines is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JkernelMachines is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JkernelMachines. If not, see <http://www.gnu.org/licenses/>. Copyright David Picard - 2010 */ package fr.lip6.jkernelmachines.classifier; import java.io.Serializable; import java.util.Collections; import java.util.List; import fr.lip6.jkernelmachines.kernel.typed.DoubleLinear; import fr.lip6.jkernelmachines.type.TrainingSample; import fr.lip6.jkernelmachines.type.TrainingSampleStream; /** * <p> * Linear SVM classifier using stochastic gradient descent algorithm * </p> * * <p> * <b>Large-Scale Machine Learning with Stochastic Gradient Descent</b><br /> * Léon Bottou<br /> * <i>Proceedings of the 19th International Conference on Computational Statistics (COMPSTAT'2010)</i> * </p> * * @author picard * */ public class DoubleSGD implements Classifier<double[]>, OnlineClassifier<double[]>, Serializable { private static final long serialVersionUID = 3245177176254451010L; // Available losses /** Type of loss function using hinge */ public static final int HINGELOSS = 1; /** Type of loss function using a smoothed hinge */ public static final int SMOOTHHINGELOSS = 2; /** Type of loss function using a squared hinge */ public static final int SQUAREDHINGELOSS = 3; /** Type of loss function using log */ public static final int LOGLOSS = 10; /** Type of loss function using margin log */ public static final int LOGLOSSMARGIN = 11; //used loss function private int loss = HINGELOSS; //svm hyperplane private double[] w = null; double bias; boolean hasBias = true; //skipping decay update parameter private long t; private double lambda = 1e-4; private int epochs = 5; private double wscale; private boolean shuffle = false; //linear kernel DoubleLinear linear = new DoubleLinear(); @Override public void train(List<TrainingSample<double[]>> l) { if(l.isEmpty()) return; //new w w = new double[l.get(0).sample.length]; //init wscale = 1; bias = 0; // Shift t in order to have a // reasonable initial learning rate. // This assumes |x| \approx 1. double maxw = 1.0 / Math.sqrt(lambda); double typw = Math.sqrt(maxw); double eta0 = typw / Math.max(1.0, dloss(-typw)); t = (long) (1 / (eta0 * lambda)); for(int e = 0 ; e < epochs ; e++) { trainOnce(l); } } /* * (non-Javadoc) * * @see * fr.lip6.jkernelmachines.classifier.Classifier#train(fr.lip6.jkernelmachines * .type.TrainingSample) */ @Override public void train(TrainingSample<double[]> sample) { if(w == null) { //new w w = new double[sample.sample.length]; //init wscale = 1; bias = 0; // Shift t in order to have a // reasonable initial learning rate. // This assumes |x| \approx 1. double maxw = 1.0 / Math.sqrt(lambda); double typw = Math.sqrt(maxw); double eta0 = typw / Math.max(1.0, dloss(-typw)); t = (long) (1 / (eta0 * lambda)); } double eta = 1.0 / (lambda * t); double s = 1 - eta * lambda; wscale *= s; if (wscale < 1e-9) { for (int d = 0; d < w.length; d++) w[d] *= wscale; wscale = 1; } double[] x = sample.sample; double y = sample.label; double wx = linear.valueOf(w, x) * wscale; double z = y * (wx + bias); if (z < 1 && loss < LOGLOSS) { double etd = eta * dloss(z); for (int d = 0; d < w.length; d++) w[d] += x[d] * etd * y / wscale; // Slower rate on the bias because // it learns at each iteration. if(hasBias) bias += etd * y * 0.01; } t += 1; } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.classifier.OnlineClassifier#onlineTrain(fr.lip6.jkernelmachines.type.TrainingSampleStream) */ @Override public void onlineTrain(TrainingSampleStream<double[]> stream) { TrainingSample<double[]> t; while((t = stream.nextSample()) != null) { train(t); } } /** * Update the separating hyperplane by learning one epoch on given training list * @param l the training list */ public void trainOnce(List<TrainingSample<double[]>> l) { if(w == null) return; int imax = l.size(); if(shuffle) { Collections.shuffle(l); } for (int i = 0; i < imax; i++) { double eta = 1.0 / (lambda * t); double s = 1 - eta * lambda; wscale *= s; if (wscale < 1e-9) { for (int d = 0; d < w.length; d++) w[d] *= wscale; wscale = 1; } double[] x = l.get(i).sample; double y = l.get(i).label; double wx = linear.valueOf(w, x) * wscale; double z = y * (wx + bias); if (z < 1 && loss < LOGLOSS) { double etd = eta * dloss(z); for (int d = 0; d < w.length; d++) w[d] += x[d] * etd * y / wscale; // Slower rate on the bias because // it learns at each iteration. if(hasBias) bias += etd * y * 0.01; } t += 1; } if(!hasBias) bias = 0; } @Override public double valueOf(double[] e) { return linear.valueOf(w,e) * wscale + bias; } private double dloss(double z) { switch(loss) { case LOGLOSS : if (z < 0) return 1 / (Math.exp(z) + 1); double ez = Math.exp(-z); return ez / (ez + 1); case LOGLOSSMARGIN : if (z < 1) return 1 / (Math.exp(z-1) + 1); ez = Math.exp(1-z); return ez / (ez + 1); case SMOOTHHINGELOSS : if (z < 0) return 1; if (z < 1) return 1-z; return 0; case SQUAREDHINGELOSS : if (z < 1) return (1 - z); return 0; default : if (z < 1) return 1; return 0; } } /** * Tells the arrays of coordinate of separating hyperplane * @return the arrays of coordinate of separating hyperplane */ public double[] getW() { return w; } /** * Tells the type of loss used by this classifier (default HINGELOSS) * @return an integer representing the type of loss */ public int getLoss() { return loss; } /** * Sets the type of loss used by this classifier (default HINGELOSS) * @param loss */ public void setLoss(int loss) { this.loss = loss; } /** * Sets the learning rate lambda * @param l the learning rate */ public void setLambda(double l) { lambda = l; } /** * Tells if this classifier is using a bias term * @return true if a bias term is used */ public boolean isHasBias() { return hasBias; } /** * Sets the use of a bias term * @param hasBias true if use of bias term */ public void setHasBias(boolean hasBias) { this.hasBias = hasBias; } /** * Tells the number of epochs this classifier uses for learning * @return the number of epochs */ public int getEpochs() { return epochs; } /** * Sets the number of epochs this classifier uses for learning * @param epochs the number of epochs */ public void setEpochs(int epochs) { this.epochs = epochs; } /** * Tells if samples are shuffled while learning * @return true if samples are shuffled */ public boolean isShuffle() { return shuffle; } /** * Sets if samples should be shuffled while learning * @param shuffle true if shuffle */ public void setShuffle(boolean shuffle) { this.shuffle = shuffle; } /** * Creates and returns a copy of this object. * @see java.lang.Object#clone() */ @Override public DoubleSGD copy() throws CloneNotSupportedException { return (DoubleSGD) super.clone(); } /** * Returns the hyper-parameter lambda * @return lambda */ public double getLambda() { return lambda; } }
src/fr/lip6/jkernelmachines/classifier/DoubleSGD.java
/** This file is part of JkernelMachines. JkernelMachines is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JkernelMachines is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JkernelMachines. If not, see <http://www.gnu.org/licenses/>. Copyright David Picard - 2010 */ package fr.lip6.jkernelmachines.classifier; import java.util.Collections; import java.util.List; import fr.lip6.jkernelmachines.kernel.typed.DoubleLinear; import fr.lip6.jkernelmachines.type.TrainingSample; import fr.lip6.jkernelmachines.type.TrainingSampleStream; /** * <p> * Linear SVM classifier using stochastic gradient descent algorithm * </p> * * <p> * <b>Large-Scale Machine Learning with Stochastic Gradient Descent</b><br /> * Léon Bottou<br /> * <i>Proceedings of the 19th International Conference on Computational Statistics (COMPSTAT'2010)</i> * </p> * * @author picard * */ public class DoubleSGD implements Classifier<double[]>, OnlineClassifier<double[]> { // Available losses /** Type of loss function using hinge */ public static final int HINGELOSS = 1; /** Type of loss function using a smoothed hinge */ public static final int SMOOTHHINGELOSS = 2; /** Type of loss function using a squared hinge */ public static final int SQUAREDHINGELOSS = 3; /** Type of loss function using log */ public static final int LOGLOSS = 10; /** Type of loss function using margin log */ public static final int LOGLOSSMARGIN = 11; //used loss function private int loss = HINGELOSS; //svm hyperplane private double[] w = null; double bias; boolean hasBias = true; //skipping decay update parameter private long t; private double lambda = 1e-4; private int epochs = 5; private double wscale; private boolean shuffle = false; //linear kernel DoubleLinear linear = new DoubleLinear(); @Override public void train(List<TrainingSample<double[]>> l) { if(l.isEmpty()) return; //new w w = new double[l.get(0).sample.length]; //init wscale = 1; bias = 0; // Shift t in order to have a // reasonable initial learning rate. // This assumes |x| \approx 1. double maxw = 1.0 / Math.sqrt(lambda); double typw = Math.sqrt(maxw); double eta0 = typw / Math.max(1.0, dloss(-typw)); t = (long) (1 / (eta0 * lambda)); for(int e = 0 ; e < epochs ; e++) { trainOnce(l); } } /* * (non-Javadoc) * * @see * fr.lip6.jkernelmachines.classifier.Classifier#train(fr.lip6.jkernelmachines * .type.TrainingSample) */ @Override public void train(TrainingSample<double[]> sample) { if(w == null) { //new w w = new double[sample.sample.length]; //init wscale = 1; bias = 0; // Shift t in order to have a // reasonable initial learning rate. // This assumes |x| \approx 1. double maxw = 1.0 / Math.sqrt(lambda); double typw = Math.sqrt(maxw); double eta0 = typw / Math.max(1.0, dloss(-typw)); t = (long) (1 / (eta0 * lambda)); } double eta = 1.0 / (lambda * t); double s = 1 - eta * lambda; wscale *= s; if (wscale < 1e-9) { for (int d = 0; d < w.length; d++) w[d] *= wscale; wscale = 1; } double[] x = sample.sample; double y = sample.label; double wx = linear.valueOf(w, x) * wscale; double z = y * (wx + bias); if (z < 1 && loss < LOGLOSS) { double etd = eta * dloss(z); for (int d = 0; d < w.length; d++) w[d] += x[d] * etd * y / wscale; // Slower rate on the bias because // it learns at each iteration. if(hasBias) bias += etd * y * 0.01; } t += 1; } /* (non-Javadoc) * @see fr.lip6.jkernelmachines.classifier.OnlineClassifier#onlineTrain(fr.lip6.jkernelmachines.type.TrainingSampleStream) */ @Override public void onlineTrain(TrainingSampleStream<double[]> stream) { TrainingSample<double[]> t; while((t = stream.nextSample()) != null) { train(t); } } /** * Update the separating hyperplane by learning one epoch on given training list * @param l the training list */ public void trainOnce(List<TrainingSample<double[]>> l) { if(w == null) return; int imax = l.size(); if(shuffle) { Collections.shuffle(l); } for (int i = 0; i < imax; i++) { double eta = 1.0 / (lambda * t); double s = 1 - eta * lambda; wscale *= s; if (wscale < 1e-9) { for (int d = 0; d < w.length; d++) w[d] *= wscale; wscale = 1; } double[] x = l.get(i).sample; double y = l.get(i).label; double wx = linear.valueOf(w, x) * wscale; double z = y * (wx + bias); if (z < 1 && loss < LOGLOSS) { double etd = eta * dloss(z); for (int d = 0; d < w.length; d++) w[d] += x[d] * etd * y / wscale; // Slower rate on the bias because // it learns at each iteration. if(hasBias) bias += etd * y * 0.01; } t += 1; } if(!hasBias) bias = 0; } @Override public double valueOf(double[] e) { return linear.valueOf(w,e) * wscale + bias; } private double dloss(double z) { switch(loss) { case LOGLOSS : if (z < 0) return 1 / (Math.exp(z) + 1); double ez = Math.exp(-z); return ez / (ez + 1); case LOGLOSSMARGIN : if (z < 1) return 1 / (Math.exp(z-1) + 1); ez = Math.exp(1-z); return ez / (ez + 1); case SMOOTHHINGELOSS : if (z < 0) return 1; if (z < 1) return 1-z; return 0; case SQUAREDHINGELOSS : if (z < 1) return (1 - z); return 0; default : if (z < 1) return 1; return 0; } } /** * Tells the arrays of coordinate of separating hyperplane * @return the arrays of coordinate of separating hyperplane */ public double[] getW() { return w; } /** * Tells the type of loss used by this classifier (default HINGELOSS) * @return an integer representing the type of loss */ public int getLoss() { return loss; } /** * Sets the type of loss used by this classifier (default HINGELOSS) * @param loss */ public void setLoss(int loss) { this.loss = loss; } /** * Sets the learning rate lambda * @param l the learning rate */ public void setLambda(double l) { lambda = l; } /** * Tells if this classifier is using a bias term * @return true if a bias term is used */ public boolean isHasBias() { return hasBias; } /** * Sets the use of a bias term * @param hasBias true if use of bias term */ public void setHasBias(boolean hasBias) { this.hasBias = hasBias; } /** * Tells the number of epochs this classifier uses for learning * @return the number of epochs */ public int getEpochs() { return epochs; } /** * Sets the number of epochs this classifier uses for learning * @param epochs the number of epochs */ public void setEpochs(int epochs) { this.epochs = epochs; } /** * Tells if samples are shuffled while learning * @return true if samples are shuffled */ public boolean isShuffle() { return shuffle; } /** * Sets if samples should be shuffled while learning * @param shuffle true if shuffle */ public void setShuffle(boolean shuffle) { this.shuffle = shuffle; } /** * Creates and returns a copy of this object. * @see java.lang.Object#clone() */ @Override public DoubleSGD copy() throws CloneNotSupportedException { return (DoubleSGD) super.clone(); } /** * Returns the hyper-parameter lambda * @return lambda */ public double getLambda() { return lambda; } }
implement serializable
src/fr/lip6/jkernelmachines/classifier/DoubleSGD.java
implement serializable
Java
mit
5ce228e9f72a68522d40d68964ea2439621772e4
0
brentvatne/react-native-video,brentvatne/react-native-video,IMGGaming/react-native-video,brentvatne/react-native-video,IMGGaming/react-native-video,IMGGaming/react-native-video,IMGGaming/react-native-video
package com.brentvatne.exoplayer; import android.annotation.SuppressLint; import android.content.Context; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.widget.FrameLayout; import com.brentvatne.react.R; import com.brentvatne.receiver.AudioBecomingNoisyReceiver; import com.brentvatne.receiver.BecomingNoisyListener; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.uimanager.ThemedReactContext; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer; import com.google.android.exoplayer2.mediacodec.MediaCodecUtil; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.MetadataRenderer; import com.google.android.exoplayer2.source.BehindLiveWindowException; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.LoopingMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.dash.DashMediaSource; import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource; import com.google.android.exoplayer2.source.hls.HlsMediaSource; import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource; import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.MappingTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.util.Util; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.lang.Math; @SuppressLint("ViewConstructor") class ReactExoplayerView extends FrameLayout implements LifecycleEventListener, ExoPlayer.EventListener, BecomingNoisyListener, AudioManager.OnAudioFocusChangeListener, MetadataRenderer.Output { private static final String TAG = "ReactExoplayerView"; private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter(); private static final CookieManager DEFAULT_COOKIE_MANAGER; private static final int SHOW_PROGRESS = 1; static { DEFAULT_COOKIE_MANAGER = new CookieManager(); DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); } private final VideoEventEmitter eventEmitter; private Handler mainHandler; private ExoPlayerView exoPlayerView; private DataSource.Factory mediaDataSourceFactory; private SimpleExoPlayer player; private MappingTrackSelector trackSelector; private boolean playerNeedsSource; private int resumeWindow; private long resumePosition; private boolean loadVideoStarted; private boolean isPaused = true; private boolean isBuffering; private float rate = 1f; // Props from React private Uri srcUri; private String extension; private boolean repeat; private boolean disableFocus; private float mProgressUpdateInterval = 250.0f; private boolean playInBackground = false; // \ End props // React private final ThemedReactContext themedReactContext; private final AudioManager audioManager; private final AudioBecomingNoisyReceiver audioBecomingNoisyReceiver; private final Handler progressHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_PROGRESS: if (player != null && player.getPlaybackState() == ExoPlayer.STATE_READY && player.getPlayWhenReady() ) { long pos = player.getCurrentPosition(); eventEmitter.progressChanged(pos, player.getBufferedPercentage()); msg = obtainMessage(SHOW_PROGRESS); sendMessageDelayed(msg, Math.round(mProgressUpdateInterval)); } break; } } }; public ReactExoplayerView(ThemedReactContext context) { super(context); this.themedReactContext = context; createViews(); this.eventEmitter = new VideoEventEmitter(context); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); themedReactContext.addLifecycleEventListener(this); audioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(themedReactContext); initializePlayer(); } @Override public void setId(int id) { super.setId(id); eventEmitter.setViewId(id); } private void createViews() { clearResumePosition(); mediaDataSourceFactory = buildDataSourceFactory(true); mainHandler = new Handler(); if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) { CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER); } LayoutParams layoutParams = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); exoPlayerView = new ExoPlayerView(getContext()); exoPlayerView.setLayoutParams(layoutParams); addView(exoPlayerView, 0, layoutParams); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initializePlayer(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); stopPlayback(); } // LifecycleEventListener implementation @Override public void onHostResume() { if (playInBackground) { return; } setPlayWhenReady(!isPaused); } @Override public void onHostPause() { if (playInBackground) { return; } setPlayWhenReady(false); } @Override public void onHostDestroy() { stopPlayback(); } public void cleanUpResources() { stopPlayback(); } // Internal methods private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); setPlayWhenReady(!isPaused); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } } private MediaSource buildMediaSource(Uri uri, String overrideExtension) { int type = Util.inferContentType(!TextUtils.isEmpty(overrideExtension) ? "." + overrideExtension : uri.getLastPathSegment()); switch (type) { case C.TYPE_SS: return new SsMediaSource(uri, buildDataSourceFactory(false), new DefaultSsChunkSource.Factory(mediaDataSourceFactory), mainHandler, null); case C.TYPE_DASH: return new DashMediaSource(uri, buildDataSourceFactory(false), new DefaultDashChunkSource.Factory(mediaDataSourceFactory), mainHandler, null); case C.TYPE_HLS: return new HlsMediaSource(uri, mediaDataSourceFactory, mainHandler, null); case C.TYPE_OTHER: return new ExtractorMediaSource(uri, mediaDataSourceFactory, new DefaultExtractorsFactory(), mainHandler, null); default: { throw new IllegalStateException("Unsupported type: " + type); } } } private void releasePlayer() { if (player != null) { isPaused = player.getPlayWhenReady(); updateResumePosition(); player.release(); player.setMetadataOutput(null); player = null; trackSelector = null; } progressHandler.removeMessages(SHOW_PROGRESS); themedReactContext.removeLifecycleEventListener(this); audioBecomingNoisyReceiver.removeListener(); } private boolean requestAudioFocus() { if (disableFocus) { return true; } int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } private void setPlayWhenReady(boolean playWhenReady) { if (player == null) { return; } if (playWhenReady) { boolean hasAudioFocus = requestAudioFocus(); if (hasAudioFocus) { player.setPlayWhenReady(true); } } else { player.setPlayWhenReady(false); } } private void startPlayback() { if (player != null) { switch (player.getPlaybackState()) { case ExoPlayer.STATE_IDLE: case ExoPlayer.STATE_ENDED: initializePlayer(); break; case ExoPlayer.STATE_BUFFERING: case ExoPlayer.STATE_READY: if (!player.getPlayWhenReady()) { setPlayWhenReady(true); } break; default: break; } } else { initializePlayer(); } if (!disableFocus) { setKeepScreenOn(true); } } private void pausePlayback() { if (player != null) { if (player.getPlayWhenReady()) { setPlayWhenReady(false); } } setKeepScreenOn(false); } private void stopPlayback() { onStopPlayback(); releasePlayer(); } private void onStopPlayback() { setKeepScreenOn(false); audioManager.abandonAudioFocus(this); } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void clearResumePosition() { resumeWindow = C.INDEX_UNSET; resumePosition = C.TIME_UNSET; } /** * Returns a new DataSource factory. * * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new * DataSource factory. * @return A new DataSource factory. */ private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) { return DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, useBandwidthMeter ? BANDWIDTH_METER : null); } // AudioManager.OnAudioFocusChangeListener implementation @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS: eventEmitter.audioFocusChanged(false); break; case AudioManager.AUDIOFOCUS_GAIN: eventEmitter.audioFocusChanged(true); break; default: break; } if (player != null) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // Lower the volume player.setVolume(0.8f); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // Raise it back to normal player.setVolume(1); } } } // AudioBecomingNoisyListener implementation @Override public void onAudioBecomingNoisy() { eventEmitter.audioBecomingNoisy(); } // ExoPlayer.EventListener implementation @Override public void onLoadingChanged(boolean isLoading) { // Do nothing. } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { String text = "onStateChanged: playWhenReady=" + playWhenReady + ", playbackState="; switch (playbackState) { case ExoPlayer.STATE_IDLE: text += "idle"; eventEmitter.idle(); break; case ExoPlayer.STATE_BUFFERING: text += "buffering"; onBuffering(true); break; case ExoPlayer.STATE_READY: text += "ready"; eventEmitter.ready(); onBuffering(false); startProgressHandler(); videoLoaded(); break; case ExoPlayer.STATE_ENDED: text += "ended"; eventEmitter.end(); onStopPlayback(); break; default: text += "unknown"; break; } Log.d(TAG, text); } private void startProgressHandler() { progressHandler.sendEmptyMessage(SHOW_PROGRESS); } private void videoLoaded() { if (loadVideoStarted) { loadVideoStarted = false; Format videoFormat = player.getVideoFormat(); int width = videoFormat != null ? videoFormat.width : 0; int height = videoFormat != null ? videoFormat.height : 0; eventEmitter.load(player.getDuration(), player.getCurrentPosition(), width, height); } } private void onBuffering(boolean buffering) { if (isBuffering == buffering) { return; } isBuffering = buffering; if (buffering) { eventEmitter.buffering(true); } else { eventEmitter.buffering(false); } } @Override public void onPositionDiscontinuity() { if (playerNeedsSource) { // This will only occur if the user has performed a seek whilst in the error state. Update the // resume position so that if the user then retries, playback will resume from the position to // which they seeked. updateResumePosition(); } } @Override public void onTimelineChanged(Timeline timeline, Object manifest) { // Do nothing. } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // Do Nothing. } @Override public void onPlaybackParametersChanged(PlaybackParameters params) { eventEmitter.playbackRateChange(params.speed); } @Override public void onPlayerError(ExoPlaybackException e) { String errorString = null; Exception ex = e; if (e.type == ExoPlaybackException.TYPE_RENDERER) { Exception cause = e.getRendererException(); if (cause instanceof MediaCodecRenderer.DecoderInitializationException) { // Special case for decoder initialization failures. MediaCodecRenderer.DecoderInitializationException decoderInitializationException = (MediaCodecRenderer.DecoderInitializationException) cause; if (decoderInitializationException.decoderName == null) { if (decoderInitializationException.getCause() instanceof MediaCodecUtil.DecoderQueryException) { errorString = getResources().getString(R.string.error_querying_decoders); } else if (decoderInitializationException.secureDecoderRequired) { errorString = getResources().getString(R.string.error_no_secure_decoder, decoderInitializationException.mimeType); } else { errorString = getResources().getString(R.string.error_no_decoder, decoderInitializationException.mimeType); } } else { errorString = getResources().getString(R.string.error_instantiating_decoder, decoderInitializationException.decoderName); } } } else if (e.type == ExoPlaybackException.TYPE_SOURCE) { ex = e.getSourceException(); errorString = getResources().getString(R.string.unrecognized_media_format); } if (errorString != null) { eventEmitter.error(errorString, ex); } playerNeedsSource = true; if (isBehindLiveWindow(e)) { clearResumePosition(); initializePlayer(); } else { updateResumePosition(); } } private static boolean isBehindLiveWindow(ExoPlaybackException e) { if (e.type != ExoPlaybackException.TYPE_SOURCE) { return false; } Throwable cause = e.getSourceException(); while (cause != null) { if (cause instanceof BehindLiveWindowException) { return true; } cause = cause.getCause(); } return false; } @Override public void onMetadata(Metadata metadata) { eventEmitter.timedMetadata(metadata); } // ReactExoplayerViewManager public api public void setSrc(final Uri uri, final String extension) { if (uri != null) { boolean isOriginalSourceNull = srcUri == null; boolean isSourceEqual = uri.equals(srcUri); this.srcUri = uri; this.extension = extension; this.mediaDataSourceFactory = DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, BANDWIDTH_METER); if (!isOriginalSourceNull && !isSourceEqual) { reloadSource(); } } } public void setProgressUpdateInterval(final float progressUpdateInterval) { mProgressUpdateInterval = progressUpdateInterval; } public void setRawSrc(final Uri uri, final String extension) { if (uri != null) { boolean isOriginalSourceNull = srcUri == null; boolean isSourceEqual = uri.equals(srcUri); this.srcUri = uri; this.extension = extension; this.mediaDataSourceFactory = DataSourceUtil.getRawDataSourceFactory(this.themedReactContext); if (!isOriginalSourceNull && !isSourceEqual) { reloadSource(); } } } private void reloadSource() { playerNeedsSource = true; initializePlayer(); } public void setResizeModeModifier(@ResizeMode.Mode int resizeMode) { exoPlayerView.setResizeMode(resizeMode); } public void setRepeatModifier(boolean repeat) { this.repeat = repeat; } public void setPausedModifier(boolean paused) { isPaused = paused; if (player != null) { if (!paused) { startPlayback(); } else { pausePlayback(); } } } public void setMutedModifier(boolean muted) { if (player != null) { player.setVolume(muted ? 0 : 1); } } public void setVolumeModifier(float volume) { if (player != null) { player.setVolume(volume); } } public void seekTo(long positionMs) { if (player != null) { eventEmitter.seek(player.getCurrentPosition(), positionMs); player.seekTo(positionMs); } } public void setRateModifier(float newRate) { rate = newRate; if (player != null) { PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } } public void setPlayInBackground(boolean playInBackground) { this.playInBackground = playInBackground; } public void setDisableFocus(boolean disableFocus) { this.disableFocus = disableFocus; } }
android-exoplayer/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java
package com.brentvatne.exoplayer; import android.annotation.SuppressLint; import android.content.Context; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.widget.FrameLayout; import com.brentvatne.react.R; import com.brentvatne.receiver.AudioBecomingNoisyReceiver; import com.brentvatne.receiver.BecomingNoisyListener; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.uimanager.ThemedReactContext; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer; import com.google.android.exoplayer2.mediacodec.MediaCodecUtil; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.MetadataRenderer; import com.google.android.exoplayer2.source.BehindLiveWindowException; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.LoopingMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.dash.DashMediaSource; import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource; import com.google.android.exoplayer2.source.hls.HlsMediaSource; import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource; import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.MappingTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.util.Util; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.lang.Math; @SuppressLint("ViewConstructor") class ReactExoplayerView extends FrameLayout implements LifecycleEventListener, ExoPlayer.EventListener, BecomingNoisyListener, AudioManager.OnAudioFocusChangeListener, MetadataRenderer.Output { private static final String TAG = "ReactExoplayerView"; private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter(); private static final CookieManager DEFAULT_COOKIE_MANAGER; private static final int SHOW_PROGRESS = 1; static { DEFAULT_COOKIE_MANAGER = new CookieManager(); DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER); } private final VideoEventEmitter eventEmitter; private Handler mainHandler; private ExoPlayerView exoPlayerView; private DataSource.Factory mediaDataSourceFactory; private SimpleExoPlayer player; private MappingTrackSelector trackSelector; private boolean playerNeedsSource; private int resumeWindow; private long resumePosition; private boolean loadVideoStarted; private boolean isPaused = true; private boolean isBuffering; private float rate = 1f; // Props from React private Uri srcUri; private String extension; private boolean repeat; private boolean disableFocus; private float mProgressUpdateInterval = 250.0f; private boolean playInBackground = false; // \ End props // React private final ThemedReactContext themedReactContext; private final AudioManager audioManager; private final AudioBecomingNoisyReceiver audioBecomingNoisyReceiver; private final Handler progressHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_PROGRESS: if (player != null && player.getPlaybackState() == ExoPlayer.STATE_READY && player.getPlayWhenReady() ) { long pos = player.getCurrentPosition(); eventEmitter.progressChanged(pos, player.getBufferedPercentage()); msg = obtainMessage(SHOW_PROGRESS); sendMessageDelayed(msg, Math.round(mProgressUpdateInterval)); } break; } } }; public ReactExoplayerView(ThemedReactContext context) { super(context); this.themedReactContext = context; createViews(); this.eventEmitter = new VideoEventEmitter(context); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); themedReactContext.addLifecycleEventListener(this); audioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(themedReactContext); initializePlayer(); } @Override public void setId(int id) { super.setId(id); eventEmitter.setViewId(id); } private void createViews() { clearResumePosition(); mediaDataSourceFactory = buildDataSourceFactory(true); mainHandler = new Handler(); if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) { CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER); } LayoutParams layoutParams = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); exoPlayerView = new ExoPlayerView(getContext()); exoPlayerView.setLayoutParams(layoutParams); addView(exoPlayerView, 0, layoutParams); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initializePlayer(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); stopPlayback(); } // LifecycleEventListener implementation @Override public void onHostResume() { if (playInBackground) { return; } setPlayWhenReady(!isPaused); } @Override public void onHostPause() { if (playInBackground) { return; } setPlayWhenReady(false); } @Override public void onHostDestroy() { stopPlayback(); } public void cleanUpResources() { stopPlayback(); } // Internal methods private void initializePlayer() { if (player == null) { TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER); trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, new DefaultLoadControl()); player.addListener(this); player.setMetadataOutput(this); exoPlayerView.setPlayer(player); audioBecomingNoisyReceiver.setListener(this); setPlayWhenReady(!isPaused); playerNeedsSource = true; PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } if (playerNeedsSource && srcUri != null) { MediaSource mediaSource = buildMediaSource(srcUri, extension); mediaSource = repeat ? new LoopingMediaSource(mediaSource) : mediaSource; boolean haveResumePosition = resumeWindow != C.INDEX_UNSET; if (haveResumePosition) { player.seekTo(resumeWindow, resumePosition); } player.prepare(mediaSource, !haveResumePosition, false); playerNeedsSource = false; eventEmitter.loadStart(); loadVideoStarted = true; } } private MediaSource buildMediaSource(Uri uri, String overrideExtension) { int type = Util.inferContentType(!TextUtils.isEmpty(overrideExtension) ? "." + overrideExtension : uri.getLastPathSegment()); switch (type) { case C.TYPE_SS: return new SsMediaSource(uri, buildDataSourceFactory(false), new DefaultSsChunkSource.Factory(mediaDataSourceFactory), mainHandler, null); case C.TYPE_DASH: return new DashMediaSource(uri, buildDataSourceFactory(false), new DefaultDashChunkSource.Factory(mediaDataSourceFactory), mainHandler, null); case C.TYPE_HLS: return new HlsMediaSource(uri, mediaDataSourceFactory, mainHandler, null); case C.TYPE_OTHER: return new ExtractorMediaSource(uri, mediaDataSourceFactory, new DefaultExtractorsFactory(), mainHandler, null); default: { throw new IllegalStateException("Unsupported type: " + type); } } } private void releasePlayer() { if (player != null) { isPaused = player.getPlayWhenReady(); updateResumePosition(); player.release(); player.setMetadataOutput(null); player = null; trackSelector = null; } progressHandler.removeMessages(SHOW_PROGRESS); themedReactContext.removeLifecycleEventListener(this); audioBecomingNoisyReceiver.removeListener(); } private boolean requestAudioFocus() { if (disableFocus) { return true; } int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } private void setPlayWhenReady(boolean playWhenReady) { if (player == null) { return; } if (playWhenReady) { boolean hasAudioFocus = requestAudioFocus(); if (hasAudioFocus) { player.setPlayWhenReady(true); } } else { player.setPlayWhenReady(false); } } private void startPlayback() { if (player != null) { switch (player.getPlaybackState()) { case ExoPlayer.STATE_IDLE: case ExoPlayer.STATE_ENDED: initializePlayer(); break; case ExoPlayer.STATE_BUFFERING: case ExoPlayer.STATE_READY: if (!player.getPlayWhenReady()) { setPlayWhenReady(true); } break; default: break; } } else { initializePlayer(); } if (!disableFocus) { setKeepScreenOn(true); } } private void pausePlayback() { if (player != null) { if (player.getPlayWhenReady()) { setPlayWhenReady(false); } } setKeepScreenOn(false); } private void stopPlayback() { onStopPlayback(); releasePlayer(); } private void onStopPlayback() { setKeepScreenOn(false); audioManager.abandonAudioFocus(this); } private void updateResumePosition() { resumeWindow = player.getCurrentWindowIndex(); resumePosition = player.isCurrentWindowSeekable() ? Math.max(0, player.getCurrentPosition()) : C.TIME_UNSET; } private void clearResumePosition() { resumeWindow = C.INDEX_UNSET; resumePosition = C.TIME_UNSET; } /** * Returns a new DataSource factory. * * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new * DataSource factory. * @return A new DataSource factory. */ private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) { return DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, useBandwidthMeter ? BANDWIDTH_METER : null); } // AudioManager.OnAudioFocusChangeListener implementation @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS: eventEmitter.audioFocusChanged(false); break; case AudioManager.AUDIOFOCUS_GAIN: eventEmitter.audioFocusChanged(true); break; default: break; } if (player != null) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // Lower the volume player.setVolume(0.8f); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // Raise it back to normal player.setVolume(1); } } } // AudioBecomingNoisyListener implementation @Override public void onAudioBecomingNoisy() { eventEmitter.audioBecomingNoisy(); } // ExoPlayer.EventListener implementation @Override public void onLoadingChanged(boolean isLoading) { // Do nothing. } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { String text = "onStateChanged: playWhenReady=" + playWhenReady + ", playbackState="; switch (playbackState) { case ExoPlayer.STATE_IDLE: text += "idle"; eventEmitter.idle(); break; case ExoPlayer.STATE_BUFFERING: text += "buffering"; onBuffering(true); break; case ExoPlayer.STATE_READY: text += "ready"; eventEmitter.ready(); onBuffering(false); startProgressHandler(); videoLoaded(); break; case ExoPlayer.STATE_ENDED: text += "ended"; eventEmitter.end(); onStopPlayback(); break; default: text += "unknown"; break; } Log.d(TAG, text); } private void startProgressHandler() { progressHandler.sendEmptyMessage(SHOW_PROGRESS); } private void videoLoaded() { if (loadVideoStarted) { loadVideoStarted = false; Format videoFormat = player.getVideoFormat(); int width = videoFormat != null ? videoFormat.width : 0; int height = videoFormat != null ? videoFormat.height : 0; eventEmitter.load(player.getDuration(), player.getCurrentPosition(), width, height); } } private void onBuffering(boolean buffering) { if (isBuffering == buffering) { return; } isBuffering = buffering; if (buffering) { eventEmitter.buffering(true); } else { eventEmitter.buffering(false); } } @Override public void onPositionDiscontinuity() { if (playerNeedsSource) { // This will only occur if the user has performed a seek whilst in the error state. Update the // resume position so that if the user then retries, playback will resume from the position to // which they seeked. updateResumePosition(); } } @Override public void onTimelineChanged(Timeline timeline, Object manifest) { // Do nothing. } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { // Do Nothing. } @Override public void onPlaybackParametersChanged(PlaybackParameters params) { eventEmitter.playbackRateChange(params.speed); } @Override public void onPlayerError(ExoPlaybackException e) { String errorString = null; Exception ex = e; if (e.type == ExoPlaybackException.TYPE_RENDERER) { Exception cause = e.getRendererException(); if (cause instanceof MediaCodecRenderer.DecoderInitializationException) { // Special case for decoder initialization failures. MediaCodecRenderer.DecoderInitializationException decoderInitializationException = (MediaCodecRenderer.DecoderInitializationException) cause; if (decoderInitializationException.decoderName == null) { if (decoderInitializationException.getCause() instanceof MediaCodecUtil.DecoderQueryException) { errorString = getResources().getString(R.string.error_querying_decoders); } else if (decoderInitializationException.secureDecoderRequired) { errorString = getResources().getString(R.string.error_no_secure_decoder, decoderInitializationException.mimeType); } else { errorString = getResources().getString(R.string.error_no_decoder, decoderInitializationException.mimeType); } } else { errorString = getResources().getString(R.string.error_instantiating_decoder, decoderInitializationException.decoderName); } } } else if (e.type == ExoPlaybackException.TYPE_SOURCE) { ex = e.getSourceException(); errorString = getResources().getString(R.string.unrecognized_media_format); } if (errorString != null) { eventEmitter.error(errorString, ex); } playerNeedsSource = true; if (isBehindLiveWindow(e)) { clearResumePosition(); initializePlayer(); } else { updateResumePosition(); } } private static boolean isBehindLiveWindow(ExoPlaybackException e) { if (e.type != ExoPlaybackException.TYPE_SOURCE) { return false; } Throwable cause = e.getSourceException(); while (cause != null) { if (cause instanceof BehindLiveWindowException) { return true; } cause = cause.getCause(); } return false; } @Override public void onMetadata(Metadata metadata) { eventEmitter.timedMetadata(metadata); } // ReactExoplayerViewManager public api public void setSrc(final Uri uri, final String extension) { if (uri != null) { boolean isOriginalSourceNull = srcUri == null; boolean isSourceEqual = uri.equals(srcUri); this.srcUri = uri; this.extension = extension; this.mediaDataSourceFactory = DataSourceUtil.getDefaultDataSourceFactory(this.themedReactContext, BANDWIDTH_METER); if (!isOriginalSourceNull && !isSourceEqual) { reloadSource(); } } } public void setProgressUpdateInterval(final float progressUpdateInterval) { mProgressUpdateInterval = progressUpdateInterval; } public void setRawSrc(final Uri uri, final String extension) { if (uri != null) { boolean isOriginalSourceNull = srcUri == null; boolean isSourceEqual = uri.equals(srcUri); this.srcUri = uri; this.extension = extension; this.mediaDataSourceFactory = DataSourceUtil.getRawDataSourceFactory(this.themedReactContext); if (!isOriginalSourceNull && !isSourceEqual) { reloadSource(); } } } private void reloadSource() { playerNeedsSource = true; initializePlayer(); } public void setResizeModeModifier(@ResizeMode.Mode int resizeMode) { exoPlayerView.setResizeMode(resizeMode); } public void setRepeatModifier(boolean repeat) { this.repeat = repeat; } public void setPausedModifier(boolean paused) { isPaused = paused; if (player != null) { if (!paused) { startPlayback(); } else { pausePlayback(); } } } public void setMutedModifier(boolean muted) { if (player != null) { player.setVolume(muted ? 0 : 1); } } public void setVolumeModifier(float volume) { if (player != null) { player.setVolume(volume); } } public void seekTo(long positionMs) { if (player != null) { eventEmitter.seek(player.getCurrentPosition(), positionMs); player.seekTo(positionMs); } } public void setRateModifier(float newRate) { rate = newRate; if (player != null) { PlaybackParameters params = new PlaybackParameters(rate, 1f); player.setPlaybackParameters(params); } } public void setPlayInBackground(boolean playInBackground) { this.playInBackground = playInBackground; } public void setDisableFocus(boolean disableFocus) { this.disableFocus = disableFocus; } }
Minor formatting cleanups Fix spacing
android-exoplayer/src/main/java/com/brentvatne/exoplayer/ReactExoplayerView.java
Minor formatting cleanups
Java
mit
33a148f1781f5aedc6302af290b49cd7379fc7f8
0
Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial,Ronneesley/redesocial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.redesocial.modelo.dao; import br.com.redesocial.modelo.dto.Multimidia; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /** * * @author Lara */ public class MultimidiaDAO extends DAOBase { /* METÓDO PARA CONECTAR AO BANCO DE DADOS*/ public void inserir( Multimidia dto ) throws Exception { Connection conexao = getConexao(); if (dto.getDescricao().trim().equals("")){ throw new Exception("A descrição não pode estar vazia!"); } PreparedStatement pstmt; pstmt = conexao.prepareStatement("insert into posts(descricao, autor) values(?, ?)"); pstmt.setString(1, dto.getDescricao()); pstmt.setString(2, dto.getAutor()); pstmt.executeUpdate(); } public void excluir(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("delete from multimidia where id = ?"); pstmt.setInt(1, id); pstmt.executeUpdate(); } }
codigo/RedeSocial/src/br/com/redesocial/modelo/dao/MultimidiaDAO.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.redesocial.modelo.dao; import java.sql.Connection; import java.sql.PreparedStatement; /** * * @author Lara */ public class MultimidiaDAO { /* METÓDO PARA CONECTAR AO BANCO DE DADOS*/ private Connection getConexao() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void excluir(int id) throws Exception { Connection conexao = getConexao(); PreparedStatement pstmt; pstmt = conexao.prepareStatement("delete from multimidia where id = ?"); pstmt.setInt(1, id); pstmt.executeUpdate(); } }
Implementação Metodo Inserir Multimidia
codigo/RedeSocial/src/br/com/redesocial/modelo/dao/MultimidiaDAO.java
Implementação Metodo Inserir Multimidia
Java
mit
a5721c5c2b76ec9eeb33ab04262b2d42ba0cf58a
0
etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler,irudyak/statsd-jvm-profiler,etsy/statsd-jvm-profiler,etsy/statsd-jvm-profiler,jasonchaffee/statsd-jvm-profiler,irudyak/statsd-jvm-profiler,jasonchaffee/statsd-jvm-profiler,danosipov/statsd-jvm-profiler,danosipov/statsd-jvm-profiler,danosipov/statsd-jvm-profiler,jasonchaffee/statsd-jvm-profiler,jasonchaffee/statsd-jvm-profiler,danosipov/statsd-jvm-profiler,irudyak/statsd-jvm-profiler,etsy/statsd-jvm-profiler,irudyak/statsd-jvm-profiler
package com.etsy.profiler.memory; import com.etsy.profiler.Profiler; import com.timgroup.statsd.StatsDClient; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.util.List; /** * Profiles memory usage and GC statistics * * @author Andrew Johnson */ public class MemoryProfiler implements Profiler { private StatsDClient client; private MemoryMXBean memoryMXBean; private List<GarbageCollectorMXBean> gcMXBeans; public MemoryProfiler(StatsDClient client) { this.client = client; memoryMXBean = ManagementFactory.getMemoryMXBean(); gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); } /** * Profile memory usage and GC statistics */ @Override public void profile() { int finalizationPendingCount = memoryMXBean.getObjectPendingFinalizationCount(); MemoryUsage heap = memoryMXBean.getHeapMemoryUsage(); MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage(); client.recordGaugeValue("pending-finalization-count", finalizationPendingCount); recordMemoryUsage("heap", heap); recordMemoryUsage("nonheap", nonHeap); for (GarbageCollectorMXBean gcMXBean : gcMXBeans) { client.recordGaugeValue("gc." + gcMXBean.getName() + ".count", gcMXBean.getCollectionCount()); client.recordGaugeValue("gc." + gcMXBean.getName() + ".time", gcMXBean.getCollectionTime()); } } /** * Records memory usage * * @param prefix The prefix to use for this object * @param memory The MemoryUsage object containing the memory usage info */ private void recordMemoryUsage(String prefix, MemoryUsage memory) { client.recordGaugeValue(prefix + ".init", memory.getInit()); client.recordGaugeValue(prefix + ".used", memory.getUsed()); client.recordGaugeValue(prefix + ".committed", memory.getCommitted()); client.recordGaugeValue(prefix + ".max", memory.getMax()); } }
src/main/java/com/etsy/profiler/memory/MemoryProfiler.java
package com.etsy.profiler.memory; import com.etsy.profiler.Profiler; import com.timgroup.statsd.StatsDClient; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.util.List; /** * Profiles memory usage and GC statistics * * @author Andrew Johnson */ public class MemoryProfiler implements Profiler { private StatsDClient client; private MemoryMXBean memoryMXBean; private List<GarbageCollectorMXBean> gcMXBeans; public MemoryProfiler(StatsDClient client) { this.client = client; memoryMXBean = ManagementFactory.getMemoryMXBean(); gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); } @Override /** * Profile memory usage and GC statistics */ public void profile() { int finalizationPendingCount = memoryMXBean.getObjectPendingFinalizationCount(); MemoryUsage heap = memoryMXBean.getHeapMemoryUsage(); MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage(); client.recordGaugeValue("pending-finalization-count", finalizationPendingCount); recordMemoryUsage("heap", heap); recordMemoryUsage("nonheap", nonHeap); for (GarbageCollectorMXBean gcMXBean : gcMXBeans) { client.recordGaugeValue("gc." + gcMXBean.getName() + ".count", gcMXBean.getCollectionCount()); client.recordGaugeValue("gc." + gcMXBean.getName() + ".time", gcMXBean.getCollectionTime()); } } /** * Records memory usage * * @param prefix The prefix to use for this object * @param memory The MemoryUsage object containing the memory usage info */ private void recordMemoryUsage(String prefix, MemoryUsage memory) { client.recordGaugeValue(prefix + ".init", memory.getInit()); client.recordGaugeValue(prefix + ".used", memory.getUsed()); client.recordGaugeValue(prefix + ".committed", memory.getCommitted()); client.recordGaugeValue(prefix + ".max", memory.getMax()); } }
Minor
src/main/java/com/etsy/profiler/memory/MemoryProfiler.java
Minor
Java
epl-1.0
9fdf6d246f20ef5b5f94df0df0a85cdfba153eb9
0
Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.device.swt; import org.eclipse.birt.chart.computation.BoundingBox; import org.eclipse.birt.chart.computation.IConstants; import org.eclipse.birt.chart.computation.Methods; import org.eclipse.birt.chart.computation.RotatedRectangle; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IPrimitiveRenderer; import org.eclipse.birt.chart.device.ITextMetrics; import org.eclipse.birt.chart.device.swt.i18n.Messages; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.attribute.AttributeFactory; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.FontDefinition; import org.eclipse.birt.chart.model.attribute.HorizontalAlignment; import org.eclipse.birt.chart.model.attribute.Insets; import org.eclipse.birt.chart.model.attribute.LineAttributes; import org.eclipse.birt.chart.model.attribute.LineStyle; import org.eclipse.birt.chart.model.attribute.Location; import org.eclipse.birt.chart.model.attribute.Text; import org.eclipse.birt.chart.model.attribute.TextAlignment; import org.eclipse.birt.chart.model.attribute.VerticalAlignment; import org.eclipse.birt.chart.model.attribute.impl.LocationImpl; import org.eclipse.birt.chart.model.component.Label; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.Rectangle; /** * Contains useful methods for rendering text on an SWT graphics context */ final class SwtTextRenderer implements IConstants { /** * */ private static final PaletteData PALETTE_DATA = new PaletteData( 0xFF0000, 0xFF00, 0xFF ); /** * */ private static final int TRANSPARENT_COLOR = 0x123456; /** * */ private static SwtTextRenderer _tr = null; private SwtDisplayServer _sxs = null; private static final int SHADOW_THICKNESS = 3; /** * */ private SwtTextRenderer( ) { } /** * * @return */ public synchronized static final SwtTextRenderer instance( SwtDisplayServer sxs ) { if ( _tr == null ) { _tr = new SwtTextRenderer( ); _tr._sxs = sxs; } return _tr; } /** * This method renders the 'shadow' at an offset from the text 'rotated * rectangle' subsequently rendered. * * @param ipr * @param iLabelPosition * The position of the label w.r.t. the location specified by * 'lo' * @param lo * The location (specified as a 2d point) where the text is to be * rendered * @param la * The chart model structure containing the encapsulated text * (and attributes) to be rendered */ public final void renderShadowAtLocation( IPrimitiveRenderer ipr, int iLabelPosition, // IConstants. LEFT, RIGHT, ABOVE or BELOW Location lo, // POINT WHERE THE CORNER OF THE ROTATED RECTANGLE // (OR EDGE CENTERED) IS RENDERED Label la ) throws ChartException { if ( !ChartUtil.isShadowDefined( la ) ) { return; } final ColorDefinition cdShadow = la.getShadowColor( ); if ( cdShadow == null ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, "SwtTextRenderer.exception.undefined.shadow.color", //$NON-NLS-1$ Messages.getResourceBundle( _sxs.getULocale( ) ) ); } switch ( iLabelPosition ) { case ABOVE : showTopValue( ipr, lo, la, false ); break; case BELOW : showBottomValue( ipr, lo, la, false ); break; case LEFT : showLeftValue( ipr, lo, la, false ); break; case RIGHT : showRightValue( ipr, lo, la, false ); break; } } /** * @param ipr * @param lo * @param la * @param b */ private void showRightValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showLeftValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showBottomValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showTopValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { GC gc = (GC) ( (IDeviceRenderer) ipr ).getGraphicsContext( ); double dX = lo.getX( ), dY = lo.getY( ); final FontDefinition fd = la.getCaption( ).getFont( ); final double dAngleInDegrees = fd.getRotation( ); final double dAngleInRadians = Math.toRadians( dAngleInDegrees ); final Color clrBackground = (Color) _sxs.getColor( la.getShadowColor( ) ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dFH = itm.getFullHeight( ); double scaledThickness = SHADOW_THICKNESS * _sxs.getDpiResolution( ) / 72d; gc.setBackground( clrBackground ); R31Enhance.setAlpha( gc, la.getShadowColor( ) ); // HORIZONTAL TEXT if ( dAngleInDegrees == 0 ) { gc.fillRectangle( (int) ( dX + scaledThickness ), (int) ( dY + scaledThickness ), (int) dFW, (int) dFH ); } // TEXT AT POSITIVE ANGLE < 90 (TOP RIGHT HIGHER THAN TOP LEFT CORNER) else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 ) { /** * y = kx + a; (x-x0)^2 + (y-y0)^2 = 2t^2 */ double k = Math.tan( dAngleInRadians - Math.PI / 4d ); double a = dY - k * dX; double k21 = k * k + 1; double A = 2 * scaledThickness * scaledThickness / k21 - ( ( a - dY ) * ( a - dY ) + dX * dX ) / k21 + ( ( k * a - k * dY - dX ) / k21 ) * ( ( k * a - k * dY - dX ) / k21 ); double sqa = Math.sqrt( A ); double ax = ( ( k * a - k * dY - dX ) / k21 ); double xx1 = sqa - ax; double yy1 = k * xx1 + a; double xx2 = -sqa - ax; double yy2 = k * xx2 + a; if ( xx1 > dX ) { dX = xx1; dY = yy1; } else { dX = xx2; dY = yy2; } int[] iPolyCoordinates = new int[8]; // BLC iPolyCoordinates[0] = (int) dX; iPolyCoordinates[1] = (int) dY; // BRC iPolyCoordinates[2] = (int) ( dX + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[3] = (int) ( dY - dFW * Math.sin( dAngleInRadians ) ); // TRC iPolyCoordinates[4] = (int) ( dX + dFH * Math.sin( dAngleInRadians ) + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[5] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) - dFW * Math.sin( dAngleInRadians ) ); // TLC iPolyCoordinates[6] = (int) ( dX + dFH * Math.sin( dAngleInRadians ) ); iPolyCoordinates[7] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) ); // RENDER IT gc.fillPolygon( iPolyCoordinates ); } // TEXT AT NEGATIVE ANGLE > -90 (TOP RIGHT LOWER THAN TOP LEFT CORNER) else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 ) { /** * y = kx + a; (x-x0)^2 + (y-y0)^2 = 2t^2 */ double k = Math.tan( dAngleInRadians - Math.PI / 4d ); double a = dY - k * dX; double k21 = k * k + 1; double A = 2 * scaledThickness * scaledThickness / k21 - ( ( a - dY ) * ( a - dY ) + dX * dX ) / k21 + ( ( k * a - k * dY - dX ) / k21 ) * ( ( k * a - k * dY - dX ) / k21 ); double sqa = Math.sqrt( A ); double ax = ( ( k * a - k * dY - dX ) / k21 ); double xx1 = sqa - ax; double yy1 = k * xx1 + a; double xx2 = -sqa - ax; double yy2 = k * xx2 + a; if ( yy1 > dY ) { dX = xx1; dY = yy1; } else { dX = xx2; dY = yy2; } int[] iPolyCoordinates = new int[8]; // BLC iPolyCoordinates[0] = (int) dX; iPolyCoordinates[1] = (int) dY; // BRC iPolyCoordinates[2] = (int) ( dX + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[3] = (int) ( dY + dFW * Math.abs( Math.sin( dAngleInRadians ) ) ); // TRC iPolyCoordinates[4] = (int) ( dX - dFH * Math.abs( Math.sin( dAngleInRadians ) ) + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[5] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) + dFW * Math.abs( Math.sin( dAngleInRadians ) ) ); // TLC iPolyCoordinates[6] = (int) ( dX - dFH * Math.abs( Math.sin( dAngleInRadians ) ) ); iPolyCoordinates[7] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) ); // RENDER IT gc.fillPolygon( iPolyCoordinates ); } // TEXT AT POSITIVE 90 (TOP RIGHT HIGHER THAN TOP LEFT CORNER) else if ( dAngleInDegrees == 90 ) { gc.fillRectangle( (int) ( dX + scaledThickness ), (int) ( dY - dFW - scaledThickness ), (int) dFH, (int) dFW ); } // TEXT AT NEGATIVE 90 (TOP RIGHT LOWER THAN TOP LEFT CORNER) else if ( dAngleInDegrees == -90 ) { gc.fillRectangle( (int) ( dX - dFH - scaledThickness ), (int) ( dY + scaledThickness ), (int) dFH, (int) dFW ); } } /** * * @param ipr * @param iLabelPosition * @param lo * @param la * @throws RenderingException */ public final void renderTextAtLocation( IPrimitiveRenderer idr, int iLabelPosition, // IConstants. LEFT, RIGHT, ABOVE // or BELOW Location lo, // POINT WHERE THE CORNER OF THE ROTATED RECTANGLE // (OR // EDGE CENTERED) IS RENDERED Label la ) throws ChartException { final GC gc = (GC) ( (IDeviceRenderer) idr ).getGraphicsContext( ); BoundingBox bb = null; try { bb = Methods.computeBox( _sxs, iLabelPosition, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } switch ( iLabelPosition ) { case ABOVE : bb.setTop( lo.getY( ) - bb.getHeight( ) ); bb.setLeft( lo.getX( ) - bb.getHotPoint( ) ); break; case BELOW : bb.setTop( lo.getY( ) ); bb.setLeft( lo.getX( ) - bb.getHotPoint( ) ); break; case LEFT : bb.setTop( lo.getY( ) - bb.getHotPoint( ) ); bb.setLeft( lo.getX( ) - bb.getWidth( ) ); break; case RIGHT : bb.setTop( lo.getY( ) - bb.getHotPoint( ) ); bb.setLeft( lo.getX( ) ); break; } // RENDER Shadow around the text label if ( ChartUtil.isShadowDefined( la ) ) { try { final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFH = itm.getFullHeight( ); Location tmpLoc = Methods.computeRotatedTopPoint( _sxs, bb, la, dFH ); renderShadowAtLocation( idr, IConstants.ABOVE, tmpLoc, la ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } } if ( la.getCaption( ).getFont( ).getRotation( ) == 0 || R31Enhance.isR31Available( ) ) { renderHorizontalText( gc, la, bb.getLeft( ), bb.getTop( ) ); } else { final Image imgText = rotatedTextAsImage( la ); gc.drawImage( imgText, (int) bb.getLeft( ), (int) bb.getTop( ) ); imgText.dispose( ); } renderBorder( gc, la, iLabelPosition, lo ); } /** * * @param idr * @param boBlock * @param taBlock * @param la */ public final void renderTextInBlock( IDeviceRenderer idr, Bounds boBlock, TextAlignment taBlock, Label la ) throws ChartException { Text t = la.getCaption( ); String sText = t.getValue( ); ColorDefinition cdText = t.getColor( ); if ( cdText == null ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, "SwtTextRenderer.exception.undefined.text.color", //$NON-NLS-1$ Messages.getResourceBundle( _sxs.getULocale( ) ) ); } final GC gc = (GC) idr.getGraphicsContext( ); la.getCaption( ).setValue( sText ); BoundingBox bb = null; try { bb = Methods.computeBox( _sxs, ABOVE, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } if ( taBlock == null ) { taBlock = AttributeFactory.eINSTANCE.createTextAlignment( ); taBlock.setHorizontalAlignment( HorizontalAlignment.CENTER_LITERAL ); taBlock.setVerticalAlignment( VerticalAlignment.CENTER_LITERAL ); } HorizontalAlignment haBlock = taBlock.getHorizontalAlignment( ); VerticalAlignment vaBlock = taBlock.getVerticalAlignment( ); switch ( haBlock.getValue( ) ) { case HorizontalAlignment.CENTER : bb.setLeft( boBlock.getLeft( ) + ( boBlock.getWidth( ) - bb.getWidth( ) ) / 2 ); break; case HorizontalAlignment.LEFT : bb.setLeft( boBlock.getLeft( ) ); break; case HorizontalAlignment.RIGHT : bb.setLeft( boBlock.getLeft( ) + boBlock.getWidth( ) - bb.getWidth( ) ); break; } switch ( vaBlock.getValue( ) ) { case VerticalAlignment.TOP : bb.setTop( boBlock.getTop( ) ); break; case VerticalAlignment.CENTER : bb.setTop( boBlock.getTop( ) + ( boBlock.getHeight( ) - bb.getHeight( ) ) / 2 ); break; case VerticalAlignment.BOTTOM : bb.setTop( boBlock.getTop( ) + boBlock.getHeight( ) - bb.getHeight( ) ); break; } // RENDER Shadow around the text label if ( ChartUtil.isShadowDefined( la ) ) { try { final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFH = itm.getFullHeight( ); Location tmpLoc = Methods.computeRotatedTopPoint( _sxs, bb, la, dFH ); renderShadowAtLocation( idr, IConstants.ABOVE, tmpLoc, la ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } } if ( la.getCaption( ).getFont( ).getRotation( ) == 0 || R31Enhance.isR31Available( ) ) { renderHorizontalText( gc, la, bb.getLeft( ), bb.getTop( ) ); } else { final Image imgText = rotatedTextAsImage( la ); gc.drawImage( imgText, (int) bb.getLeft( ), (int) bb.getTop( ) ); imgText.dispose( ); } renderBorder( gc, la, IConstants.ABOVE, LocationImpl.create( bb.getLeft( ) + bb.getHotPoint( ), bb.getTop( ) + bb.getHeight( ) ) ); } /** * * @param gc * @param la * @param iLabelLocation * @param lo */ private final void renderBorder( GC gc, Label la, int iLabelLocation, Location lo ) throws ChartException { // RENDER THE OUTLINE/BORDER final LineAttributes lia = la.getOutline( ); if ( lia != null && lia.isVisible( ) && lia.isSetStyle( ) && lia.isSetThickness( ) && lia.getColor( ) != null ) { RotatedRectangle rr = null; try { rr = Methods.computePolygon( _sxs, iLabelLocation, la, lo.getX( ), lo.getY( ) ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } final int iOldLineStyle = gc.getLineStyle( ); final int iOldLineWidth = gc.getLineWidth( ); final Color cFG = (Color) _sxs.getColor( lia.getColor( ) ); gc.setForeground( cFG ); R31Enhance.setAlpha( gc, lia.getColor( ) ); int iLineStyle = SWT.LINE_SOLID; switch ( lia.getStyle( ).getValue( ) ) { case ( LineStyle.DOTTED ) : iLineStyle = SWT.LINE_DOT; break; case ( LineStyle.DASH_DOTTED ) : iLineStyle = SWT.LINE_DASHDOT; break; case ( LineStyle.DASHED ) : iLineStyle = SWT.LINE_DASH; break; } gc.setLineStyle( iLineStyle ); gc.setLineWidth( lia.getThickness( ) ); gc.drawPolygon( rr.getSwtPoints( ) ); gc.setLineStyle( iOldLineStyle ); gc.setLineWidth( iOldLineWidth ); cFG.dispose( ); } } /** * Use this optimized routine for rendering horizontal ONLY text * * @param gc * @param la * @param lo */ private final void renderHorizontalText( GC gc, Label la, double dX, double dY ) { final FontDefinition fd = la.getCaption( ).getFont( ); final Color clrText = (Color) _sxs.getColor( la.getCaption( ) .getColor( ) ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dH = itm.getHeight( ); final double dFH = itm.getFullHeight( ); double dXOffset = 0; double dW = 0; final Insets ins = la.getInsets( ) .scaledInstance( _sxs.getDpiResolution( ) / 72d ); final HorizontalAlignment ha = la.getCaption( ) .getFont( ) .getAlignment( ) .getHorizontalAlignment( ); final boolean bRightAligned = ha.getValue( ) == HorizontalAlignment.RIGHT; final boolean bCenterAligned = ha.getValue( ) == HorizontalAlignment.CENTER; final Rectangle r; Object tr = null; // In Linux-Cairo environment, it uses a cascaded transform setting // policy, not a overriding policy. So we must set a reverse tranforming // again to restore to original state. see bugzilla 137654. // This transform object records the reverse tranforming, which is used // to restore original state. Object rtr = null; if ( R31Enhance.isR31Available( ) ) { r = new Rectangle( 0, 0, (int) dFW, (int) dFH ); tr = R31Enhance.newTransform( _sxs.getDevice( ) ); rtr = R31Enhance.newTransform( _sxs.getDevice( ) ); if ( la.getCaption( ).getFont( ).getRotation( ) != 0 ) { float rotate = (float) la.getCaption( ) .getFont( ) .getRotation( ); double dAngleInRadians = ( ( -rotate * Math.PI ) / 180.0 ); double dSineTheta = Math.sin( dAngleInRadians ); float tTx = (float) ( dX - dFW / 2 ); float tTy = (float) ( dY - dFH / 2 ); if ( rotate > 0 ) tTy += dFW * Math.abs( dSineTheta ); else tTx += dFH * Math.abs( dSineTheta ); R31Enhance.translate( gc, tr, (float) ( dFW / 2 ), (float) ( dFH / 2 ) ); R31Enhance.translate( gc, tr, tTx, tTy ); R31Enhance.rotate( gc, tr, -rotate ); R31Enhance.rotate( gc, rtr, rotate ); R31Enhance.translate( gc, rtr, -tTx, -tTy ); R31Enhance.translate( gc, rtr, (float) ( -dFW / 2 ), (float) ( -dFH / 2 ) ); } else { R31Enhance.translate( gc, tr, (float) dX, (float) dY ); R31Enhance.translate( gc, rtr, (float) -dX, (float) -dY ); } R31Enhance.setTransform( gc, tr ); } else { r = new Rectangle( (int) dX, (int) dY, (int) dFW, (int) dFH ); } // RENDER THE BACKGROUND boolean bFullyTransparent = true; if ( la.getBackground( ) != null ) { bFullyTransparent = ( ( (ColorDefinition) la.getBackground( ) ).getTransparency( ) == 0 ); R31Enhance.setAlpha( gc, 255 ); } if ( !bFullyTransparent ) { final Color clrBackground = (Color) _sxs.getColor( (ColorDefinition) la.getBackground( ) ); final Color clrPreviousBackground = gc.getBackground( ); if ( ( (ColorDefinition) la.getBackground( ) ).isSetTransparency( ) ) { R31Enhance.setAlpha( gc, (ColorDefinition) la.getBackground( ) ); } gc.setBackground( clrBackground ); gc.fillRectangle( r ); clrBackground.dispose( ); gc.setBackground( clrPreviousBackground ); } // RENDER THE TEXT gc.setForeground( clrText ); R31Enhance.setAlpha( gc, la.getCaption( ).getColor( ) ); final Font f = (Font) _sxs.createFont( fd ); gc.setFont( f ); // R31Enhance.setTextAntialias( gc, 1 ); // SWT.ON if ( R31Enhance.isR31Available( ) ) { for ( int i = 0; i < itm.getLineCount( ); i++ ) { String oText = itm.getLine( i ); dW = gc.textExtent( oText ).x; if ( bRightAligned ) { dXOffset = -ins.getLeft( ) + dFW - dW - ins.getRight( ); } else if ( bCenterAligned ) { dXOffset = -ins.getLeft( ) + ( dFW - dW ) / 2; } gc.drawText( oText, (int) ( dXOffset + ins.getLeft( ) ), (int) ( dH * i + ins.getTop( ) ), true ); } } else { for ( int i = 0; i < itm.getLineCount( ); i++ ) { String oText = itm.getLine( i ); dW = gc.textExtent( oText ).x; if ( bRightAligned ) { dXOffset = -ins.getLeft( ) + dFW - dW - ins.getRight( ); } else if ( bCenterAligned ) { dXOffset = -ins.getLeft( ) + ( dFW - dW ) / 2; } gc.drawText( oText, (int) ( dX + dXOffset + ins.getLeft( ) ), (int) ( dY + dH * i + ins.getTop( ) ), true ); } } // apply reverse tranforming. R31Enhance.setTransform( gc, rtr ); // keep this null setting for other platforms. R31Enhance.setTransform( gc, null ); R31Enhance.disposeTransform( rtr ); R31Enhance.disposeTransform( tr ); f.dispose( ); clrText.dispose( ); itm.dispose( ); } /** * NOTE: Need a better algorithm for rendering smoother rotated text * * @param la * @return */ final Image rotatedTextAsImage( Label la ) { double dX = 0, dY = 0; final FontDefinition fd = la.getCaption( ).getFont( ); final double dAngleInDegrees = fd.getRotation( ); final Color clrText = (Color) _sxs.getColor( la.getCaption( ) .getColor( ) ); double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dH = itm.getHeight( ); final double dFH = itm.getFullHeight( ); final int iLC = itm.getLineCount( ); final Insets ins = la.getInsets( ) .scaledInstance( _sxs.getDpiResolution( ) / 72d ); dY += dFH; double dCosTheta = Math.cos( dAngleInRadians ); double dSineTheta = Math.sin( dAngleInRadians ); final double dFWt = Math.abs( dFW * dCosTheta + dFH * Math.abs( dSineTheta ) ); final double dFHt = Math.abs( dFH * dCosTheta + dFW * Math.abs( dSineTheta ) ); final int clipWs = (int) dFW; final int clipHs = (int) dFH; final int clipWt = (int) dFWt; final int clipHt = (int) dFHt; // RENDER THE TEXT ON AN OFFSCREEN CANVAS ImageData imgdtaS = new ImageData( clipWs, clipHs, 32, PALETTE_DATA ); imgdtaS.transparentPixel = TRANSPARENT_COLOR; final Image imgSource = new Image( _sxs.getDevice( ), imgdtaS ); for ( int i = 0; i < clipHs; i++ ) { for ( int j = 0; j < clipWs; j++ ) { imgdtaS.setPixel( j, i, imgdtaS.transparentPixel ); } } final GC gc = new GC( imgSource ); final Font f = (Font) _sxs.createFont( fd ); final Rectangle r = new Rectangle( (int) dX, (int) ( dY - dFH ), (int) dFW, (int) dFH ); // RENDER THE BACKGROUND final boolean bFullyTransparent = ( ( (ColorDefinition) la.getBackground( ) ).getTransparency( ) == 0 ); if ( !bFullyTransparent ) { final Color clrBackground = (Color) _sxs.getColor( (ColorDefinition) la.getBackground( ) ); gc.setBackground( clrBackground ); gc.fillRectangle( r ); clrBackground.dispose( ); } else { final Color cTransparent = new Color( _sxs.getDevice( ), 0x12, 0x34, 0x56 ); gc.setBackground( cTransparent ); gc.fillRectangle( r ); cTransparent.dispose( ); } // RENDER THE TEXT gc.setForeground( clrText ); gc.setFont( f ); for ( int i = 0; i < itm.getLineCount( ); i++ ) { gc.drawText( itm.getLine( iLC - i - 1 ), (int) ( dX + ins.getLeft( ) ), (int) ( dY - dH - dH * i + ins.getTop( ) ), false ); } clrText.dispose( ); itm.dispose( ); f.dispose( ); gc.dispose( ); imgdtaS = imgSource.getImageData( ); final ImageData imgdtaT = new ImageData( clipWt, clipHt, 32, PALETTE_DATA ); imgdtaT.palette = imgdtaS.palette; imgdtaT.transparentPixel = imgdtaS.transparentPixel; for ( int i = 0; i < clipHt; i++ ) { for ( int j = 0; j < clipWt; j++ ) { imgdtaT.setPixel( j, i, imgdtaT.transparentPixel ); } } final int neg = ( dAngleInDegrees < 0 ) ? (int) ( clipHs * dSineTheta ) : 0; final int pos = ( dAngleInDegrees > 0 ) ? (int) ( clipWs * Math.abs( dSineTheta ) ) : 0; final int yMax = clipHt - pos; final int xMax = clipWt - neg; int xSrc = 0, ySrc = 0, xDest = 0, yDest = 0, x = 0, y = 0; double yDestCosTheta, yDestSineTheta; // PIXEL TRANSFER LOOP for ( yDest = -pos; yDest < yMax; yDest++ ) { yDestCosTheta = yDest * dCosTheta; yDestSineTheta = yDest * dSineTheta; for ( xDest = -neg; xDest < xMax; xDest++ ) { // CALC SRC CO-ORDINATES xSrc = (int) Math.round( xDest * dCosTheta + yDestSineTheta ); ySrc = (int) Math.round( yDestCosTheta - xDest * dSineTheta ); if ( xSrc < 0 || xSrc >= clipWs || ySrc < 0 || ySrc >= clipHs ) // OUT // OF // RANGE { continue; } // CALC DEST CO-ORDINATES x = xDest + neg; y = yDest + pos; if ( x < 0 || x >= clipWt || y < 0 || y >= clipHt ) // OUT OF // RANGE { continue; } // NOW THAT BOTH CO-ORDINATES ARE WITHIN RANGE, TRANSFER A PIXEL imgdtaT.setPixel( x, y, imgdtaS.getPixel( xSrc, ySrc ) ); } } imgSource.dispose( ); // BUILD THE IMAGE USING THE NEWLY MANIPULATED BYTES return new Image( _sxs.getDevice( ), imgdtaT ); }; }
chart/org.eclipse.birt.chart.device.swt/src/org/eclipse/birt/chart/device/swt/SwtTextRenderer.java
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.device.swt; import org.eclipse.birt.chart.computation.BoundingBox; import org.eclipse.birt.chart.computation.IConstants; import org.eclipse.birt.chart.computation.Methods; import org.eclipse.birt.chart.computation.RotatedRectangle; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IPrimitiveRenderer; import org.eclipse.birt.chart.device.ITextMetrics; import org.eclipse.birt.chart.device.swt.i18n.Messages; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.attribute.AttributeFactory; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.FontDefinition; import org.eclipse.birt.chart.model.attribute.HorizontalAlignment; import org.eclipse.birt.chart.model.attribute.Insets; import org.eclipse.birt.chart.model.attribute.LineAttributes; import org.eclipse.birt.chart.model.attribute.LineStyle; import org.eclipse.birt.chart.model.attribute.Location; import org.eclipse.birt.chart.model.attribute.Text; import org.eclipse.birt.chart.model.attribute.TextAlignment; import org.eclipse.birt.chart.model.attribute.VerticalAlignment; import org.eclipse.birt.chart.model.attribute.impl.LocationImpl; import org.eclipse.birt.chart.model.component.Label; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.Rectangle; /** * Contains useful methods for rendering text on an SWT graphics context */ final class SwtTextRenderer implements IConstants { /** * */ private static final PaletteData PALETTE_DATA = new PaletteData( 0xFF0000, 0xFF00, 0xFF ); /** * */ private static final int TRANSPARENT_COLOR = 0x123456; /** * */ private static SwtTextRenderer _tr = null; private SwtDisplayServer _sxs = null; private static final int SHADOW_THICKNESS = 3; /** * */ private SwtTextRenderer( ) { } /** * * @return */ public synchronized static final SwtTextRenderer instance( SwtDisplayServer sxs ) { if ( _tr == null ) { _tr = new SwtTextRenderer( ); _tr._sxs = sxs; } return _tr; } /** * This method renders the 'shadow' at an offset from the text 'rotated * rectangle' subsequently rendered. * * @param ipr * @param iLabelPosition * The position of the label w.r.t. the location specified by * 'lo' * @param lo * The location (specified as a 2d point) where the text is to be * rendered * @param la * The chart model structure containing the encapsulated text * (and attributes) to be rendered */ public final void renderShadowAtLocation( IPrimitiveRenderer ipr, int iLabelPosition, // IConstants. LEFT, RIGHT, ABOVE or BELOW Location lo, // POINT WHERE THE CORNER OF THE ROTATED RECTANGLE // (OR EDGE CENTERED) IS RENDERED Label la ) throws ChartException { if ( !ChartUtil.isShadowDefined( la ) ) { return; } final ColorDefinition cdShadow = la.getShadowColor( ); if ( cdShadow == null ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, "SwtTextRenderer.exception.undefined.shadow.color", //$NON-NLS-1$ Messages.getResourceBundle( _sxs.getULocale( ) ) ); } switch ( iLabelPosition ) { case ABOVE : showTopValue( ipr, lo, la, false ); break; case BELOW : showBottomValue( ipr, lo, la, false ); break; case LEFT : showLeftValue( ipr, lo, la, false ); break; case RIGHT : showRightValue( ipr, lo, la, false ); break; } } /** * @param ipr * @param lo * @param la * @param b */ private void showRightValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showLeftValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showBottomValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { // TODO not used temporarily } /** * @param ipr * @param lo * @param la * @param b */ private void showTopValue( IPrimitiveRenderer ipr, Location lo, Label la, boolean b ) { GC gc = (GC) ( (IDeviceRenderer) ipr ).getGraphicsContext( ); double dX = lo.getX( ), dY = lo.getY( ); final FontDefinition fd = la.getCaption( ).getFont( ); final double dAngleInDegrees = fd.getRotation( ); final double dAngleInRadians = Math.toRadians( dAngleInDegrees ); final Color clrBackground = (Color) _sxs.getColor( la.getShadowColor( ) ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dFH = itm.getFullHeight( ); double scaledThickness = SHADOW_THICKNESS * _sxs.getDpiResolution( ) / 72d; gc.setBackground( clrBackground ); R31Enhance.setAlpha( gc, la.getShadowColor( ) ); // HORIZONTAL TEXT if ( dAngleInDegrees == 0 ) { gc.fillRectangle( (int) ( dX + scaledThickness ), (int) ( dY + scaledThickness ), (int) dFW, (int) dFH ); } // TEXT AT POSITIVE ANGLE < 90 (TOP RIGHT HIGHER THAN TOP LEFT CORNER) else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 ) { /** * y = kx + a; (x-x0)^2 + (y-y0)^2 = 2t^2 */ double k = Math.tan( dAngleInRadians - Math.PI / 4d ); double a = dY - k * dX; double k21 = k * k + 1; double A = 2 * scaledThickness * scaledThickness / k21 - ( ( a - dY ) * ( a - dY ) + dX * dX ) / k21 + ( ( k * a - k * dY - dX ) / k21 ) * ( ( k * a - k * dY - dX ) / k21 ); double sqa = Math.sqrt( A ); double ax = ( ( k * a - k * dY - dX ) / k21 ); double xx1 = sqa - ax; double yy1 = k * xx1 + a; double xx2 = -sqa - ax; double yy2 = k * xx2 + a; if ( xx1 > dX ) { dX = xx1; dY = yy1; } else { dX = xx2; dY = yy2; } int[] iPolyCoordinates = new int[8]; // BLC iPolyCoordinates[0] = (int) dX; iPolyCoordinates[1] = (int) dY; // BRC iPolyCoordinates[2] = (int) ( dX + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[3] = (int) ( dY - dFW * Math.sin( dAngleInRadians ) ); // TRC iPolyCoordinates[4] = (int) ( dX + dFH * Math.sin( dAngleInRadians ) + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[5] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) - dFW * Math.sin( dAngleInRadians ) ); // TLC iPolyCoordinates[6] = (int) ( dX + dFH * Math.sin( dAngleInRadians ) ); iPolyCoordinates[7] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) ); // RENDER IT gc.fillPolygon( iPolyCoordinates ); } // TEXT AT NEGATIVE ANGLE > -90 (TOP RIGHT LOWER THAN TOP LEFT CORNER) else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 ) { /** * y = kx + a; (x-x0)^2 + (y-y0)^2 = 2t^2 */ double k = Math.tan( dAngleInRadians - Math.PI / 4d ); double a = dY - k * dX; double k21 = k * k + 1; double A = 2 * scaledThickness * scaledThickness / k21 - ( ( a - dY ) * ( a - dY ) + dX * dX ) / k21 + ( ( k * a - k * dY - dX ) / k21 ) * ( ( k * a - k * dY - dX ) / k21 ); double sqa = Math.sqrt( A ); double ax = ( ( k * a - k * dY - dX ) / k21 ); double xx1 = sqa - ax; double yy1 = k * xx1 + a; double xx2 = -sqa - ax; double yy2 = k * xx2 + a; if ( yy1 > dY ) { dX = xx1; dY = yy1; } else { dX = xx2; dY = yy2; } int[] iPolyCoordinates = new int[8]; // BLC iPolyCoordinates[0] = (int) dX; iPolyCoordinates[1] = (int) dY; // BRC iPolyCoordinates[2] = (int) ( dX + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[3] = (int) ( dY + dFW * Math.abs( Math.sin( dAngleInRadians ) ) ); // TRC iPolyCoordinates[4] = (int) ( dX - dFH * Math.abs( Math.sin( dAngleInRadians ) ) + dFW * Math.cos( dAngleInRadians ) ); iPolyCoordinates[5] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) + dFW * Math.abs( Math.sin( dAngleInRadians ) ) ); // TLC iPolyCoordinates[6] = (int) ( dX - dFH * Math.abs( Math.sin( dAngleInRadians ) ) ); iPolyCoordinates[7] = (int) ( dY + dFH * Math.cos( dAngleInRadians ) ); // RENDER IT gc.fillPolygon( iPolyCoordinates ); } // TEXT AT POSITIVE 90 (TOP RIGHT HIGHER THAN TOP LEFT CORNER) else if ( dAngleInDegrees == 90 ) { gc.fillRectangle( (int) ( dX + scaledThickness ), (int) ( dY - dFW - scaledThickness ), (int) dFH, (int) dFW ); } // TEXT AT NEGATIVE 90 (TOP RIGHT LOWER THAN TOP LEFT CORNER) else if ( dAngleInDegrees == -90 ) { gc.fillRectangle( (int) ( dX - dFH - scaledThickness ), (int) ( dY + scaledThickness ), (int) dFH, (int) dFW ); } } /** * * @param ipr * @param iLabelPosition * @param lo * @param la * @throws RenderingException */ public final void renderTextAtLocation( IPrimitiveRenderer idr, int iLabelPosition, // IConstants. LEFT, RIGHT, ABOVE // or BELOW Location lo, // POINT WHERE THE CORNER OF THE ROTATED RECTANGLE // (OR // EDGE CENTERED) IS RENDERED Label la ) throws ChartException { final GC gc = (GC) ( (IDeviceRenderer) idr ).getGraphicsContext( ); BoundingBox bb = null; try { bb = Methods.computeBox( _sxs, iLabelPosition, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } switch ( iLabelPosition ) { case ABOVE : bb.setTop( lo.getY( ) - bb.getHeight( ) ); bb.setLeft( lo.getX( ) - bb.getHotPoint( ) ); break; case BELOW : bb.setTop( lo.getY( ) ); bb.setLeft( lo.getX( ) - bb.getHotPoint( ) ); break; case LEFT : bb.setTop( lo.getY( ) - bb.getHotPoint( ) ); bb.setLeft( lo.getX( ) - bb.getWidth( ) ); break; case RIGHT : bb.setTop( lo.getY( ) - bb.getHotPoint( ) ); bb.setLeft( lo.getX( ) ); break; } // RENDER Shadow around the text label if ( ChartUtil.isShadowDefined( la ) ) { try { final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFH = itm.getFullHeight( ); Location tmpLoc = Methods.computeRotatedTopPoint( _sxs, bb, la, dFH ); renderShadowAtLocation( idr, IConstants.ABOVE, tmpLoc, la ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } } if ( la.getCaption( ).getFont( ).getRotation( ) == 0 || R31Enhance.isR31Available( ) ) { renderHorizontalText( gc, la, bb.getLeft( ), bb.getTop( ) ); } else { final Image imgText = rotatedTextAsImage( la ); gc.drawImage( imgText, (int) bb.getLeft( ), (int) bb.getTop( ) ); imgText.dispose( ); } renderBorder( gc, la, iLabelPosition, lo ); } /** * * @param idr * @param boBlock * @param taBlock * @param la */ public final void renderTextInBlock( IDeviceRenderer idr, Bounds boBlock, TextAlignment taBlock, Label la ) throws ChartException { Text t = la.getCaption( ); String sText = t.getValue( ); ColorDefinition cdText = t.getColor( ); if ( cdText == null ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, "SwtTextRenderer.exception.undefined.text.color", //$NON-NLS-1$ Messages.getResourceBundle( _sxs.getULocale( ) ) ); } final GC gc = (GC) idr.getGraphicsContext( ); la.getCaption( ).setValue( sText ); BoundingBox bb = null; try { bb = Methods.computeBox( _sxs, ABOVE, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } if ( taBlock == null ) { taBlock = AttributeFactory.eINSTANCE.createTextAlignment( ); taBlock.setHorizontalAlignment( HorizontalAlignment.CENTER_LITERAL ); taBlock.setVerticalAlignment( VerticalAlignment.CENTER_LITERAL ); } HorizontalAlignment haBlock = taBlock.getHorizontalAlignment( ); VerticalAlignment vaBlock = taBlock.getVerticalAlignment( ); switch ( haBlock.getValue( ) ) { case HorizontalAlignment.CENTER : bb.setLeft( boBlock.getLeft( ) + ( boBlock.getWidth( ) - bb.getWidth( ) ) / 2 ); break; case HorizontalAlignment.LEFT : bb.setLeft( boBlock.getLeft( ) ); break; case HorizontalAlignment.RIGHT : bb.setLeft( boBlock.getLeft( ) + boBlock.getWidth( ) - bb.getWidth( ) ); break; } switch ( vaBlock.getValue( ) ) { case VerticalAlignment.TOP : bb.setTop( boBlock.getTop( ) ); break; case VerticalAlignment.CENTER : bb.setTop( boBlock.getTop( ) + ( boBlock.getHeight( ) - bb.getHeight( ) ) / 2 ); break; case VerticalAlignment.BOTTOM : bb.setTop( boBlock.getTop( ) + boBlock.getHeight( ) - bb.getHeight( ) ); break; } // RENDER Shadow around the text label if ( ChartUtil.isShadowDefined( la ) ) { try { final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFH = itm.getFullHeight( ); Location tmpLoc = Methods.computeRotatedTopPoint( _sxs, bb, la, dFH ); renderShadowAtLocation( idr, IConstants.ABOVE, tmpLoc, la ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } } if ( la.getCaption( ).getFont( ).getRotation( ) == 0 || R31Enhance.isR31Available( ) ) { renderHorizontalText( gc, la, bb.getLeft( ), bb.getTop( ) ); } else { final Image imgText = rotatedTextAsImage( la ); gc.drawImage( imgText, (int) bb.getLeft( ), (int) bb.getTop( ) ); imgText.dispose( ); } renderBorder( gc, la, IConstants.ABOVE, LocationImpl.create( bb.getLeft( ) + bb.getHotPoint( ), bb.getTop( ) + bb.getHeight( ) ) ); } /** * * @param gc * @param la * @param iLabelLocation * @param lo */ private final void renderBorder( GC gc, Label la, int iLabelLocation, Location lo ) throws ChartException { // RENDER THE OUTLINE/BORDER final LineAttributes lia = la.getOutline( ); if ( lia != null && lia.isVisible( ) && lia.isSetStyle( ) && lia.isSetThickness( ) && lia.getColor( ) != null ) { RotatedRectangle rr = null; try { rr = Methods.computePolygon( _sxs, iLabelLocation, la, lo.getX( ), lo.getY( ) ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartDeviceSwtActivator.ID, ChartException.RENDERING, uiex ); } final int iOldLineStyle = gc.getLineStyle( ); final int iOldLineWidth = gc.getLineWidth( ); final Color cFG = (Color) _sxs.getColor( lia.getColor( ) ); gc.setForeground( cFG ); R31Enhance.setAlpha( gc, lia.getColor( ) ); int iLineStyle = SWT.LINE_SOLID; switch ( lia.getStyle( ).getValue( ) ) { case ( LineStyle.DOTTED ) : iLineStyle = SWT.LINE_DOT; break; case ( LineStyle.DASH_DOTTED ) : iLineStyle = SWT.LINE_DASHDOT; break; case ( LineStyle.DASHED ) : iLineStyle = SWT.LINE_DASH; break; } gc.setLineStyle( iLineStyle ); gc.setLineWidth( lia.getThickness( ) ); gc.drawPolygon( rr.getSwtPoints( ) ); gc.setLineStyle( iOldLineStyle ); gc.setLineWidth( iOldLineWidth ); cFG.dispose( ); } } /** * Use this optimized routine for rendering horizontal ONLY text * * @param gc * @param la * @param lo */ private final void renderHorizontalText( GC gc, Label la, double dX, double dY ) { final FontDefinition fd = la.getCaption( ).getFont( ); final Color clrText = (Color) _sxs.getColor( la.getCaption( ) .getColor( ) ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dH = itm.getHeight( ); final double dFH = itm.getFullHeight( ); double dXOffset = 0; double dW = 0; final Insets ins = la.getInsets( ) .scaledInstance( _sxs.getDpiResolution( ) / 72d ); final HorizontalAlignment ha = la.getCaption( ) .getFont( ) .getAlignment( ) .getHorizontalAlignment( ); final boolean bRightAligned = ha.getValue( ) == HorizontalAlignment.RIGHT; final boolean bCenterAligned = ha.getValue( ) == HorizontalAlignment.CENTER; final Rectangle r; Object tr = null; if ( R31Enhance.isR31Available( ) ) { r = new Rectangle( 0, 0, (int) dFW, (int) dFH ); tr = R31Enhance.newTransform( _sxs.getDevice( ) ); if ( la.getCaption( ).getFont( ).getRotation( ) != 0 ) { float rotate = (float) la.getCaption( ) .getFont( ) .getRotation( ); double dAngleInRadians = ( ( -rotate * Math.PI ) / 180.0 ); double dSineTheta = Math.sin( dAngleInRadians ); float tTx = (float) ( dX - dFW / 2 ); float tTy = (float) ( dY - dFH / 2 ); if ( rotate > 0 ) tTy += dFW * Math.abs( dSineTheta ); else tTx += dFH * Math.abs( dSineTheta ); R31Enhance.translate( gc, tr, (float) ( dFW / 2 ), (float) ( dFH / 2 ) ); R31Enhance.translate( gc, tr, tTx, tTy ); R31Enhance.rotate( gc, tr, -rotate ); } else { R31Enhance.translate( gc, tr, (float) dX, (float) dY ); } R31Enhance.setTransform( gc, tr ); } else { r = new Rectangle( (int) dX, (int) dY, (int) dFW, (int) dFH ); } // RENDER THE BACKGROUND boolean bFullyTransparent = true; if ( la.getBackground( ) != null ) { bFullyTransparent = ( ( (ColorDefinition) la.getBackground( ) ).getTransparency( ) == 0 ); R31Enhance.setAlpha( gc, 255 ); } if ( !bFullyTransparent ) { final Color clrBackground = (Color) _sxs.getColor( (ColorDefinition) la.getBackground( ) ); final Color clrPreviousBackground = gc.getBackground( ); if ( ( (ColorDefinition) la.getBackground( ) ).isSetTransparency( ) ) { R31Enhance.setAlpha( gc, (ColorDefinition) la.getBackground( ) ); } gc.setBackground( clrBackground ); gc.fillRectangle( r ); clrBackground.dispose( ); gc.setBackground( clrPreviousBackground ); } // RENDER THE TEXT gc.setForeground( clrText ); R31Enhance.setAlpha( gc, la.getCaption( ).getColor( ) ); final Font f = (Font) _sxs.createFont( fd ); gc.setFont( f ); // R31Enhance.setTextAntialias( gc, 1 ); // SWT.ON if ( R31Enhance.isR31Available( ) ) { for ( int i = 0; i < itm.getLineCount( ); i++ ) { String oText = itm.getLine( i ); dW = gc.textExtent( oText ).x; if ( bRightAligned ) { dXOffset = -ins.getLeft( ) + dFW - dW - ins.getRight( ); } else if ( bCenterAligned ) { dXOffset = -ins.getLeft( ) + ( dFW - dW ) / 2; } gc.drawText( oText, (int) ( dXOffset + ins.getLeft( ) ), (int) ( dH * i + ins.getTop( ) ), true ); } } else { for ( int i = 0; i < itm.getLineCount( ); i++ ) { String oText = itm.getLine( i ); dW = gc.textExtent( oText ).x; if ( bRightAligned ) { dXOffset = -ins.getLeft( ) + dFW - dW - ins.getRight( ); } else if ( bCenterAligned ) { dXOffset = -ins.getLeft( ) + ( dFW - dW ) / 2; } gc.drawText( oText, (int) ( dX + dXOffset + ins.getLeft( ) ), (int) ( dY + dH * i + ins.getTop( ) ), true ); } } R31Enhance.setTransform( gc, null ); R31Enhance.disposeTransform( tr ); f.dispose( ); clrText.dispose( ); itm.dispose( ); } /** * NOTE: Need a better algorithm for rendering smoother rotated text * * @param la * @return */ final Image rotatedTextAsImage( Label la ) { double dX = 0, dY = 0; final FontDefinition fd = la.getCaption( ).getFont( ); final double dAngleInDegrees = fd.getRotation( ); final Color clrText = (Color) _sxs.getColor( la.getCaption( ) .getColor( ) ); double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 ); final ITextMetrics itm = new SwtTextMetrics( _sxs, la ); final double dFW = itm.getFullWidth( ); final double dH = itm.getHeight( ); final double dFH = itm.getFullHeight( ); final int iLC = itm.getLineCount( ); final Insets ins = la.getInsets( ) .scaledInstance( _sxs.getDpiResolution( ) / 72d ); dY += dFH; double dCosTheta = Math.cos( dAngleInRadians ); double dSineTheta = Math.sin( dAngleInRadians ); final double dFWt = Math.abs( dFW * dCosTheta + dFH * Math.abs( dSineTheta ) ); final double dFHt = Math.abs( dFH * dCosTheta + dFW * Math.abs( dSineTheta ) ); final int clipWs = (int) dFW; final int clipHs = (int) dFH; final int clipWt = (int) dFWt; final int clipHt = (int) dFHt; // RENDER THE TEXT ON AN OFFSCREEN CANVAS ImageData imgdtaS = new ImageData( clipWs, clipHs, 32, PALETTE_DATA ); imgdtaS.transparentPixel = TRANSPARENT_COLOR; final Image imgSource = new Image( _sxs.getDevice( ), imgdtaS ); for ( int i = 0; i < clipHs; i++ ) { for ( int j = 0; j < clipWs; j++ ) { imgdtaS.setPixel( j, i, imgdtaS.transparentPixel ); } } final GC gc = new GC( imgSource ); final Font f = (Font) _sxs.createFont( fd ); final Rectangle r = new Rectangle( (int) dX, (int) ( dY - dFH ), (int) dFW, (int) dFH ); // RENDER THE BACKGROUND final boolean bFullyTransparent = ( ( (ColorDefinition) la.getBackground( ) ).getTransparency( ) == 0 ); if ( !bFullyTransparent ) { final Color clrBackground = (Color) _sxs.getColor( (ColorDefinition) la.getBackground( ) ); gc.setBackground( clrBackground ); gc.fillRectangle( r ); clrBackground.dispose( ); } else { final Color cTransparent = new Color( _sxs.getDevice( ), 0x12, 0x34, 0x56 ); gc.setBackground( cTransparent ); gc.fillRectangle( r ); cTransparent.dispose( ); } // RENDER THE TEXT gc.setForeground( clrText ); gc.setFont( f ); for ( int i = 0; i < itm.getLineCount( ); i++ ) { gc.drawText( itm.getLine( iLC - i - 1 ), (int) ( dX + ins.getLeft( ) ), (int) ( dY - dH - dH * i + ins.getTop( ) ), false ); } clrText.dispose( ); itm.dispose( ); f.dispose( ); gc.dispose( ); imgdtaS = imgSource.getImageData( ); final ImageData imgdtaT = new ImageData( clipWt, clipHt, 32, PALETTE_DATA ); imgdtaT.palette = imgdtaS.palette; imgdtaT.transparentPixel = imgdtaS.transparentPixel; for ( int i = 0; i < clipHt; i++ ) { for ( int j = 0; j < clipWt; j++ ) { imgdtaT.setPixel( j, i, imgdtaT.transparentPixel ); } } final int neg = ( dAngleInDegrees < 0 ) ? (int) ( clipHs * dSineTheta ) : 0; final int pos = ( dAngleInDegrees > 0 ) ? (int) ( clipWs * Math.abs( dSineTheta ) ) : 0; final int yMax = clipHt - pos; final int xMax = clipWt - neg; int xSrc = 0, ySrc = 0, xDest = 0, yDest = 0, x = 0, y = 0; double yDestCosTheta, yDestSineTheta; // PIXEL TRANSFER LOOP for ( yDest = -pos; yDest < yMax; yDest++ ) { yDestCosTheta = yDest * dCosTheta; yDestSineTheta = yDest * dSineTheta; for ( xDest = -neg; xDest < xMax; xDest++ ) { // CALC SRC CO-ORDINATES xSrc = (int) Math.round( xDest * dCosTheta + yDestSineTheta ); ySrc = (int) Math.round( yDestCosTheta - xDest * dSineTheta ); if ( xSrc < 0 || xSrc >= clipWs || ySrc < 0 || ySrc >= clipHs ) // OUT // OF // RANGE { continue; } // CALC DEST CO-ORDINATES x = xDest + neg; y = yDest + pos; if ( x < 0 || x >= clipWt || y < 0 || y >= clipHt ) // OUT OF // RANGE { continue; } // NOW THAT BOTH CO-ORDINATES ARE WITHIN RANGE, TRANSFER A PIXEL imgdtaT.setPixel( x, y, imgdtaS.getPixel( xSrc, ySrc ) ); } } imgSource.dispose( ); // BUILD THE IMAGE USING THE NEWLY MANIPULATED BYTES return new Image( _sxs.getDevice( ), imgdtaT ); }; }
- Summary: fix linux bug:137655, 137654 - Bugzilla Bug (s) Resolved: 137655, 137654 - Description: In Linux-Cairo environment, it uses a cascaded transform setting policy, not a overriding policy. So we must set a reverse tranforming explicitly to restore to original state. And maybe this is a bug for swt on linux. - Tests Description : Manual test - Files Edited: @changelist - Files Added: @addlist - Files Deleted: @deletelist - Notes to Build Team: - Notes to Developers: - Notes to QA: - Notes to Documentation:
chart/org.eclipse.birt.chart.device.swt/src/org/eclipse/birt/chart/device/swt/SwtTextRenderer.java
- Summary: fix linux bug:137655, 137654 - Bugzilla Bug (s) Resolved: 137655, 137654 - Description: In Linux-Cairo environment, it uses a cascaded transform setting policy, not a overriding policy. So we must set a reverse tranforming explicitly to restore to original state. And maybe this is a bug for swt on linux. - Tests Description : Manual test - Files Edited: @changelist - Files Added: @addlist - Files Deleted: @deletelist - Notes to Build Team:
Java
agpl-3.0
736b927c8e04a6f9135b4b5b1a3a94991891a17d
0
KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.gedcomimport; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JTextArea; import nl.mpi.arbil.util.ArbilBugCatcher; /** * Document : CsvImporter * Created on : May 30, 2011, 10:29:24 AM * Author : Peter Withers */ public class CsvImporter extends EntityImporter implements GenericImporter { public CsvImporter(boolean overwriteExistingLocal) { super(overwriteExistingLocal); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".csv")); } private String cleanCsvString(String valueString) { valueString = valueString.replaceAll("^\"", ""); valueString = valueString.replaceAll("\"$", ""); valueString = valueString.replaceAll("\"\"", ""); return valueString; } @Override public URI[] importFile(JTextArea importTextArea, InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); HashMap<String, EntityDocument> createdDocuments = new HashMap<String, EntityDocument>(); createdNodeIds = new HashMap<String, ArrayList<String>>(); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); File destinationDirectory = super.getDestinationDirectory(); String inputLine; try { // "ID","Gender","Name1","Name2","Name3","Name4","Name5","Name6","Date of Birth","Date of Death","sub_group","Parents1-ID","Parents1-Gender","Parents1-Name1","Parents1-Name2","Parents1-Name3","Parents1-Name4","Parents1-Name5","Parents1-Name6","Parents1-Date of Birth","Parents1-Date of Death","Parents1-sub_group","Parents2-ID","Parents2-Gender","Parents2-Name1","Parents2-Name2","Parents2-Name3","Parents2-Name4","Parents2-Name5","Parents2-Name6","Parents2-Date of Birth","Parents2-Date of Death","Parents2-sub_group","Spouses1-ID","Spouses1-Gender","Spouses1-Name1","Spouses1-Name2","Spouses1-Name3","Spouses1-Name4","Spouses1-Name5","Spouses1-Name6","Spouses1-Date of Birth","Spouses1-Date of Death","Spouses1-sub_group","Spouses2-ID","Spouses2-Gender","Spouses2-Name1","Spouses2-Name2","Spouses2-Name3","Spouses2-Name4","Spouses2-Name5","Spouses2-Name6","Spouses2-Date of Birth","Spouses2-Date of Death","Spouses2-sub_group","Spouses3-ID","Spouses3-Gender","Spouses3-Name1","Spouses3-Name2","Spouses3-Name3","Spouses3-Name4","Spouses3-Name5","Spouses3-Name6","Spouses3-Date of Birth","Spouses3-Date of Death","Spouses3-sub_group","Spouses4-ID","Spouses4-Gender","Spouses4-Name1","Spouses4-Name2","Spouses4-Name3","Spouses4-Name4","Spouses4-Name5","Spouses4-Name6","Spouses4-Date of Birth","Spouses4-Date of Death","Spouses4-sub_group","Spouses5-ID","Spouses5-Gender","Spouses5-Name1","Spouses5-Name2","Spouses5-Name3","Spouses5-Name4","Spouses5-Name5","Spouses5-Name6","Spouses5-Date of Birth","Spouses5-Date of Death","Spouses5-sub_group","Spouses6-ID","Spouses6-Gender","Spouses6-Name1","Spouses6-Name2","Spouses6-Name3","Spouses6-Name4","Spouses6-Name5","Spouses6-Name6","Spouses6-Date of Birth","Spouses6-Date of Death","Spouses6-sub_group","Children1-ID","Children1-Gender","Children1-Name1","Children1-Name2","Children1-Name3","Children1-Name4","Children1-Name5","Children1-Name6","Children1-Date of Birth","Children1-Date of Death","Children1-sub_group","Children2-ID","Children2-Gender","Children2-Name1","Children2-Name2","Children2-Name3","Children2-Name4","Children2-Name5","Children2-Name6","Children2-Date of Birth","Children2-Date of Death","Children2-sub_group","Children3-ID","Children3-Gender","Children3-Name1","Children3-Name2","Children3-Name3","Children3-Name4","Children3-Name5","Children3-Name6","Children3-Date of Birth","Children3-Date of Death","Children3-sub_group","Children4-ID","Children4-Gender","Children4-Name1","Children4-Name2","Children4-Name3","Children4-Name4","Children4-Name5","Children4-Name6","Children4-Date of Birth","Children4-Date of Death","Children4-sub_group","Children5-ID","Children5-Gender","Children5-Name1","Children5-Name2","Children5-Name3","Children5-Name4","Children5-Name5","Children5-Name6","Children5-Date of Birth","Children5-Date of Death","Children5-sub_group","Children6-ID","Children6-Gender","Children6-Name1","Children6-Name2","Children6-Name3","Children6-Name4","Children6-Name5","Children6-Name6","Children6-Date of Birth","Children6-Date of Death","Children6-sub_group","Children7-ID","Children7-Gender","Children7-Name1","Children7-Name2","Children7-Name3","Children7-Name4","Children7-Name5","Children7-Name6","Children7-Date of Birth","Children7-Date of Death","Children7-sub_group","Children8-ID","Children8-Gender","Children8-Name1","Children8-Name2","Children8-Name3","Children8-Name4","Children8-Name5","Children8-Name6","Children8-Date of Birth","Children8-Date of Death","Children8-sub_group","Children9-ID","Children9-Gender","Children9-Name1","Children9-Name2","Children9-Name3","Children9-Name4","Children9-Name5","Children9-Name6","Children9-Date of Birth","Children9-Date of Death","Children9-sub_group","Children10-ID","Children10-Gender","Children10-Name1","Children10-Name2","Children10-Name3","Children10-Name4","Children10-Name5","Children10-Name6","Children10-Date of Birth","Children10-Date of Death","Children10-sub_group","Children11-ID","Children11-Gender","Children11-Name1","Children11-Name2","Children11-Name3","Children11-Name4","Children11-Name5","Children11-Name6","Children11-Date of Birth","Children11-Date of Death","Children11-sub_group","Children12-ID","Children12-Gender","Children12-Name1","Children12-Name2","Children12-Name3","Children12-Name4","Children12-Name5","Children12-Name6","Children12-Date of Birth","Children12-Date of Death","Children12-sub_group","Children13-ID","Children13-Gender","Children13-Name1","Children13-Name2","Children13-Name3","Children13-Name4","Children13-Name5","Children13-Name6","Children13-Date of Birth","Children13-Date of Death","Children13-sub_group","Children14-ID","Children14-Gender","Children14-Name1","Children14-Name2","Children14-Name3","Children14-Name4","Children14-Name5","Children14-Name6","Children14-Date of Birth","Children14-Date of Death","Children14-sub_group","Children15-ID","Children15-Gender","Children15-Name1","Children15-Name2","Children15-Name3","Children15-Name4","Children15-Name5","Children15-Name6","Children15-Date of Birth","Children15-Date of Death","Children15-sub_group","Children16-ID","Children16-Gender","Children16-Name1","Children16-Name2","Children16-Name3","Children16-Name4","Children16-Name5","Children16-Name6","Children16-Date of Birth","Children16-Date of Death","Children16-sub_group","Children17-ID","Children17-Gender","Children17-Name1","Children17-Name2","Children17-Name3","Children17-Name4","Children17-Name5","Children17-Name6","Children17-Date of Birth","Children17-Date of Death","Children17-sub_group","Children18-ID","Children18-Gender","Children18-Name1","Children18-Name2","Children18-Name3","Children18-Name4","Children18-Name5","Children18-Name6","Children18-Date of Birth","Children18-Date of Death","Children18-sub_group","Children19-ID","Children19-Gender","Children19-Name1","Children19-Name2","Children19-Name3","Children19-Name4","Children19-Name5","Children19-Name6","Children19-Date of Birth","Children19-Date of Death","Children19-sub_group","Children20-ID","Children20-Gender","Children20-Name1","Children20-Name2","Children20-Name3","Children20-Name4","Children20-Name5","Children20-Name6","Children20-Date of Birth","Children20-Date of Death","Children20-sub_group" String headingLine = bufferedReader.readLine(); if (headingLine != null) { ArrayList<String> allHeadings = new ArrayList<String>(); for (String headingString : headingLine.split(",")) { String cleanHeading = cleanCsvString(headingString); allHeadings.add(cleanHeading); // appendToTaskOutput(importTextArea, "Heading: " + cleanHeading); } try { while ((inputLine = bufferedReader.readLine()) != null) { EntityDocument currentEntity = null; int valueCount = 0; for (String entityLineString : inputLine.split(",")) { String cleanValue = cleanCsvString(entityLineString); if (currentEntity == null) { // create a new entity file String idString = super.cleanFileName(cleanValue); currentEntity = new EntityDocument(destinationDirectory, idString); appendToTaskOutput(importTextArea, "created: " + currentEntity.getFilePath()); createdNodes.add(currentEntity.createDocument(overwriteExisting)); createdDocuments.put(idString, currentEntity); String typeString = "Entity"; if (createdNodeIds.get(typeString) == null) { ArrayList<String> idArray = new ArrayList<String>(); idArray.add(currentEntity.getUniquieIdentifier()); createdNodeIds.put(typeString, idArray); } else { createdNodeIds.get(typeString).add(currentEntity.getUniquieIdentifier()); } } else if (cleanValue.length() > 0) { currentEntity.insertValue(allHeadings.get(valueCount), cleanValue); appendToTaskOutput(importTextArea, allHeadings.get(valueCount) + " : " + cleanValue); } valueCount++; } break; // appendToTaskOutput(importTextArea, inputLine); // boolean skipFileEntity = false; // if (skipFileEntity) { // skipFileEntity = false; // while ((inputLine = bufferedReader.readLine()) != null) { // if (inputLine.startsWith("0")) { // break; // } // } // } } } catch (ImportException exception) { appendToTaskOutput(importTextArea, exception.getMessage()); } } for (EntityDocument currentDocument : createdDocuments.values()) { currentDocument.saveDocument(); appendToTaskOutput(importTextArea, "saved: " + currentDocument.getFilePath()); } } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error: " + exception.getMessage()); } // catch (ParserConfigurationException parserConfigurationException) { // new ArbilBugCatcher().logError(parserConfigurationException); // appendToTaskOutput(importTextArea, "Error: " + parserConfigurationException.getMessage()); // } catch (DOMException dOMException) { // new ArbilBugCatcher().logError(dOMException); // appendToTaskOutput(importTextArea, "Error: " + dOMException.getMessage()); // } catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); // }catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); // } return createdNodes.toArray(new URI[]{}); } }
src/main/java/nl/mpi/kinnate/gedcomimport/CsvImporter.java
package nl.mpi.kinnate.gedcomimport; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JTextArea; import nl.mpi.arbil.util.ArbilBugCatcher; /** * Document : CsvImporter * Created on : May 30, 2011, 10:29:24 AM * Author : Peter Withers */ public class CsvImporter extends EntityImporter implements GenericImporter { public CsvImporter(boolean overwriteExistingLocal) { super(overwriteExistingLocal); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".csv")); } private String cleanCsvString(String valueString) { valueString = valueString.replaceAll("^\"", ""); valueString = valueString.replaceAll("\"$", ""); valueString = valueString.replaceAll("\"\"", ""); return valueString; } @Override public URI[] importFile(JTextArea importTextArea, InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); createdNodeIds = new HashMap<String, ArrayList<String>>(); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); File destinationDirectory = super.getDestinationDirectory(); String inputLine; try { // "ID","Gender","Name1","Name2","Name3","Name4","Name5","Name6","Date of Birth","Date of Death","sub_group","Parents1-ID","Parents1-Gender","Parents1-Name1","Parents1-Name2","Parents1-Name3","Parents1-Name4","Parents1-Name5","Parents1-Name6","Parents1-Date of Birth","Parents1-Date of Death","Parents1-sub_group","Parents2-ID","Parents2-Gender","Parents2-Name1","Parents2-Name2","Parents2-Name3","Parents2-Name4","Parents2-Name5","Parents2-Name6","Parents2-Date of Birth","Parents2-Date of Death","Parents2-sub_group","Spouses1-ID","Spouses1-Gender","Spouses1-Name1","Spouses1-Name2","Spouses1-Name3","Spouses1-Name4","Spouses1-Name5","Spouses1-Name6","Spouses1-Date of Birth","Spouses1-Date of Death","Spouses1-sub_group","Spouses2-ID","Spouses2-Gender","Spouses2-Name1","Spouses2-Name2","Spouses2-Name3","Spouses2-Name4","Spouses2-Name5","Spouses2-Name6","Spouses2-Date of Birth","Spouses2-Date of Death","Spouses2-sub_group","Spouses3-ID","Spouses3-Gender","Spouses3-Name1","Spouses3-Name2","Spouses3-Name3","Spouses3-Name4","Spouses3-Name5","Spouses3-Name6","Spouses3-Date of Birth","Spouses3-Date of Death","Spouses3-sub_group","Spouses4-ID","Spouses4-Gender","Spouses4-Name1","Spouses4-Name2","Spouses4-Name3","Spouses4-Name4","Spouses4-Name5","Spouses4-Name6","Spouses4-Date of Birth","Spouses4-Date of Death","Spouses4-sub_group","Spouses5-ID","Spouses5-Gender","Spouses5-Name1","Spouses5-Name2","Spouses5-Name3","Spouses5-Name4","Spouses5-Name5","Spouses5-Name6","Spouses5-Date of Birth","Spouses5-Date of Death","Spouses5-sub_group","Spouses6-ID","Spouses6-Gender","Spouses6-Name1","Spouses6-Name2","Spouses6-Name3","Spouses6-Name4","Spouses6-Name5","Spouses6-Name6","Spouses6-Date of Birth","Spouses6-Date of Death","Spouses6-sub_group","Children1-ID","Children1-Gender","Children1-Name1","Children1-Name2","Children1-Name3","Children1-Name4","Children1-Name5","Children1-Name6","Children1-Date of Birth","Children1-Date of Death","Children1-sub_group","Children2-ID","Children2-Gender","Children2-Name1","Children2-Name2","Children2-Name3","Children2-Name4","Children2-Name5","Children2-Name6","Children2-Date of Birth","Children2-Date of Death","Children2-sub_group","Children3-ID","Children3-Gender","Children3-Name1","Children3-Name2","Children3-Name3","Children3-Name4","Children3-Name5","Children3-Name6","Children3-Date of Birth","Children3-Date of Death","Children3-sub_group","Children4-ID","Children4-Gender","Children4-Name1","Children4-Name2","Children4-Name3","Children4-Name4","Children4-Name5","Children4-Name6","Children4-Date of Birth","Children4-Date of Death","Children4-sub_group","Children5-ID","Children5-Gender","Children5-Name1","Children5-Name2","Children5-Name3","Children5-Name4","Children5-Name5","Children5-Name6","Children5-Date of Birth","Children5-Date of Death","Children5-sub_group","Children6-ID","Children6-Gender","Children6-Name1","Children6-Name2","Children6-Name3","Children6-Name4","Children6-Name5","Children6-Name6","Children6-Date of Birth","Children6-Date of Death","Children6-sub_group","Children7-ID","Children7-Gender","Children7-Name1","Children7-Name2","Children7-Name3","Children7-Name4","Children7-Name5","Children7-Name6","Children7-Date of Birth","Children7-Date of Death","Children7-sub_group","Children8-ID","Children8-Gender","Children8-Name1","Children8-Name2","Children8-Name3","Children8-Name4","Children8-Name5","Children8-Name6","Children8-Date of Birth","Children8-Date of Death","Children8-sub_group","Children9-ID","Children9-Gender","Children9-Name1","Children9-Name2","Children9-Name3","Children9-Name4","Children9-Name5","Children9-Name6","Children9-Date of Birth","Children9-Date of Death","Children9-sub_group","Children10-ID","Children10-Gender","Children10-Name1","Children10-Name2","Children10-Name3","Children10-Name4","Children10-Name5","Children10-Name6","Children10-Date of Birth","Children10-Date of Death","Children10-sub_group","Children11-ID","Children11-Gender","Children11-Name1","Children11-Name2","Children11-Name3","Children11-Name4","Children11-Name5","Children11-Name6","Children11-Date of Birth","Children11-Date of Death","Children11-sub_group","Children12-ID","Children12-Gender","Children12-Name1","Children12-Name2","Children12-Name3","Children12-Name4","Children12-Name5","Children12-Name6","Children12-Date of Birth","Children12-Date of Death","Children12-sub_group","Children13-ID","Children13-Gender","Children13-Name1","Children13-Name2","Children13-Name3","Children13-Name4","Children13-Name5","Children13-Name6","Children13-Date of Birth","Children13-Date of Death","Children13-sub_group","Children14-ID","Children14-Gender","Children14-Name1","Children14-Name2","Children14-Name3","Children14-Name4","Children14-Name5","Children14-Name6","Children14-Date of Birth","Children14-Date of Death","Children14-sub_group","Children15-ID","Children15-Gender","Children15-Name1","Children15-Name2","Children15-Name3","Children15-Name4","Children15-Name5","Children15-Name6","Children15-Date of Birth","Children15-Date of Death","Children15-sub_group","Children16-ID","Children16-Gender","Children16-Name1","Children16-Name2","Children16-Name3","Children16-Name4","Children16-Name5","Children16-Name6","Children16-Date of Birth","Children16-Date of Death","Children16-sub_group","Children17-ID","Children17-Gender","Children17-Name1","Children17-Name2","Children17-Name3","Children17-Name4","Children17-Name5","Children17-Name6","Children17-Date of Birth","Children17-Date of Death","Children17-sub_group","Children18-ID","Children18-Gender","Children18-Name1","Children18-Name2","Children18-Name3","Children18-Name4","Children18-Name5","Children18-Name6","Children18-Date of Birth","Children18-Date of Death","Children18-sub_group","Children19-ID","Children19-Gender","Children19-Name1","Children19-Name2","Children19-Name3","Children19-Name4","Children19-Name5","Children19-Name6","Children19-Date of Birth","Children19-Date of Death","Children19-sub_group","Children20-ID","Children20-Gender","Children20-Name1","Children20-Name2","Children20-Name3","Children20-Name4","Children20-Name5","Children20-Name6","Children20-Date of Birth","Children20-Date of Death","Children20-sub_group" String headingLine = bufferedReader.readLine(); if (headingLine != null) { ArrayList<String> allHeadings = new ArrayList<String>(); for (String headingString : headingLine.split(",")) { String cleanHeading = cleanCsvString(headingString); allHeadings.add(cleanHeading); // appendToTaskOutput(importTextArea, "Heading: " + cleanHeading); } while ((inputLine = bufferedReader.readLine()) != null) { int valueCount = 0; for (String entityLineString : inputLine.split(",")) { if (valueCount == 0) { // create a new entity file } String cleanValue = cleanCsvString(entityLineString); if (cleanValue.length() > 0) { appendToTaskOutput(importTextArea, allHeadings.get(valueCount) + " : " + cleanValue); } valueCount++; } break; // appendToTaskOutput(importTextArea, inputLine); // boolean skipFileEntity = false; // if (skipFileEntity) { // skipFileEntity = false; // while ((inputLine = bufferedReader.readLine()) != null) { // if (inputLine.startsWith("0")) { // break; // } // } // } } } } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error: " + exception.getMessage()); } // catch (ParserConfigurationException parserConfigurationException) { // new ArbilBugCatcher().logError(parserConfigurationException); // appendToTaskOutput(importTextArea, "Error: " + parserConfigurationException.getMessage()); // } catch (DOMException dOMException) { // new ArbilBugCatcher().logError(dOMException); // appendToTaskOutput(importTextArea, "Error: " + dOMException.getMessage()); // } catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); // }catch (SAXException sAXException) { // new ArbilBugCatcher().logError(sAXException); // appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); // } return createdNodes.toArray(new URI[]{}); } }
Separated the Gedcom import into an interface and super class so that other importers can easily be written.
src/main/java/nl/mpi/kinnate/gedcomimport/CsvImporter.java
Separated the Gedcom import into an interface and super class so that other importers can easily be written.
Java
agpl-3.0
eef6877066ea05d04451c3a6633b58594230558f
0
kuali/kfs,kkronenb/kfs,kuali/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,kkronenb/kfs,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,bhutchinson/kfs,smith750/kfs,bhutchinson/kfs,kuali/kfs,smith750/kfs,bhutchinson/kfs,kuali/kfs,smith750/kfs,ua-eas/kfs,ua-eas/kfs
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.vendor.rules; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; 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 org.apache.commons.lang.StringUtils; import org.kuali.core.authorization.FieldAuthorization; import org.kuali.core.bo.BusinessRule; import org.kuali.core.bo.PersistableBusinessObject; import org.kuali.core.bo.PersistableBusinessObjectBase; import org.kuali.core.bo.user.UniversalUser; import org.kuali.core.document.MaintenanceDocument; import org.kuali.core.document.authorization.MaintenanceDocumentAuthorizations; import org.kuali.core.document.authorization.MaintenanceDocumentAuthorizer; import org.kuali.core.exceptions.UnknownDocumentIdException; import org.kuali.core.maintenance.Maintainable; import org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase; import org.kuali.core.rule.KualiParameterRule; import org.kuali.core.service.DocumentService; import org.kuali.core.util.GlobalVariables; import org.kuali.core.util.KualiDecimal; import org.kuali.core.util.ObjectUtils; import org.kuali.core.workflow.service.KualiWorkflowDocument; import org.kuali.kfs.KFSConstants; import org.kuali.kfs.KFSKeyConstants; import org.kuali.kfs.KFSPropertyConstants; import org.kuali.kfs.bo.Country; import org.kuali.kfs.util.SpringServiceLocator; import org.kuali.module.chart.bo.Chart; import org.kuali.module.chart.bo.Org; import org.kuali.module.vendor.VendorConstants; import org.kuali.module.vendor.VendorKeyConstants; import org.kuali.module.vendor.VendorPropertyConstants; import org.kuali.module.vendor.VendorRuleConstants; import org.kuali.module.vendor.bo.AddressType; import org.kuali.module.vendor.bo.OwnershipType; import org.kuali.module.vendor.bo.VendorAddress; import org.kuali.module.vendor.bo.VendorContact; import org.kuali.module.vendor.bo.VendorContract; import org.kuali.module.vendor.bo.VendorContractOrganization; import org.kuali.module.vendor.bo.VendorCustomerNumber; import org.kuali.module.vendor.bo.VendorDefaultAddress; import org.kuali.module.vendor.bo.VendorDetail; import edu.iu.uis.eden.exception.WorkflowException; public class VendorRule extends MaintenanceDocumentRuleBase implements VendorRuleConstants { private VendorDetail oldVendor; private VendorDetail newVendor; private static KualiDecimal VENDOR_MIN_ORDER_AMOUNT; /** * This method is needed to override the setupBaseConvenienceObjects from the superclass because we cannot use the * setupBaseConvenienceObjects from the superclass. The reason we cannot use the superclass method is because it calls the * updateNonUpdateableReferences for everything and we cannot do that for parent vendors, because we want to update vendor * header information only on parent vendors, so the saving of the vendor header is done manually. If we call the * updateNonUpdateableReferences, it is going to overwrite any changes that the user might have done in the vendor header with * the existing values in the database. * * @param document The MaintenanceDocument object containing the vendorDetail objects to be setup. */ @Override public void setupBaseConvenienceObjects(MaintenanceDocument document) { oldVendor = (VendorDetail) document.getOldMaintainableObject().getBusinessObject(); newVendor = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); super.setNewBo(newVendor); setupConvenienceObjects(); } /** * This method setups oldVendor and newVendor convenience objects, make sure all possible sub-objects are populated. */ @Override public void setupConvenienceObjects() { // setup oldVendor convenience objects, make sure all possible sub-objects are populated refreshSubObjects(oldVendor); // setup newVendor convenience objects, make sure all possible sub-objects are populated refreshSubObjects(newVendor); } /** * This method overrides the checkAuthorizationRestrictions in MaintenanceDocumentRuleBase. The reason we needed to override it * is because in vendor, we had to save the fields in the vendor header separately than vendor detail, and those fields are only * editable when the vendor is a parent. Therefore we had to override the setupBaseConvenienceObjects method, which then causes * us unable to set the oldBo of the super class because the oldBo is not accessible from outside the class. This will cause the * checkAuthorizationRestrictions of the superclass to fail while processing division vendors that contain those restricted * (uneditable) fields, because the oldBo is null and will throw the null pointer exception. Therefore we're overriding the * checkAuthorizationRestrictions in here and we'll use the oldVendor instead of oldBo of the superclass while comparing the old * and new values. This also does not enforce the authorization restrictions if the restricted fields are the fields in vendor * header or the vendor is not a parent vendor, because in this case, the fields are uneditable from the user interface. * * @see org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase#checkAuthorizationRestrictions(org.kuali.core.document.MaintenanceDocument) */ @Override protected boolean checkAuthorizationRestrictions(MaintenanceDocument document) { boolean success = true; boolean changed = false; boolean isInitiator = false; boolean isApprover = false; Object oldValue = null; Object newValue = null; Object savedValue = null; KualiWorkflowDocument workflowDocument = null; UniversalUser user = GlobalVariables.getUserSession().getUniversalUser(); try { workflowDocument = getWorkflowDocumentService().createWorkflowDocument(Long.valueOf(document.getDocumentNumber()), user); } catch (WorkflowException e) { throw new UnknownDocumentIdException("no document found for documentHeaderId '" + document.getDocumentNumber() + "'", e); } if (user.getPersonUserIdentifier().equalsIgnoreCase(workflowDocument.getInitiatorNetworkId())) { // if these are the same person then we know it is the initiator isInitiator = true; } else if (workflowDocument.isApprovalRequested()) { isApprover = true; } // get the correct documentAuthorizer for this document MaintenanceDocumentAuthorizer documentAuthorizer = (MaintenanceDocumentAuthorizer) documentAuthorizationService.getDocumentAuthorizer(document); // get a new instance of MaintenanceDocumentAuthorizations for this context MaintenanceDocumentAuthorizations auths = documentAuthorizer.getFieldAuthorizations(document, user); // load a temp copy of the document from the DB to compare to for changes MaintenanceDocument savedDoc = null; Maintainable savedNewMaintainable = null; PersistableBusinessObject savedNewBo = null; if (isApprover) { try { DocumentService docService = SpringServiceLocator.getDocumentService(); savedDoc = (MaintenanceDocument) docService.getByDocumentHeaderId(document.getDocumentNumber()); } catch (WorkflowException e) { throw new RuntimeException("A WorkflowException was thrown which prevented the loading of " + "the comparison document (" + document.getDocumentNumber() + ")", e); } // attempt to retrieve the BO, but leave it blank if it or any of the objects on the path // to it are blank if (savedDoc != null) { savedNewMaintainable = savedDoc.getNewMaintainableObject(); if (savedNewMaintainable != null) { savedNewBo = savedNewMaintainable.getBusinessObject(); } } } // setup in-loop members FieldAuthorization fieldAuthorization = null; // walk through all the restrictions Collection restrictedFields = auths.getAuthFieldNames(); for (Iterator iter = restrictedFields.iterator(); iter.hasNext();) { String fieldName = (String) iter.next(); if (fieldName.indexOf(VendorPropertyConstants.VENDOR_HEADER_PREFIX) < 0 || newVendor.isVendorParentIndicator()) { // get the specific field authorization structure fieldAuthorization = auths.getAuthFieldAuthorization(fieldName); // if there are any restrictions, then enforce them if (fieldAuthorization.isRestricted()) { // reset the changed flag changed = false; // new value should always be the same regardles of who is // making the request newValue = ObjectUtils.getNestedValue(newVendor, fieldName); // first we need to handle the case of edit doc && initiator if (isInitiator && document.isEdit()) { // old value must equal new value oldValue = ObjectUtils.getNestedValue(oldVendor, fieldName); } else if (isApprover && savedNewBo != null) { oldValue = ObjectUtils.getNestedValue(savedNewBo, fieldName); } // check to make sure nothing has changed if (oldValue == null && newValue == null) { changed = false; } else if ((oldValue == null && newValue != null) || (oldValue != null && newValue == null)) { changed = true; } else if (oldValue != null && newValue != null) { if (!oldValue.equals(newValue)) { changed = true; } } // if changed and a NEW doc, but the new value is the default value, then let it go // we dont allow changing to default values for EDIT docs though, only NEW if (changed && document.isNew()) { String defaultValue = maintDocDictionaryService.getFieldDefaultValue(document.getNewMaintainableObject().getBoClass(), fieldName); // get the string value of newValue String newStringValue = newValue.toString(); // if the newValue is the default value, then ignore if (newStringValue.equalsIgnoreCase(defaultValue)) { changed = false; } } // if anything has changed, complain if (changed) { String humanReadableFieldName = ddService.getAttributeLabel(document.getNewMaintainableObject().getBoClass(), fieldName); putFieldError(fieldName, KFSKeyConstants.ERROR_DOCUMENT_AUTHORIZATION_RESTRICTED_FIELD_CHANGED, humanReadableFieldName); success &= false; } } } } return success; } /** * This method refreshes the references of vendor detail and its sub objects */ void refreshSubObjects(VendorDetail vendor) { if (vendor == null) { return; } // If this is a division vendor, we need to do a refreshNonUpdateableReferences // and also refreshes the vendor header, since the user aren't supposed to // make any updates of vendor header's attributes while editing a division vendor if (!vendor.isVendorParentIndicator()) { vendor.refreshNonUpdateableReferences(); vendor.getVendorHeader().refreshNonUpdateableReferences(); } else { // Retrieve the references objects of the vendor header of this vendor. List<String> headerFieldNames = getObjectReferencesListFromBOClass(vendor.getVendorHeader().getClass()); SpringServiceLocator.getPersistenceService().retrieveReferenceObjects(vendor.getVendorHeader(), headerFieldNames); // We still need to retrieve all the other references of this vendor in addition to // vendor header. Since this is a parent vendor, whose vendor header saving is handled manually, // we have already retrieved references for vendor header's attributes above, so we should // exclude retrieving reference objects of vendor header. List<String> detailFieldNames = getObjectReferencesListFromBOClass(vendor.getClass()); detailFieldNames.remove(VendorConstants.VENDOR_HEADER_ATTR); SpringServiceLocator.getPersistenceService().retrieveReferenceObjects(vendor, detailFieldNames); } // refresh addresses if (vendor.getVendorAddresses() != null) { for (VendorAddress address : vendor.getVendorAddresses()) { address.refreshNonUpdateableReferences(); if (address.getVendorDefaultAddresses() != null) { for (VendorDefaultAddress defaultAddress : address.getVendorDefaultAddresses()) { defaultAddress.refreshNonUpdateableReferences(); } } } } // refresh contacts if (vendor.getVendorContacts() != null) { for (VendorContact contact : vendor.getVendorContacts()) { contact.refreshNonUpdateableReferences(); } } // refresh contracts if (vendor.getVendorContracts() != null) { for (VendorContract contract : vendor.getVendorContracts()) { contract.refreshNonUpdateableReferences(); } } } /** * This method is currently used as a helper to get a list of object references (e.g. vendorType, vendorOwnershipType, etc) from * a BusinessObject (e.g. VendorHeader, VendorDetail, etc) class dynamically. Feel free to enhance it, refactor it or move it to * a superclass or elsewhere as you see appropriate. * * @return List a List of attributes of the class */ private List getObjectReferencesListFromBOClass(Class theClass) { List<String> results = new ArrayList(); for (Field theField : theClass.getDeclaredFields()) { try { theField.getType().asSubclass(PersistableBusinessObjectBase.class); // only add the field to the result list if this is not // a UniversalUser if (!theField.getType().equals(UniversalUser.class)) { results.add(theField.getName()); } } catch (ClassCastException e) { // If we catches this, it means the "theField" can't be casted as a BusinessObjectBase, // so we won't add it to the results list because this method is aiming at getting // a list of object references that are subclasses of BusinessObjectBase. } } return results; } protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) { boolean valid = processValidation(document); return valid & super.processCustomApproveDocumentBusinessRules(document); } protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { boolean valid = processValidation(document); return valid & super.processCustomRouteDocumentBusinessRules(document); } protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { boolean valid = true; return valid & super.processCustomSaveDocumentBusinessRules(document); } private boolean processValidation(MaintenanceDocument document) { boolean valid = true; valid &= processVendorValidation(document); if (ObjectUtils.isNotNull(newVendor.getVendorHeader().getVendorType())) { valid &= processAddressValidation(document); } valid &= processContractValidation(document); return valid; } boolean processVendorValidation(MaintenanceDocument document) { boolean valid = true; VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); valid &= validateTaxTypeAndTaxNumberBlankness(vendorDetail); valid &= validateParentVendorTaxNumber(vendorDetail); valid &= validateOwnershipTypeAllowed(vendorDetail); valid &= validateTaxNumberFromTaxNumberService(vendorDetail); valid &= validateInactiveReasonRequiredness(vendorDetail); if (ObjectUtils.isNotNull(vendorDetail.getVendorHeader().getVendorType())) { valid &= validateTaxNumberRequiredness(vendorDetail); } valid &= validateVendorNames(vendorDetail); valid &= validateMinimumOrderAmount(vendorDetail); valid &= validateOwnershipCategory(vendorDetail); return valid; } /** * This method validates that if the vendor is set to be inactive, the inactive reason is required. * * @param vendorDetail the VendorDetail object to be validated * @return False if the vendor is inactive and the inactive reason is empty */ boolean validateInactiveReasonRequiredness(VendorDetail vendorDetail) { if (!vendorDetail.isActiveIndicator() && StringUtils.isEmpty(vendorDetail.getVendorInactiveReasonCode())) { putFieldError(VendorPropertyConstants.VENDOR_INACTIVE_REASON, VendorKeyConstants.ERROR_INACTIVE_REASON_REQUIRED); return false; } return true; } /** * This method validates that if the vendor is not foreign and if the vendor type's tax number required indicator is true, then * the tax number is required. If the vendor foreign indicator is true, then the tax number is not required regardless of its * vendor type. * * @param vendorDetail the VendorDetail object to be validated * @return False if there is no tax number and the indicator is true. */ boolean validateTaxNumberRequiredness(VendorDetail vendorDetail) { if (!vendorDetail.getVendorHeader().getVendorForeignIndicator() && vendorDetail.getVendorHeader().getVendorType().isVendorTaxNumberRequiredIndicator() && StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber())) { if (vendorDetail.isVendorParentIndicator()) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_TYPE_REQUIRES_TAX_NUMBER, vendorDetail.getVendorHeader().getVendorType().getVendorTypeDescription()); } else { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return false; } return true; } /** * This method validates that if vendor is parent, then tax # and tax type combo should be unique by checking for the existence * of vendor(s) with the same tax # and tax type in the existing vendor header table. Ideally we're also supposed to check for * pending vendors, but at the moment, the pending vendors are under research investigation, so we're only checking the existing * vendors for now. If the vendor is a parent and the validation fails, display the actual error message. If the vendor is not a * parent and the validation fails, display the error message that the parent of this vendor needs to be changed, please contact * Purchasing Dept. While checking for the existence of vendors with the same tax # and tax type, exclude the vendors with the * same id. KULPURAP-302: Allow a duplication of a tax number in vendor header if there are only "inactive" header records with * the duplicate record * * @param vendorDetail the VendorDetail object to be validated * @return boolean true if the vendorDetail passes the unique tax # and tax type validation. */ boolean validateParentVendorTaxNumber(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); Map criteria = new HashMap(); criteria.put(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, vendorDetail.getVendorHeader().getVendorTaxTypeCode()); criteria.put(VendorPropertyConstants.VENDOR_TAX_NUMBER, vendorDetail.getVendorHeader().getVendorTaxNumber()); criteria.put(KFSPropertyConstants.ACTIVE_INDICATOR, true); Map negativeCriteria = new HashMap(); int existingVendor = 0; // If this is editing an existing vendor, we have to include the current vendor's // header generated id in the negative criteria so that the current vendor is // excluded from the search if (ObjectUtils.isNotNull(vendorDetail.getVendorHeaderGeneratedIdentifier())) { negativeCriteria.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID, vendorDetail.getVendorHeaderGeneratedIdentifier()); existingVendor = getBoService().countMatching(VendorDetail.class, criteria, negativeCriteria); } else { // If this is creating a new vendor, we can't include the header generated id // in the negative criteria because it's null, so we'll only look for existing // vendors with the same tax # and tax type regardless of the vendor header generated id. existingVendor = getBoService().countMatching(VendorDetail.class, criteria); } if (existingVendor > 0) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_AND_NUMBER_COMBO_EXISTS); } else { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } valid &= false; } return valid; } /** * This method validates that the following business rules are satisfied: 1. Tax type cannot be blank if the tax # is not blank. * 2. Tax type cannot be set if the tax # is blank. If the vendor is a parent and the validation fails, we'll display an error * message indicating that the tax type cannot be blank if the tax # is not blank or that the tax type cannot be set if the tax # * is blank. If the vendor is not a parent and the validation fails, we'll display an error message indicating that the parent * of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail the VendorDetail object to be validated * @return boolean true if the vendor Detail passes the validation and false otherwise. */ boolean validateTaxTypeAndTaxNumberBlankness(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); if (!StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber()) && (StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxTypeCode()))) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_CANNOT_BE_BLANK); } valid &= false; } else if (StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber()) && !StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxTypeCode())) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_CANNOT_BE_SET); } valid &= false; } if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * This method validates the vendorName, vendorFirstName and vendorLastName fields according to these business rules: 1. At * least one of the three vendor name fields must be filled in. 2. Both of the two ways of entering vendor name (One vendor name * field vs VendorFirstName/VendorLastName) cannot be used 3. If either the vendor first name or the vendor last name have been * entered, the other must be entered. * * @param vendorDetail The VendorDetail object to be validated * @return boolean true if the vendorDetail passes this validation and false otherwise. */ protected boolean validateVendorNames(VendorDetail vendorDetail) { boolean valid = true; if (StringUtils.isBlank(vendorDetail.getVendorName())) { // At least one of the three vendor name fields must be filled in. if (StringUtils.isBlank(vendorDetail.getVendorFirstName()) && StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_NAME_REQUIRED); valid &= false; } // If either the vendor first name or the vendor last name have been entered, the other must be entered. else if (StringUtils.isBlank(vendorDetail.getVendorFirstName()) || StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_BOTH_NAME_REQUIRED); valid &= false; } } else { // Both of the two ways of entering vendor name (One vendor name field vs VendorFirstName/VendorLastName) cannot be used if (!StringUtils.isBlank(vendorDetail.getVendorFirstName()) || !StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_NAME_INVALID); valid &= false; } } return valid; } /** * This method validates the ownership type codes that aren't allowed for the tax type of the vendor. The rules are : 1. If tax * type is "SSN", then check the ownership type against the allowed types for "SSN" in the Rules table. 2. If tax type is * "FEIN", then check the ownership type against the allowed types for "FEIN" in the Rules table. If the vendor is a parent and * the validation fails, display the actual error message. If the vendor is not a parent and the validation fails, display the * error message that the parent of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail The VendorDetail object to be validated * @return TRUE if the ownership type is allowed and FALSE otherwise. */ private boolean validateOwnershipTypeAllowed(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); String ownershipTypeCode = vendorDetail.getVendorHeader().getVendorOwnershipCode(); String taxTypeCode = vendorDetail.getVendorHeader().getVendorTaxTypeCode(); if (StringUtils.isNotEmpty(ownershipTypeCode) && StringUtils.isNotEmpty(taxTypeCode)) { if (VendorConstants.TAX_TYPE_FEIN.equals(taxTypeCode)) { KualiParameterRule feinRule = SpringServiceLocator.getKualiConfigurationService().getApplicationParameterRule(PURAP_ADMIN_GROUP, PURAP_FEIN_ALLOWED_OWNERSHIP_TYPES); if (feinRule.failsRule(ownershipTypeCode)) { valid &= false; } } else if (VendorConstants.TAX_TYPE_SSN.equals(taxTypeCode)) { KualiParameterRule ssnRule = SpringServiceLocator.getKualiConfigurationService().getApplicationParameterRule(PURAP_ADMIN_GROUP, PURAP_SSN_ALLOWED_OWNERSHIP_TYPES); if (ssnRule.failsRule(ownershipTypeCode)) { valid &= false; } } } if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_OWNERSHIP_TYPE_CODE_NOT_ALLOWED, new String[] { vendorDetail.getVendorHeader().getVendorOwnership().getVendorOwnershipDescription(), taxTypeCode }); } else if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * Per code review 9/19, these business rules should be moved to the rule table. This method validates that the minimum order * amount is less than the minimum order amount constant that is currently defined in VendorConstants.java but someday should be * moved to APC. * * @param vendorDetail The VendorDetail object to be validated * @return True if the vendorMinimumOrderAmount is less than the minimum order amount specified in the VendorConstants (in the * future the amount will be in APC). */ private boolean validateMinimumOrderAmount(VendorDetail vendorDetail) { boolean valid = true; KualiDecimal minimumOrderAmount = vendorDetail.getVendorMinimumOrderAmount(); if (minimumOrderAmount != null) { if (ObjectUtils.isNull(VENDOR_MIN_ORDER_AMOUNT)) { BusinessRule minOrderAmountRule = getKualiConfigurationService().getApplicationRule(PURAP_ADMIN_GROUP, PURAP_VENDOR_MIN_ORDER_AMOUNT); VENDOR_MIN_ORDER_AMOUNT = new KualiDecimal(minOrderAmountRule.getRuleText()); } if ((VENDOR_MIN_ORDER_AMOUNT.compareTo(minimumOrderAmount) < 1) || (minimumOrderAmount.isNegative())) { putFieldError(VendorPropertyConstants.VENDOR_MIN_ORDER_AMOUNT, VendorKeyConstants.ERROR_VENDOR_MAX_MIN_ORDER_AMOUNT, VENDOR_MIN_ORDER_AMOUNT.toString()); valid &= false; } } return valid; } /** * This method validates that if the ownership category allowed indicator is false, the vendor does not have ownership category. * It will return false if the vendor contains ownership category. If the vendor is a parent and the validation fails, display * the actual error message. If the vendor is not a parent and the validation fails, display the error message that the parent * of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail The VendorDetail to be validated * @return true if the vendor does not contain ownership category and false otherwise */ private boolean validateOwnershipCategory(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); OwnershipType ot = vendorDetail.getVendorHeader().getVendorOwnership(); if (ot != null && !ot.getVendorOwnershipCategoryAllowedIndicator()) { if (ObjectUtils.isNotNull(vendorDetail.getVendorHeader().getVendorOwnershipCategory())) { valid &= false; } } if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CATEGORY_CODE, VendorKeyConstants.ERROR_OWNERSHIP_CATEGORY_CODE_NOT_ALLOWED, new String[] { vendorDetail.getVendorHeader().getVendorOwnershipCategory().getVendorOwnershipCategoryDescription(), vendorDetail.getVendorHeader().getVendorOwnership().getVendorOwnershipDescription() }); } else if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * This method calls the methods in TaxNumberService to validate the tax number for these business rules: 1. Tax number must be * 9 digits and cannot be all zeros (but can be blank). 2. First three digits of a SSN cannot be 000. 3. First three digits of a * SSN cannot be 666. 4. Middle two digits of a SSN cannot be 00. 5. Last four digits of a SSN cannot be 0000. 6. First two * digits of a FEIN cannot be 00. 7. TODO: This tax number is not allowed: 356001673 * * @param vendorDetail The VendorDetail object to be validated * @return true if the tax number is a valid tax number and false otherwise. */ private boolean validateTaxNumberFromTaxNumberService(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); String taxNumber = vendorDetail.getVendorHeader().getVendorTaxNumber(); String taxType = vendorDetail.getVendorHeader().getVendorTaxTypeCode(); if (!StringUtils.isEmpty(taxType) && !StringUtils.isEmpty(taxNumber)) { valid = SpringServiceLocator.getTaxNumberService().isValidTaxNumber(taxNumber, taxType); if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_TAX_NUMBER_INVALID); } valid = SpringServiceLocator.getTaxNumberService().isAllowedTaxNumber(taxNumber); if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_TAX_NUMBER_NOT_ALLOWED); } } if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } boolean processAddressValidation(MaintenanceDocument document) { boolean valid = true; boolean validAddressType = false; List<VendorAddress> addresses = newVendor.getVendorAddresses(); String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode(); String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType().getVendorAddressTypeRequiredCode(); for (int i = 0; i < addresses.size(); i++) { VendorAddress address = addresses.get(i); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) { validAddressType = true; } valid &= checkFaxNumber(address); valid &= checkAddressCountryEmptyStateZip(address); GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } // validate Address Type if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode) && !validAddressType) { String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode }; putFieldError(VendorPropertyConstants.VENDOR_TYPE_CODE, VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters); valid = false; } valid &= validateDefaultAddressCampus(newVendor); // Check to see if all divisions have one desired address for this vendor type Map fieldValues = new HashMap(); fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID, newVendor.getVendorHeaderGeneratedIdentifier()); // Find all the addresses for this vendor and its divisions: List<VendorAddress> vendorDivisionAddresses = new ArrayList(SpringServiceLocator.getBusinessObjectService().findMatchingOrderBy(VendorAddress.class, fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true)); // This set stores the vendorDetailedAssignedIds for the vendor divisions which is // bascically the division numbers 0, 1, 2, ... HashSet<Integer> vendorDetailedIds = new HashSet(); // This set stores the vendor division numbers of the ones which have one address of the desired type HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet(); for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) { vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier()); if (vendorDivisionAddress.getVendorAddressTypeCode().equalsIgnoreCase(vendorAddressTypeRequiredCode)) { vendorDivisionsIdsWithDesiredAddressType.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier()); } } // If the number of divisions with the desired address type is less than the number of divisions for his vendor if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) { Iterator itr = vendorDetailedIds.iterator(); Integer value; String vendorId; while (itr.hasNext()) { value = (Integer) itr.next(); if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) { vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-' + value.toString(); String[] parameters = new String[] { vendorId, vendorTypeCode, vendorAddressTypeRequiredCode }; putFieldError(VendorPropertyConstants.VENDOR_TYPE_CODE, VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters); valid = false; } } } return valid; } /** * This method validates that if US is selcted for country that the state and zip are not empty * * @param addresses * @return */ boolean checkAddressCountryEmptyStateZip(VendorAddress address) { boolean valid = true; boolean noPriorErrMsg = true; Country country = address.getVendorCountry(); if (ObjectUtils.isNotNull(country) && StringUtils.equals(KFSConstants.COUNTRY_CODE_UNITED_STATES, country.getPostalCountryCode())) { if ((ObjectUtils.isNull(address.getVendorState()) || StringUtils.isEmpty(address.getVendorState().getPostalStateCode()))) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_ADDRESS_STATE, VendorKeyConstants.ERROR_US_REQUIRES_STATE); valid &= false; noPriorErrMsg = false; } // The error message here will be the same for both, and should not be repeated (KULPURAP-516). if (noPriorErrMsg && StringUtils.isEmpty(address.getVendorZipCode())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_ADDRESS_ZIP, VendorKeyConstants.ERROR_US_REQUIRES_ZIP); valid &= false; } } return valid; } /** * This method checks if the "allow default indicator" is true or false for this address. * * @param addresses * @return */ boolean findAllowDefaultAddressIndicatorHelper(VendorAddress vendorAddress) { AddressType addressType = new AddressType(); addressType = vendorAddress.getVendorAddressType(); if (ObjectUtils.isNull(addressType)) { return false; } // Retreiving the Default Address Indicator for this Address Type: return addressType.getVendorDefaultIndicator(); } /** * This method When add button is selected on Default Address, checks if the allow default indicator is set to false for this * address type then it does not allow user to select a default address for this address and if it is true then it allows only * one campus to be default for this address. * * @param addresses * @return */ // TODO: Naser See if there is a way to put the error message in the address tab instead of down the page boolean checkDefaultAddressCampus(VendorDetail vendorDetail, VendorDefaultAddress addedDefaultAddress, VendorAddress parent) { VendorAddress vendorAddress = parent; if (ObjectUtils.isNull(vendorAddress)) { return false; } int j = vendorDetail.getVendorAddresses().indexOf(vendorAddress); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + j + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); // Retreiving the Default Address Indicator for this Address Type: boolean allowDefaultAddressIndicator = findAllowDefaultAddressIndicatorHelper(vendorAddress); String addedAddressCampusCode = addedDefaultAddress.getVendorCampusCode(); String addedAddressTypeCode = vendorAddress.getVendorAddressTypeCode(); // if the selected address type does not allow defaults, then the user should not be allowed to // select the default indicator or add any campuses to the address if (allowDefaultAddressIndicator == false) { String[] parameters = new String[] { addedAddressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + 0 + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS_NOT_ALLOWED, parameters); return false; } List<VendorDefaultAddress> vendorDefaultAddresses = vendorAddress.getVendorDefaultAddresses(); for (int i = 0; i < vendorDefaultAddresses.size(); i++) { VendorDefaultAddress vendorDefaultAddress = vendorDefaultAddresses.get(i); if (vendorDefaultAddress.getVendorCampusCode().equalsIgnoreCase(addedAddressCampusCode)) { String[] parameters = new String[] { addedAddressCampusCode, addedAddressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + i + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS, parameters); // GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); return false; } } return true; } /** * This method checks if the allow default indicator is set to false for this address the default indicator cannot be set to * true/yes. If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set * (no more, no less) and only one campus to be set as default for this address. * * @param vendorDetail * @return false or true */ boolean validateDefaultAddressCampus(VendorDetail vendorDetail) { List<VendorAddress> vendorAddresses = vendorDetail.getVendorAddresses(); String addressTypeCode; String campusCode; boolean valid = true; boolean previousValue = false; // This is a HashMap to store the default Address Type Codes and their associated default Indicator HashMap addressTypeCodeDefaultIndicator = new HashMap(); // This is a HashMap to store Address Type Codes and Address Campus Codes for Default Addresses HashMap addressTypeDefaultCampus = new HashMap(); // This is a HashSet for storing only the Address Type Codes which have at leat one default Indicator set to true HashSet addressTypesHavingDefaultTrue = new HashSet(); int i = 0; for (VendorAddress address : vendorAddresses) { addressTypeCode = address.getVendorAddressTypeCode(); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); String[] parameters = new String[] { addressTypeCode }; // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set (no // more, no less). // For example, if a vendor contains three PO type addresses and the PO address type is set to allow defaults in the // address type table, // then only one of these PO addresses can have the default indicator set to true/yes. if (findAllowDefaultAddressIndicatorHelper(address)) { if (address.isVendorDefaultAddressIndicator()) { addressTypesHavingDefaultTrue.add(addressTypeCode); } if (!addressTypeCodeDefaultIndicator.isEmpty() && addressTypeCodeDefaultIndicator.containsKey(addressTypeCode)) { previousValue = ((Boolean) addressTypeCodeDefaultIndicator.get(addressTypeCode)).booleanValue(); } if (addressTypeCodeDefaultIndicator.put(addressTypeCode, address.isVendorDefaultAddressIndicator()) != null && previousValue && address.isVendorDefaultAddressIndicator()) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR, parameters); valid = false; } } // If "allow default indicator" is set to false/no for address type, the default indicator cannot be set to true/yes. else { if (address.isVendorDefaultAddressIndicator()) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_ADDRESS_NOT_ALLOWED, parameters); valid = false; } } List<VendorDefaultAddress> vendorDefaultAddresses = address.getVendorDefaultAddresses(); // If "allow default indicator" is set to true/yes for address type, a campus can only be set on one of each type of // Address. // For example, Bloomington can not be included in the campus list for two PO type addresses. // Each campus can only have one default address. int j = 0; for (VendorDefaultAddress defaultAddress : vendorDefaultAddresses) { campusCode = (String) addressTypeDefaultCampus.put(addressTypeCode, defaultAddress.getVendorCampusCode()); if (StringUtils.isNotBlank(campusCode) && campusCode.equalsIgnoreCase(defaultAddress.getVendorCampusCode())) { String[] newParameters = new String[] { defaultAddress.getVendorCampusCode(), addressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + j + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS, newParameters); valid = false; } j++; } i++; GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set to true if (!addressTypeCodeDefaultIndicator.isEmpty()) { Set<String> addressTypes = addressTypeCodeDefaultIndicator.keySet(); for (String addressType : addressTypes) { if (!addressTypesHavingDefaultTrue.contains(addressType)) { String[] parameters = new String[] { addressType }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR, parameters); valid = false; } } } return valid; } /** * This method validates that the Vendor Fax Number is a valid phone number. * * @param addresses * @return */ boolean checkFaxNumber(VendorAddress address) { boolean valid = true; String faxNumber = address.getVendorFaxNumber(); if (StringUtils.isNotEmpty(faxNumber) && !SpringServiceLocator.getPhoneNumberService().isValidPhoneNumber(faxNumber)) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_FAX_NUMBER, VendorKeyConstants.ERROR_FAX_NUMBER); valid &= false; } return valid; } private boolean processContactValidation(MaintenanceDocument document) { boolean valid = true; // leaving stub method here as placeholder for future Contact Validation return valid; } private boolean processCustomerNumberValidation(MaintenanceDocument document) { boolean valid = true; List<VendorCustomerNumber> customerNumbers = newVendor.getVendorCustomerNumbers(); for (VendorCustomerNumber customerNumber : customerNumbers) { valid &= validateVendorCustomerNumber(customerNumber); } return valid; } boolean validateVendorCustomerNumber(VendorCustomerNumber customerNumber) { boolean valid = true; // The chart and org must exist in the database. String chartOfAccountsCode = customerNumber.getChartOfAccountsCode(); String orgCode = customerNumber.getVendorOrganizationCode(); if (!StringUtils.isBlank(chartOfAccountsCode) && !StringUtils.isBlank(orgCode)) { Map chartOrgMap = new HashMap(); chartOrgMap.put("chartOfAccountsCode", chartOfAccountsCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Chart.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CUSTOMER_NUMBER_CHART_OF_ACCOUNTS_CODE, KFSKeyConstants.ERROR_EXISTENCE, chartOfAccountsCode); valid &= false; } chartOrgMap.put("organizationCode", orgCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Org.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CUSTOMER_NUMBER_ORGANIZATION_CODE, KFSKeyConstants.ERROR_EXISTENCE, orgCode); valid &= false; } } return valid; } private boolean processContractValidation(MaintenanceDocument document) { boolean valid = true; List<VendorContract> contracts = newVendor.getVendorContracts(); if (ObjectUtils.isNull(contracts)) { return valid; } //If the vendorContractAllowedIndicator is false, it cannot have vendor contracts, return false; if (contracts.size() > 0 && !newVendor.getVendorHeader().getVendorType().isVendorContractAllowedIndicator()) { valid = false; String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_CONTRACT + "[0]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); GlobalVariables.getErrorMap().putError( VendorPropertyConstants.VENDOR_CONTRACT_NAME, VendorKeyConstants.ERROR_VENDOR_CONTRACT_NOT_ALLOWED ); return valid; } for (int i = 0; i < contracts.size(); i++) { VendorContract contract = contracts.get(i); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_CONTRACT + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); valid &= validateVendorContractPOLimitAndExcludeFlagCombination(contract); valid &= validateVendorContractBeginEndDates(contract); GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } return valid; } /** * This method validates that the proper combination of Exclude Indicator and APO Amount is present on a vendor contract. Do not * perform this validation on Contract add line as the user cannot currently enter the sub-collection of contract-orgs so we * should not force this until the document is submitted. The rules are : 1. Must enter a Default APO Limit or at least one * organization with an APO Amount. 2. If the Exclude Indicator for an organization is N, an organization APO Amount is * required. 3. If the Exclude Indicator for an organization is Y, the organization APO Amount is not allowed. * * @return True if the proper combination of Exclude Indicator and APO Amount is present. False otherwise. */ boolean validateVendorContractPOLimitAndExcludeFlagCombination(VendorContract contract) { boolean valid = true; boolean NoOrgHasApoLimit = true; List<VendorContractOrganization> organizations = contract.getVendorContractOrganizations(); if (ObjectUtils.isNotNull(organizations)) { int organizationCounter = 0; for (VendorContractOrganization organization : organizations) { if (ObjectUtils.isNotNull(organization.getVendorContractPurchaseOrderLimitAmount())) { NoOrgHasApoLimit = false; } valid &= validateVendorContractOrganization(organization); organizationCounter++; } } if (NoOrgHasApoLimit && ObjectUtils.isNull(contract.getOrganizationAutomaticPurchaseOrderLimit())) { // Rule #1 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_DEFAULT_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_NO_APO_LIMIT); valid &= false; } return valid; } /** * This method validates that: 1. If the VendorContractBeginningDate is entered then the VendorContractEndDate is also entered, * and vice versa. 2. If both dates are entered, the VendorContractBeginningDate is before the VendorContractEndDate. The date * fields are required so we should know that we have valid dates. * * @return True if the beginning date is before the end date. False if only one date is entered or the beginning date is after * the end date. */ boolean validateVendorContractBeginEndDates(VendorContract contract) { boolean valid = true; if (ObjectUtils.isNotNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNull(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_END_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_BEGIN_DATE_NO_END_DATE); valid &= false; } else { if (ObjectUtils.isNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNotNull(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_BEGIN_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_END_DATE_NO_BEGIN_DATE); valid &= false; } } if (valid && ObjectUtils.isNotNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNotNull(contract.getVendorContractEndDate())) { if (contract.getVendorContractBeginningDate().after(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_BEGIN_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_BEGIN_DATE_AFTER_END); valid &= false; } } // contractCounter++; // } return valid; } /** * This method validates a vendor contract organization. The rules are : 1. If the Exclude Indicator for the organization is N, * an organization APO Amount is required. 2. If the Exclude Indicator for the organization is Y, an organization APO Amount is * not allowed. 3. The chart and org for the organization must exist in the database. * * @return True if these three rules are passed. False otherwise. */ boolean validateVendorContractOrganization(VendorContractOrganization organization) { boolean valid = true; boolean isExcluded = organization.isVendorContractExcludeIndicator(); if (isExcluded) { if (ObjectUtils.isNotNull(organization.getVendorContractPurchaseOrderLimitAmount())) { // Rule #2 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_ORG_EXCLUDED_WITH_APO_LIMIT); valid &= false; } } else { // isExcluded = false if (ObjectUtils.isNull(organization.getVendorContractPurchaseOrderLimitAmount())) { // Rule #1 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_ORG_NOT_EXCLUDED_NO_APO_LIMIT); valid &= false; } } // The chart and org must exist in the database. String chartOfAccountsCode = organization.getChartOfAccountsCode(); String orgCode = organization.getOrganizationCode(); if (!StringUtils.isBlank(chartOfAccountsCode) && !StringUtils.isBlank(orgCode)) { Map chartOrgMap = new HashMap(); chartOrgMap.put("chartOfAccountsCode", chartOfAccountsCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Chart.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_CHART_OF_ACCOUNTS_CODE, KFSKeyConstants.ERROR_EXISTENCE, chartOfAccountsCode); valid &= false; } chartOrgMap.put("organizationCode", orgCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Org.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_CODE, KFSKeyConstants.ERROR_EXISTENCE, orgCode); valid &= false; } } return valid; } public boolean processCustomAddCollectionLineBusinessRules(MaintenanceDocument document, String collectionName, PersistableBusinessObject bo) { boolean success = true; // this incoming bo needs to be refreshed because it doesn't have its subobjects setup // TODO: can this be moved up? bo.refreshNonUpdateableReferences(); if (bo instanceof VendorAddress) { VendorAddress address = (VendorAddress) bo; success &= checkAddressCountryEmptyStateZip(address); VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); } if (bo instanceof VendorContract) { VendorContract contract = (VendorContract) bo; success &= validateVendorContractBeginEndDates(contract); } if (bo instanceof VendorContractOrganization) { VendorContractOrganization contractOrg = (VendorContractOrganization) bo; success &= validateVendorContractOrganization(contractOrg); } if (bo instanceof VendorCustomerNumber) { VendorCustomerNumber customerNumber = (VendorCustomerNumber) bo; success &= validateVendorCustomerNumber(customerNumber); } if (bo instanceof VendorDefaultAddress) { VendorDefaultAddress defaultAddress = (VendorDefaultAddress) bo; // TODO: this is a total hack we shouldn't have to set the foreign key here, this should be set in the parent // in a much more general way see issue KULPURAP-266 for a preliminary discussion String parentName = StringUtils.substringBeforeLast(collectionName, "."); VendorAddress parent = (VendorAddress) ObjectUtils.getPropertyValue(this.getNewBo(), parentName); VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); success &= checkDefaultAddressCampus(vendorDetail, defaultAddress, parent); } return success; } }
work/src/org/kuali/kfs/vnd/document/validation/impl/VendorRule.java
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.vendor.rules; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; 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 org.apache.commons.lang.StringUtils; import org.kuali.core.authorization.FieldAuthorization; import org.kuali.core.bo.BusinessRule; import org.kuali.core.bo.PersistableBusinessObject; import org.kuali.core.bo.PersistableBusinessObjectBase; import org.kuali.core.bo.user.UniversalUser; import org.kuali.core.document.MaintenanceDocument; import org.kuali.core.document.authorization.MaintenanceDocumentAuthorizations; import org.kuali.core.document.authorization.MaintenanceDocumentAuthorizer; import org.kuali.core.exceptions.UnknownDocumentIdException; import org.kuali.core.maintenance.Maintainable; import org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase; import org.kuali.core.rule.KualiParameterRule; import org.kuali.core.service.DocumentService; import org.kuali.core.util.GlobalVariables; import org.kuali.core.util.KualiDecimal; import org.kuali.core.util.ObjectUtils; import org.kuali.core.workflow.service.KualiWorkflowDocument; import org.kuali.kfs.KFSConstants; import org.kuali.kfs.KFSKeyConstants; import org.kuali.kfs.KFSPropertyConstants; import org.kuali.kfs.bo.Country; import org.kuali.kfs.util.SpringServiceLocator; import org.kuali.module.chart.bo.Chart; import org.kuali.module.chart.bo.Org; import org.kuali.module.vendor.VendorConstants; import org.kuali.module.vendor.VendorKeyConstants; import org.kuali.module.vendor.VendorPropertyConstants; import org.kuali.module.vendor.VendorRuleConstants; import org.kuali.module.vendor.bo.AddressType; import org.kuali.module.vendor.bo.OwnershipType; import org.kuali.module.vendor.bo.VendorAddress; import org.kuali.module.vendor.bo.VendorContact; import org.kuali.module.vendor.bo.VendorContract; import org.kuali.module.vendor.bo.VendorContractOrganization; import org.kuali.module.vendor.bo.VendorCustomerNumber; import org.kuali.module.vendor.bo.VendorDefaultAddress; import org.kuali.module.vendor.bo.VendorDetail; import edu.iu.uis.eden.exception.WorkflowException; public class VendorRule extends MaintenanceDocumentRuleBase implements VendorRuleConstants { private VendorDetail oldVendor; private VendorDetail newVendor; private static KualiDecimal VENDOR_MIN_ORDER_AMOUNT; /** * This method is needed to override the setupBaseConvenienceObjects from the superclass because we cannot use the * setupBaseConvenienceObjects from the superclass. The reason we cannot use the superclass method is because it calls the * updateNonUpdateableReferences for everything and we cannot do that for parent vendors, because we want to update vendor * header information only on parent vendors, so the saving of the vendor header is done manually. If we call the * updateNonUpdateableReferences, it is going to overwrite any changes that the user might have done in the vendor header with * the existing values in the database. * * @param document The MaintenanceDocument object containing the vendorDetail objects to be setup. */ @Override public void setupBaseConvenienceObjects(MaintenanceDocument document) { oldVendor = (VendorDetail) document.getOldMaintainableObject().getBusinessObject(); newVendor = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); super.setNewBo(newVendor); setupConvenienceObjects(); } /** * This method setups oldVendor and newVendor convenience objects, make sure all possible sub-objects are populated. */ @Override public void setupConvenienceObjects() { // setup oldVendor convenience objects, make sure all possible sub-objects are populated refreshSubObjects(oldVendor); // setup newVendor convenience objects, make sure all possible sub-objects are populated refreshSubObjects(newVendor); } /** * This method overrides the checkAuthorizationRestrictions in MaintenanceDocumentRuleBase. The reason we needed to override it * is because in vendor, we had to save the fields in the vendor header separately than vendor detail, and those fields are only * editable when the vendor is a parent. Therefore we had to override the setupBaseConvenienceObjects method, which then causes * us unable to set the oldBo of the super class because the oldBo is not accessible from outside the class. This will cause the * checkAuthorizationRestrictions of the superclass to fail while processing division vendors that contain those restricted * (uneditable) fields, because the oldBo is null and will throw the null pointer exception. Therefore we're overriding the * checkAuthorizationRestrictions in here and we'll use the oldVendor instead of oldBo of the superclass while comparing the old * and new values. This also does not enforce the authorization restrictions if the restricted fields are the fields in vendor * header or the vendor is not a parent vendor, because in this case, the fields are uneditable from the user interface. * * @see org.kuali.core.maintenance.rules.MaintenanceDocumentRuleBase#checkAuthorizationRestrictions(org.kuali.core.document.MaintenanceDocument) */ @Override protected boolean checkAuthorizationRestrictions(MaintenanceDocument document) { boolean success = true; boolean changed = false; boolean isInitiator = false; boolean isApprover = false; Object oldValue = null; Object newValue = null; Object savedValue = null; KualiWorkflowDocument workflowDocument = null; UniversalUser user = GlobalVariables.getUserSession().getUniversalUser(); try { workflowDocument = getWorkflowDocumentService().createWorkflowDocument(Long.valueOf(document.getDocumentNumber()), user); } catch (WorkflowException e) { throw new UnknownDocumentIdException("no document found for documentHeaderId '" + document.getDocumentNumber() + "'", e); } if (user.getPersonUserIdentifier().equalsIgnoreCase(workflowDocument.getInitiatorNetworkId())) { // if these are the same person then we know it is the initiator isInitiator = true; } else if (workflowDocument.isApprovalRequested()) { isApprover = true; } // get the correct documentAuthorizer for this document MaintenanceDocumentAuthorizer documentAuthorizer = (MaintenanceDocumentAuthorizer) documentAuthorizationService.getDocumentAuthorizer(document); // get a new instance of MaintenanceDocumentAuthorizations for this context MaintenanceDocumentAuthorizations auths = documentAuthorizer.getFieldAuthorizations(document, user); // load a temp copy of the document from the DB to compare to for changes MaintenanceDocument savedDoc = null; Maintainable savedNewMaintainable = null; PersistableBusinessObject savedNewBo = null; if (isApprover) { try { DocumentService docService = SpringServiceLocator.getDocumentService(); savedDoc = (MaintenanceDocument) docService.getByDocumentHeaderId(document.getDocumentNumber()); } catch (WorkflowException e) { throw new RuntimeException("A WorkflowException was thrown which prevented the loading of " + "the comparison document (" + document.getDocumentNumber() + ")", e); } // attempt to retrieve the BO, but leave it blank if it or any of the objects on the path // to it are blank if (savedDoc != null) { savedNewMaintainable = savedDoc.getNewMaintainableObject(); if (savedNewMaintainable != null) { savedNewBo = savedNewMaintainable.getBusinessObject(); } } } // setup in-loop members FieldAuthorization fieldAuthorization = null; // walk through all the restrictions Collection restrictedFields = auths.getAuthFieldNames(); for (Iterator iter = restrictedFields.iterator(); iter.hasNext();) { String fieldName = (String) iter.next(); if (fieldName.indexOf(VendorPropertyConstants.VENDOR_HEADER_PREFIX) < 0 || newVendor.isVendorParentIndicator()) { // get the specific field authorization structure fieldAuthorization = auths.getAuthFieldAuthorization(fieldName); // if there are any restrictions, then enforce them if (fieldAuthorization.isRestricted()) { // reset the changed flag changed = false; // new value should always be the same regardles of who is // making the request newValue = ObjectUtils.getNestedValue(newVendor, fieldName); // first we need to handle the case of edit doc && initiator if (isInitiator && document.isEdit()) { // old value must equal new value oldValue = ObjectUtils.getNestedValue(oldVendor, fieldName); } else if (isApprover && savedNewBo != null) { oldValue = ObjectUtils.getNestedValue(savedNewBo, fieldName); } // check to make sure nothing has changed if (oldValue == null && newValue == null) { changed = false; } else if ((oldValue == null && newValue != null) || (oldValue != null && newValue == null)) { changed = true; } else if (oldValue != null && newValue != null) { if (!oldValue.equals(newValue)) { changed = true; } } // if changed and a NEW doc, but the new value is the default value, then let it go // we dont allow changing to default values for EDIT docs though, only NEW if (changed && document.isNew()) { String defaultValue = maintDocDictionaryService.getFieldDefaultValue(document.getNewMaintainableObject().getBoClass(), fieldName); // get the string value of newValue String newStringValue = newValue.toString(); // if the newValue is the default value, then ignore if (newStringValue.equalsIgnoreCase(defaultValue)) { changed = false; } } // if anything has changed, complain if (changed) { String humanReadableFieldName = ddService.getAttributeLabel(document.getNewMaintainableObject().getBoClass(), fieldName); putFieldError(fieldName, KFSKeyConstants.ERROR_DOCUMENT_AUTHORIZATION_RESTRICTED_FIELD_CHANGED, humanReadableFieldName); success &= false; } } } } return success; } /** * This method refreshes the references of vendor detail and its sub objects */ void refreshSubObjects(VendorDetail vendor) { if (vendor == null) { return; } // If this is a division vendor, we need to do a refreshNonUpdateableReferences // and also refreshes the vendor header, since the user aren't supposed to // make any updates of vendor header's attributes while editing a division vendor if (!vendor.isVendorParentIndicator()) { vendor.refreshNonUpdateableReferences(); vendor.getVendorHeader().refreshNonUpdateableReferences(); } else { // Retrieve the references objects of the vendor header of this vendor. List<String> headerFieldNames = getObjectReferencesListFromBOClass(vendor.getVendorHeader().getClass()); SpringServiceLocator.getPersistenceService().retrieveReferenceObjects(vendor.getVendorHeader(), headerFieldNames); // We still need to retrieve all the other references of this vendor in addition to // vendor header. Since this is a parent vendor, whose vendor header saving is handled manually, // we have already retrieved references for vendor header's attributes above, so we should // exclude retrieving reference objects of vendor header. List<String> detailFieldNames = getObjectReferencesListFromBOClass(vendor.getClass()); detailFieldNames.remove(VendorConstants.VENDOR_HEADER_ATTR); SpringServiceLocator.getPersistenceService().retrieveReferenceObjects(vendor, detailFieldNames); } // refresh addresses if (vendor.getVendorAddresses() != null) { for (VendorAddress address : vendor.getVendorAddresses()) { address.refreshNonUpdateableReferences(); if (address.getVendorDefaultAddresses() != null) { for (VendorDefaultAddress defaultAddress : address.getVendorDefaultAddresses()) { defaultAddress.refreshNonUpdateableReferences(); } } } } // refresh contacts if (vendor.getVendorContacts() != null) { for (VendorContact contact : vendor.getVendorContacts()) { contact.refreshNonUpdateableReferences(); } } // refresh contracts if (vendor.getVendorContracts() != null) { for (VendorContract contract : vendor.getVendorContracts()) { contract.refreshNonUpdateableReferences(); } } } /** * This method is currently used as a helper to get a list of object references (e.g. vendorType, vendorOwnershipType, etc) from * a BusinessObject (e.g. VendorHeader, VendorDetail, etc) class dynamically. Feel free to enhance it, refactor it or move it to * a superclass or elsewhere as you see appropriate. * * @return List a List of attributes of the class */ private List getObjectReferencesListFromBOClass(Class theClass) { List<String> results = new ArrayList(); for (Field theField : theClass.getDeclaredFields()) { try { theField.getType().asSubclass(PersistableBusinessObjectBase.class); // only add the field to the result list if this is not // a UniversalUser if (!theField.getType().equals(UniversalUser.class)) { results.add(theField.getName()); } } catch (ClassCastException e) { // If we catches this, it means the "theField" can't be casted as a BusinessObjectBase, // so we won't add it to the results list because this method is aiming at getting // a list of object references that are subclasses of BusinessObjectBase. } } return results; } protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) { boolean valid = processValidation(document); return valid & super.processCustomApproveDocumentBusinessRules(document); } protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { boolean valid = processValidation(document); return valid & super.processCustomRouteDocumentBusinessRules(document); } protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { boolean valid = true; return valid & super.processCustomSaveDocumentBusinessRules(document); } private boolean processValidation(MaintenanceDocument document) { boolean valid = true; valid &= processVendorValidation(document); if (ObjectUtils.isNotNull(newVendor.getVendorHeader().getVendorType())) { valid &= processAddressValidation(document); } valid &= processContractValidation(document); return valid; } boolean processVendorValidation(MaintenanceDocument document) { boolean valid = true; VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); valid &= validateTaxTypeAndTaxNumberBlankness(vendorDetail); valid &= validateParentVendorTaxNumber(vendorDetail); valid &= validateOwnershipTypeAllowed(vendorDetail); valid &= validateTaxNumberFromTaxNumberService(vendorDetail); valid &= validateInactiveReasonRequiredness(vendorDetail); if (ObjectUtils.isNotNull(vendorDetail.getVendorHeader().getVendorType())) { valid &= validateTaxNumberRequiredness(vendorDetail); } valid &= validateVendorNames(vendorDetail); valid &= validateMinimumOrderAmount(vendorDetail); valid &= validateOwnershipCategory(vendorDetail); return valid; } /** * This method validates that if the vendor is set to be inactive, the inactive reason is required. * * @param vendorDetail the VendorDetail object to be validated * @return False if the vendor is inactive and the inactive reason is empty */ boolean validateInactiveReasonRequiredness(VendorDetail vendorDetail) { if (!vendorDetail.isActiveIndicator() && StringUtils.isEmpty(vendorDetail.getVendorInactiveReasonCode())) { putFieldError(VendorPropertyConstants.VENDOR_INACTIVE_REASON, VendorKeyConstants.ERROR_INACTIVE_REASON_REQUIRED); return false; } return true; } /** * This method validates that if the vendor is not foreign and if the vendor type's tax number required indicator is true, then * the tax number is required. If the vendor foreign indicator is true, then the tax number is not required regardless of its * vendor type. * * @param vendorDetail the VendorDetail object to be validated * @return False if there is no tax number and the indicator is true. */ boolean validateTaxNumberRequiredness(VendorDetail vendorDetail) { if (!vendorDetail.getVendorHeader().getVendorForeignIndicator() && vendorDetail.getVendorHeader().getVendorType().isVendorTaxNumberRequiredIndicator() && StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber())) { if (vendorDetail.isVendorParentIndicator()) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_TYPE_REQUIRES_TAX_NUMBER, vendorDetail.getVendorHeader().getVendorType().getVendorTypeDescription()); } else { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return false; } return true; } /** * This method validates that if vendor is parent, then tax # and tax type combo should be unique by checking for the existence * of vendor(s) with the same tax # and tax type in the existing vendor header table. Ideally we're also supposed to check for * pending vendors, but at the moment, the pending vendors are under research investigation, so we're only checking the existing * vendors for now. If the vendor is a parent and the validation fails, display the actual error message. If the vendor is not a * parent and the validation fails, display the error message that the parent of this vendor needs to be changed, please contact * Purchasing Dept. While checking for the existence of vendors with the same tax # and tax type, exclude the vendors with the * same id. KULPURAP-302: Allow a duplication of a tax number in vendor header if there are only "inactive" header records with * the duplicate record * * @param vendorDetail the VendorDetail object to be validated * @return boolean true if the vendorDetail passes the unique tax # and tax type validation. */ boolean validateParentVendorTaxNumber(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); Map criteria = new HashMap(); criteria.put(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, vendorDetail.getVendorHeader().getVendorTaxTypeCode()); criteria.put(VendorPropertyConstants.VENDOR_TAX_NUMBER, vendorDetail.getVendorHeader().getVendorTaxNumber()); criteria.put(KFSPropertyConstants.ACTIVE_INDICATOR, true); Map negativeCriteria = new HashMap(); int existingVendor = 0; // If this is editing an existing vendor, we have to include the current vendor's // header generated id in the negative criteria so that the current vendor is // excluded from the search if (ObjectUtils.isNotNull(vendorDetail.getVendorHeaderGeneratedIdentifier())) { negativeCriteria.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID, vendorDetail.getVendorHeaderGeneratedIdentifier()); existingVendor = getBoService().countMatching(VendorDetail.class, criteria, negativeCriteria); } else { // If this is creating a new vendor, we can't include the header generated id // in the negative criteria because it's null, so we'll only look for existing // vendors with the same tax # and tax type regardless of the vendor header generated id. existingVendor = getBoService().countMatching(VendorDetail.class, criteria); } if (existingVendor > 0) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_AND_NUMBER_COMBO_EXISTS); } else { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } valid &= false; } return valid; } /** * This method validates that the following business rules are satisfied: 1. Tax type cannot be blank if the tax # is not blank. * 2. Tax type cannot be set if the tax # is blank. If the vendor is a parent and the validation fails, we'll display an error * message indicating that the tax type cannot be blank if the tax # is not blank or that the tax type cannot be set if the tax # * is blank. If the vendor is not a parent and the validation fails, we'll display an error message indicating that the parent * of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail the VendorDetail object to be validated * @return boolean true if the vendor Detail passes the validation and false otherwise. */ boolean validateTaxTypeAndTaxNumberBlankness(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); if (!StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber()) && (StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxTypeCode()))) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_CANNOT_BE_BLANK); } valid &= false; } else if (StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxNumber()) && !StringUtils.isBlank(vendorDetail.getVendorHeader().getVendorTaxTypeCode())) { if (isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_TAX_TYPE_CANNOT_BE_SET); } valid &= false; } if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_TYPE_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * This method validates the vendorName, vendorFirstName and vendorLastName fields according to these business rules: 1. At * least one of the three vendor name fields must be filled in. 2. Both of the two ways of entering vendor name (One vendor name * field vs VendorFirstName/VendorLastName) cannot be used 3. If either the vendor first name or the vendor last name have been * entered, the other must be entered. * * @param vendorDetail The VendorDetail object to be validated * @return boolean true if the vendorDetail passes this validation and false otherwise. */ protected boolean validateVendorNames(VendorDetail vendorDetail) { boolean valid = true; if (StringUtils.isBlank(vendorDetail.getVendorName())) { // At least one of the three vendor name fields must be filled in. if (StringUtils.isBlank(vendorDetail.getVendorFirstName()) && StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_NAME_REQUIRED); valid &= false; } // If either the vendor first name or the vendor last name have been entered, the other must be entered. else if (StringUtils.isBlank(vendorDetail.getVendorFirstName()) || StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_BOTH_NAME_REQUIRED); valid &= false; } } else { // Both of the two ways of entering vendor name (One vendor name field vs VendorFirstName/VendorLastName) cannot be used if (!StringUtils.isBlank(vendorDetail.getVendorFirstName()) || !StringUtils.isBlank(vendorDetail.getVendorLastName())) { putFieldError(VendorPropertyConstants.VENDOR_NAME, VendorKeyConstants.ERROR_VENDOR_NAME_INVALID); valid &= false; } } return valid; } /** * This method validates the ownership type codes that aren't allowed for the tax type of the vendor. The rules are : 1. If tax * type is "SSN", then check the ownership type against the allowed types for "SSN" in the Rules table. 2. If tax type is * "FEIN", then check the ownership type against the allowed types for "FEIN" in the Rules table. If the vendor is a parent and * the validation fails, display the actual error message. If the vendor is not a parent and the validation fails, display the * error message that the parent of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail The VendorDetail object to be validated * @return TRUE if the ownership type is allowed and FALSE otherwise. */ private boolean validateOwnershipTypeAllowed(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); String ownershipTypeCode = vendorDetail.getVendorHeader().getVendorOwnershipCode(); String taxTypeCode = vendorDetail.getVendorHeader().getVendorTaxTypeCode(); if (StringUtils.isNotEmpty(ownershipTypeCode) && StringUtils.isNotEmpty(taxTypeCode)) { if (VendorConstants.TAX_TYPE_FEIN.equals(taxTypeCode)) { KualiParameterRule feinRule = SpringServiceLocator.getKualiConfigurationService().getApplicationParameterRule(PURAP_ADMIN_GROUP, PURAP_FEIN_ALLOWED_OWNERSHIP_TYPES); if (feinRule.failsRule(ownershipTypeCode)) { valid &= false; } } else if (VendorConstants.TAX_TYPE_SSN.equals(taxTypeCode)) { KualiParameterRule ssnRule = SpringServiceLocator.getKualiConfigurationService().getApplicationParameterRule(PURAP_ADMIN_GROUP, PURAP_SSN_ALLOWED_OWNERSHIP_TYPES); if (ssnRule.failsRule(ownershipTypeCode)) { valid &= false; } } } if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_OWNERSHIP_TYPE_CODE_NOT_ALLOWED, new String[] { vendorDetail.getVendorHeader().getVendorOwnership().getVendorOwnershipDescription(), taxTypeCode }); } else if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * Per code review 9/19, these business rules should be moved to the rule table. This method validates that the minimum order * amount is less than the minimum order amount constant that is currently defined in VendorConstants.java but someday should be * moved to APC. * * @param vendorDetail The VendorDetail object to be validated * @return True if the vendorMinimumOrderAmount is less than the minimum order amount specified in the VendorConstants (in the * future the amount will be in APC). */ private boolean validateMinimumOrderAmount(VendorDetail vendorDetail) { boolean valid = true; KualiDecimal minimumOrderAmount = vendorDetail.getVendorMinimumOrderAmount(); if (minimumOrderAmount != null) { if (ObjectUtils.isNull(VENDOR_MIN_ORDER_AMOUNT)) { BusinessRule minOrderAmountRule = getKualiConfigurationService().getApplicationRule(PURAP_ADMIN_GROUP, PURAP_VENDOR_MIN_ORDER_AMOUNT); VENDOR_MIN_ORDER_AMOUNT = new KualiDecimal(minOrderAmountRule.getRuleText()); } if ((VENDOR_MIN_ORDER_AMOUNT.compareTo(minimumOrderAmount) < 1) || (minimumOrderAmount.isNegative())) { putFieldError(VendorPropertyConstants.VENDOR_MIN_ORDER_AMOUNT, VendorKeyConstants.ERROR_VENDOR_MAX_MIN_ORDER_AMOUNT, VENDOR_MIN_ORDER_AMOUNT.toString()); valid &= false; } } return valid; } /** * This method validates that if the ownership category allowed indicator is false, the vendor does not have ownership category. * It will return false if the vendor contains ownership category. If the vendor is a parent and the validation fails, display * the actual error message. If the vendor is not a parent and the validation fails, display the error message that the parent * of this vendor needs to be changed, please contact Purchasing Dept. * * @param vendorDetail The VendorDetail to be validated * @return true if the vendor does not contain ownership category and false otherwise */ private boolean validateOwnershipCategory(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); OwnershipType ot = vendorDetail.getVendorHeader().getVendorOwnership(); if (ot != null && !ot.getVendorOwnershipCategoryAllowedIndicator()) { if (ObjectUtils.isNotNull(vendorDetail.getVendorHeader().getVendorOwnershipCategory())) { valid &= false; } } if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CATEGORY_CODE, VendorKeyConstants.ERROR_OWNERSHIP_CATEGORY_CODE_NOT_ALLOWED, new String[] { vendorDetail.getVendorHeader().getVendorOwnershipCategory().getVendorOwnershipCategoryDescription(), vendorDetail.getVendorHeader().getVendorOwnership().getVendorOwnershipDescription() }); } else if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_OWNERSHIP_CODE, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } /** * This method calls the methods in TaxNumberService to validate the tax number for these business rules: 1. Tax number must be * 9 digits and cannot be all zeros (but can be blank). 2. First three digits of a SSN cannot be 000. 3. First three digits of a * SSN cannot be 666. 4. Middle two digits of a SSN cannot be 00. 5. Last four digits of a SSN cannot be 0000. 6. First two * digits of a FEIN cannot be 00. 7. TODO: This tax number is not allowed: 356001673 * * @param vendorDetail The VendorDetail object to be validated * @return true if the tax number is a valid tax number and false otherwise. */ private boolean validateTaxNumberFromTaxNumberService(VendorDetail vendorDetail) { boolean valid = true; boolean isParent = vendorDetail.isVendorParentIndicator(); String taxNumber = vendorDetail.getVendorHeader().getVendorTaxNumber(); String taxType = vendorDetail.getVendorHeader().getVendorTaxTypeCode(); if (!StringUtils.isEmpty(taxType) && !StringUtils.isEmpty(taxNumber)) { valid = SpringServiceLocator.getTaxNumberService().isValidTaxNumber(taxNumber, taxType); if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_TAX_NUMBER_INVALID); } valid = SpringServiceLocator.getTaxNumberService().isAllowedTaxNumber(taxNumber); if (!valid && isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_TAX_NUMBER_NOT_ALLOWED); } } if (!valid && !isParent) { putFieldError(VendorPropertyConstants.VENDOR_TAX_NUMBER, VendorKeyConstants.ERROR_VENDOR_PARENT_NEEDS_CHANGED); } return valid; } boolean processAddressValidation(MaintenanceDocument document) { boolean valid = true; boolean validAddressType = false; List<VendorAddress> addresses = newVendor.getVendorAddresses(); String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode(); String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType().getVendorAddressTypeRequiredCode(); for (int i = 0; i < addresses.size(); i++) { VendorAddress address = addresses.get(i); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) { validAddressType = true; } valid &= checkFaxNumber(address); valid &= checkAddressCountryEmptyStateZip(address); GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } // validate Address Type if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode) && !validAddressType) { String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode }; putFieldError(VendorPropertyConstants.VENDOR_TYPE_CODE, VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters); valid = false; } valid &= validateDefaultAddressCampus(newVendor); // Check to see if all divisions have one desired address for this vendor type Map fieldValues = new HashMap(); fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID, newVendor.getVendorHeaderGeneratedIdentifier()); // Find all the addresses for this vendor and its divisions: List<VendorAddress> vendorDivisionAddresses = new ArrayList(SpringServiceLocator.getBusinessObjectService().findMatchingOrderBy(VendorAddress.class, fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true)); // This set stores the vendorDetailedAssignedIds for the vendor divisions which is // bascically the division numbers 0, 1, 2, ... HashSet<Integer> vendorDetailedIds = new HashSet(); // This set stores the vendor division numbers of the ones which have one address of the desired type HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet(); for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) { vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier()); if (vendorDivisionAddress.getVendorAddressTypeCode().equalsIgnoreCase(vendorAddressTypeRequiredCode)) { vendorDivisionsIdsWithDesiredAddressType.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier()); } } // If the number of divisions with the desired address type is less than the number of divisions for his vendor if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) { Iterator itr = vendorDetailedIds.iterator(); Integer value; String vendorId; while (itr.hasNext()) { value = (Integer) itr.next(); if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) { vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-' + value.toString(); String[] parameters = new String[] { vendorId, vendorTypeCode, vendorAddressTypeRequiredCode }; putFieldError(VendorPropertyConstants.VENDOR_TYPE_CODE, VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters); valid = false; } } } return valid; } /** * This method validates that if US is selcted for country that the state and zip are not empty * * @param addresses * @return */ boolean checkAddressCountryEmptyStateZip(VendorAddress address) { boolean valid = true; boolean noPriorErrMsg = true; Country country = address.getVendorCountry(); if (ObjectUtils.isNotNull(country) && StringUtils.equals(KFSConstants.COUNTRY_CODE_UNITED_STATES, country.getPostalCountryCode())) { if ((ObjectUtils.isNull(address.getVendorState()) || StringUtils.isEmpty(address.getVendorState().getPostalStateCode()))) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_ADDRESS_STATE, VendorKeyConstants.ERROR_US_REQUIRES_STATE); valid &= false; noPriorErrMsg = false; } // The error message here will be the same for both, and should not be repeated (KULPURAP-516). if (noPriorErrMsg && StringUtils.isEmpty(address.getVendorZipCode())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_ADDRESS_ZIP, VendorKeyConstants.ERROR_US_REQUIRES_ZIP); valid &= false; } } return valid; } /** * This method checks if the "allow default indicator" is true or false for this address. * * @param addresses * @return */ boolean findAllowDefaultAddressIndicatorHelper(VendorAddress vendorAddress) { AddressType addressType = new AddressType(); addressType = vendorAddress.getVendorAddressType(); if (ObjectUtils.isNull(addressType)) { return false; } // Retreiving the Default Address Indicator for this Address Type: return addressType.getVendorDefaultIndicator(); } /** * This method When add button is selected on Default Address, checks if the allow default indicator is set to false for this * address type then it does not allow user to select a default address for this address and if it is true then it allows only * one campus to be default for this address. * * @param addresses * @return */ // TODO: Naser See if there is a way to put the error message in the address tab instead of down the page boolean checkDefaultAddressCampus(VendorDetail vendorDetail, VendorDefaultAddress addedDefaultAddress, VendorAddress parent) { VendorAddress vendorAddress = parent; if (ObjectUtils.isNull(vendorAddress)) { return false; } int j = vendorDetail.getVendorAddresses().indexOf(vendorAddress); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + j + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); // Retreiving the Default Address Indicator for this Address Type: boolean allowDefaultAddressIndicator = findAllowDefaultAddressIndicatorHelper(vendorAddress); String addedAddressCampusCode = addedDefaultAddress.getVendorCampusCode(); String addedAddressTypeCode = vendorAddress.getVendorAddressTypeCode(); // if the selected address type does not allow defaults, then the user should not be allowed to // select the default indicator or add any campuses to the address if (allowDefaultAddressIndicator == false) { String[] parameters = new String[] { addedAddressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + 0 + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS_NOT_ALLOWED, parameters); return false; } List<VendorDefaultAddress> vendorDefaultAddresses = vendorAddress.getVendorDefaultAddresses(); for (int i = 0; i < vendorDefaultAddresses.size(); i++) { VendorDefaultAddress vendorDefaultAddress = vendorDefaultAddresses.get(i); if (vendorDefaultAddress.getVendorCampusCode().equalsIgnoreCase(addedAddressCampusCode)) { String[] parameters = new String[] { addedAddressCampusCode, addedAddressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + i + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS, parameters); // GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); return false; } } return true; } /** * This method checks if the allow default indicator is set to false for this address the default indicator cannot be set to * true/yes. If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set * (no more, no less) and only one campus to be set as default for this address. * * @param vendorDetail * @return false or true */ boolean validateDefaultAddressCampus(VendorDetail vendorDetail) { List<VendorAddress> vendorAddresses = vendorDetail.getVendorAddresses(); String addressTypeCode; String campusCode; boolean valid = true; boolean previousValue = false; // This is a HashMap to store the default Address Type Codes and their associated default Indicator HashMap addressTypeCodeDefaultIndicator = new HashMap(); // This is a HashMap to store Address Type Codes and Address Campus Codes for Default Addresses HashMap addressTypeDefaultCampus = new HashMap(); // This is a HashSet for storing only the Address Type Codes which have at leat one default Indicator set to true HashSet addressTypesHavingDefaultTrue = new HashSet(); int i = 0; for (VendorAddress address : vendorAddresses) { addressTypeCode = address.getVendorAddressTypeCode(); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); String[] parameters = new String[] { addressTypeCode }; // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set (no // more, no less). // For example, if a vendor contains three PO type addresses and the PO address type is set to allow defaults in the // address type table, // then only one of these PO addresses can have the default indicator set to true/yes. if (findAllowDefaultAddressIndicatorHelper(address)) { if (address.isVendorDefaultAddressIndicator()) { addressTypesHavingDefaultTrue.add(addressTypeCode); } if (!addressTypeCodeDefaultIndicator.isEmpty() && addressTypeCodeDefaultIndicator.containsKey(addressTypeCode)) { previousValue = ((Boolean) addressTypeCodeDefaultIndicator.get(addressTypeCode)).booleanValue(); } if (addressTypeCodeDefaultIndicator.put(addressTypeCode, address.isVendorDefaultAddressIndicator()) != null && previousValue && address.isVendorDefaultAddressIndicator()) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR, parameters); valid = false; } } // If "allow default indicator" is set to false/no for address type, the default indicator cannot be set to true/yes. else { if (address.isVendorDefaultAddressIndicator()) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_ADDRESS_NOT_ALLOWED, parameters); valid = false; } } List<VendorDefaultAddress> vendorDefaultAddresses = address.getVendorDefaultAddresses(); // If "allow default indicator" is set to true/yes for address type, a campus can only be set on one of each type of // Address. // For example, Bloomington can not be included in the campus list for two PO type addresses. // Each campus can only have one default address. int j = 0; for (VendorDefaultAddress defaultAddress : vendorDefaultAddresses) { campusCode = (String) addressTypeDefaultCampus.put(addressTypeCode, defaultAddress.getVendorCampusCode()); if (StringUtils.isNotBlank(campusCode) && campusCode.equalsIgnoreCase(defaultAddress.getVendorCampusCode())) { String[] newParameters = new String[] { defaultAddress.getVendorCampusCode(), addressTypeCode }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS + "[" + j + "]." + VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_CAMPUS, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_CAMPUS, newParameters); valid = false; } j++; } i++; GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } // If "allow default indicator" is set to true/yes for address type, one address must have the default indicator set to true if (!addressTypeCodeDefaultIndicator.isEmpty()) { Set<String> addressTypes = addressTypeCodeDefaultIndicator.keySet(); for (String addressType : addressTypes) { if (!addressTypesHavingDefaultTrue.contains(addressType)) { String[] parameters = new String[] { addressType }; GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_DEFAULT_ADDRESS_INDICATOR, VendorKeyConstants.ERROR_ADDRESS_DEFAULT_INDICATOR, parameters); valid = false; } } } return valid; } /** * This method validates that the Vendor Fax Number is a valid phone number. * * @param addresses * @return */ boolean checkFaxNumber(VendorAddress address) { boolean valid = true; String faxNumber = address.getVendorFaxNumber(); if (StringUtils.isNotEmpty(faxNumber) && !SpringServiceLocator.getPhoneNumberService().isValidPhoneNumber(faxNumber)) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_FAX_NUMBER, VendorKeyConstants.ERROR_FAX_NUMBER); valid &= false; } return valid; } private boolean processContactValidation(MaintenanceDocument document) { boolean valid = true; // leaving stub method here as placeholder for future Contact Validation return valid; } private boolean processCustomerNumberValidation(MaintenanceDocument document) { boolean valid = true; List<VendorCustomerNumber> customerNumbers = newVendor.getVendorCustomerNumbers(); for (VendorCustomerNumber customerNumber : customerNumbers) { valid &= validateVendorCustomerNumber(customerNumber); } return valid; } boolean validateVendorCustomerNumber(VendorCustomerNumber customerNumber) { boolean valid = true; // The chart and org must exist in the database. String chartOfAccountsCode = customerNumber.getChartOfAccountsCode(); String orgCode = customerNumber.getVendorOrganizationCode(); if (!StringUtils.isBlank(chartOfAccountsCode) && !StringUtils.isBlank(orgCode)) { Map chartOrgMap = new HashMap(); chartOrgMap.put("chartOfAccountsCode", chartOfAccountsCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Chart.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CUSTOMER_NUMBER_CHART_OF_ACCOUNTS_CODE, KFSKeyConstants.ERROR_EXISTENCE, chartOfAccountsCode); valid &= false; } chartOrgMap.put("organizationCode", orgCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Org.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CUSTOMER_NUMBER_ORGANIZATION_CODE, KFSKeyConstants.ERROR_EXISTENCE, orgCode); valid &= false; } } return valid; } private boolean processContractValidation(MaintenanceDocument document) { boolean valid = true; List<VendorContract> contracts = newVendor.getVendorContracts(); if (ObjectUtils.isNull(contracts)) { return valid; } //If the vendorContractAllowedIndicator is false, it cannot have vendor contracts, return false; if (!newVendor.getVendorHeader().getVendorType().isVendorContractAllowedIndicator()) { valid = false; String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_CONTRACT + "[0]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); GlobalVariables.getErrorMap().putError( VendorPropertyConstants.VENDOR_CONTRACT_NAME, VendorKeyConstants.ERROR_VENDOR_CONTRACT_NOT_ALLOWED ); return valid; } for (int i = 0; i < contracts.size(); i++) { VendorContract contract = contracts.get(i); String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_CONTRACT + "[" + i + "]"; GlobalVariables.getErrorMap().addToErrorPath(errorPath); valid &= validateVendorContractPOLimitAndExcludeFlagCombination(contract); valid &= validateVendorContractBeginEndDates(contract); GlobalVariables.getErrorMap().removeFromErrorPath(errorPath); } return valid; } /** * This method validates that the proper combination of Exclude Indicator and APO Amount is present on a vendor contract. Do not * perform this validation on Contract add line as the user cannot currently enter the sub-collection of contract-orgs so we * should not force this until the document is submitted. The rules are : 1. Must enter a Default APO Limit or at least one * organization with an APO Amount. 2. If the Exclude Indicator for an organization is N, an organization APO Amount is * required. 3. If the Exclude Indicator for an organization is Y, the organization APO Amount is not allowed. * * @return True if the proper combination of Exclude Indicator and APO Amount is present. False otherwise. */ boolean validateVendorContractPOLimitAndExcludeFlagCombination(VendorContract contract) { boolean valid = true; boolean NoOrgHasApoLimit = true; List<VendorContractOrganization> organizations = contract.getVendorContractOrganizations(); if (ObjectUtils.isNotNull(organizations)) { int organizationCounter = 0; for (VendorContractOrganization organization : organizations) { if (ObjectUtils.isNotNull(organization.getVendorContractPurchaseOrderLimitAmount())) { NoOrgHasApoLimit = false; } valid &= validateVendorContractOrganization(organization); organizationCounter++; } } if (NoOrgHasApoLimit && ObjectUtils.isNull(contract.getOrganizationAutomaticPurchaseOrderLimit())) { // Rule #1 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_DEFAULT_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_NO_APO_LIMIT); valid &= false; } return valid; } /** * This method validates that: 1. If the VendorContractBeginningDate is entered then the VendorContractEndDate is also entered, * and vice versa. 2. If both dates are entered, the VendorContractBeginningDate is before the VendorContractEndDate. The date * fields are required so we should know that we have valid dates. * * @return True if the beginning date is before the end date. False if only one date is entered or the beginning date is after * the end date. */ boolean validateVendorContractBeginEndDates(VendorContract contract) { boolean valid = true; if (ObjectUtils.isNotNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNull(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_END_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_BEGIN_DATE_NO_END_DATE); valid &= false; } else { if (ObjectUtils.isNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNotNull(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_BEGIN_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_END_DATE_NO_BEGIN_DATE); valid &= false; } } if (valid && ObjectUtils.isNotNull(contract.getVendorContractBeginningDate()) && ObjectUtils.isNotNull(contract.getVendorContractEndDate())) { if (contract.getVendorContractBeginningDate().after(contract.getVendorContractEndDate())) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_BEGIN_DATE, VendorKeyConstants.ERROR_VENDOR_CONTRACT_BEGIN_DATE_AFTER_END); valid &= false; } } // contractCounter++; // } return valid; } /** * This method validates a vendor contract organization. The rules are : 1. If the Exclude Indicator for the organization is N, * an organization APO Amount is required. 2. If the Exclude Indicator for the organization is Y, an organization APO Amount is * not allowed. 3. The chart and org for the organization must exist in the database. * * @return True if these three rules are passed. False otherwise. */ boolean validateVendorContractOrganization(VendorContractOrganization organization) { boolean valid = true; boolean isExcluded = organization.isVendorContractExcludeIndicator(); if (isExcluded) { if (ObjectUtils.isNotNull(organization.getVendorContractPurchaseOrderLimitAmount())) { // Rule #2 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_ORG_EXCLUDED_WITH_APO_LIMIT); valid &= false; } } else { // isExcluded = false if (ObjectUtils.isNull(organization.getVendorContractPurchaseOrderLimitAmount())) { // Rule #1 in the above java doc has been violated. GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_APO_LIMIT, VendorKeyConstants.ERROR_VENDOR_CONTRACT_ORG_NOT_EXCLUDED_NO_APO_LIMIT); valid &= false; } } // The chart and org must exist in the database. String chartOfAccountsCode = organization.getChartOfAccountsCode(); String orgCode = organization.getOrganizationCode(); if (!StringUtils.isBlank(chartOfAccountsCode) && !StringUtils.isBlank(orgCode)) { Map chartOrgMap = new HashMap(); chartOrgMap.put("chartOfAccountsCode", chartOfAccountsCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Chart.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_CHART_OF_ACCOUNTS_CODE, KFSKeyConstants.ERROR_EXISTENCE, chartOfAccountsCode); valid &= false; } chartOrgMap.put("organizationCode", orgCode); if (SpringServiceLocator.getBusinessObjectService().countMatching(Org.class, chartOrgMap) < 1) { GlobalVariables.getErrorMap().putError(VendorPropertyConstants.VENDOR_CONTRACT_ORGANIZATION_CODE, KFSKeyConstants.ERROR_EXISTENCE, orgCode); valid &= false; } } return valid; } public boolean processCustomAddCollectionLineBusinessRules(MaintenanceDocument document, String collectionName, PersistableBusinessObject bo) { boolean success = true; // this incoming bo needs to be refreshed because it doesn't have its subobjects setup // TODO: can this be moved up? bo.refreshNonUpdateableReferences(); if (bo instanceof VendorAddress) { VendorAddress address = (VendorAddress) bo; success &= checkAddressCountryEmptyStateZip(address); VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); } if (bo instanceof VendorContract) { VendorContract contract = (VendorContract) bo; success &= validateVendorContractBeginEndDates(contract); } if (bo instanceof VendorContractOrganization) { VendorContractOrganization contractOrg = (VendorContractOrganization) bo; success &= validateVendorContractOrganization(contractOrg); } if (bo instanceof VendorCustomerNumber) { VendorCustomerNumber customerNumber = (VendorCustomerNumber) bo; success &= validateVendorCustomerNumber(customerNumber); } if (bo instanceof VendorDefaultAddress) { VendorDefaultAddress defaultAddress = (VendorDefaultAddress) bo; // TODO: this is a total hack we shouldn't have to set the foreign key here, this should be set in the parent // in a much more general way see issue KULPURAP-266 for a preliminary discussion String parentName = StringUtils.substringBeforeLast(collectionName, "."); VendorAddress parent = (VendorAddress) ObjectUtils.getPropertyValue(this.getNewBo(), parentName); VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject(); success &= checkDefaultAddressCampus(vendorDetail, defaultAddress, parent); } return success; } }
KULPURAP-675
work/src/org/kuali/kfs/vnd/document/validation/impl/VendorRule.java
KULPURAP-675
Java
apache-2.0
628d0ced8860f6f18eb76f70346042e8b0fa273a
0
GoogleCloudPlatform/dataproc-templates,GoogleCloudPlatform/dataproc-templates,GoogleCloudPlatform/dataproc-templates
/* * Copyright (C) 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.dataproc.templates.gcs; import static com.google.cloud.dataproc.templates.gcs.GCSToJDBCConfig.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.cloud.dataproc.templates.util.PropertyUtil; import com.google.cloud.dataproc.templates.util.ValidationUtil.ValidationException; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.ThrowingSupplier; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class GCStoJDBCTest { private static final Logger LOGGER = LoggerFactory.getLogger(GCStoJDBCTest.class); @BeforeEach void setUp() { PropertyUtil.getProperties().setProperty(GCS_JDBC_INPUT_FORMAT, "avro"); PropertyUtil.getProperties().setProperty(GCS_JDBC_INPUT_LOCATION, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_DRIVER, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_TABLE, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_URL, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_SAVE_MODE, "Append"); } @Test void runTemplateWithValidParameters() { LOGGER.info("Running test: runTemplateWithValidParameters"); assertDoesNotThrow((ThrowingSupplier<GCSToJDBC>) GCSToJDBC::of); } @ParameterizedTest @MethodSource("requiredPropertyKeys") void runTemplateWithMissingRequiredParameters(String propKey) { LOGGER.info("Running test: runTemplateWithInvalidParameters"); PropertyUtil.getProperties().setProperty(propKey, ""); ValidationException exception = assertThrows(ValidationException.class, GCSToJDBC::of); } static Stream<String> requiredPropertyKeys() { return Stream.of( GCS_JDBC_INPUT_FORMAT, GCS_JDBC_INPUT_LOCATION, GCS_JDBC_OUTPUT_DRIVER, GCS_JDBC_OUTPUT_TABLE, GCS_JDBC_OUTPUT_URL, GCS_JDBC_OUTPUT_SAVE_MODE); } }
java/src/test/java/com/google/cloud/dataproc/templates/gcs/GCStoJDBCTest.java
/* * Copyright (C) 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.dataproc.templates.gcs; import static com.google.cloud.dataproc.templates.gcs.GCSToJDBCConfig.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.cloud.dataproc.templates.util.PropertyUtil; import com.google.cloud.dataproc.templates.util.ValidationUtil.ValidationException; import jakarta.validation.ConstraintViolation; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.ThrowingSupplier; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class GCStoJDBCTest { private static final Logger LOGGER = LoggerFactory.getLogger(GCStoJDBCTest.class); @BeforeEach void setUp() { PropertyUtil.getProperties().setProperty(GCS_JDBC_INPUT_FORMAT, "avro"); PropertyUtil.getProperties().setProperty(GCS_JDBC_INPUT_LOCATION, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_DRIVER, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_TABLE, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_URL, "some_value"); PropertyUtil.getProperties().setProperty(GCS_JDBC_OUTPUT_SAVE_MODE, "Append"); } @Test void runTemplateWithValidParameters() { LOGGER.info("Running test: runTemplateWithValidParameters"); assertDoesNotThrow((ThrowingSupplier<GCSToJDBC>) GCSToJDBC::of); } @ParameterizedTest @MethodSource("requiredPropertyKeys") void runTemplateWithMissingRequiredParameters(String propKey) { LOGGER.info("Running test: runTemplateWithInvalidParameters"); PropertyUtil.getProperties().setProperty(propKey, ""); ValidationException exception = assertThrows(ValidationException.class, GCSToJDBC::of); } static Stream<String> requiredPropertyKeys() { return Stream.of( GCS_JDBC_INPUT_FORMAT, GCS_JDBC_INPUT_LOCATION, GCS_JDBC_OUTPUT_DRIVER, GCS_JDBC_OUTPUT_TABLE, GCS_JDBC_OUTPUT_URL, GCS_JDBC_OUTPUT_SAVE_MODE); } }
updated spotless
java/src/test/java/com/google/cloud/dataproc/templates/gcs/GCStoJDBCTest.java
updated spotless
Java
apache-2.0
61cee0d57e118476ea5020afa1e7b796c21c17e9
0
RuckusWirelessIL/pentaho-kafka-consumer
package com.ruckuswireless.pentaho.kafka.consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import kafka.consumer.ConsumerConfig; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /** * Kafka Consumer step definitions and serializer to/from XML and to/from Kettle * repository. * * @author Michael Spector */ public class KafkaConsumerMeta extends BaseStepMeta implements StepMetaInterface { public static final String[] KAFKA_PROPERTIES_NAMES = new String[] { "zookeeper.connect", "group.id", "consumer.id", "socket.timeout.ms", "socket.receive.buffer.bytes", "fetch.message.max.bytes", "auto.commit.interval.ms", "queued.max.message.chunks", "rebalance.max.retries", "fetch.min.bytes", "fetch.wait.max.ms", "rebalance.backoff.ms", "refresh.leader.backoff.ms", "auto.commit.enable", "auto.offset.reset", "consumer.timeout.ms", "client.id", "zookeeper.session.timeout.ms", "zookeeper.connection.timeout.ms", "zookeeper.sync.time.ms" }; public static final Map<String, String> KAFKA_PROPERTIES_DEFAULTS = new HashMap<String, String>(); static { KAFKA_PROPERTIES_DEFAULTS.put("zookeeper.connect", "localhost:2181"); KAFKA_PROPERTIES_DEFAULTS.put("group.id", "group"); } private Properties kafkaProperties = new Properties(); private String topic; private String field; private String keyField; private long limit; private long timeout; private boolean stopOnEmptyTopic; Properties getKafkaProperties() { return kafkaProperties; } /** * @return Kafka topic name */ public String getTopic() { return topic; } /** * @param topic * Kafka topic name */ public void setTopic(String topic) { this.topic = topic; } /** * @return Target field name in Kettle stream */ public String getField() { return field; } /** * @param field * Target field name in Kettle stream */ public void setField(String field) { this.field = field; } /** * @return Target key field name in Kettle stream */ public String getKeyField() { return keyField; } /** * @param keyField * Target key field name in Kettle stream */ public void setKeyField(String keyField) { this.keyField = keyField; } /** * @return Limit number of entries to read from Kafka queue */ public long getLimit() { return limit; } /** * @param limit * Limit number of entries to read from Kafka queue */ public void setLimit(long limit) { this.limit = limit; } /** * @return Time limit for reading entries from Kafka queue (in ms) */ public long getTimeout() { return timeout; } /** * @param timeout * Time limit for reading entries from Kafka queue (in ms) */ public void setTimeout(long timeout) { this.timeout = timeout; } /** * @return 'true' if the consumer should stop when no more messages are available */ public boolean isStopOnEmptyTopic() { return stopOnEmptyTopic; } /** * @param stopOnEmptyTopic * If 'true', stop the consumer when no more messages are available on the topic */ public void setStopOnEmptyTopic(boolean stopOnEmptyTopic) { this.stopOnEmptyTopic = stopOnEmptyTopic; } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { if (topic == null) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages .getString("KafkaConsumerMeta.Check.InvalidTopic"), stepMeta)); } if (field == null) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages .getString("KafkaConsumerMeta.Check.InvalidField"), stepMeta)); } try { new ConsumerConfig(kafkaProperties); } catch (IllegalArgumentException e) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, e.getMessage(), stepMeta)); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new KafkaConsumerStep(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new KafkaConsumerData(); } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { try { topic = XMLHandler.getTagValue(stepnode, "TOPIC"); field = XMLHandler.getTagValue(stepnode, "FIELD"); String limitVal = XMLHandler.getTagValue(stepnode, "LIMIT"); if (limitVal != null) { limit = Long.parseLong(limitVal); } String timeoutVal = XMLHandler.getTagValue(stepnode, "TIMEOUT"); if (timeoutVal != null) { timeout = Long.parseLong(timeoutVal); } // This tag only exists if the value is "true", so we can directly populate the field stopOnEmptyTopic = XMLHandler.getTagValue(stepnode, "STOPONEMPTYTOPIC") != null; Node kafkaNode = XMLHandler.getSubNode(stepnode, "KAFKA"); for (String name : KAFKA_PROPERTIES_NAMES) { String value = XMLHandler.getTagValue(kafkaNode, name); if (value != null) { kafkaProperties.put(name, value); } } } catch (Exception e) { throw new KettleXMLException(Messages.getString("KafkaConsumerMeta.Exception.loadXml"), e); } } public String getXML() throws KettleException { StringBuilder retval = new StringBuilder(); if (topic != null) { retval.append(" ").append(XMLHandler.addTagValue("TOPIC", topic)); } if (field != null) { retval.append(" ").append(XMLHandler.addTagValue("FIELD", field)); } if (limit > 0) { retval.append(" ").append(XMLHandler.addTagValue("LIMIT", limit)); } if (timeout > 0) { retval.append(" ").append(XMLHandler.addTagValue("TIMEOUT", timeout)); } if (stopOnEmptyTopic) { retval.append(" ").append(XMLHandler.addTagValue("STOPONEMPTYTOPIC", "true")); } retval.append(" ").append(XMLHandler.openTag("KAFKA")).append(Const.CR); for (String name : KAFKA_PROPERTIES_NAMES) { String value = kafkaProperties.getProperty(name); if (value != null) { retval.append(" " + XMLHandler.addTagValue(name, value)); } } retval.append(" ").append(XMLHandler.closeTag("KAFKA")).append(Const.CR); return retval.toString(); } public void readRep(Repository rep, ObjectId stepId, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { topic = rep.getStepAttributeString(stepId, "TOPIC"); field = rep.getStepAttributeString(stepId, "FIELD"); limit = rep.getStepAttributeInteger(stepId, "LIMIT"); timeout = rep.getStepAttributeInteger(stepId, "TIMEOUT"); stopOnEmptyTopic = rep.getStepAttributeBoolean(stepId, "STOPONEMPTYTOPIC"); for (String name : KAFKA_PROPERTIES_NAMES) { String value = rep.getStepAttributeString(stepId, name); if (value != null) { kafkaProperties.put(name, value); } } } catch (Exception e) { throw new KettleException("KafkaConsumerMeta.Exception.loadRep", e); } } public void saveRep(Repository rep, ObjectId transformationId, ObjectId stepId) throws KettleException { try { if (topic != null) { rep.saveStepAttribute(transformationId, stepId, "TOPIC", topic); } if (field != null) { rep.saveStepAttribute(transformationId, stepId, "FIELD", field); } if (limit > 0) { rep.saveStepAttribute(transformationId, stepId, "LIMIT", limit); } if (timeout > 0) { rep.saveStepAttribute(transformationId, stepId, "TIMEOUT", timeout); } rep.saveStepAttribute(transformationId, stepId, "STOPONEMPTYTOPIC", stopOnEmptyTopic); for (String name : KAFKA_PROPERTIES_NAMES) { String value = kafkaProperties.getProperty(name); if (value != null) { rep.saveStepAttribute(transformationId, stepId, name, value); } } } catch (Exception e) { throw new KettleException("KafkaConsumerMeta.Exception.saveRep", e); } } public void setDefault() { } public void getFields(RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { ValueMetaInterface valueMeta = new ValueMeta(getField(), ValueMetaInterface.TYPE_BINARY); valueMeta.setOrigin(origin); rowMeta.addValueMeta(valueMeta); } }
src/main/java/com/ruckuswireless/pentaho/kafka/consumer/KafkaConsumerMeta.java
package com.ruckuswireless.pentaho.kafka.consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import kafka.consumer.ConsumerConfig; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /** * Kafka Consumer step definitions and serializer to/from XML and to/from Kettle * repository. * * @author Michael Spector */ public class KafkaConsumerMeta extends BaseStepMeta implements StepMetaInterface { public static final String[] KAFKA_PROPERTIES_NAMES = new String[] { "zookeeper.connect", "group.id", "consumer.id", "socket.timeout.ms", "socket.receive.buffer.bytes", "fetch.message.max.bytes", "auto.commit.interval.ms", "queued.max.message.chunks", "rebalance.max.retries", "fetch.min.bytes", "fetch.wait.max.ms", "rebalance.backoff.ms", "refresh.leader.backoff.ms", "auto.commit.enable", "auto.offset.reset", "consumer.timeout.ms", "client.id", "zookeeper.session.timeout.ms", "zookeeper.connection.timeout.ms", "zookeeper.sync.time.ms" }; public static final Map<String, String> KAFKA_PROPERTIES_DEFAULTS = new HashMap<String, String>(); static { KAFKA_PROPERTIES_DEFAULTS.put("zookeeper.connect", "localhost:2181"); KAFKA_PROPERTIES_DEFAULTS.put("group.id", "group"); } private Properties kafkaProperties = new Properties(); private String topic; private String field; private long limit; private long timeout; private boolean stopOnEmptyTopic; Properties getKafkaProperties() { return kafkaProperties; } /** * @return Kafka topic name */ public String getTopic() { return topic; } /** * @param topic * Kafka topic name */ public void setTopic(String topic) { this.topic = topic; } /** * @return Target field name in Kettle stream */ public String getField() { return field; } /** * @param field * Target field name in Kettle stream */ public void setField(String field) { this.field = field; } /** * @return Limit number of entries to read from Kafka queue */ public long getLimit() { return limit; } /** * @param limit * Limit number of entries to read from Kafka queue */ public void setLimit(long limit) { this.limit = limit; } /** * @return Time limit for reading entries from Kafka queue (in ms) */ public long getTimeout() { return timeout; } /** * @param timeout * Time limit for reading entries from Kafka queue (in ms) */ public void setTimeout(long timeout) { this.timeout = timeout; } /** * @return 'true' if the consumer should stop when no more messages are available */ public boolean isStopOnEmptyTopic() { return stopOnEmptyTopic; } /** * @param stopOnEmptyTopic * If 'true', stop the consumer when no more messages are available on the topic */ public void setStopOnEmptyTopic(boolean stopOnEmptyTopic) { this.stopOnEmptyTopic = stopOnEmptyTopic; } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { if (topic == null) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages .getString("KafkaConsumerMeta.Check.InvalidTopic"), stepMeta)); } if (field == null) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages .getString("KafkaConsumerMeta.Check.InvalidField"), stepMeta)); } try { new ConsumerConfig(kafkaProperties); } catch (IllegalArgumentException e) { remarks.add(new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, e.getMessage(), stepMeta)); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new KafkaConsumerStep(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new KafkaConsumerData(); } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { try { topic = XMLHandler.getTagValue(stepnode, "TOPIC"); field = XMLHandler.getTagValue(stepnode, "FIELD"); String limitVal = XMLHandler.getTagValue(stepnode, "LIMIT"); if (limitVal != null) { limit = Long.parseLong(limitVal); } String timeoutVal = XMLHandler.getTagValue(stepnode, "TIMEOUT"); if (timeoutVal != null) { timeout = Long.parseLong(timeoutVal); } // This tag only exists if the value is "true", so we can directly populate the field stopOnEmptyTopic = XMLHandler.getTagValue(stepnode, "STOPONEMPTYTOPIC") != null; Node kafkaNode = XMLHandler.getSubNode(stepnode, "KAFKA"); for (String name : KAFKA_PROPERTIES_NAMES) { String value = XMLHandler.getTagValue(kafkaNode, name); if (value != null) { kafkaProperties.put(name, value); } } } catch (Exception e) { throw new KettleXMLException(Messages.getString("KafkaConsumerMeta.Exception.loadXml"), e); } } public String getXML() throws KettleException { StringBuilder retval = new StringBuilder(); if (topic != null) { retval.append(" ").append(XMLHandler.addTagValue("TOPIC", topic)); } if (field != null) { retval.append(" ").append(XMLHandler.addTagValue("FIELD", field)); } if (limit > 0) { retval.append(" ").append(XMLHandler.addTagValue("LIMIT", limit)); } if (timeout > 0) { retval.append(" ").append(XMLHandler.addTagValue("TIMEOUT", timeout)); } if (stopOnEmptyTopic) { retval.append(" ").append(XMLHandler.addTagValue("STOPONEMPTYTOPIC", "true")); } retval.append(" ").append(XMLHandler.openTag("KAFKA")).append(Const.CR); for (String name : KAFKA_PROPERTIES_NAMES) { String value = kafkaProperties.getProperty(name); if (value != null) { retval.append(" " + XMLHandler.addTagValue(name, value)); } } retval.append(" ").append(XMLHandler.closeTag("KAFKA")).append(Const.CR); return retval.toString(); } public void readRep(Repository rep, ObjectId stepId, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { topic = rep.getStepAttributeString(stepId, "TOPIC"); field = rep.getStepAttributeString(stepId, "FIELD"); limit = rep.getStepAttributeInteger(stepId, "LIMIT"); timeout = rep.getStepAttributeInteger(stepId, "TIMEOUT"); stopOnEmptyTopic = rep.getStepAttributeBoolean(stepId, "STOPONEMPTYTOPIC"); for (String name : KAFKA_PROPERTIES_NAMES) { String value = rep.getStepAttributeString(stepId, name); if (value != null) { kafkaProperties.put(name, value); } } } catch (Exception e) { throw new KettleException("KafkaConsumerMeta.Exception.loadRep", e); } } public void saveRep(Repository rep, ObjectId transformationId, ObjectId stepId) throws KettleException { try { if (topic != null) { rep.saveStepAttribute(transformationId, stepId, "TOPIC", topic); } if (field != null) { rep.saveStepAttribute(transformationId, stepId, "FIELD", field); } if (limit > 0) { rep.saveStepAttribute(transformationId, stepId, "LIMIT", limit); } if (timeout > 0) { rep.saveStepAttribute(transformationId, stepId, "TIMEOUT", timeout); } rep.saveStepAttribute(transformationId, stepId, "STOPONEMPTYTOPIC", stopOnEmptyTopic); for (String name : KAFKA_PROPERTIES_NAMES) { String value = kafkaProperties.getProperty(name); if (value != null) { rep.saveStepAttribute(transformationId, stepId, name, value); } } } catch (Exception e) { throw new KettleException("KafkaConsumerMeta.Exception.saveRep", e); } } public void setDefault() { } public void getFields(RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { ValueMetaInterface valueMeta = new ValueMeta(getField(), ValueMetaInterface.TYPE_BINARY); valueMeta.setOrigin(origin); rowMeta.addValueMeta(valueMeta); } }
add keyField field to KafkaConsumerMeta class
src/main/java/com/ruckuswireless/pentaho/kafka/consumer/KafkaConsumerMeta.java
add keyField field to KafkaConsumerMeta class
Java
apache-2.0
0ab59832d8d7955758c493d002c19a7edabda775
0
apc999/alluxio,Alluxio/alluxio,jswudi/alluxio,wwjiang007/alluxio,jswudi/alluxio,jsimsa/alluxio,aaudiber/alluxio,bf8086/alluxio,maboelhassan/alluxio,PasaLab/tachyon,apc999/alluxio,calvinjia/tachyon,aaudiber/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,calvinjia/tachyon,maboelhassan/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,Reidddddd/alluxio,jswudi/alluxio,apc999/alluxio,ShailShah/alluxio,ShailShah/alluxio,calvinjia/tachyon,ShailShah/alluxio,riversand963/alluxio,maboelhassan/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,calvinjia/tachyon,riversand963/alluxio,Reidddddd/mo-alluxio,aaudiber/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,aaudiber/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,uronce-cc/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,PasaLab/tachyon,maobaolong/alluxio,Reidddddd/mo-alluxio,ChangerYoung/alluxio,jsimsa/alluxio,maobaolong/alluxio,madanadit/alluxio,Reidddddd/alluxio,bf8086/alluxio,ShailShah/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,maobaolong/alluxio,calvinjia/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,maobaolong/alluxio,aaudiber/alluxio,madanadit/alluxio,uronce-cc/alluxio,bf8086/alluxio,Alluxio/alluxio,maobaolong/alluxio,riversand963/alluxio,maobaolong/alluxio,bf8086/alluxio,aaudiber/alluxio,riversand963/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,bf8086/alluxio,ChangerYoung/alluxio,madanadit/alluxio,apc999/alluxio,calvinjia/tachyon,ShailShah/alluxio,yuluo-ding/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,jswudi/alluxio,jsimsa/alluxio,maboelhassan/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,Alluxio/alluxio,maboelhassan/alluxio,jsimsa/alluxio,PasaLab/tachyon,apc999/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Alluxio/alluxio,yuluo-ding/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,ShailShah/alluxio,madanadit/alluxio,Reidddddd/alluxio,Alluxio/alluxio,PasaLab/tachyon,ChangerYoung/alluxio,Alluxio/alluxio,madanadit/alluxio,WilliamZapata/alluxio,jswudi/alluxio,Reidddddd/alluxio,maobaolong/alluxio,bf8086/alluxio,calvinjia/tachyon,aaudiber/alluxio,jswudi/alluxio,wwjiang007/alluxio,calvinjia/tachyon,riversand963/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,apc999/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.underfs.hdfs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.security.SecurityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; import tachyon.Constants; import tachyon.conf.TachyonConf; import tachyon.retry.RetryPolicy; import tachyon.retry.SleepingRetry; import tachyon.underfs.UnderFileSystem; /** * HDFS {@link UnderFileSystem} implementation */ public class HdfsUnderFileSystem extends UnderFileSystem { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); private static final int MAX_TRY = 5; private static final long SLEEP_TIME = 0; private FileSystem mFs = null; private String mUfsPrefix = null; // TODO(hy): Add a sticky bit and narrow down the permission in hadoop 2. private static final FsPermission PERMISSION = new FsPermission((short) 0777) .applyUMask(FsPermission.createImmutable((short) 0000)); public HdfsUnderFileSystem(String fsDefaultName, TachyonConf tachyonConf, Object conf) { super(tachyonConf); mUfsPrefix = fsDefaultName; Configuration tConf; if (conf != null && conf instanceof Configuration) { tConf = (Configuration) conf; } else { tConf = new Configuration(); } prepareConfiguration(fsDefaultName, tachyonConf, tConf); tConf.addResource(new Path(tConf.get(Constants.UNDERFS_HDFS_CONFIGURATION))); HdfsUnderFileSystemUtils.addS3Credentials(tConf); Path path = new Path(mUfsPrefix); try { mFs = path.getFileSystem(tConf); } catch (IOException e) { LOG.error("Exception thrown when trying to get FileSystem for {}", mUfsPrefix, e); throw Throwables.propagate(e); } } @Override public UnderFSType getUnderFSType() { return UnderFSType.HDFS; } /** * Prepares the Hadoop configuration necessary to successfully obtain a {@link FileSystem} * instance that can access the provided path * <p> * Derived implementations that work with specialised Hadoop {@linkplain FileSystem} API * compatible implementations can override this method to add implementation specific * configuration necessary for obtaining a usable {@linkplain FileSystem} instance. * </p> * * @param path File system path * @param config Hadoop Configuration */ protected void prepareConfiguration(String path, TachyonConf tachyonConf, Configuration config) { // On Hadoop 2.x this is strictly unnecessary since it uses ServiceLoader to automatically // discover available file system implementations. However this configuration setting is // required for earlier Hadoop versions plus it is still honoured as an override even in 2.x so // if present propagate it to the Hadoop configuration String ufsHdfsImpl = mTachyonConf.get(Constants.UNDERFS_HDFS_IMPL); if (!StringUtils.isEmpty(ufsHdfsImpl)) { config.set("fs.hdfs.impl", ufsHdfsImpl); } // To disable the instance cache for hdfs client, otherwise it causes the // FileSystem closed exception. Being configurable for unit/integration // test only, and not expose to the end-user currently. config.set("fs.hdfs.impl.disable.cache", System.getProperty("fs.hdfs.impl.disable.cache", "false")); HdfsUnderFileSystemUtils.addKey(config, tachyonConf, Constants.UNDERFS_HDFS_CONFIGURATION); } @Override public void close() throws IOException { // Don't close mFs; FileSystems are singletons so closing it here could break other users } @Override public FSDataOutputStream create(String path) throws IOException { IOException te = null; RetryPolicy retryPolicy = new SleepingRetry(MAX_TRY) { @Override protected long getSleepTime() { return SLEEP_TIME; } }; while (true) { try { LOG.debug("Creating HDFS file at {}", path); return FileSystem.create(mFs, new Path(path), PERMISSION); } catch (IOException e) { LOG.error("Retry count {} : {}", retryPolicy.getRetryCount(), e); te = e; if (!retryPolicy.attemptRetry()) { break; } } } throw te; } /** * BlockSize should be a multiple of 512 */ @Override public FSDataOutputStream create(String path, int blockSizeByte) throws IOException { // TODO(hy): Fix this. // return create(path, (short) Math.min(3, mFs.getDefaultReplication()), blockSizeBytes); return create(path); } @Override public FSDataOutputStream create(String path, short replication, int blockSizeByte) throws IOException { // TODO(hy): Fix this. // return create(path, (short) Math.min(3, mFs.getDefaultReplication()), blockSizeBytes); return create(path); // LOG.info("{} {} {}", path, replication, blockSizeBytes); // IOException te = null; // int cnt = 0; // while (cnt < MAX_TRY) { // try { // return mFs.create(new Path(path), true, 4096, replication, blockSizeBytes); // } catch (IOException e) { // cnt ++; // LOG.error("{} : {}", cnt, e.getMessage(), e); // te = e; // continue; // } // } // throw te; } @Override public boolean delete(String path, boolean recursive) throws IOException { LOG.debug("deleting {} {}", path, recursive); IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.delete(new Path(path), recursive); } catch (IOException e) { cnt ++; LOG.error("{} : {}", cnt, e.getMessage(), e); te = e; } } throw te; } @Override public boolean exists(String path) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.exists(new Path(path)); } catch (IOException e) { cnt ++; LOG.error("{} try to check if {} exists : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public long getBlockSizeByte(String path) throws IOException { Path tPath = new Path(path); if (!mFs.exists(tPath)) { throw new FileNotFoundException(path); } FileStatus fs = mFs.getFileStatus(tPath); return fs.getBlockSize(); } @Override public Object getConf() { return mFs.getConf(); } @Override public List<String> getFileLocations(String path) throws IOException { return getFileLocations(path, 0); } @Override public List<String> getFileLocations(String path, long offset) throws IOException { List<String> ret = new ArrayList<String>(); try { FileStatus fStatus = mFs.getFileStatus(new Path(path)); BlockLocation[] bLocations = mFs.getFileBlockLocations(fStatus, offset, 1); if (bLocations.length > 0) { String[] names = bLocations[0].getNames(); Collections.addAll(ret, names); } } catch (IOException e) { LOG.error("Unable to get file location for {}", path, e); } return ret; } @Override public long getFileSize(String path) throws IOException { int cnt = 0; Path tPath = new Path(path); while (cnt < MAX_TRY) { try { FileStatus fs = mFs.getFileStatus(tPath); return fs.getLen(); } catch (IOException e) { cnt ++; LOG.error("{} try to get file size for {} : {}", cnt, path, e.getMessage(), e); } } return -1; } @Override public long getModificationTimeMs(String path) throws IOException { Path tPath = new Path(path); if (!mFs.exists(tPath)) { throw new FileNotFoundException(path); } FileStatus fs = mFs.getFileStatus(tPath); return fs.getModificationTime(); } @Override public long getSpace(String path, SpaceType type) throws IOException { // Ignoring the path given, will give information for entire cluster // as Tachyon can load/store data out of entire HDFS cluster if (mFs instanceof DistributedFileSystem) { switch (type) { case SPACE_TOTAL: return ((DistributedFileSystem) mFs).getDiskStatus().getCapacity(); case SPACE_USED: return ((DistributedFileSystem) mFs).getDiskStatus().getDfsUsed(); case SPACE_FREE: return ((DistributedFileSystem) mFs).getDiskStatus().getRemaining(); default: throw new IOException("Unknown getSpace parameter: " + type); } } return -1; } @Override public boolean isFile(String path) throws IOException { return mFs.isFile(new Path(path)); } @Override public String[] list(String path) throws IOException { FileStatus[] files; try { files = mFs.listStatus(new Path(path)); } catch (FileNotFoundException e) { return null; } if (files != null && !isFile(path)) { String[] rtn = new String[files.length]; int i = 0; for (FileStatus status : files) { // only return the relative path, to keep consistent with java.io.File.list() rtn[i ++] = status.getPath().getName(); } return rtn; } else { return null; } } @Override public void connectFromMaster(TachyonConf conf, String host) throws IOException { if (!conf.containsKey(Constants.MASTER_KEYTAB_KEY) || !conf.containsKey(Constants.MASTER_PRINCIPAL_KEY)) { return; } String masterKeytab = conf.get(Constants.MASTER_KEYTAB_KEY); String masterPrincipal = conf.get(Constants.MASTER_PRINCIPAL_KEY); login(Constants.MASTER_KEYTAB_KEY, masterKeytab, Constants.MASTER_PRINCIPAL_KEY, masterPrincipal, host); } @Override public void connectFromWorker(TachyonConf conf, String host) throws IOException { if (!conf.containsKey(Constants.WORKER_KEYTAB_KEY) || !conf.containsKey(Constants.WORKER_PRINCIPAL_KEY)) { return; } String workerKeytab = conf.get(Constants.WORKER_KEYTAB_KEY); String workerPrincipal = conf.get(Constants.WORKER_PRINCIPAL_KEY); login(Constants.WORKER_KEYTAB_KEY, workerKeytab, Constants.WORKER_PRINCIPAL_KEY, workerPrincipal, host); } private void login(String keytabFileKey, String keytabFile, String principalKey, String principal, String hostname) throws IOException { Configuration conf = new Configuration(); conf.set(keytabFileKey, keytabFile); conf.set(principalKey, principal); SecurityUtil.login(conf, keytabFileKey, principalKey, hostname); } @Override public boolean mkdirs(String path, boolean createParent) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { Path hdfsPath = new Path(path); if (mFs.exists(hdfsPath)) { LOG.debug("Trying to create existing directory at {}", path); return false; } // Create directories one by one with explicit permissions to ensure no umask is applied, // using mkdirs will apply the permission only to the last directory Stack<Path> dirsToMake = new Stack<Path>(); dirsToMake.push(hdfsPath); Path parent = hdfsPath.getParent(); while (!mFs.exists(parent)) { dirsToMake.push(parent); parent = parent.getParent(); } while (!dirsToMake.empty()) { if (!FileSystem.mkdirs(mFs, dirsToMake.pop(), PERMISSION)) { return false; } } return true; } catch (IOException e) { cnt ++; LOG.error("{} try to make directory for {} : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public FSDataInputStream open(String path) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.open(new Path(path)); } catch (IOException e) { cnt ++; LOG.error("{} try to open {} : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public boolean rename(String src, String dst) throws IOException { LOG.debug("Renaming from {} to {}", src, dst); if (!exists(src)) { LOG.error("File {} does not exist. Therefore rename to {} failed.", src, dst); return false; } if (exists(dst)) { LOG.error("File {} does exist. Therefore rename from {} failed.", dst, src); return false; } int cnt = 0; IOException te = null; while (cnt < MAX_TRY) { try { return mFs.rename(new Path(src), new Path(dst)); } catch (IOException e) { cnt ++; LOG.error("{} try to rename {} to {} : {}", cnt, src, dst, e.getMessage(), e); te = e; } } throw te; } @Override public void setConf(Object conf) { mFs.setConf((Configuration) conf); } @Override public void setPermission(String path, String posixPerm) throws IOException { try { FileStatus fileStatus = mFs.getFileStatus(new Path(path)); LOG.info("Changing file '{}' permissions from: {} to {}", fileStatus.getPath(), fileStatus.getPermission(), posixPerm); FsPermission perm = new FsPermission(Short.parseShort(posixPerm)); mFs.setPermission(fileStatus.getPath(), perm); } catch (IOException e) { LOG.error("Fail to set permission for {} with perm {}", path, posixPerm, e); throw e; } } }
underfs/hdfs/src/main/java/tachyon/underfs/hdfs/HdfsUnderFileSystem.java
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.underfs.hdfs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.security.SecurityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; import tachyon.Constants; import tachyon.conf.TachyonConf; import tachyon.underfs.UnderFileSystem; /** * HDFS {@link UnderFileSystem} implementation */ public class HdfsUnderFileSystem extends UnderFileSystem { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); private static final int MAX_TRY = 5; private FileSystem mFs = null; private String mUfsPrefix = null; // TODO(hy): Add a sticky bit and narrow down the permission in hadoop 2. private static final FsPermission PERMISSION = new FsPermission((short) 0777) .applyUMask(FsPermission.createImmutable((short) 0000)); public HdfsUnderFileSystem(String fsDefaultName, TachyonConf tachyonConf, Object conf) { super(tachyonConf); mUfsPrefix = fsDefaultName; Configuration tConf; if (conf != null && conf instanceof Configuration) { tConf = (Configuration) conf; } else { tConf = new Configuration(); } prepareConfiguration(fsDefaultName, tachyonConf, tConf); tConf.addResource(new Path(tConf.get(Constants.UNDERFS_HDFS_CONFIGURATION))); HdfsUnderFileSystemUtils.addS3Credentials(tConf); Path path = new Path(mUfsPrefix); try { mFs = path.getFileSystem(tConf); } catch (IOException e) { LOG.error("Exception thrown when trying to get FileSystem for {}", mUfsPrefix, e); throw Throwables.propagate(e); } } @Override public UnderFSType getUnderFSType() { return UnderFSType.HDFS; } /** * Prepares the Hadoop configuration necessary to successfully obtain a {@link FileSystem} * instance that can access the provided path * <p> * Derived implementations that work with specialised Hadoop {@linkplain FileSystem} API * compatible implementations can override this method to add implementation specific * configuration necessary for obtaining a usable {@linkplain FileSystem} instance. * </p> * * @param path File system path * @param config Hadoop Configuration */ protected void prepareConfiguration(String path, TachyonConf tachyonConf, Configuration config) { // On Hadoop 2.x this is strictly unnecessary since it uses ServiceLoader to automatically // discover available file system implementations. However this configuration setting is // required for earlier Hadoop versions plus it is still honoured as an override even in 2.x so // if present propagate it to the Hadoop configuration String ufsHdfsImpl = mTachyonConf.get(Constants.UNDERFS_HDFS_IMPL); if (!StringUtils.isEmpty(ufsHdfsImpl)) { config.set("fs.hdfs.impl", ufsHdfsImpl); } // To disable the instance cache for hdfs client, otherwise it causes the // FileSystem closed exception. Being configurable for unit/integration // test only, and not expose to the end-user currently. config.set("fs.hdfs.impl.disable.cache", System.getProperty("fs.hdfs.impl.disable.cache", "false")); HdfsUnderFileSystemUtils.addKey(config, tachyonConf, Constants.UNDERFS_HDFS_CONFIGURATION); } @Override public void close() throws IOException { // Don't close mFs; FileSystems are singletons so closing it here could break other users } @Override public FSDataOutputStream create(String path) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { LOG.debug("Creating HDFS file at {}", path); return FileSystem.create(mFs, new Path(path), PERMISSION); } catch (IOException e) { cnt ++; LOG.error("{} : {}", cnt, e.getMessage(), e); te = e; } } throw te; } /** * BlockSize should be a multiple of 512 */ @Override public FSDataOutputStream create(String path, int blockSizeByte) throws IOException { // TODO(hy): Fix this. // return create(path, (short) Math.min(3, mFs.getDefaultReplication()), blockSizeBytes); return create(path); } @Override public FSDataOutputStream create(String path, short replication, int blockSizeByte) throws IOException { // TODO(hy): Fix this. // return create(path, (short) Math.min(3, mFs.getDefaultReplication()), blockSizeBytes); return create(path); // LOG.info("{} {} {}", path, replication, blockSizeBytes); // IOException te = null; // int cnt = 0; // while (cnt < MAX_TRY) { // try { // return mFs.create(new Path(path), true, 4096, replication, blockSizeBytes); // } catch (IOException e) { // cnt ++; // LOG.error("{} : {}", cnt, e.getMessage(), e); // te = e; // continue; // } // } // throw te; } @Override public boolean delete(String path, boolean recursive) throws IOException { LOG.debug("deleting {} {}", path, recursive); IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.delete(new Path(path), recursive); } catch (IOException e) { cnt ++; LOG.error("{} : {}", cnt, e.getMessage(), e); te = e; } } throw te; } @Override public boolean exists(String path) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.exists(new Path(path)); } catch (IOException e) { cnt ++; LOG.error("{} try to check if {} exists : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public long getBlockSizeByte(String path) throws IOException { Path tPath = new Path(path); if (!mFs.exists(tPath)) { throw new FileNotFoundException(path); } FileStatus fs = mFs.getFileStatus(tPath); return fs.getBlockSize(); } @Override public Object getConf() { return mFs.getConf(); } @Override public List<String> getFileLocations(String path) throws IOException { return getFileLocations(path, 0); } @Override public List<String> getFileLocations(String path, long offset) throws IOException { List<String> ret = new ArrayList<String>(); try { FileStatus fStatus = mFs.getFileStatus(new Path(path)); BlockLocation[] bLocations = mFs.getFileBlockLocations(fStatus, offset, 1); if (bLocations.length > 0) { String[] names = bLocations[0].getNames(); Collections.addAll(ret, names); } } catch (IOException e) { LOG.error("Unable to get file location for {}", path, e); } return ret; } @Override public long getFileSize(String path) throws IOException { int cnt = 0; Path tPath = new Path(path); while (cnt < MAX_TRY) { try { FileStatus fs = mFs.getFileStatus(tPath); return fs.getLen(); } catch (IOException e) { cnt ++; LOG.error("{} try to get file size for {} : {}", cnt, path, e.getMessage(), e); } } return -1; } @Override public long getModificationTimeMs(String path) throws IOException { Path tPath = new Path(path); if (!mFs.exists(tPath)) { throw new FileNotFoundException(path); } FileStatus fs = mFs.getFileStatus(tPath); return fs.getModificationTime(); } @Override public long getSpace(String path, SpaceType type) throws IOException { // Ignoring the path given, will give information for entire cluster // as Tachyon can load/store data out of entire HDFS cluster if (mFs instanceof DistributedFileSystem) { switch (type) { case SPACE_TOTAL: return ((DistributedFileSystem) mFs).getDiskStatus().getCapacity(); case SPACE_USED: return ((DistributedFileSystem) mFs).getDiskStatus().getDfsUsed(); case SPACE_FREE: return ((DistributedFileSystem) mFs).getDiskStatus().getRemaining(); default: throw new IOException("Unknown getSpace parameter: " + type); } } return -1; } @Override public boolean isFile(String path) throws IOException { return mFs.isFile(new Path(path)); } @Override public String[] list(String path) throws IOException { FileStatus[] files; try { files = mFs.listStatus(new Path(path)); } catch (FileNotFoundException e) { return null; } if (files != null && !isFile(path)) { String[] rtn = new String[files.length]; int i = 0; for (FileStatus status : files) { // only return the relative path, to keep consistent with java.io.File.list() rtn[i ++] = status.getPath().getName(); } return rtn; } else { return null; } } @Override public void connectFromMaster(TachyonConf conf, String host) throws IOException { if (!conf.containsKey(Constants.MASTER_KEYTAB_KEY) || !conf.containsKey(Constants.MASTER_PRINCIPAL_KEY)) { return; } String masterKeytab = conf.get(Constants.MASTER_KEYTAB_KEY); String masterPrincipal = conf.get(Constants.MASTER_PRINCIPAL_KEY); login(Constants.MASTER_KEYTAB_KEY, masterKeytab, Constants.MASTER_PRINCIPAL_KEY, masterPrincipal, host); } @Override public void connectFromWorker(TachyonConf conf, String host) throws IOException { if (!conf.containsKey(Constants.WORKER_KEYTAB_KEY) || !conf.containsKey(Constants.WORKER_PRINCIPAL_KEY)) { return; } String workerKeytab = conf.get(Constants.WORKER_KEYTAB_KEY); String workerPrincipal = conf.get(Constants.WORKER_PRINCIPAL_KEY); login(Constants.WORKER_KEYTAB_KEY, workerKeytab, Constants.WORKER_PRINCIPAL_KEY, workerPrincipal, host); } private void login(String keytabFileKey, String keytabFile, String principalKey, String principal, String hostname) throws IOException { Configuration conf = new Configuration(); conf.set(keytabFileKey, keytabFile); conf.set(principalKey, principal); SecurityUtil.login(conf, keytabFileKey, principalKey, hostname); } @Override public boolean mkdirs(String path, boolean createParent) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { Path hdfsPath = new Path(path); if (mFs.exists(hdfsPath)) { LOG.debug("Trying to create existing directory at {}", path); return false; } // Create directories one by one with explicit permissions to ensure no umask is applied, // using mkdirs will apply the permission only to the last directory Stack<Path> dirsToMake = new Stack<Path>(); dirsToMake.push(hdfsPath); Path parent = hdfsPath.getParent(); while (!mFs.exists(parent)) { dirsToMake.push(parent); parent = parent.getParent(); } while (!dirsToMake.empty()) { if (!FileSystem.mkdirs(mFs, dirsToMake.pop(), PERMISSION)) { return false; } } return true; } catch (IOException e) { cnt ++; LOG.error("{} try to make directory for {} : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public FSDataInputStream open(String path) throws IOException { IOException te = null; int cnt = 0; while (cnt < MAX_TRY) { try { return mFs.open(new Path(path)); } catch (IOException e) { cnt ++; LOG.error("{} try to open {} : {}", cnt, path, e.getMessage(), e); te = e; } } throw te; } @Override public boolean rename(String src, String dst) throws IOException { LOG.debug("Renaming from {} to {}", src, dst); if (!exists(src)) { LOG.error("File {} does not exist. Therefore rename to {} failed.", src, dst); return false; } if (exists(dst)) { LOG.error("File {} does exist. Therefore rename from {} failed.", dst, src); return false; } int cnt = 0; IOException te = null; while (cnt < MAX_TRY) { try { return mFs.rename(new Path(src), new Path(dst)); } catch (IOException e) { cnt ++; LOG.error("{} try to rename {} to {} : {}", cnt, src, dst, e.getMessage(), e); te = e; } } throw te; } @Override public void setConf(Object conf) { mFs.setConf((Configuration) conf); } @Override public void setPermission(String path, String posixPerm) throws IOException { try { FileStatus fileStatus = mFs.getFileStatus(new Path(path)); LOG.info("Changing file '{}' permissions from: {} to {}", fileStatus.getPath(), fileStatus.getPermission(), posixPerm); FsPermission perm = new FsPermission(Short.parseShort(posixPerm)); mFs.setPermission(fileStatus.getPath(), perm); } catch (IOException e) { LOG.error("Fail to set permission for {} with perm {}", path, posixPerm, e); throw e; } } }
[TACHYON-1451] minor change of using SleepingRetry for Hdfs path create
underfs/hdfs/src/main/java/tachyon/underfs/hdfs/HdfsUnderFileSystem.java
[TACHYON-1451] minor change of using SleepingRetry for Hdfs path create
Java
apache-2.0
7e80bc01b7ea5d3a9d862f96d1daf9dcdbfae9b6
0
enioka/jqm,enioka/jqm,enioka/jqm,enioka/jqm,enioka/jqm
/** * Copyright © 2013 enioka. All rights reserved * Authors: Marc-Antoine GOUILLART (marc-antoine.gouillart@enioka.com) * Pierre COPPEE (pierre.coppee@enioka.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.enioka.jqm.tools; import java.io.IOException; import java.io.InputStream; import java.lang.management.ManagementFactory; import java.security.SecureRandom; import java.sql.SQLTransientException; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.zip.ZipFile; import javax.mail.MessagingException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import org.apache.commons.io.IOUtils; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.RollingFileAppender; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.Sha512Hash; import org.apache.shiro.util.ByteSource; import org.apache.shiro.util.StringUtils; import org.hibernate.LazyInitializationException; import org.hibernate.exception.JDBCConnectionException; import com.enioka.jqm.jpamodel.Deliverable; import com.enioka.jqm.jpamodel.DeploymentParameter; import com.enioka.jqm.jpamodel.GlobalParameter; import com.enioka.jqm.jpamodel.History; import com.enioka.jqm.jpamodel.JndiObjectResource; import com.enioka.jqm.jpamodel.JndiObjectResourceParameter; import com.enioka.jqm.jpamodel.JobDef; import com.enioka.jqm.jpamodel.JobInstance; import com.enioka.jqm.jpamodel.Message; import com.enioka.jqm.jpamodel.Node; import com.enioka.jqm.jpamodel.Queue; import com.enioka.jqm.jpamodel.RPermission; import com.enioka.jqm.jpamodel.RRole; import com.enioka.jqm.jpamodel.RUser; import com.enioka.jqm.jpamodel.State; /** * This is a helper class for internal use only. * */ final class Helpers { private static final String PERSISTENCE_UNIT = "jobqueue-api-pu"; private static Logger jqmlogger = Logger.getLogger(Helpers.class); // The one and only EMF in the engine. private static Properties props = new Properties(); private static EntityManagerFactory emf; // Resource file contains at least the jqm jdbc connection definition. Static because JNDI root context is common to the whole JVM. static String resourceFile = "resources.xml"; private Helpers() { } /** * Get a fresh EM on the jobqueue-api-pu persistence Unit * * @return an EntityManager */ static EntityManager getNewEm() { getEmf(); return emf.createEntityManager(); } static void setEmf(EntityManagerFactory newEmf) { emf = newEmf; } static EntityManagerFactory getEmf() { if (emf == null) { emf = createFactory(); } return emf; } private static EntityManagerFactory createFactory() { InputStream fis = null; try { Properties p = new Properties(); fis = Helpers.class.getClassLoader().getResourceAsStream("jqm.properties"); if (fis != null) { jqmlogger.trace("A jqm.properties file was found"); p.load(fis); IOUtils.closeQuietly(fis); props.putAll(p); } return Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, props); } catch (IOException e) { jqmlogger.fatal("conf/jqm.properties file is invalid", e); IOUtils.closeQuietly(fis); throw new JqmInitError("Invalid JQM configuration file", e); } catch (Exception e) { jqmlogger.fatal("Unable to connect with the database. Maybe your configuration file is wrong. " + "Please check the password or the url in the $JQM_DIR/conf/resources.xml", e); throw new JqmInitError("Database connection issue", e); } finally { IOUtils.closeQuietly(fis); } } static void closeQuietly(EntityManager em) { try { if (em != null) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } catch (Exception e) { // fail silently } } static void closeQuietly(ZipFile zf) { try { if (zf != null) { zf.close(); } } catch (Exception e) { jqmlogger.warn("could not close jar file", e); } } static void allowCreateSchema() { props.put("hibernate.hbm2ddl.auto", "update"); } static void registerJndiIfNeeded() { try { JndiContext.createJndiContext(); } catch (NamingException e) { throw new JqmInitError("Could not register the JNDI provider", e); } } /** * For internal test use only <br/> * <bold>WARNING</bold> This will invalidate all open EntityManagers! */ static void resetEmf() { if (emf != null) { emf.close(); emf = null; } } static void setLogFileName(String name) { Appender a = Logger.getRootLogger().getAppender("rollingfile"); if (a == null) { return; } RollingFileAppender r = (RollingFileAppender) a; r.setFile("./logs/jqm-" + name + ".log"); r.activateOptions(); } static void setLogLevel(String level) { try { Logger.getRootLogger().setLevel(Level.toLevel(level)); Logger.getLogger("com.enioka").setLevel(Level.toLevel(level)); jqmlogger.info("Setting general log level at " + level + " which translates as log4j level " + Level.toLevel(level)); } catch (Exception e) { jqmlogger.warn("Log level could not be set", e); } } /** * Create a text message that will be stored in the database. Must be called inside a JPA transaction. * * @return the JPA message created */ static Message createMessage(String textMessage, JobInstance jobInstance, EntityManager em) { Message m = new Message(); m.setTextMessage(textMessage); m.setJi(jobInstance.getId()); em.persist(m); return m; } /** * Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a JPA transaction * * @param path * FilePath (relative to a root directory - cf. Node) * @param originalFileName * FileName * @param fileFamily * File family (may be null). E.g.: "daily report" * @param jobId * Job Instance ID * @param em * the EM to use. */ static Deliverable createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, EntityManager em) { Deliverable j = new Deliverable(); j.setFilePath(path); j.setRandomId(UUID.randomUUID().toString()); j.setFileFamily(fileFamily); j.setJobId(jobId); j.setOriginalFileName(originalFileName); em.persist(j); return j; } /** * Retrieve the value of a single-valued parameter. * * @param key * @param defaultValue * @param em */ static String getParameter(String key, String defaultValue, EntityManager em) { try { GlobalParameter gp = em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class) .setParameter("key", key).getSingleResult(); return gp.getValue(); } catch (NoResultException e) { return defaultValue; } } /** * Checks if a parameter exists. If it exists, it is left untouched. If it doesn't, it is created. Only works for parameters which key * is unique. Must be called from within an open JPA transaction. */ static void initSingleParam(String key, String initValue, EntityManager em) { try { em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class).setParameter("key", key) .getSingleResult(); return; } catch (NoResultException e) { GlobalParameter gp = new GlobalParameter(); gp.setKey(key); gp.setValue(initValue); em.persist(gp); } catch (NonUniqueResultException e) { // It exists! Nothing to do... } } /** * Checks if a parameter exists. If it exists, it is updated. If it doesn't, it is created. Only works for parameters which key is * unique. Will create a transaction on the given entity manager. */ static void setSingleParam(String key, String value, EntityManager em) { try { em.getTransaction().begin(); GlobalParameter prm = em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class) .setParameter("key", key).getSingleResult(); prm.setValue(value); em.getTransaction().commit(); } catch (NoResultException e) { GlobalParameter gp = new GlobalParameter(); gp.setKey(key); gp.setValue(value); em.persist(gp); em.getTransaction().commit(); } } static void checkConfiguration(String nodeName, EntityManager em) { // Node long n = em.createQuery("SELECT COUNT(n) FROM Node n WHERE n.name = :l", Long.class).setParameter("l", nodeName).getSingleResult(); if (n == 0L) { throw new JqmInitError("The node does not exist. It must be referenced (CLI option createnode) before it can be used"); } Node nn = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName).getSingleResult(); if (!StringUtils.hasText(nn.getDlRepo()) || !StringUtils.hasText(nn.getRepo()) || !StringUtils.hasText(nn.getTmpDirectory())) { throw new JqmInitError( "The node does not have all its paths specified. Check node configuration (or recreate it with the CLI)."); } // Default queue long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu where qu.defaultQueue = true").getSingleResult(); if (i == 0L) { throw new JqmInitError("There is no default queue. Correct this (for example with CLI option -u, or with the web admin)"); } if (i > 1L) { throw new JqmInitError( "There is more than one default queue. Correct this (for example with CLI option -u, or with the web admin)"); } // Deployment parameters i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node.name = :localnode", Long.class) .setParameter("localnode", nodeName).getSingleResult(); if (i == 0L) { jqmlogger.warn( "This node is not bound to any queue. Either use the GUI to bind it or use CLI option -u to bind it to the default queue"); } // Roles i = em.createQuery("SELECT count(rr) from RRole rr WHERE rr.name = :rr", Long.class).setParameter("rr", "administrator") .getSingleResult(); if (i == 0L) { throw new JqmInitError("The 'administrator' role does not exist. It is needed for the APIs. Run CLI option -u to create it."); } // Mail session i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn").setParameter("nn", "mail/default") .getSingleResult(); if (i == 0L) { throw new JqmInitError("Mail session named mail/default does not exist but is required for the engine to run" + ". Use CLI option -u to create an empty one or use the admin web GUI to create it."); } } /** * Creates or updates a node.<br> * This method makes the assumption metadata is valid. e.g. there MUST be a single default queue.<br> * Call {@link #updateConfiguration(EntityManager)} before to be sure if necessary. * * @param nodeName * name of the node that should be created or updated (if incompletely defined only) * @param em * an EntityManager on which a transaction will be opened. */ static void updateNodeConfiguration(String nodeName, EntityManager em) { // Node Node n = null; try { n = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName).getSingleResult(); } catch (NoResultException e) { jqmlogger.info("Node " + nodeName + " does not exist in the configuration and will be created with default values"); em.getTransaction().begin(); n = new Node(); n.setDlRepo(System.getProperty("user.dir") + "/outputfiles/"); n.setName(nodeName); n.setPort(0); n.setRepo(System.getProperty("user.dir") + "/jobs/"); n.setTmpDirectory(System.getProperty("user.dir") + "/tmp/"); n.setRootLogLevel("INFO"); em.persist(n); em.getTransaction().commit(); } // Deployment parameters DeploymentParameter dp = null; long i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node = :localnode") .setParameter("localnode", n).getSingleResult(); if (i == 0) { jqmlogger.info("As this node is not bound to any queue, it will be set to poll from the default queue with default parameters"); Queue q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class).getSingleResult(); em.getTransaction().begin(); dp = new DeploymentParameter(); dp.setNbThread(5); dp.setNode(n); dp.setPollingInterval(1000); dp.setQueue(q); em.persist(dp); em.getTransaction().commit(); } } /** * Creates or updates metadata common to all nodes: default queue, global parameters, roles...<br> * It is idempotent. It also has the effect of making broken metadata viable again. */ static void updateConfiguration(EntityManager em) { em.getTransaction().begin(); // Default queue Queue q = null; long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu").getSingleResult(); if (i == 0L) { q = new Queue(); q.setDefaultQueue(true); q.setDescription("default queue"); q.setTimeToLive(1024); q.setName("DEFAULT"); em.persist(q); jqmlogger.info("A default queue was created in the configuration"); } else { try { q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class).getSingleResult(); jqmlogger.info("Default queue is named " + q.getName()); } catch (NonUniqueResultException e) { // Faulty configuration, but why not q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0); q.setDefaultQueue(true); jqmlogger.info("Queue " + q.getName() + " was modified to become the default queue as there were mutliple default queue"); } catch (NoResultException e) { // Faulty configuration, but why not q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0); q.setDefaultQueue(true); jqmlogger.warn("Queue " + q.getName() + " was modified to become the default queue as there was no default queue"); } } // Global parameters initSingleParam("mavenRepo", "http://repo1.maven.org/maven2/", em); initSingleParam(Constants.GP_DEFAULT_CONNECTION_KEY, Constants.GP_JQM_CONNECTION_ALIAS, em); initSingleParam("logFilePerLaunch", "true", em); initSingleParam("internalPollingPeriodMs", "60000", em); initSingleParam("disableWsApi", "false", em); initSingleParam("enableWsApiSsl", "false", em); initSingleParam("enableWsApiAuth", "true", em); initSingleParam("enableInternalPki", "true", em); // Roles RRole adminr = createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*"); createRoleIfMissing(em, "config admin", "can read and write all configuration, except security configuration", "node:*", "queue:*", "qmapping:*", "jndi:*", "prm:*", "jd:*"); createRoleIfMissing(em, "config viewer", "can read all configuration except for security configuration", "node:read", "queue:read", "qmapping:read", "jndi:read", "prm:read", "jd:read"); createRoleIfMissing(em, "client", "can use the full client API except reading logs, files and altering position", "node:read", "queue:read", "job_instance:*", "jd:read"); createRoleIfMissing(em, "client power user", "can use the full client API", "node:read", "queue:read", "job_instance:*", "jd:read", "logs:read", "queue_position:create", "files:read"); createRoleIfMissing(em, "client read only", "can query job instances and get their files", "queue:read", "job_instance:read", "logs:read", "files:read"); // Users createUserIfMissing(em, "root", "all powerful user", adminr); // Mail session i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn").setParameter("nn", "mail/default") .getSingleResult(); if (i == 0) { HashMap<String, String> prms = new HashMap<String, String>(); prms.put("smtpServerHost", "smtp.gmail.com"); JndiObjectResource res = new JndiObjectResource(); res.setAuth(null); res.setDescription("default parameters used to send e-mails"); res.setFactory("com.enioka.jqm.providers.MailSessionFactory"); res.setName("mail/default"); res.setType("javax.mail.Session"); res.setSingleton(true); em.persist(res); JndiObjectResourceParameter prm = new JndiObjectResourceParameter(); prm.setKey("smtpServerHost"); prm.setValue("smtp.gmail.com"); res.getParameters().add(prm); prm.setResource(res); } // Done em.getTransaction().commit(); } static RRole createRoleIfMissing(EntityManager em, String roleName, String description, String... permissions) { try { return em.createQuery("SELECT rr from RRole rr WHERE rr.name = :r", RRole.class).setParameter("r", roleName).getSingleResult(); } catch (NoResultException e) { RRole r = new RRole(); r.setName(roleName); r.setDescription(description); em.persist(r); for (String s : permissions) { RPermission p = new RPermission(); p.setName(s); p.setRole(r); em.persist(p); r.getPermissions().add(p); } return r; } } static RUser createUserIfMissing(EntityManager em, String login, String description, RRole... roles) { RUser res = null; try { res = em.createQuery("SELECT r from RUser r WHERE r.login = :l", RUser.class).setParameter("l", login).getSingleResult(); } catch (NoResultException e) { res = new RUser(); res.setFreeText(description); res.setLogin(login); res.setPassword(String.valueOf((new SecureRandom()).nextInt())); encodePassword(res); em.persist(res); } res.setLocked(false); for (RRole r : res.getRoles()) { r.getUsers().remove(res); } res.getRoles().clear(); for (RRole r : roles) { res.getRoles().add(r); r.getUsers().add(res); } return res; } static void encodePassword(RUser user) { ByteSource salt = new SecureRandomNumberGenerator().nextBytes(); user.setPassword(new Sha512Hash(user.getPassword(), salt, 100000).toHex()); user.setHashSalt(salt.toHex()); } /** * Transaction is not opened nor committed here but needed. * */ static History createHistory(JobInstance job, EntityManager em, State finalState, Calendar endDate) { History h = new History(); h.setId(job.getId()); h.setJd(job.getJd()); h.setApplicationName(job.getJd().getApplicationName()); h.setSessionId(job.getSessionID()); h.setQueue(job.getQueue()); h.setQueueName(job.getQueue().getName()); h.setEnqueueDate(job.getCreationDate()); h.setEndDate(endDate); h.setAttributionDate(job.getAttributionDate()); h.setExecutionDate(job.getExecutionDate()); h.setUserName(job.getUserName()); h.setEmail(job.getEmail()); h.setParentJobId(job.getParentId()); h.setApplication(job.getJd().getApplication()); h.setModule(job.getJd().getModule()); h.setKeyword1(job.getJd().getKeyword1()); h.setKeyword2(job.getJd().getKeyword2()); h.setKeyword3(job.getJd().getKeyword3()); h.setInstanceApplication(job.getApplication()); h.setInstanceKeyword1(job.getKeyword1()); h.setInstanceKeyword2(job.getKeyword2()); h.setInstanceKeyword3(job.getKeyword3()); h.setInstanceModule(job.getModule()); h.setProgress(job.getProgress()); h.setStatus(finalState); h.setNode(job.getNode()); h.setNodeName(job.getNode().getName()); h.setHighlander(job.getJd().isHighlander()); em.persist(h); return h; } static String getMavenVersion() { String res = System.getProperty("mavenVersion"); if (res != null) { return res; } InputStream is = Main.class.getResourceAsStream("/META-INF/maven/com.enioka.jqm/jqm-engine/pom.properties"); Properties p = new Properties(); try { p.load(is); res = p.getProperty("version"); } catch (Exception e) { res = "maven version not found"; jqmlogger.warn("maven version not found"); } return res; } static JobDef findJobDef(String applicationName, EntityManager em) { try { return em.createQuery("SELECT j FROM JobDef j WHERE j.applicationName = :n", JobDef.class).setParameter("n", applicationName) .getSingleResult(); } catch (NoResultException ex) { return null; } } static Queue findQueue(String qName, EntityManager em) { try { return em.createQuery("SELECT q FROM Queue q WHERE q.name = :name", Queue.class).setParameter("name", qName).getSingleResult(); } catch (NoResultException ex) { return null; } } static void dumpParameters(EntityManager em, Node n) { String terse = getParameter("disableVerboseStartup", "false", em); if ("false".equals(terse)) { jqmlogger.info("Global cluster parameters are as follow:"); List<GlobalParameter> prms = em.createQuery("SELECT gp FROM GlobalParameter gp", GlobalParameter.class).getResultList(); for (GlobalParameter prm : prms) { jqmlogger.info(String.format("\t%1$s = %2$s", prm.getKey(), prm.getValue())); } jqmlogger.info("Node parameters are as follow:"); jqmlogger.info("\tfile produced storage directory: " + n.getDlRepo()); jqmlogger.info("\tHTTP listening interface: " + n.getDns()); jqmlogger.info("\tlooks for payloads inside: " + n.getRepo()); jqmlogger.info("\tlog level: " + n.getRootLogLevel()); jqmlogger.info("\ttemp files will be created inside: " + n.getTmpDirectory()); jqmlogger.info("\tJMX registry port: " + n.getJmxRegistryPort()); jqmlogger.info("\tJMX server port: " + n.getJmxServerPort()); jqmlogger.info("\tHTTP listening port: " + n.getPort()); jqmlogger.info("\tAPI admin enabled: " + n.getLoadApiAdmin()); jqmlogger.info("\tAPI client enabled: " + n.getLoadApiClient()); jqmlogger.info("\tAPI simple enabled: " + n.getLoapApiSimple()); jqmlogger.info("Node polling parameters are as follow:"); List<DeploymentParameter> dps = em .createQuery("SELECT dp FROM DeploymentParameter dp WHERE dp.node.id = :n", DeploymentParameter.class) .setParameter("n", n.getId()).getResultList(); // Pollers for (DeploymentParameter dp : dps) { jqmlogger.info("\t" + dp.getQueue().getName() + " - every " + dp.getPollingInterval() + "ms - maximum " + dp.getNbThread() + " concurrent threads"); } // Some technical data from the JVM hosting the node Runtime rt = Runtime.getRuntime(); jqmlogger.info("JVM parameters are as follow:"); jqmlogger.info("\tMax usable memory reported by Java runtime, MB: " + (int) (rt.maxMemory() / 1024 / 1024)); jqmlogger.info("\tJVM arguments are: " + ManagementFactory.getRuntimeMXBean().getInputArguments()); } } /** * Send a mail message using a JNDI resource.<br> * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the * MailSessionFactory offered to payloads, making it accessible also to the engine. * * @param to * @param subject * @param body * @param mailSessionJndiAlias * @throws MessagingException */ @SuppressWarnings({ "unchecked", "rawtypes" }) static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias) throws MessagingException { jqmlogger.debug("sending mail to " + to + " - subject is " + subject); ClassLoader extLoader = getExtClassLoader(); ClassLoader old = Thread.currentThread().getContextClassLoader(); Object mailSession = null; try { mailSession = InitialContext.doLookup(mailSessionJndiAlias); } catch (NamingException e) { throw new MessagingException("could not find mail session description", e); } try { Thread.currentThread().setContextClassLoader(extLoader); Class transportZ = extLoader.loadClass("javax.mail.Transport"); Class sessionZ = extLoader.loadClass("javax.mail.Session"); Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage"); Class messageZ = extLoader.loadClass("javax.mail.Message"); Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType"); Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession); mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg, recipientTypeZ.getField("TO").get(null), to); mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject); mimeMessageZ.getMethod("setText", String.class).invoke(msg, body); transportZ.getMethod("send", messageZ).invoke(null, msg); jqmlogger.trace("Mail was sent"); } catch (Exception e) { throw new MessagingException("an exception occurred during mail sending", e); } finally { Thread.currentThread().setContextClassLoader(old); } } static void sendEndMessage(JobInstance ji) { try { String message = "The Job number " + ji.getId() + " finished correctly\n\n" + "Job description:\n" + "- Job definition: " + ji.getJd().getApplicationName() + "\n" + "- Parent: " + ji.getParentId() + "\n" + "- User name: " + ji.getUserName() + "\n" + "- Session ID: " + ji.getSessionID() + "\n" + "- Queue: " + ji.getQueue().getName() + "\n" + "- Node: " + ji.getNode().getName() + "\n" + "Best regards,\n"; sendMessage(ji.getEmail(), "[JQM] Job: " + ji.getId() + " ENDED", message, "mail/default"); } catch (Exception e) { jqmlogger.warn("Could not send email. Job has nevertheless run correctly", e); } } static ClassLoader getExtClassLoader() { try { return ((JndiContext) NamingManager.getInitialContext(null)).getExtCl(); } catch (NamingException e) { // Don't do anything - this actually cannot happen. Death to checked exceptions. return null; } } static boolean testDbFailure(Exception e) { return (e instanceof LazyInitializationException) || (e instanceof JDBCConnectionException) || (e.getCause() instanceof JDBCConnectionException) || (e.getCause() != null && e.getCause().getCause() instanceof JDBCConnectionException) || (e.getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() != null && e.getCause().getCause().getCause().getCause() instanceof SQLTransientException); } }
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java
/** * Copyright © 2013 enioka. All rights reserved * Authors: Marc-Antoine GOUILLART (marc-antoine.gouillart@enioka.com) * Pierre COPPEE (pierre.coppee@enioka.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.enioka.jqm.tools; import java.io.IOException; import java.io.InputStream; import java.security.SecureRandom; import java.sql.SQLTransientException; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.zip.ZipFile; import javax.mail.MessagingException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import org.apache.commons.io.IOUtils; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.RollingFileAppender; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.Sha512Hash; import org.apache.shiro.util.ByteSource; import org.apache.shiro.util.StringUtils; import org.hibernate.LazyInitializationException; import org.hibernate.exception.JDBCConnectionException; import com.enioka.jqm.jpamodel.Deliverable; import com.enioka.jqm.jpamodel.DeploymentParameter; import com.enioka.jqm.jpamodel.GlobalParameter; import com.enioka.jqm.jpamodel.History; import com.enioka.jqm.jpamodel.JndiObjectResource; import com.enioka.jqm.jpamodel.JndiObjectResourceParameter; import com.enioka.jqm.jpamodel.JobDef; import com.enioka.jqm.jpamodel.JobInstance; import com.enioka.jqm.jpamodel.Message; import com.enioka.jqm.jpamodel.Node; import com.enioka.jqm.jpamodel.Queue; import com.enioka.jqm.jpamodel.RPermission; import com.enioka.jqm.jpamodel.RRole; import com.enioka.jqm.jpamodel.RUser; import com.enioka.jqm.jpamodel.State; /** * This is a helper class for internal use only. * */ final class Helpers { private static final String PERSISTENCE_UNIT = "jobqueue-api-pu"; private static Logger jqmlogger = Logger.getLogger(Helpers.class); // The one and only EMF in the engine. private static Properties props = new Properties(); private static EntityManagerFactory emf; // Resource file contains at least the jqm jdbc connection definition. Static because JNDI root context is common to the whole JVM. static String resourceFile = "resources.xml"; private Helpers() { } /** * Get a fresh EM on the jobqueue-api-pu persistence Unit * * @return an EntityManager */ static EntityManager getNewEm() { getEmf(); return emf.createEntityManager(); } static void setEmf(EntityManagerFactory newEmf) { emf = newEmf; } static EntityManagerFactory getEmf() { if (emf == null) { emf = createFactory(); } return emf; } private static EntityManagerFactory createFactory() { InputStream fis = null; try { Properties p = new Properties(); fis = Helpers.class.getClassLoader().getResourceAsStream("jqm.properties"); if (fis != null) { jqmlogger.trace("A jqm.properties file was found"); p.load(fis); IOUtils.closeQuietly(fis); props.putAll(p); } return Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, props); } catch (IOException e) { jqmlogger.fatal("conf/jqm.properties file is invalid", e); IOUtils.closeQuietly(fis); throw new JqmInitError("Invalid JQM configuration file", e); } catch (Exception e) { jqmlogger.fatal("Unable to connect with the database. Maybe your configuration file is wrong. " + "Please check the password or the url in the $JQM_DIR/conf/resources.xml", e); throw new JqmInitError("Database connection issue", e); } finally { IOUtils.closeQuietly(fis); } } static void closeQuietly(EntityManager em) { try { if (em != null) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } } catch (Exception e) { // fail silently } } static void closeQuietly(ZipFile zf) { try { if (zf != null) { zf.close(); } } catch (Exception e) { jqmlogger.warn("could not close jar file", e); } } static void allowCreateSchema() { props.put("hibernate.hbm2ddl.auto", "update"); } static void registerJndiIfNeeded() { try { JndiContext.createJndiContext(); } catch (NamingException e) { throw new JqmInitError("Could not register the JNDI provider", e); } } /** * For internal test use only <br/> * <bold>WARNING</bold> This will invalidate all open EntityManagers! */ static void resetEmf() { if (emf != null) { emf.close(); emf = null; } } static void setLogFileName(String name) { Appender a = Logger.getRootLogger().getAppender("rollingfile"); if (a == null) { return; } RollingFileAppender r = (RollingFileAppender) a; r.setFile("./logs/jqm-" + name + ".log"); r.activateOptions(); } static void setLogLevel(String level) { try { Logger.getRootLogger().setLevel(Level.toLevel(level)); Logger.getLogger("com.enioka").setLevel(Level.toLevel(level)); jqmlogger.info("Setting general log level at " + level + " which translates as log4j level " + Level.toLevel(level)); } catch (Exception e) { jqmlogger.warn("Log level could not be set", e); } } /** * Create a text message that will be stored in the database. Must be called inside a JPA transaction. * * @return the JPA message created */ static Message createMessage(String textMessage, JobInstance jobInstance, EntityManager em) { Message m = new Message(); m.setTextMessage(textMessage); m.setJi(jobInstance.getId()); em.persist(m); return m; } /** * Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a JPA transaction * * @param path * FilePath (relative to a root directory - cf. Node) * @param originalFileName * FileName * @param fileFamily * File family (may be null). E.g.: "daily report" * @param jobId * Job Instance ID * @param em * the EM to use. */ static Deliverable createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId, EntityManager em) { Deliverable j = new Deliverable(); j.setFilePath(path); j.setRandomId(UUID.randomUUID().toString()); j.setFileFamily(fileFamily); j.setJobId(jobId); j.setOriginalFileName(originalFileName); em.persist(j); return j; } /** * Retrieve the value of a single-valued parameter. * * @param key * @param defaultValue * @param em */ static String getParameter(String key, String defaultValue, EntityManager em) { try { GlobalParameter gp = em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class) .setParameter("key", key).getSingleResult(); return gp.getValue(); } catch (NoResultException e) { return defaultValue; } } /** * Checks if a parameter exists. If it exists, it is left untouched. If it doesn't, it is created. Only works for parameters which key * is unique. Must be called from within an open JPA transaction. */ static void initSingleParam(String key, String initValue, EntityManager em) { try { em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class).setParameter("key", key) .getSingleResult(); return; } catch (NoResultException e) { GlobalParameter gp = new GlobalParameter(); gp.setKey(key); gp.setValue(initValue); em.persist(gp); } catch (NonUniqueResultException e) { // It exists! Nothing to do... } } /** * Checks if a parameter exists. If it exists, it is updated. If it doesn't, it is created. Only works for parameters which key is * unique. Will create a transaction on the given entity manager. */ static void setSingleParam(String key, String value, EntityManager em) { try { em.getTransaction().begin(); GlobalParameter prm = em.createQuery("SELECT n from GlobalParameter n WHERE n.key = :key", GlobalParameter.class) .setParameter("key", key).getSingleResult(); prm.setValue(value); em.getTransaction().commit(); } catch (NoResultException e) { GlobalParameter gp = new GlobalParameter(); gp.setKey(key); gp.setValue(value); em.persist(gp); em.getTransaction().commit(); } } static void checkConfiguration(String nodeName, EntityManager em) { // Node long n = em.createQuery("SELECT COUNT(n) FROM Node n WHERE n.name = :l", Long.class).setParameter("l", nodeName).getSingleResult(); if (n == 0L) { throw new JqmInitError("The node does not exist. It must be referenced (CLI option createnode) before it can be used"); } Node nn = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName).getSingleResult(); if (!StringUtils.hasText(nn.getDlRepo()) || !StringUtils.hasText(nn.getRepo()) || !StringUtils.hasText(nn.getTmpDirectory())) { throw new JqmInitError( "The node does not have all its paths specified. Check node configuration (or recreate it with the CLI)."); } // Default queue long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu where qu.defaultQueue = true").getSingleResult(); if (i == 0L) { throw new JqmInitError("There is no default queue. Correct this (for example with CLI option -u, or with the web admin)"); } if (i > 1L) { throw new JqmInitError( "There is more than one default queue. Correct this (for example with CLI option -u, or with the web admin)"); } // Deployment parameters i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node.name = :localnode", Long.class) .setParameter("localnode", nodeName).getSingleResult(); if (i == 0L) { jqmlogger.warn( "This node is not bound to any queue. Either use the GUI to bind it or use CLI option -u to bind it to the default queue"); } // Roles i = em.createQuery("SELECT count(rr) from RRole rr WHERE rr.name = :rr", Long.class).setParameter("rr", "administrator") .getSingleResult(); if (i == 0L) { throw new JqmInitError("The 'administrator' role does not exist. It is needed for the APIs. Run CLI option -u to create it."); } // Mail session i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn").setParameter("nn", "mail/default") .getSingleResult(); if (i == 0L) { throw new JqmInitError("Mail session named mail/default does not exist but is required for the engine to run" + ". Use CLI option -u to create an empty one or use the admin web GUI to create it."); } } /** * Creates or updates a node.<br> * This method makes the assumption metadata is valid. e.g. there MUST be a single default queue.<br> * Call {@link #updateConfiguration(EntityManager)} before to be sure if necessary. * * @param nodeName * name of the node that should be created or updated (if incompletely defined only) * @param em * an EntityManager on which a transaction will be opened. */ static void updateNodeConfiguration(String nodeName, EntityManager em) { // Node Node n = null; try { n = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName).getSingleResult(); } catch (NoResultException e) { jqmlogger.info("Node " + nodeName + " does not exist in the configuration and will be created with default values"); em.getTransaction().begin(); n = new Node(); n.setDlRepo(System.getProperty("user.dir") + "/outputfiles/"); n.setName(nodeName); n.setPort(0); n.setRepo(System.getProperty("user.dir") + "/jobs/"); n.setTmpDirectory(System.getProperty("user.dir") + "/tmp/"); n.setRootLogLevel("INFO"); em.persist(n); em.getTransaction().commit(); } // Deployment parameters DeploymentParameter dp = null; long i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node = :localnode") .setParameter("localnode", n).getSingleResult(); if (i == 0) { jqmlogger.info("As this node is not bound to any queue, it will be set to poll from the default queue with default parameters"); Queue q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class).getSingleResult(); em.getTransaction().begin(); dp = new DeploymentParameter(); dp.setNbThread(5); dp.setNode(n); dp.setPollingInterval(1000); dp.setQueue(q); em.persist(dp); em.getTransaction().commit(); } } /** * Creates or updates metadata common to all nodes: default queue, global parameters, roles...<br> * It is idempotent. It also has the effect of making broken metadata viable again. */ static void updateConfiguration(EntityManager em) { em.getTransaction().begin(); // Default queue Queue q = null; long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu").getSingleResult(); if (i == 0L) { q = new Queue(); q.setDefaultQueue(true); q.setDescription("default queue"); q.setTimeToLive(1024); q.setName("DEFAULT"); em.persist(q); jqmlogger.info("A default queue was created in the configuration"); } else { try { q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class).getSingleResult(); jqmlogger.info("Default queue is named " + q.getName()); } catch (NonUniqueResultException e) { // Faulty configuration, but why not q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0); q.setDefaultQueue(true); jqmlogger.info("Queue " + q.getName() + " was modified to become the default queue as there were mutliple default queue"); } catch (NoResultException e) { // Faulty configuration, but why not q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0); q.setDefaultQueue(true); jqmlogger.warn("Queue " + q.getName() + " was modified to become the default queue as there was no default queue"); } } // Global parameters initSingleParam("mavenRepo", "http://repo1.maven.org/maven2/", em); initSingleParam(Constants.GP_DEFAULT_CONNECTION_KEY, Constants.GP_JQM_CONNECTION_ALIAS, em); initSingleParam("logFilePerLaunch", "true", em); initSingleParam("internalPollingPeriodMs", "60000", em); initSingleParam("disableWsApi", "false", em); initSingleParam("enableWsApiSsl", "false", em); initSingleParam("enableWsApiAuth", "true", em); initSingleParam("enableInternalPki", "true", em); // Roles RRole adminr = createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*"); createRoleIfMissing(em, "config admin", "can read and write all configuration, except security configuration", "node:*", "queue:*", "qmapping:*", "jndi:*", "prm:*", "jd:*"); createRoleIfMissing(em, "config viewer", "can read all configuration except for security configuration", "node:read", "queue:read", "qmapping:read", "jndi:read", "prm:read", "jd:read"); createRoleIfMissing(em, "client", "can use the full client API except reading logs, files and altering position", "node:read", "queue:read", "job_instance:*", "jd:read"); createRoleIfMissing(em, "client power user", "can use the full client API", "node:read", "queue:read", "job_instance:*", "jd:read", "logs:read", "queue_position:create", "files:read"); createRoleIfMissing(em, "client read only", "can query job instances and get their files", "queue:read", "job_instance:read", "logs:read", "files:read"); // Users createUserIfMissing(em, "root", "all powerful user", adminr); // Mail session i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn").setParameter("nn", "mail/default") .getSingleResult(); if (i == 0) { HashMap<String, String> prms = new HashMap<String, String>(); prms.put("smtpServerHost", "smtp.gmail.com"); JndiObjectResource res = new JndiObjectResource(); res.setAuth(null); res.setDescription("default parameters used to send e-mails"); res.setFactory("com.enioka.jqm.providers.MailSessionFactory"); res.setName("mail/default"); res.setType("javax.mail.Session"); res.setSingleton(true); em.persist(res); JndiObjectResourceParameter prm = new JndiObjectResourceParameter(); prm.setKey("smtpServerHost"); prm.setValue("smtp.gmail.com"); res.getParameters().add(prm); prm.setResource(res); } // Done em.getTransaction().commit(); } static RRole createRoleIfMissing(EntityManager em, String roleName, String description, String... permissions) { try { return em.createQuery("SELECT rr from RRole rr WHERE rr.name = :r", RRole.class).setParameter("r", roleName).getSingleResult(); } catch (NoResultException e) { RRole r = new RRole(); r.setName(roleName); r.setDescription(description); em.persist(r); for (String s : permissions) { RPermission p = new RPermission(); p.setName(s); p.setRole(r); em.persist(p); r.getPermissions().add(p); } return r; } } static RUser createUserIfMissing(EntityManager em, String login, String description, RRole... roles) { RUser res = null; try { res = em.createQuery("SELECT r from RUser r WHERE r.login = :l", RUser.class).setParameter("l", login).getSingleResult(); } catch (NoResultException e) { res = new RUser(); res.setFreeText(description); res.setLogin(login); res.setPassword(String.valueOf((new SecureRandom()).nextInt())); encodePassword(res); em.persist(res); } res.setLocked(false); for (RRole r : res.getRoles()) { r.getUsers().remove(res); } res.getRoles().clear(); for (RRole r : roles) { res.getRoles().add(r); r.getUsers().add(res); } return res; } static void encodePassword(RUser user) { ByteSource salt = new SecureRandomNumberGenerator().nextBytes(); user.setPassword(new Sha512Hash(user.getPassword(), salt, 100000).toHex()); user.setHashSalt(salt.toHex()); } /** * Transaction is not opened nor committed here but needed. * */ static History createHistory(JobInstance job, EntityManager em, State finalState, Calendar endDate) { History h = new History(); h.setId(job.getId()); h.setJd(job.getJd()); h.setApplicationName(job.getJd().getApplicationName()); h.setSessionId(job.getSessionID()); h.setQueue(job.getQueue()); h.setQueueName(job.getQueue().getName()); h.setEnqueueDate(job.getCreationDate()); h.setEndDate(endDate); h.setAttributionDate(job.getAttributionDate()); h.setExecutionDate(job.getExecutionDate()); h.setUserName(job.getUserName()); h.setEmail(job.getEmail()); h.setParentJobId(job.getParentId()); h.setApplication(job.getJd().getApplication()); h.setModule(job.getJd().getModule()); h.setKeyword1(job.getJd().getKeyword1()); h.setKeyword2(job.getJd().getKeyword2()); h.setKeyword3(job.getJd().getKeyword3()); h.setInstanceApplication(job.getApplication()); h.setInstanceKeyword1(job.getKeyword1()); h.setInstanceKeyword2(job.getKeyword2()); h.setInstanceKeyword3(job.getKeyword3()); h.setInstanceModule(job.getModule()); h.setProgress(job.getProgress()); h.setStatus(finalState); h.setNode(job.getNode()); h.setNodeName(job.getNode().getName()); h.setHighlander(job.getJd().isHighlander()); em.persist(h); return h; } static String getMavenVersion() { String res = System.getProperty("mavenVersion"); if (res != null) { return res; } InputStream is = Main.class.getResourceAsStream("/META-INF/maven/com.enioka.jqm/jqm-engine/pom.properties"); Properties p = new Properties(); try { p.load(is); res = p.getProperty("version"); } catch (Exception e) { res = "maven version not found"; jqmlogger.warn("maven version not found"); } return res; } static JobDef findJobDef(String applicationName, EntityManager em) { try { return em.createQuery("SELECT j FROM JobDef j WHERE j.applicationName = :n", JobDef.class).setParameter("n", applicationName) .getSingleResult(); } catch (NoResultException ex) { return null; } } static Queue findQueue(String qName, EntityManager em) { try { return em.createQuery("SELECT q FROM Queue q WHERE q.name = :name", Queue.class).setParameter("name", qName).getSingleResult(); } catch (NoResultException ex) { return null; } } static void dumpParameters(EntityManager em, Node n) { String terse = getParameter("disableVerboseStartup", "false", em); if ("false".equals(terse)) { jqmlogger.info("Global cluster parameters are as follow:"); List<GlobalParameter> prms = em.createQuery("SELECT gp FROM GlobalParameter gp", GlobalParameter.class).getResultList(); for (GlobalParameter prm : prms) { jqmlogger.info(String.format("\t%1$s = %2$s", prm.getKey(), prm.getValue())); } jqmlogger.info("Node parameters are as follow:"); jqmlogger.info("\tfile produced storage directory: " + n.getDlRepo()); jqmlogger.info("\tHTTP listening interface: " + n.getDns()); jqmlogger.info("\tlooks for payloads inside: " + n.getRepo()); jqmlogger.info("\tlog level: " + n.getRootLogLevel()); jqmlogger.info("\ttemp files will be created inside: " + n.getTmpDirectory()); jqmlogger.info("\tJMX registry port: " + n.getJmxRegistryPort()); jqmlogger.info("\tJMX server port: " + n.getJmxServerPort()); jqmlogger.info("\tHTTP listening port: " + n.getPort()); jqmlogger.info("\tAPI admin enabled: " + n.getLoadApiAdmin()); jqmlogger.info("\tAPI client enabled: " + n.getLoadApiClient()); jqmlogger.info("\tAPI simple enabled: " + n.getLoapApiSimple()); jqmlogger.info("Node polling parameters are as follow:"); List<DeploymentParameter> dps = em .createQuery("SELECT dp FROM DeploymentParameter dp WHERE dp.node.id = :n", DeploymentParameter.class) .setParameter("n", n.getId()).getResultList(); // Pollers for (DeploymentParameter dp : dps) { jqmlogger.info("\t" + dp.getQueue().getName() + " - every " + dp.getPollingInterval() + "ms - maximum " + dp.getNbThread() + " concurrent threads"); } } } /** * Send a mail message using a JNDI resource.<br> * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the * MailSessionFactory offered to payloads, making it accessible also to the engine. * * @param to * @param subject * @param body * @param mailSessionJndiAlias * @throws MessagingException */ @SuppressWarnings({ "unchecked", "rawtypes" }) static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias) throws MessagingException { jqmlogger.debug("sending mail to " + to + " - subject is " + subject); ClassLoader extLoader = getExtClassLoader(); ClassLoader old = Thread.currentThread().getContextClassLoader(); Object mailSession = null; try { mailSession = InitialContext.doLookup(mailSessionJndiAlias); } catch (NamingException e) { throw new MessagingException("could not find mail session description", e); } try { Thread.currentThread().setContextClassLoader(extLoader); Class transportZ = extLoader.loadClass("javax.mail.Transport"); Class sessionZ = extLoader.loadClass("javax.mail.Session"); Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage"); Class messageZ = extLoader.loadClass("javax.mail.Message"); Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType"); Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession); mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg, recipientTypeZ.getField("TO").get(null), to); mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject); mimeMessageZ.getMethod("setText", String.class).invoke(msg, body); transportZ.getMethod("send", messageZ).invoke(null, msg); jqmlogger.trace("Mail was sent"); } catch (Exception e) { throw new MessagingException("an exception occurred during mail sending", e); } finally { Thread.currentThread().setContextClassLoader(old); } } static void sendEndMessage(JobInstance ji) { try { String message = "The Job number " + ji.getId() + " finished correctly\n\n" + "Job description:\n" + "- Job definition: " + ji.getJd().getApplicationName() + "\n" + "- Parent: " + ji.getParentId() + "\n" + "- User name: " + ji.getUserName() + "\n" + "- Session ID: " + ji.getSessionID() + "\n" + "- Queue: " + ji.getQueue().getName() + "\n" + "- Node: " + ji.getNode().getName() + "\n" + "Best regards,\n"; sendMessage(ji.getEmail(), "[JQM] Job: " + ji.getId() + " ENDED", message, "mail/default"); } catch (Exception e) { jqmlogger.warn("Could not send email. Job has nevertheless run correctly", e); } } static ClassLoader getExtClassLoader() { try { return ((JndiContext) NamingManager.getInitialContext(null)).getExtCl(); } catch (NamingException e) { // Don't do anything - this actually cannot happen. Death to checked exceptions. return null; } } static boolean testDbFailure(Exception e) { return (e instanceof LazyInitializationException) || (e instanceof JDBCConnectionException) || (e.getCause() instanceof JDBCConnectionException) || (e.getCause() != null && e.getCause().getCause() instanceof JDBCConnectionException) || (e.getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() instanceof SQLTransientException) || (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getCause() != null && e.getCause().getCause().getCause().getCause() instanceof SQLTransientException); } }
Added more envt logging to main log file.
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/Helpers.java
Added more envt logging to main log file.
Java
apache-2.0
01fb64fb589869673f7b6e21a08fe1fc32633f3b
0
alibaba/nacos,alibaba/nacos,alibaba/nacos,alibaba/nacos
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client.monitor; import io.prometheus.client.Gauge; import io.prometheus.client.Histogram; /** * Metrics Monitor. * * @author Nacos */ public class MetricsMonitor { private static final Gauge NACOS_MONITOR = Gauge.build().name("nacos_monitor").labelNames("module", "name") .help("nacos_monitor").register(); private static final Histogram NACOS_CLIENT_REQUEST_HISTOGRAM = Histogram.build() .labelNames("module", "method", "url", "code").name("nacos_client_request").help("nacos_client_request") .register(); public static Gauge.Child getServiceInfoMapSizeMonitor() { return NACOS_MONITOR.labels("naming", "serviceInfoMapSize"); } public static Gauge.Child getDom2BeatSizeMonitor() { return NACOS_MONITOR.labels("naming", "dom2BeatSize"); } public static Gauge.Child getListenConfigCountMonitor() { return NACOS_MONITOR.labels("config", "listenConfigCount"); } public static Histogram.Child getConfigRequestMonitor(String method, String url, String code) { return NACOS_CLIENT_REQUEST_HISTOGRAM.labels("config", method, url, code); } public static Histogram.Child getNamingRequestMonitor(String method, String url, String code) { return NACOS_CLIENT_REQUEST_HISTOGRAM.labels("naming", method, url, code); } }
client/src/main/java/com/alibaba/nacos/client/monitor/MetricsMonitor.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client.monitor; import io.prometheus.client.Gauge; import io.prometheus.client.Histogram; /** * Metrics Monitor. * * @author Nacos */ public class MetricsMonitor { private static final Gauge NACOS_MONITOR = Gauge.build().name("nacos_monitor").labelNames("module", "name") .help("nacos_monitor").register(); private static final Histogram NACOS_CLIENT_REQUEST_HISTOGRAM = Histogram.build() .labelNames("module", "method", "url", "code").name("nacos_client_request").help("nacos_client_request") .register(); public static Gauge.Child getServiceInfoMapSizeMonitor() { return NACOS_MONITOR.labels("naming", "serviceInfoMapSize"); } public static Gauge.Child getDom2BeatSizeMonitor() { return NACOS_MONITOR.labels("naming", "dom2BeatSize"); } public static Gauge.Child getListenConfigCountMonitor() { return NACOS_MONITOR.labels("naming", "listenConfigCount"); } public static Histogram.Child getConfigRequestMonitor(String method, String url, String code) { return NACOS_CLIENT_REQUEST_HISTOGRAM.labels("config", method, url, code); } public static Histogram.Child getNamingRequestMonitor(String method, String url, String code) { return NACOS_CLIENT_REQUEST_HISTOGRAM.labels("naming", method, url, code); } }
Fix typo (#8567)
client/src/main/java/com/alibaba/nacos/client/monitor/MetricsMonitor.java
Fix typo (#8567)
Java
apache-2.0
ac3af3c672ff1355aed0a5484d2d8bfc4e1d7dd3
0
Cognifide/knotx,Cognifide/knotx
/* * Copyright (C) 2016 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.knotx.knot.service.service; import io.knotx.dataobjects.AdapterRequest; import io.knotx.dataobjects.AdapterResponse; import io.knotx.dataobjects.KnotContext; import io.knotx.knot.service.ServiceKnotConfiguration; import io.knotx.reactivex.proxy.AdapterProxy; import io.reactivex.Single; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.reactivex.core.Vertx; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; public class ServiceEngine { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceEngine.class); private static final String RESULT_NAMESPACE_KEY = "_result"; private static final String RESPONSE_NAMESPACE_KEY = "_response"; private final ServiceKnotConfiguration configuration; private final Map<String, AdapterProxy> adapters; public ServiceEngine(Vertx vertx, ServiceKnotConfiguration serviceConfiguration) { this.configuration = serviceConfiguration; this.adapters = new HashMap<>(); this.configuration.getServices().stream().forEach( service -> adapters.put(service.getAddress(), AdapterProxy.createProxyWithOptions( vertx, service.getAddress(), configuration.getDeliveryOptions()) ) ); } public Single<JsonObject> doServiceCall(ServiceEntry serviceEntry, KnotContext knotContext) { AdapterRequest adapterRequest = new AdapterRequest() .setRequest(knotContext.getClientRequest()) .setParams(serviceEntry.getParams()); return adapters.get(serviceEntry.getAddress()).rxProcess(adapterRequest) .map(resp -> buildResultObject(adapterRequest, resp)); } public ServiceEntry mergeWithConfiguration(final ServiceEntry serviceEntry) { Optional<ServiceKnotConfiguration.ServiceMetadata> serviceMetadata = configuration.getServices() .stream() .filter(service -> serviceEntry.getName().matches(service.getName())) .findFirst(); return serviceMetadata.map( metadata -> new ServiceEntry(serviceEntry) .setAddress(metadata.getAddress()) .mergeParams(metadata.getParams()) .setCacheKey(metadata.getCacheKey())) .orElseThrow(() -> { LOGGER.error("Missing service configuration for: {}", serviceEntry.getName()); return new IllegalStateException("Missing service configuration"); }); } private JsonObject buildResultObject(AdapterRequest adapterRequest, AdapterResponse adapterResponse) { JsonObject object = new JsonObject(); String rawData = adapterResponse.getResponse().getBody().toString().trim(); if (rawData.charAt(0) == '[') { object.put(RESULT_NAMESPACE_KEY, new JsonArray(rawData)); } else if (rawData.charAt(0) == '{') { object.put(RESULT_NAMESPACE_KEY, new JsonObject(rawData)); } else { LOGGER.error("Result of [{} {}] neither Json Array nor Json Object: [{}]", adapterRequest.getRequest().getMethod(), adapterRequest.getRequest().getPath(), StringUtils.abbreviate(rawData, 15)); } object.put(RESPONSE_NAMESPACE_KEY, new JsonObject() .put("statusCode", Integer.toString(adapterResponse.getResponse().getStatusCode()))); return object; } }
knotx-knot/knotx-knot-service/src/main/java/io/knotx/knot/service/service/ServiceEngine.java
/* * Copyright (C) 2016 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.knotx.knot.service.service; import io.knotx.dataobjects.AdapterRequest; import io.knotx.dataobjects.AdapterResponse; import io.knotx.dataobjects.KnotContext; import io.knotx.knot.service.ServiceKnotConfiguration; import io.knotx.reactivex.proxy.AdapterProxy; import io.reactivex.Single; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.reactivex.core.Vertx; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; public class ServiceEngine { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceEngine.class); private static final String RESULT_NAMESPACE_KEY = "_result"; private static final String RESPONSE_NAMESPACE_KEY = "_response"; private final ServiceKnotConfiguration configuration; private final Map<String, AdapterProxy> adapters; public ServiceEngine(Vertx vertx, ServiceKnotConfiguration serviceConfiguration) { this.configuration = serviceConfiguration; this.adapters = new HashMap<>(); this.configuration.getServices().stream().forEach(service -> adapters .put(service.getAddress(), AdapterProxy.createProxyWithOptions(vertx, service.getAddress(), configuration.getDeliveryOptions()))); } public Single<JsonObject> doServiceCall(ServiceEntry serviceEntry, KnotContext knotContext) { AdapterRequest adapterRequest = new AdapterRequest() .setRequest(knotContext.getClientRequest()) .setParams(serviceEntry.getParams()); return adapters.get(serviceEntry.getAddress()).rxProcess(adapterRequest) .map(resp -> buildResultObject(adapterRequest, resp)); } public ServiceEntry mergeWithConfiguration(final ServiceEntry serviceEntry) { Optional<ServiceKnotConfiguration.ServiceMetadata> serviceMetadata = configuration.getServices() .stream() .filter(service -> serviceEntry.getName().matches(service.getName())) .findFirst(); return serviceMetadata.map( metadata -> new ServiceEntry(serviceEntry) .setAddress(metadata.getAddress()) .mergeParams(metadata.getParams()) .setCacheKey(metadata.getCacheKey())) .orElseThrow(() -> { LOGGER.error("Missing service configuration for: {}", serviceEntry.getName()); return new IllegalStateException("Missing service configuration"); }); } private JsonObject buildResultObject(AdapterRequest adapterRequest, AdapterResponse adapterResponse) { JsonObject object = new JsonObject(); String rawData = adapterResponse.getResponse().getBody().toString().trim(); if (rawData.charAt(0) == '[') { object.put(RESULT_NAMESPACE_KEY, new JsonArray(rawData)); } else if (rawData.charAt(0) == '{') { object.put(RESULT_NAMESPACE_KEY, new JsonObject(rawData)); } else { LOGGER.error("Result of [{} {}] neither Json Array nor Json Object: [{}]", adapterRequest.getRequest().getMethod(), adapterRequest.getRequest().getPath(), StringUtils.abbreviate(rawData, 15)); } object.put(RESPONSE_NAMESPACE_KEY, new JsonObject() .put("statusCode", Integer.toString(adapterResponse.getResponse().getStatusCode()))); return object; } }
Formatted oneliner
knotx-knot/knotx-knot-service/src/main/java/io/knotx/knot/service/service/ServiceEngine.java
Formatted oneliner
Java
apache-2.0
085426a9d8e4a1f94dc6c97734740544ecb69515
0
sammyyx/ACAMPController,sammyyx/ACAMPController,sammyyx/ACAMPController,sammyyx/ACAMPController,sammyyx/ACAMPController
package net.floodlightcontroller.acamp.agent; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import net.floodlightcontroller.acamp.msgele.TestMsgEle; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.packet.ACAMP; import net.floodlightcontroller.packet.ACAMPData; import net.floodlightcontroller.packet.ACAMPMsgEle; import net.floodlightcontroller.packet.Data; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.packet.UDP; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPacketOut; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.IpProtocol; import org.projectfloodlight.openflow.types.MacAddress; import org.projectfloodlight.openflow.types.OFPort; import org.projectfloodlight.openflow.types.TransportPort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ACAMPagent implements IOFMessageListener, IFloodlightModule { protected static Logger logger; protected IFloodlightProviderService floodlightProvider; private static void sendMessage(IOFSwitch sw, OFPort inPort, MacAddress srcMac, MacAddress dstMac, IPv4Address srcAddress, IPv4Address dstAddress, TransportPort srcPort, TransportPort dstPort, byte[] acamp_bytes) { Ethernet l2 = new Ethernet(); l2.setSourceMACAddress(srcMac); l2.setDestinationMACAddress(dstMac); l2.setEtherType(EthType.IPv4); IPv4 l3 = new IPv4(); l3.setDestinationAddress(dstAddress); l3.setSourceAddress(srcAddress); l3.setTtl((byte)64); l3.setProtocol(IpProtocol.UDP); UDP l4 = new UDP(); l4.setSourcePort(srcPort); l4.setDestinationPort(dstPort); Data l7 = new Data(); l7.setData(acamp_bytes); l4.setPayload(l7); l3.setPayload(l4); l2.setPayload(l3); byte[] serializeData = l2.serialize(); OFPacketOut po = sw.getOFFactory().buildPacketOut() .setData(serializeData) .setActions(Collections.singletonList((OFAction) sw.getOFFactory().actions().output(inPort, 0xffFFffFF))) .setInPort(OFPort.CONTROLLER) .build(); sw.write(po); } @Override public String getName() { return ACAMPagent.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { // TODO Auto-generated method stub return null; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { // TODO Auto-generated method stub return null; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> depList = new ArrayList<Class<? extends IFloodlightService>>(); depList.add(IFloodlightProviderService.class); return depList; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); logger = LoggerFactory.getLogger(ACAMPagent.class); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); } @Override public net.floodlightcontroller.core.IListener.Command receive( IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { switch(msg.getType()) { case PACKET_IN: { OFPacketIn myPacketIn = (OFPacketIn) msg; OFPort inPort = (myPacketIn.getVersion().compareTo(OFVersion.OF_12) < 0) ? myPacketIn.getInPort() : myPacketIn.getMatch().get(MatchField.IN_PORT); logger.info("A Packet-In Message has arrive Controller which comes from:" + "{}"+ " Port:{}", sw.getId().toString(), inPort.toString()); Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); MacAddress srcMacAddress = eth.getSourceMACAddress(); MacAddress dstMacAddress = eth.getDestinationMACAddress(); IPv4 ipv4 = (IPv4)eth.getPayload(); IPv4Address srcIpAddr = ipv4.getSourceAddress(); IPv4Address dstIpAddr = ipv4.getDestinationAddress(); if(ipv4.getProtocol().equals(IpProtocol.UDP)) { UDP udp = (UDP) ipv4.getPayload(); TransportPort srcPort = udp.getSourcePort(); TransportPort dstPort = udp.getDestinationPort(); ACAMP acmap = new ACAMP(); ACAMPMsgEle msgEle = new ACAMPMsgEle(); TestMsgEle testMsgEle = new TestMsgEle(); testMsgEle.setTypeValue(5656); msgEle.setMessageElementType((short)ACAMPMsgEle.RESULT_CODE) .setPayload(testMsgEle); ACAMPMsgEle msgEle2 = new ACAMPMsgEle(); TestMsgEle testMsgEle2 = new TestMsgEle(); testMsgEle2.setTypeValue(5656); msgEle2.setMessageElementType((short)ACAMPMsgEle.RESULT_CODE) .setPayload(testMsgEle2); ACAMPData acampData = new ACAMPData(); acampData.addMessageElement(msgEle); acampData.addMessageElement(msgEle2); acmap.setVersion((byte)10) .setType((byte)11) .setAPID((short)12) .setSequenceNumber((int)88888888) .setMessageType((short)13) .setPayload(acampData); byte[] data = acmap.serialize(); ACAMPagent.sendMessage(sw, inPort, dstMacAddress, srcMacAddress, dstIpAddr, srcIpAddr, dstPort, srcPort, data); } break; } default: break; } return Command.STOP; } }
src/main/java/net/floodlightcontroller/acamp/agent/ACAMPagent.java
package net.floodlightcontroller.acamp.agent; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import net.floodlightcontroller.acamp.msgele.TestMsgEle; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.packet.ACAMP; import net.floodlightcontroller.packet.ACAMPData; import net.floodlightcontroller.packet.ACAMPMsgEle; import net.floodlightcontroller.packet.Data; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.packet.UDP; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPacketOut; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.IpProtocol; import org.projectfloodlight.openflow.types.MacAddress; import org.projectfloodlight.openflow.types.OFPort; import org.projectfloodlight.openflow.types.TransportPort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ACAMPagent implements IOFMessageListener, IFloodlightModule { protected static Logger logger; protected IFloodlightProviderService floodlightProvider; private static void sendMessage(IOFSwitch sw, OFPort inPort, MacAddress srcMac, MacAddress dstMac, IPv4Address srcAddress, IPv4Address dstAddress, TransportPort srcPort, TransportPort dstPort, byte[] acamp_bytes) { Ethernet l2 = new Ethernet(); l2.setSourceMACAddress(srcMac); l2.setDestinationMACAddress(dstMac); l2.setEtherType(EthType.IPv4); IPv4 l3 = new IPv4(); l3.setDestinationAddress(dstAddress); l3.setSourceAddress(srcAddress); l3.setTtl((byte)64); l3.setProtocol(IpProtocol.UDP); UDP l4 = new UDP(); l4.setSourcePort(srcPort); l4.setDestinationPort(dstPort); Data l7 = new Data(); l7.setData(acamp_bytes); l4.setPayload(l7); l3.setPayload(l4); l2.setPayload(l3); byte[] serializeData = l2.serialize(); OFPacketOut po = sw.getOFFactory().buildPacketOut() .setData(serializeData) .setActions(Collections.singletonList((OFAction) sw.getOFFactory().actions().output(inPort, 0xffFFffFF))) .setInPort(OFPort.CONTROLLER) .build(); sw.write(po); } @Override public String getName() { return ACAMPagent.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { // TODO Auto-generated method stub return false; } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { // TODO Auto-generated method stub return null; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { // TODO Auto-generated method stub return null; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> depList = new ArrayList<Class<? extends IFloodlightService>>(); depList.add(IFloodlightProviderService.class); return depList; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); logger = LoggerFactory.getLogger(ACAMPagent.class); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); } @Override public net.floodlightcontroller.core.IListener.Command receive( IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { switch(msg.getType()) { case PACKET_IN: { OFPacketIn myPacketIn = (OFPacketIn) msg; OFPort inPort = (myPacketIn.getVersion().compareTo(OFVersion.OF_12) < 0) ? myPacketIn.getInPort() : myPacketIn.getMatch().get(MatchField.IN_PORT); logger.info("A Packet-In Message has arrive Controller which comes from:" + "{}"+ " Port:{}", sw.getId().toString(), inPort.toString()); Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); MacAddress srcMacAddress = eth.getSourceMACAddress(); MacAddress dstMacAddress = eth.getDestinationMACAddress(); IPv4 ipv4 = (IPv4)eth.getPayload(); IPv4Address srcIpAddr = ipv4.getSourceAddress(); IPv4Address dstIpAddr = ipv4.getDestinationAddress(); if(ipv4.getProtocol().equals(IpProtocol.UDP)) { UDP udp = (UDP) ipv4.getPayload(); TransportPort srcPort = udp.getSourcePort(); TransportPort dstPort = udp.getDestinationPort(); ACAMP acmap = new ACAMP(); ACAMPMsgEle msgEle = new ACAMPMsgEle(); TestMsgEle testMsgEle = new TestMsgEle(); testMsgEle.setTypeValue(5656); msgEle.setMessageElementType((short)ACAMPMsgEle.RESULT_CODE) .setPayload(testMsgEle); ACAMPData acampData = new ACAMPData(); acampData.addMessageElement(msgEle); acmap.setVersion((byte)10) .setType((byte)11) .setAPID((short)12) .setSequenceNumber((int)88888888) .setMessageType((short)13) .setPayload(acampData); byte[] data = acmap.serialize(); ACAMPagent.sendMessage(sw, inPort, dstMacAddress, srcMacAddress, dstIpAddr, srcIpAddr, dstPort, srcPort, data); } break; } default: break; } return Command.STOP; } }
Add two message element for test
src/main/java/net/floodlightcontroller/acamp/agent/ACAMPagent.java
Add two message element for test
Java
apache-2.0
96674d59ab93ebc85b4436c25cb81bac2c4c919a
0
material-components/material-components-android
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.material.bottomsheet; import com.google.android.material.R; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.os.Build; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Parcel; import android.os.Parcelable; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat; import androidx.core.view.accessibility.AccessibilityViewCommand; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import androidx.annotation.FloatRange; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams; import androidx.core.math.MathUtils; import androidx.customview.view.AbsSavedState; import androidx.customview.widget.ViewDragHelper; import com.google.android.material.internal.ViewUtils; import com.google.android.material.internal.ViewUtils.RelativePadding; import com.google.android.material.resources.MaterialResources; import com.google.android.material.shape.MaterialShapeDrawable; import com.google.android.material.shape.ShapeAppearanceModel; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * An interaction behavior plugin for a child view of {@link CoordinatorLayout} to make it work as a * bottom sheet. * * <p>To send useful accessibility events, set a title on bottom sheets that are windows or are * window-like. For BottomSheetDialog use {@link BottomSheetDialog#setTitle(int)}, and for * BottomSheetDialogFragment use {@link ViewCompat#setAccessibilityPaneTitle(View, CharSequence)}. */ public class BottomSheetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { /** Callback for monitoring events about bottom sheets. */ public abstract static class BottomSheetCallback { /** * Called when the bottom sheet changes its state. * * @param bottomSheet The bottom sheet view. * @param newState The new state. This will be one of {@link #STATE_DRAGGING}, {@link * #STATE_SETTLING}, {@link #STATE_EXPANDED}, {@link #STATE_COLLAPSED}, {@link * #STATE_HIDDEN}, or {@link #STATE_HALF_EXPANDED}. */ public abstract void onStateChanged(@NonNull View bottomSheet, @State int newState); /** * Called when the bottom sheet is being dragged. * * @param bottomSheet The bottom sheet view. * @param slideOffset The new offset of this bottom sheet within [-1,1] range. Offset increases * as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and * expanded states and from -1 to 0 it is between hidden and collapsed states. */ public abstract void onSlide(@NonNull View bottomSheet, float slideOffset); } /** The bottom sheet is dragging. */ public static final int STATE_DRAGGING = 1; /** The bottom sheet is settling. */ public static final int STATE_SETTLING = 2; /** The bottom sheet is expanded. */ public static final int STATE_EXPANDED = 3; /** The bottom sheet is collapsed. */ public static final int STATE_COLLAPSED = 4; /** The bottom sheet is hidden. */ public static final int STATE_HIDDEN = 5; /** The bottom sheet is half-expanded (used when mFitToContents is false). */ public static final int STATE_HALF_EXPANDED = 6; /** @hide */ @RestrictTo(LIBRARY_GROUP) @IntDef({ STATE_EXPANDED, STATE_COLLAPSED, STATE_DRAGGING, STATE_SETTLING, STATE_HIDDEN, STATE_HALF_EXPANDED }) @Retention(RetentionPolicy.SOURCE) public @interface State {} /** * Peek at the 16:9 ratio keyline of its parent. * * <p>This can be used as a parameter for {@link #setPeekHeight(int)}. {@link #getPeekHeight()} * will return this when the value is set. */ public static final int PEEK_HEIGHT_AUTO = -1; /** This flag will preserve the peekHeight int value on configuration change. */ public static final int SAVE_PEEK_HEIGHT = 0x1; /** This flag will preserve the fitToContents boolean value on configuration change. */ public static final int SAVE_FIT_TO_CONTENTS = 1 << 1; /** This flag will preserve the hideable boolean value on configuration change. */ public static final int SAVE_HIDEABLE = 1 << 2; /** This flag will preserve the skipCollapsed boolean value on configuration change. */ public static final int SAVE_SKIP_COLLAPSED = 1 << 3; /** This flag will preserve all aforementioned values on configuration change. */ public static final int SAVE_ALL = -1; /** * This flag will not preserve the aforementioned values set at runtime if the view is destroyed * and recreated. The only value preserved will be the positional state, e.g. collapsed, hidden, * expanded, etc. This is the default behavior. */ public static final int SAVE_NONE = 0; /** @hide */ @RestrictTo(LIBRARY_GROUP) @IntDef( flag = true, value = { SAVE_PEEK_HEIGHT, SAVE_FIT_TO_CONTENTS, SAVE_HIDEABLE, SAVE_SKIP_COLLAPSED, SAVE_ALL, SAVE_NONE, }) @Retention(RetentionPolicy.SOURCE) public @interface SaveFlags {} private static final String TAG = "BottomSheetBehavior"; @SaveFlags private int saveFlags = SAVE_NONE; private static final int SIGNIFICANT_VEL_THRESHOLD = 500; private static final float HIDE_THRESHOLD = 0.5f; private static final float HIDE_FRICTION = 0.1f; private static final int CORNER_ANIMATION_DURATION = 500; private boolean fitToContents = true; private boolean updateImportantForAccessibilityOnSiblings = false; private float maximumVelocity; /** Peek height set by the user. */ private int peekHeight; /** Whether or not to use automatic peek height. */ private boolean peekHeightAuto; /** Minimum peek height permitted. */ private int peekHeightMin; /** True if Behavior has a non-null value for the @shapeAppearance attribute */ private boolean shapeThemingEnabled; private MaterialShapeDrawable materialShapeDrawable; private int gestureInsetBottom; private boolean gestureInsetBottomIgnored; /** Default Shape Appearance to be used in bottomsheet */ private ShapeAppearanceModel shapeAppearanceModelDefault; private boolean isShapeExpanded; private SettleRunnable settleRunnable = null; @Nullable private ValueAnimator interpolatorAnimator; private static final int DEF_STYLE_RES = R.style.Widget_Design_BottomSheet_Modal; int expandedOffset; int fitToContentsOffset; int halfExpandedOffset; float halfExpandedRatio = 0.5f; int collapsedOffset; float elevation = -1; boolean hideable; private boolean skipCollapsed; private boolean draggable = true; @State int state = STATE_COLLAPSED; @Nullable ViewDragHelper viewDragHelper; private boolean ignoreEvents; private int lastNestedScrollDy; private boolean nestedScrolled; int parentWidth; int parentHeight; @Nullable WeakReference<V> viewRef; @Nullable WeakReference<View> nestedScrollingChildRef; @NonNull private final ArrayList<BottomSheetCallback> callbacks = new ArrayList<>(); @Nullable private VelocityTracker velocityTracker; int activePointerId; private int initialY; boolean touchingScrollingChild; @Nullable private Map<View, Integer> importantForAccessibilityMap; public BottomSheetBehavior() {} public BottomSheetBehavior(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout); this.shapeThemingEnabled = a.hasValue(R.styleable.BottomSheetBehavior_Layout_shapeAppearance); boolean hasBackgroundTint = a.hasValue(R.styleable.BottomSheetBehavior_Layout_backgroundTint); if (hasBackgroundTint) { ColorStateList bottomSheetColor = MaterialResources.getColorStateList( context, a, R.styleable.BottomSheetBehavior_Layout_backgroundTint); createMaterialShapeDrawable(context, attrs, hasBackgroundTint, bottomSheetColor); } else { createMaterialShapeDrawable(context, attrs, hasBackgroundTint); } createShapeValueAnimator(); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { this.elevation = a.getDimension(R.styleable.BottomSheetBehavior_Layout_android_elevation, -1); } TypedValue value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight); if (value != null && value.data == PEEK_HEIGHT_AUTO) { setPeekHeight(value.data); } else { setPeekHeight( a.getDimensionPixelSize( R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO)); } setHideable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false)); setGestureInsetBottomIgnored( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_gestureInsetBottomIgnored, false)); setFitToContents( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true)); setSkipCollapsed( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false)); setDraggable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_draggable, true)); setSaveFlags(a.getInt(R.styleable.BottomSheetBehavior_Layout_behavior_saveFlags, SAVE_NONE)); setHalfExpandedRatio( a.getFloat(R.styleable.BottomSheetBehavior_Layout_behavior_halfExpandedRatio, 0.5f)); value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset); if (value != null && value.type == TypedValue.TYPE_FIRST_INT) { setExpandedOffset(value.data); } else { setExpandedOffset( a.getDimensionPixelOffset( R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset, 0)); } a.recycle(); ViewConfiguration configuration = ViewConfiguration.get(context); maximumVelocity = configuration.getScaledMaximumFlingVelocity(); } @NonNull @Override public Parcelable onSaveInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child) { return new SavedState(super.onSaveInstanceState(parent, child), this); } @Override public void onRestoreInstanceState( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(parent, child, ss.getSuperState()); // Restore Optional State values designated by saveFlags restoreOptionalState(ss); // Intermediate states are restored as collapsed state if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) { this.state = STATE_COLLAPSED; } else { this.state = ss.state; } } @Override public void onAttachedToLayoutParams(@NonNull LayoutParams layoutParams) { super.onAttachedToLayoutParams(layoutParams); // These may already be null, but just be safe, explicitly assign them. This lets us know the // first time we layout with this behavior by checking (viewRef == null). viewRef = null; viewDragHelper = null; } @Override public void onDetachedFromLayoutParams() { super.onDetachedFromLayoutParams(); // Release references so we don't run unnecessary codepaths while not attached to a view. viewRef = null; viewDragHelper = null; } @Override public boolean onLayoutChild( @NonNull CoordinatorLayout parent, @NonNull V child, int layoutDirection) { if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) { child.setFitsSystemWindows(true); } if (viewRef == null) { // First layout with this behavior. peekHeightMin = parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min); setSystemGestureInsets(child); viewRef = new WeakReference<>(child); // Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will // default to android:background declared in styles or layout. if (shapeThemingEnabled && materialShapeDrawable != null) { ViewCompat.setBackground(child, materialShapeDrawable); } // Set elevation on MaterialShapeDrawable if (materialShapeDrawable != null) { // Use elevation attr if set on bottomsheet; otherwise, use elevation of child view. materialShapeDrawable.setElevation( elevation == -1 ? ViewCompat.getElevation(child) : elevation); // Update the material shape based on initial state. isShapeExpanded = state == STATE_EXPANDED; materialShapeDrawable.setInterpolation(isShapeExpanded ? 0f : 1f); } updateAccessibilityActions(); if (ViewCompat.getImportantForAccessibility(child) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } } if (viewDragHelper == null) { viewDragHelper = ViewDragHelper.create(parent, dragCallback); } int savedTop = child.getTop(); // First let the parent lay it out parent.onLayoutChild(child, layoutDirection); // Offset the bottom sheet parentWidth = parent.getWidth(); parentHeight = parent.getHeight(); fitToContentsOffset = Math.max(0, parentHeight - child.getHeight()); calculateHalfExpandedOffset(); calculateCollapsedOffset(); if (state == STATE_EXPANDED) { ViewCompat.offsetTopAndBottom(child, getExpandedOffset()); } else if (state == STATE_HALF_EXPANDED) { ViewCompat.offsetTopAndBottom(child, halfExpandedOffset); } else if (hideable && state == STATE_HIDDEN) { ViewCompat.offsetTopAndBottom(child, parentHeight); } else if (state == STATE_COLLAPSED) { ViewCompat.offsetTopAndBottom(child, collapsedOffset); } else if (state == STATE_DRAGGING || state == STATE_SETTLING) { ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop()); } nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child)); return true; } @Override public boolean onInterceptTouchEvent( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) { if (!child.isShown() || !draggable) { ignoreEvents = true; return false; } int action = event.getActionMasked(); // Record the velocity if (action == MotionEvent.ACTION_DOWN) { reset(); } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: touchingScrollingChild = false; activePointerId = MotionEvent.INVALID_POINTER_ID; // Reset the ignore flag if (ignoreEvents) { ignoreEvents = false; return false; } break; case MotionEvent.ACTION_DOWN: int initialX = (int) event.getX(); initialY = (int) event.getY(); // Only intercept nested scrolling events here if the view not being moved by the // ViewDragHelper. if (state != STATE_SETTLING) { View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (scroll != null && parent.isPointInChildBounds(scroll, initialX, initialY)) { activePointerId = event.getPointerId(event.getActionIndex()); touchingScrollingChild = true; } } ignoreEvents = activePointerId == MotionEvent.INVALID_POINTER_ID && !parent.isPointInChildBounds(child, initialX, initialY); break; default: // fall out } if (!ignoreEvents && viewDragHelper != null && viewDragHelper.shouldInterceptTouchEvent(event)) { return true; } // We have to handle cases that the ViewDragHelper does not capture the bottom sheet because // it is not the top most view of its parent. This is not necessary when the touch event is // happening over the scrolling content as nested scrolling logic handles that case. View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; return action == MotionEvent.ACTION_MOVE && scroll != null && !ignoreEvents && state != STATE_DRAGGING && !parent.isPointInChildBounds(scroll, (int) event.getX(), (int) event.getY()) && viewDragHelper != null && Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop(); } @Override public boolean onTouchEvent( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) { if (!child.isShown()) { return false; } int action = event.getActionMasked(); if (state == STATE_DRAGGING && action == MotionEvent.ACTION_DOWN) { return true; } if (viewDragHelper != null) { viewDragHelper.processTouchEvent(event); } // Record the velocity if (action == MotionEvent.ACTION_DOWN) { reset(); } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); // The ViewDragHelper tries to capture only the top-most View. We have to explicitly tell it // to capture the bottom sheet in case it is not captured and the touch slop is passed. if (action == MotionEvent.ACTION_MOVE && !ignoreEvents) { if (Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop()) { viewDragHelper.captureChildView(child, event.getPointerId(event.getActionIndex())); } } return !ignoreEvents; } @Override public boolean onStartNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { lastNestedScrollDy = 0; nestedScrolled = false; return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } @Override public void onNestedPreScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { if (type == ViewCompat.TYPE_NON_TOUCH) { // Ignore fling here. The ViewDragHelper handles it. return; } View scrollingChild = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (target != scrollingChild) { return; } int currentTop = child.getTop(); int newTop = currentTop - dy; if (dy > 0) { // Upward if (newTop < getExpandedOffset()) { consumed[1] = currentTop - getExpandedOffset(); ViewCompat.offsetTopAndBottom(child, -consumed[1]); setStateInternal(STATE_EXPANDED); } else { if (!draggable) { // Prevent dragging return; } consumed[1] = dy; ViewCompat.offsetTopAndBottom(child, -dy); setStateInternal(STATE_DRAGGING); } } else if (dy < 0) { // Downward if (!target.canScrollVertically(-1)) { if (newTop <= collapsedOffset || hideable) { if (!draggable) { // Prevent dragging return; } consumed[1] = dy; ViewCompat.offsetTopAndBottom(child, -dy); setStateInternal(STATE_DRAGGING); } else { consumed[1] = currentTop - collapsedOffset; ViewCompat.offsetTopAndBottom(child, -consumed[1]); setStateInternal(STATE_COLLAPSED); } } } dispatchOnSlide(child.getTop()); lastNestedScrollDy = dy; nestedScrolled = true; } @Override public void onStopNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int type) { if (child.getTop() == getExpandedOffset()) { setStateInternal(STATE_EXPANDED); return; } if (nestedScrollingChildRef == null || target != nestedScrollingChildRef.get() || !nestedScrolled) { return; } int top; int targetState; if (lastNestedScrollDy > 0) { if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { int currentTop = child.getTop(); if (currentTop > halfExpandedOffset) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = expandedOffset; targetState = STATE_EXPANDED; } } } else if (hideable && shouldHide(child, getYVelocity())) { top = parentHeight; targetState = STATE_HIDDEN; } else if (lastNestedScrollDy == 0) { int currentTop = child.getTop(); if (fitToContents) { if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } else { if (currentTop < halfExpandedOffset) { if (currentTop < Math.abs(currentTop - collapsedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else { if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } } else { if (fitToContents) { top = collapsedOffset; targetState = STATE_COLLAPSED; } else { // Settle to nearest height. int currentTop = child.getTop(); if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } startSettlingAnimation(child, targetState, top, false); nestedScrolled = false; } @Override public void onNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) { // Overridden to prevent the default consumption of the entire scroll distance. } @Override public boolean onNestedPreFling( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, float velocityX, float velocityY) { if (nestedScrollingChildRef != null) { return target == nestedScrollingChildRef.get() && (state != STATE_EXPANDED || super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY)); } else { return false; } } /** * @return whether the height of the expanded sheet is determined by the height of its contents, * or if it is expanded in two stages (half the height of the parent container, full height of * parent container). */ public boolean isFitToContents() { return fitToContents; } /** * Sets whether the height of the expanded sheet is determined by the height of its contents, or * if it is expanded in two stages (half the height of the parent container, full height of parent * container). Default value is true. * * @param fitToContents whether or not to fit the expanded sheet to its contents. */ public void setFitToContents(boolean fitToContents) { if (this.fitToContents == fitToContents) { return; } this.fitToContents = fitToContents; // If sheet is already laid out, recalculate the collapsed offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (viewRef != null) { calculateCollapsedOffset(); } // Fix incorrect expanded settings depending on whether or not we are fitting sheet to contents. setStateInternal((this.fitToContents && state == STATE_HALF_EXPANDED) ? STATE_EXPANDED : state); updateAccessibilityActions(); } /** * Sets the height of the bottom sheet when it is collapsed. * * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public void setPeekHeight(int peekHeight) { setPeekHeight(peekHeight, false); } /** * Sets the height of the bottom sheet when it is collapsed while optionally animating between the * old height and the new height. * * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline. * @param animate Whether to animate between the old height and the new height. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public final void setPeekHeight(int peekHeight, boolean animate) { boolean layout = false; if (peekHeight == PEEK_HEIGHT_AUTO) { if (!peekHeightAuto) { peekHeightAuto = true; layout = true; } } else if (peekHeightAuto || this.peekHeight != peekHeight) { peekHeightAuto = false; this.peekHeight = Math.max(0, peekHeight); layout = true; } // If sheet is already laid out, recalculate the collapsed offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (layout) { updatePeekHeight(animate); } } private void updatePeekHeight(boolean animate) { if (viewRef != null) { calculateCollapsedOffset(); if (state == STATE_COLLAPSED) { V view = viewRef.get(); if (view != null) { if (animate) { settleToStatePendingLayout(state); } else { view.requestLayout(); } } } } } /** * Gets the height of the bottom sheet when it is collapsed. * * @return The height of the collapsed bottom sheet in pixels, or {@link #PEEK_HEIGHT_AUTO} if the * sheet is configured to peek automatically at 16:9 ratio keyline * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public int getPeekHeight() { return peekHeightAuto ? PEEK_HEIGHT_AUTO : peekHeight; } /** * Determines the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. The * material guidelines recommended a value of 0.5, which results in the sheet filling half of the * parent. The height of the BottomSheet will be smaller as this ratio is decreased and taller as * it is increased. The default value is 0.5. * * @param ratio a float between 0 and 1, representing the {@link #STATE_HALF_EXPANDED} ratio. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio */ public void setHalfExpandedRatio(@FloatRange(from = 0.0f, to = 1.0f) float ratio) { if ((ratio <= 0) || (ratio >= 1)) { throw new IllegalArgumentException("ratio must be a float value between 0 and 1"); } this.halfExpandedRatio = ratio; // If sheet is already laid out, recalculate the half expanded offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (viewRef != null) { calculateHalfExpandedOffset(); } } /** * Gets the ratio for the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. * * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio */ @FloatRange(from = 0.0f, to = 1.0f) public float getHalfExpandedRatio() { return halfExpandedRatio; } /** * Determines the top offset of the BottomSheet in the {@link #STATE_EXPANDED} state when * fitsToContent is false. The default value is 0, which results in the sheet matching the * parent's top. * * @param offset an integer value greater than equal to 0, representing the {@link * #STATE_EXPANDED} offset. Value must not exceed the offset in the half expanded state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset */ public void setExpandedOffset(int offset) { if (offset < 0) { throw new IllegalArgumentException("offset must be greater than or equal to 0"); } this.expandedOffset = offset; } /** * Returns the current expanded offset. If {@code fitToContents} is true, it will automatically * pick the offset depending on the height of the content. * * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset */ public int getExpandedOffset() { return fitToContents ? fitToContentsOffset : expandedOffset; } /** * Sets whether this bottom sheet can hide when it is swiped down. * * @param hideable {@code true} to make this bottom sheet hideable. * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable */ public void setHideable(boolean hideable) { if (this.hideable != hideable) { this.hideable = hideable; if (!hideable && state == STATE_HIDDEN) { // Lift up to collapsed state setState(STATE_COLLAPSED); } updateAccessibilityActions(); } } /** * Gets whether this bottom sheet can hide when it is swiped down. * * @return {@code true} if this bottom sheet can hide. * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable */ public boolean isHideable() { return hideable; } /** * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it * is expanded once. Setting this to true has no effect unless the sheet is hideable. * * @param skipCollapsed True if the bottom sheet should skip the collapsed state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed */ public void setSkipCollapsed(boolean skipCollapsed) { this.skipCollapsed = skipCollapsed; } /** * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it * is expanded once. * * @return Whether the bottom sheet should skip the collapsed state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed */ public boolean getSkipCollapsed() { return skipCollapsed; } /** * Sets whether this bottom sheet is can be collapsed/expanded by dragging. Note: When disabling * dragging, an app will require to implement a custom way to expand/collapse the bottom sheet * * @param draggable {@code false} to prevent dragging the sheet to collapse and expand * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_draggable */ public void setDraggable(boolean draggable) { this.draggable = draggable; } public boolean isDraggable() { return draggable; } /** * Sets save flags to be preserved in bottomsheet on configuration change. * * @param flags bitwise int of {@link #SAVE_PEEK_HEIGHT}, {@link #SAVE_FIT_TO_CONTENTS}, {@link * #SAVE_HIDEABLE}, {@link #SAVE_SKIP_COLLAPSED}, {@link #SAVE_ALL} and {@link #SAVE_NONE}. * @see #getSaveFlags() * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags */ public void setSaveFlags(@SaveFlags int flags) { this.saveFlags = flags; } /** * Returns the save flags. * * @see #setSaveFlags(int) * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags */ @SaveFlags public int getSaveFlags() { return this.saveFlags; } /** * Sets a callback to be notified of bottom sheet events. * * @param callback The callback to notify when bottom sheet events occur. * @deprecated use {@link #addBottomSheetCallback(BottomSheetCallback)} and {@link * #removeBottomSheetCallback(BottomSheetCallback)} instead */ @Deprecated public void setBottomSheetCallback(BottomSheetCallback callback) { Log.w( TAG, "BottomSheetBehavior now supports multiple callbacks. `setBottomSheetCallback()` removes" + " all existing callbacks, including ones set internally by library authors, which" + " may result in unintended behavior. This may change in the future. Please use" + " `addBottomSheetCallback()` and `removeBottomSheetCallback()` instead to set your" + " own callbacks."); callbacks.clear(); if (callback != null) { callbacks.add(callback); } } /** * Adds a callback to be notified of bottom sheet events. * * @param callback The callback to notify when bottom sheet events occur. */ public void addBottomSheetCallback(@NonNull BottomSheetCallback callback) { if (!callbacks.contains(callback)) { callbacks.add(callback); } } /** * Removes a previously added callback. * * @param callback The callback to remove. */ public void removeBottomSheetCallback(@NonNull BottomSheetCallback callback) { callbacks.remove(callback); } /** * Sets the state of the bottom sheet. The bottom sheet will transition to that state with * animation. * * @param state One of {@link #STATE_COLLAPSED}, {@link #STATE_EXPANDED}, {@link #STATE_HIDDEN}, * or {@link #STATE_HALF_EXPANDED}. */ public void setState(@State int state) { if (state == this.state) { return; } if (viewRef == null) { // The view is not laid out yet; modify mState and let onLayoutChild handle it later if (state == STATE_COLLAPSED || state == STATE_EXPANDED || state == STATE_HALF_EXPANDED || (hideable && state == STATE_HIDDEN)) { this.state = state; } return; } settleToStatePendingLayout(state); } /** * Sets whether this bottom sheet should adjust it's position based on the system gesture area on * Android Q and above. * * <p>Note: the bottom sheet will only adjust it's position if it would be unable to be scrolled * upwards because the peekHeight is less than the gesture inset margins,(because that would cause * a gesture conflict), gesture navigation is enabled, and this {@code ignoreGestureInsetBottom} * flag is false. */ public void setGestureInsetBottomIgnored(boolean gestureInsetBottomIgnored) { this.gestureInsetBottomIgnored = gestureInsetBottomIgnored; } /** * Returns whether this bottom sheet should adjust it's position based on the system gesture area. */ public boolean isGestureInsetBottomIgnored() { return gestureInsetBottomIgnored; } private void settleToStatePendingLayout(@State int state) { final V child = viewRef.get(); if (child == null) { return; } // Start the animation; wait until a pending layout if there is one. ViewParent parent = child.getParent(); if (parent != null && parent.isLayoutRequested() && ViewCompat.isAttachedToWindow(child)) { final int finalState = state; child.post( new Runnable() { @Override public void run() { settleToState(child, finalState); } }); } else { settleToState(child, state); } } /** * Gets the current state of the bottom sheet. * * @return One of {@link #STATE_EXPANDED}, {@link #STATE_HALF_EXPANDED}, {@link #STATE_COLLAPSED}, * {@link #STATE_DRAGGING}, {@link #STATE_SETTLING}, or {@link #STATE_HALF_EXPANDED}. */ @State public int getState() { return state; } void setStateInternal(@State int state) { if (this.state == state) { return; } this.state = state; if (viewRef == null) { return; } View bottomSheet = viewRef.get(); if (bottomSheet == null) { return; } if (state == STATE_EXPANDED) { updateImportantForAccessibility(true); } else if (state == STATE_HALF_EXPANDED || state == STATE_HIDDEN || state == STATE_COLLAPSED) { updateImportantForAccessibility(false); } updateDrawableForTargetState(state); for (int i = 0; i < callbacks.size(); i++) { callbacks.get(i).onStateChanged(bottomSheet, state); } updateAccessibilityActions(); } private void updateDrawableForTargetState(@State int state) { if (state == STATE_SETTLING) { // Special case: we want to know which state we're settling to, so wait for another call. return; } boolean expand = state == STATE_EXPANDED; if (isShapeExpanded != expand) { isShapeExpanded = expand; if (materialShapeDrawable != null && interpolatorAnimator != null) { if (interpolatorAnimator.isRunning()) { interpolatorAnimator.reverse(); } else { float to = expand ? 0f : 1f; float from = 1f - to; interpolatorAnimator.setFloatValues(from, to); interpolatorAnimator.start(); } } } } private int calculatePeekHeight() { if (peekHeightAuto) { return Math.max(peekHeightMin, parentHeight - parentWidth * 9 / 16); } return peekHeight + (gestureInsetBottomIgnored ? 0 : gestureInsetBottom); } private void calculateCollapsedOffset() { int peek = calculatePeekHeight(); if (fitToContents) { collapsedOffset = Math.max(parentHeight - peek, fitToContentsOffset); } else { collapsedOffset = parentHeight - peek; } } private void calculateHalfExpandedOffset() { this.halfExpandedOffset = (int) (parentHeight * (1 - halfExpandedRatio)); } private void reset() { activePointerId = ViewDragHelper.INVALID_POINTER; if (velocityTracker != null) { velocityTracker.recycle(); velocityTracker = null; } } private void restoreOptionalState(@NonNull SavedState ss) { if (this.saveFlags == SAVE_NONE) { return; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_PEEK_HEIGHT) == SAVE_PEEK_HEIGHT) { this.peekHeight = ss.peekHeight; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_FIT_TO_CONTENTS) == SAVE_FIT_TO_CONTENTS) { this.fitToContents = ss.fitToContents; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_HIDEABLE) == SAVE_HIDEABLE) { this.hideable = ss.hideable; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_SKIP_COLLAPSED) == SAVE_SKIP_COLLAPSED) { this.skipCollapsed = ss.skipCollapsed; } } boolean shouldHide(@NonNull View child, float yvel) { if (skipCollapsed) { return true; } if (child.getTop() < collapsedOffset) { // It should not hide, but collapse. return false; } int peek = calculatePeekHeight(); final float newTop = child.getTop() + yvel * HIDE_FRICTION; return Math.abs(newTop - collapsedOffset) / (float) peek > HIDE_THRESHOLD; } @Nullable @VisibleForTesting View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; } private void createMaterialShapeDrawable( @NonNull Context context, AttributeSet attrs, boolean hasBackgroundTint) { this.createMaterialShapeDrawable(context, attrs, hasBackgroundTint, null); } private void createMaterialShapeDrawable( @NonNull Context context, AttributeSet attrs, boolean hasBackgroundTint, @Nullable ColorStateList bottomSheetColor) { if (this.shapeThemingEnabled) { this.shapeAppearanceModelDefault = ShapeAppearanceModel.builder(context, attrs, R.attr.bottomSheetStyle, DEF_STYLE_RES) .build(); this.materialShapeDrawable = new MaterialShapeDrawable(shapeAppearanceModelDefault); this.materialShapeDrawable.initializeElevationOverlay(context); if (hasBackgroundTint && bottomSheetColor != null) { materialShapeDrawable.setFillColor(bottomSheetColor); } else { // If the tint isn't set, use the theme default background color. TypedValue defaultColor = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.colorBackground, defaultColor, true); materialShapeDrawable.setTint(defaultColor.data); } } } private void createShapeValueAnimator() { interpolatorAnimator = ValueAnimator.ofFloat(0f, 1f); interpolatorAnimator.setDuration(CORNER_ANIMATION_DURATION); interpolatorAnimator.addUpdateListener( new AnimatorUpdateListener() { @Override public void onAnimationUpdate(@NonNull ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); if (materialShapeDrawable != null) { materialShapeDrawable.setInterpolation(value); } } }); } /** * Ensure the peek height is at least as large as the bottom gesture inset size so that the sheet * can always be dragged, but only when the inset is required by the system. */ private void setSystemGestureInsets(@NonNull View child) { if (VERSION.SDK_INT >= VERSION_CODES.Q && !isGestureInsetBottomIgnored() && !peekHeightAuto) { ViewUtils.doOnApplyWindowInsets( child, new ViewUtils.OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets( View view, WindowInsetsCompat insets, RelativePadding initialPadding) { gestureInsetBottom = insets.getMandatorySystemGestureInsets().bottom; updatePeekHeight(/* animate= */ false); return insets; } }); } } private float getYVelocity() { if (velocityTracker == null) { return 0; } velocityTracker.computeCurrentVelocity(1000, maximumVelocity); return velocityTracker.getYVelocity(activePointerId); } void settleToState(@NonNull View child, int state) { int top; if (state == STATE_COLLAPSED) { top = collapsedOffset; } else if (state == STATE_HALF_EXPANDED) { top = halfExpandedOffset; if (fitToContents && top <= fitToContentsOffset) { // Skip to the expanded state if we would scroll past the height of the contents. state = STATE_EXPANDED; top = fitToContentsOffset; } } else if (state == STATE_EXPANDED) { top = getExpandedOffset(); } else if (hideable && state == STATE_HIDDEN) { top = parentHeight; } else { throw new IllegalArgumentException("Illegal state argument: " + state); } startSettlingAnimation(child, state, top, false); } void startSettlingAnimation(View child, int state, int top, boolean settleFromViewDragHelper) { boolean startedSettling = settleFromViewDragHelper ? viewDragHelper.settleCapturedViewAt(child.getLeft(), top) : viewDragHelper.smoothSlideViewTo(child, child.getLeft(), top); if (startedSettling) { setStateInternal(STATE_SETTLING); // STATE_SETTLING won't animate the material shape, so do that here with the target state. updateDrawableForTargetState(state); if (settleRunnable == null) { // If the singleton SettleRunnable instance has not been instantiated, create it. settleRunnable = new SettleRunnable(child, state); } // If the SettleRunnable has not been posted, post it with the correct state. if (settleRunnable.isPosted == false) { settleRunnable.targetState = state; ViewCompat.postOnAnimation(child, settleRunnable); settleRunnable.isPosted = true; } else { // Otherwise, if it has been posted, just update the target state. settleRunnable.targetState = state; } } else { setStateInternal(state); } } private final ViewDragHelper.Callback dragCallback = new ViewDragHelper.Callback() { @Override public boolean tryCaptureView(@NonNull View child, int pointerId) { if (state == STATE_DRAGGING) { return false; } if (touchingScrollingChild) { return false; } if (state == STATE_EXPANDED && activePointerId == pointerId) { View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (scroll != null && scroll.canScrollVertically(-1)) { // Let the content scroll up return false; } } return viewRef != null && viewRef.get() == child; } @Override public void onViewPositionChanged( @NonNull View changedView, int left, int top, int dx, int dy) { dispatchOnSlide(top); } @Override public void onViewDragStateChanged(int state) { if (state == ViewDragHelper.STATE_DRAGGING && draggable) { setStateInternal(STATE_DRAGGING); } } private boolean releasedLow(@NonNull View child) { // Needs to be at least half way to the bottom. return child.getTop() > (parentHeight + getExpandedOffset()) / 2; } @Override public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) { int top; @State int targetState; if (yvel < 0) { // Moving up if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { int currentTop = releasedChild.getTop(); if (currentTop > halfExpandedOffset) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = expandedOffset; targetState = STATE_EXPANDED; } } } else if (hideable && shouldHide(releasedChild, yvel)) { // Hide if the view was either released low or it was a significant vertical swipe // otherwise settle to closest expanded state. if ((Math.abs(xvel) < Math.abs(yvel) && yvel > SIGNIFICANT_VEL_THRESHOLD) || releasedLow(releasedChild)) { top = parentHeight; targetState = STATE_HIDDEN; } else if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else if (Math.abs(releasedChild.getTop() - expandedOffset) < Math.abs(releasedChild.getTop() - halfExpandedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else if (yvel == 0.f || Math.abs(xvel) > Math.abs(yvel)) { // If the Y velocity is 0 or the swipe was mostly horizontal indicated by the X velocity // being greater than the Y velocity, settle to the nearest correct height. int currentTop = releasedChild.getTop(); if (fitToContents) { if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } else { if (currentTop < halfExpandedOffset) { if (currentTop < Math.abs(currentTop - collapsedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else { if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } } else { // Moving Down if (fitToContents) { top = collapsedOffset; targetState = STATE_COLLAPSED; } else { // Settle to the nearest correct height. int currentTop = releasedChild.getTop(); if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } startSettlingAnimation(releasedChild, targetState, top, true); } @Override public int clampViewPositionVertical(@NonNull View child, int top, int dy) { return MathUtils.clamp( top, getExpandedOffset(), hideable ? parentHeight : collapsedOffset); } @Override public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) { return child.getLeft(); } @Override public int getViewVerticalDragRange(@NonNull View child) { if (hideable) { return parentHeight; } else { return collapsedOffset; } } }; void dispatchOnSlide(int top) { View bottomSheet = viewRef.get(); if (bottomSheet != null && !callbacks.isEmpty()) { float slideOffset = (top > collapsedOffset || collapsedOffset == getExpandedOffset()) ? (float) (collapsedOffset - top) / (parentHeight - collapsedOffset) : (float) (collapsedOffset - top) / (collapsedOffset - getExpandedOffset()); for (int i = 0; i < callbacks.size(); i++) { callbacks.get(i).onSlide(bottomSheet, slideOffset); } } } @VisibleForTesting int getPeekHeightMin() { return peekHeightMin; } /** * Disables the shaped corner {@link ShapeAppearanceModel} interpolation transition animations. * Will have no effect unless the sheet utilizes a {@link MaterialShapeDrawable} with set shape * theming properties. Only For use in UI testing. * * @hide */ @RestrictTo(LIBRARY_GROUP) @VisibleForTesting public void disableShapeAnimations() { // Sets the shape value animator to null, prevents animations from occuring during testing. interpolatorAnimator = null; } private class SettleRunnable implements Runnable { private final View view; private boolean isPosted; @State int targetState; SettleRunnable(View view, @State int targetState) { this.view = view; this.targetState = targetState; } @Override public void run() { if (viewDragHelper != null && viewDragHelper.continueSettling(true)) { ViewCompat.postOnAnimation(view, this); } else { setStateInternal(targetState); } this.isPosted = false; } } /** State persisted across instances */ protected static class SavedState extends AbsSavedState { @State final int state; int peekHeight; boolean fitToContents; boolean hideable; boolean skipCollapsed; public SavedState(@NonNull Parcel source) { this(source, null); } public SavedState(@NonNull Parcel source, ClassLoader loader) { super(source, loader); //noinspection ResourceType state = source.readInt(); peekHeight = source.readInt(); fitToContents = source.readInt() == 1; hideable = source.readInt() == 1; skipCollapsed = source.readInt() == 1; } public SavedState(Parcelable superState, @NonNull BottomSheetBehavior<?> behavior) { super(superState); this.state = behavior.state; this.peekHeight = behavior.peekHeight; this.fitToContents = behavior.fitToContents; this.hideable = behavior.hideable; this.skipCollapsed = behavior.skipCollapsed; } /** * This constructor does not respect flags: {@link BottomSheetBehavior#SAVE_PEEK_HEIGHT}, {@link * BottomSheetBehavior#SAVE_FIT_TO_CONTENTS}, {@link BottomSheetBehavior#SAVE_HIDEABLE}, {@link * BottomSheetBehavior#SAVE_SKIP_COLLAPSED}. It is as if {@link BottomSheetBehavior#SAVE_NONE} * were set. * * @deprecated Use {@link #SavedState(Parcelable, BottomSheetBehavior)} instead. */ @Deprecated public SavedState(Parcelable superstate, int state) { super(superstate); this.state = state; } @Override public void writeToParcel(@NonNull Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(state); out.writeInt(peekHeight); out.writeInt(fitToContents ? 1 : 0); out.writeInt(hideable ? 1 : 0); out.writeInt(skipCollapsed ? 1 : 0); } public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() { @NonNull @Override public SavedState createFromParcel(@NonNull Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Nullable @Override public SavedState createFromParcel(@NonNull Parcel in) { return new SavedState(in, null); } @NonNull @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * A utility function to get the {@link BottomSheetBehavior} associated with the {@code view}. * * @param view The {@link View} with {@link BottomSheetBehavior}. * @return The {@link BottomSheetBehavior} associated with the {@code view}. */ @NonNull @SuppressWarnings("unchecked") public static <V extends View> BottomSheetBehavior<V> from(@NonNull V view) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (!(params instanceof CoordinatorLayout.LayoutParams)) { throw new IllegalArgumentException("The view is not a child of CoordinatorLayout"); } CoordinatorLayout.Behavior<?> behavior = ((CoordinatorLayout.LayoutParams) params).getBehavior(); if (!(behavior instanceof BottomSheetBehavior)) { throw new IllegalArgumentException("The view is not associated with BottomSheetBehavior"); } return (BottomSheetBehavior<V>) behavior; } /** * Sets whether the BottomSheet should update the accessibility status of its {@link * CoordinatorLayout} siblings when expanded. * * <p>Set this to true if the expanded state of the sheet blocks access to siblings (e.g., when * the sheet expands over the full screen). */ public void setUpdateImportantForAccessibilityOnSiblings( boolean updateImportantForAccessibilityOnSiblings) { this.updateImportantForAccessibilityOnSiblings = updateImportantForAccessibilityOnSiblings; } private void updateImportantForAccessibility(boolean expanded) { if (viewRef == null) { return; } ViewParent viewParent = viewRef.get().getParent(); if (!(viewParent instanceof CoordinatorLayout)) { return; } CoordinatorLayout parent = (CoordinatorLayout) viewParent; final int childCount = parent.getChildCount(); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) && expanded) { if (importantForAccessibilityMap == null) { importantForAccessibilityMap = new HashMap<>(childCount); } else { // The important for accessibility values of the child views have been saved already. return; } } for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); if (child == viewRef.get()) { continue; } if (expanded) { // Saves the important for accessibility value of the child view. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { importantForAccessibilityMap.put(child, child.getImportantForAccessibility()); } if (updateImportantForAccessibilityOnSiblings) { ViewCompat.setImportantForAccessibility( child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } } else { if (updateImportantForAccessibilityOnSiblings && importantForAccessibilityMap != null && importantForAccessibilityMap.containsKey(child)) { // Restores the original important for accessibility value of the child view. ViewCompat.setImportantForAccessibility(child, importantForAccessibilityMap.get(child)); } } } if (!expanded) { importantForAccessibilityMap = null; } else if (updateImportantForAccessibilityOnSiblings) { // If the siblings of the bottom sheet have been set to not important for a11y, move the focus // to the bottom sheet when expanded. viewRef.get().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); } } private void updateAccessibilityActions() { if (viewRef == null) { return; } V child = viewRef.get(); if (child == null) { return; } ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_COLLAPSE); ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_EXPAND); ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_DISMISS); if (hideable && state != STATE_HIDDEN) { addAccessibilityActionForState(child, AccessibilityActionCompat.ACTION_DISMISS, STATE_HIDDEN); } switch (state) { case STATE_EXPANDED: { int nextState = fitToContents ? STATE_COLLAPSED : STATE_HALF_EXPANDED; addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_COLLAPSE, nextState); break; } case STATE_HALF_EXPANDED: { addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_COLLAPSE, STATE_COLLAPSED); addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_EXPAND, STATE_EXPANDED); break; } case STATE_COLLAPSED: { int nextState = fitToContents ? STATE_EXPANDED : STATE_HALF_EXPANDED; addAccessibilityActionForState(child, AccessibilityActionCompat.ACTION_EXPAND, nextState); break; } default: // fall out } } private void addAccessibilityActionForState( V child, AccessibilityActionCompat action, final int state) { ViewCompat.replaceAccessibilityAction( child, action, null, new AccessibilityViewCommand() { @Override public boolean perform(@NonNull View view, @Nullable CommandArguments arguments) { setState(state); return true; } }); } }
lib/java/com/google/android/material/bottomsheet/BottomSheetBehavior.java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.material.bottomsheet; import com.google.android.material.R; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.os.Build; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Parcel; import android.os.Parcelable; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat; import androidx.core.view.accessibility.AccessibilityViewCommand; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import androidx.annotation.FloatRange; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams; import androidx.core.math.MathUtils; import androidx.customview.view.AbsSavedState; import androidx.customview.widget.ViewDragHelper; import com.google.android.material.internal.ViewUtils; import com.google.android.material.internal.ViewUtils.RelativePadding; import com.google.android.material.resources.MaterialResources; import com.google.android.material.shape.MaterialShapeDrawable; import com.google.android.material.shape.ShapeAppearanceModel; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * An interaction behavior plugin for a child view of {@link CoordinatorLayout} to make it work as a * bottom sheet. * * <p>To send useful accessibility events, set a title on bottom sheets that are windows or are * window-like. For BottomSheetDialog use {@link BottomSheetDialog#setTitle(int)}, and for * BottomSheetDialogFragment use {@link ViewCompat#setAccessibilityPaneTitle(View, CharSequence)}. */ public class BottomSheetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { /** Callback for monitoring events about bottom sheets. */ public abstract static class BottomSheetCallback { /** * Called when the bottom sheet changes its state. * * @param bottomSheet The bottom sheet view. * @param newState The new state. This will be one of {@link #STATE_DRAGGING}, {@link * #STATE_SETTLING}, {@link #STATE_EXPANDED}, {@link #STATE_COLLAPSED}, {@link * #STATE_HIDDEN}, or {@link #STATE_HALF_EXPANDED}. */ public abstract void onStateChanged(@NonNull View bottomSheet, @State int newState); /** * Called when the bottom sheet is being dragged. * * @param bottomSheet The bottom sheet view. * @param slideOffset The new offset of this bottom sheet within [-1,1] range. Offset increases * as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and * expanded states and from -1 to 0 it is between hidden and collapsed states. */ public abstract void onSlide(@NonNull View bottomSheet, float slideOffset); } /** The bottom sheet is dragging. */ public static final int STATE_DRAGGING = 1; /** The bottom sheet is settling. */ public static final int STATE_SETTLING = 2; /** The bottom sheet is expanded. */ public static final int STATE_EXPANDED = 3; /** The bottom sheet is collapsed. */ public static final int STATE_COLLAPSED = 4; /** The bottom sheet is hidden. */ public static final int STATE_HIDDEN = 5; /** The bottom sheet is half-expanded (used when mFitToContents is false). */ public static final int STATE_HALF_EXPANDED = 6; /** @hide */ @RestrictTo(LIBRARY_GROUP) @IntDef({ STATE_EXPANDED, STATE_COLLAPSED, STATE_DRAGGING, STATE_SETTLING, STATE_HIDDEN, STATE_HALF_EXPANDED }) @Retention(RetentionPolicy.SOURCE) public @interface State {} /** * Peek at the 16:9 ratio keyline of its parent. * * <p>This can be used as a parameter for {@link #setPeekHeight(int)}. {@link #getPeekHeight()} * will return this when the value is set. */ public static final int PEEK_HEIGHT_AUTO = -1; /** This flag will preserve the peekHeight int value on configuration change. */ public static final int SAVE_PEEK_HEIGHT = 0x1; /** This flag will preserve the fitToContents boolean value on configuration change. */ public static final int SAVE_FIT_TO_CONTENTS = 1 << 1; /** This flag will preserve the hideable boolean value on configuration change. */ public static final int SAVE_HIDEABLE = 1 << 2; /** This flag will preserve the skipCollapsed boolean value on configuration change. */ public static final int SAVE_SKIP_COLLAPSED = 1 << 3; /** This flag will preserve all aforementioned values on configuration change. */ public static final int SAVE_ALL = -1; /** * This flag will not preserve the aforementioned values set at runtime if the view is destroyed * and recreated. The only value preserved will be the positional state, e.g. collapsed, hidden, * expanded, etc. This is the default behavior. */ public static final int SAVE_NONE = 0; /** @hide */ @RestrictTo(LIBRARY_GROUP) @IntDef( flag = true, value = { SAVE_PEEK_HEIGHT, SAVE_FIT_TO_CONTENTS, SAVE_HIDEABLE, SAVE_SKIP_COLLAPSED, SAVE_ALL, SAVE_NONE, }) @Retention(RetentionPolicy.SOURCE) public @interface SaveFlags {} private static final String TAG = "BottomSheetBehavior"; @SaveFlags private int saveFlags = SAVE_NONE; private static final int SIGNIFICANT_VEL_THRESHOLD = 500; private static final float HIDE_THRESHOLD = 0.5f; private static final float HIDE_FRICTION = 0.1f; private static final int CORNER_ANIMATION_DURATION = 500; private boolean fitToContents = true; private boolean updateImportantForAccessibilityOnSiblings = false; private float maximumVelocity; /** Peek height set by the user. */ private int peekHeight; /** Whether or not to use automatic peek height. */ private boolean peekHeightAuto; /** Minimum peek height permitted. */ private int peekHeightMin; /** True if Behavior has a non-null value for the @shapeAppearance attribute */ private boolean shapeThemingEnabled; private MaterialShapeDrawable materialShapeDrawable; private int gestureInsetBottom; private boolean gestureInsetBottomIgnored; /** Default Shape Appearance to be used in bottomsheet */ private ShapeAppearanceModel shapeAppearanceModelDefault; private boolean isShapeExpanded; private SettleRunnable settleRunnable = null; @Nullable private ValueAnimator interpolatorAnimator; private static final int DEF_STYLE_RES = R.style.Widget_Design_BottomSheet_Modal; int expandedOffset; int fitToContentsOffset; int halfExpandedOffset; float halfExpandedRatio = 0.5f; int collapsedOffset; float elevation = -1; boolean hideable; private boolean skipCollapsed; private boolean draggable = true; @State int state = STATE_COLLAPSED; @Nullable ViewDragHelper viewDragHelper; private boolean ignoreEvents; private int lastNestedScrollDy; private boolean nestedScrolled; int parentWidth; int parentHeight; @Nullable WeakReference<V> viewRef; @Nullable WeakReference<View> nestedScrollingChildRef; @NonNull private final ArrayList<BottomSheetCallback> callbacks = new ArrayList<>(); @Nullable private VelocityTracker velocityTracker; int activePointerId; private int initialY; boolean touchingScrollingChild; @Nullable private Map<View, Integer> importantForAccessibilityMap; public BottomSheetBehavior() {} public BottomSheetBehavior(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout); this.shapeThemingEnabled = a.hasValue(R.styleable.BottomSheetBehavior_Layout_shapeAppearance); boolean hasBackgroundTint = a.hasValue(R.styleable.BottomSheetBehavior_Layout_backgroundTint); if (hasBackgroundTint) { ColorStateList bottomSheetColor = MaterialResources.getColorStateList( context, a, R.styleable.BottomSheetBehavior_Layout_backgroundTint); createMaterialShapeDrawable(context, attrs, hasBackgroundTint, bottomSheetColor); } else { createMaterialShapeDrawable(context, attrs, hasBackgroundTint); } createShapeValueAnimator(); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { this.elevation = a.getDimension(R.styleable.BottomSheetBehavior_Layout_android_elevation, -1); } TypedValue value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight); if (value != null && value.data == PEEK_HEIGHT_AUTO) { setPeekHeight(value.data); } else { setPeekHeight( a.getDimensionPixelSize( R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO)); } setHideable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false)); setGestureInsetBottomIgnored( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_gestureInsetBottomIgnored, false)); setFitToContents( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true)); setSkipCollapsed( a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false)); setDraggable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_draggable, true)); setSaveFlags(a.getInt(R.styleable.BottomSheetBehavior_Layout_behavior_saveFlags, SAVE_NONE)); setHalfExpandedRatio( a.getFloat(R.styleable.BottomSheetBehavior_Layout_behavior_halfExpandedRatio, 0.5f)); value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset); if (value != null && value.type == TypedValue.TYPE_FIRST_INT) { setExpandedOffset(value.data); } else { setExpandedOffset( a.getDimensionPixelOffset( R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset, 0)); } a.recycle(); ViewConfiguration configuration = ViewConfiguration.get(context); maximumVelocity = configuration.getScaledMaximumFlingVelocity(); } @NonNull @Override public Parcelable onSaveInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child) { return new SavedState(super.onSaveInstanceState(parent, child), this); } @Override public void onRestoreInstanceState( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(parent, child, ss.getSuperState()); // Restore Optional State values designated by saveFlags restoreOptionalState(ss); // Intermediate states are restored as collapsed state if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) { this.state = STATE_COLLAPSED; } else { this.state = ss.state; } } @Override public void onAttachedToLayoutParams(@NonNull LayoutParams layoutParams) { super.onAttachedToLayoutParams(layoutParams); // These may already be null, but just be safe, explicitly assign them. This lets us know the // first time we layout with this behavior by checking (viewRef == null). viewRef = null; viewDragHelper = null; } @Override public void onDetachedFromLayoutParams() { super.onDetachedFromLayoutParams(); // Release references so we don't run unnecessary codepaths while not attached to a view. viewRef = null; viewDragHelper = null; } @Override public boolean onLayoutChild( @NonNull CoordinatorLayout parent, @NonNull V child, int layoutDirection) { if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) { child.setFitsSystemWindows(true); } if (viewRef == null) { // First layout with this behavior. peekHeightMin = parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min); setSystemGestureInsets(child); viewRef = new WeakReference<>(child); // Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will // default to android:background declared in styles or layout. if (shapeThemingEnabled && materialShapeDrawable != null) { ViewCompat.setBackground(child, materialShapeDrawable); } // Set elevation on MaterialShapeDrawable if (materialShapeDrawable != null) { // Use elevation attr if set on bottomsheet; otherwise, use elevation of child view. materialShapeDrawable.setElevation( elevation == -1 ? ViewCompat.getElevation(child) : elevation); // Update the material shape based on initial state. isShapeExpanded = state == STATE_EXPANDED; materialShapeDrawable.setInterpolation(isShapeExpanded ? 0f : 1f); } updateAccessibilityActions(); if (ViewCompat.getImportantForAccessibility(child) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } } if (viewDragHelper == null) { viewDragHelper = ViewDragHelper.create(parent, dragCallback); } int savedTop = child.getTop(); // First let the parent lay it out parent.onLayoutChild(child, layoutDirection); // Offset the bottom sheet parentWidth = parent.getWidth(); parentHeight = parent.getHeight(); fitToContentsOffset = Math.max(0, parentHeight - child.getHeight()); calculateHalfExpandedOffset(); calculateCollapsedOffset(); if (state == STATE_EXPANDED) { ViewCompat.offsetTopAndBottom(child, getExpandedOffset()); } else if (state == STATE_HALF_EXPANDED) { ViewCompat.offsetTopAndBottom(child, halfExpandedOffset); } else if (hideable && state == STATE_HIDDEN) { ViewCompat.offsetTopAndBottom(child, parentHeight); } else if (state == STATE_COLLAPSED) { ViewCompat.offsetTopAndBottom(child, collapsedOffset); } else if (state == STATE_DRAGGING || state == STATE_SETTLING) { ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop()); } nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child)); return true; } @Override public boolean onInterceptTouchEvent( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) { if (!child.isShown() || !draggable) { ignoreEvents = true; return false; } int action = event.getActionMasked(); // Record the velocity if (action == MotionEvent.ACTION_DOWN) { reset(); } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: touchingScrollingChild = false; activePointerId = MotionEvent.INVALID_POINTER_ID; // Reset the ignore flag if (ignoreEvents) { ignoreEvents = false; return false; } break; case MotionEvent.ACTION_DOWN: int initialX = (int) event.getX(); initialY = (int) event.getY(); // Only intercept nested scrolling events here if the view not being moved by the // ViewDragHelper. if (state != STATE_SETTLING) { View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (scroll != null && parent.isPointInChildBounds(scroll, initialX, initialY)) { activePointerId = event.getPointerId(event.getActionIndex()); touchingScrollingChild = true; } } ignoreEvents = activePointerId == MotionEvent.INVALID_POINTER_ID && !parent.isPointInChildBounds(child, initialX, initialY); break; default: // fall out } if (!ignoreEvents && viewDragHelper != null && viewDragHelper.shouldInterceptTouchEvent(event)) { return true; } // We have to handle cases that the ViewDragHelper does not capture the bottom sheet because // it is not the top most view of its parent. This is not necessary when the touch event is // happening over the scrolling content as nested scrolling logic handles that case. View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; return action == MotionEvent.ACTION_MOVE && scroll != null && !ignoreEvents && state != STATE_DRAGGING && !parent.isPointInChildBounds(scroll, (int) event.getX(), (int) event.getY()) && viewDragHelper != null && Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop(); } @Override public boolean onTouchEvent( @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) { if (!child.isShown()) { return false; } int action = event.getActionMasked(); if (state == STATE_DRAGGING && action == MotionEvent.ACTION_DOWN) { return true; } if (viewDragHelper != null) { viewDragHelper.processTouchEvent(event); } // Record the velocity if (action == MotionEvent.ACTION_DOWN) { reset(); } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); // The ViewDragHelper tries to capture only the top-most View. We have to explicitly tell it // to capture the bottom sheet in case it is not captured and the touch slop is passed. if (action == MotionEvent.ACTION_MOVE && !ignoreEvents) { if (Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop()) { viewDragHelper.captureChildView(child, event.getPointerId(event.getActionIndex())); } } return !ignoreEvents; } @Override public boolean onStartNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { lastNestedScrollDy = 0; nestedScrolled = false; return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } @Override public void onNestedPreScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) { if (type == ViewCompat.TYPE_NON_TOUCH) { // Ignore fling here. The ViewDragHelper handles it. return; } View scrollingChild = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (target != scrollingChild) { return; } int currentTop = child.getTop(); int newTop = currentTop - dy; if (dy > 0) { // Upward if (newTop < getExpandedOffset()) { consumed[1] = currentTop - getExpandedOffset(); ViewCompat.offsetTopAndBottom(child, -consumed[1]); setStateInternal(STATE_EXPANDED); } else { if (!draggable) { // Prevent dragging return; } consumed[1] = dy; ViewCompat.offsetTopAndBottom(child, -dy); setStateInternal(STATE_DRAGGING); } } else if (dy < 0) { // Downward if (!target.canScrollVertically(-1)) { if (newTop <= collapsedOffset || hideable) { if (!draggable) { // Prevent dragging return; } consumed[1] = dy; ViewCompat.offsetTopAndBottom(child, -dy); setStateInternal(STATE_DRAGGING); } else { consumed[1] = currentTop - collapsedOffset; ViewCompat.offsetTopAndBottom(child, -consumed[1]); setStateInternal(STATE_COLLAPSED); } } } dispatchOnSlide(child.getTop()); lastNestedScrollDy = dy; nestedScrolled = true; } @Override public void onStopNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int type) { if (child.getTop() == getExpandedOffset()) { setStateInternal(STATE_EXPANDED); return; } if (nestedScrollingChildRef == null || target != nestedScrollingChildRef.get() || !nestedScrolled) { return; } int top; int targetState; if (lastNestedScrollDy > 0) { if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { int currentTop = child.getTop(); if (currentTop > halfExpandedOffset) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = expandedOffset; targetState = STATE_EXPANDED; } } } else if (hideable && shouldHide(child, getYVelocity())) { top = parentHeight; targetState = STATE_HIDDEN; } else if (lastNestedScrollDy == 0) { int currentTop = child.getTop(); if (fitToContents) { if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } else { if (currentTop < halfExpandedOffset) { if (currentTop < Math.abs(currentTop - collapsedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else { if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } } else { if (fitToContents) { top = collapsedOffset; targetState = STATE_COLLAPSED; } else { // Settle to nearest height. int currentTop = child.getTop(); if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } startSettlingAnimation(child, targetState, top, false); nestedScrolled = false; } @Override public void onNestedScroll( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed) { // Overridden to prevent the default consumption of the entire scroll distance. } @Override public boolean onNestedPreFling( @NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, float velocityX, float velocityY) { if (nestedScrollingChildRef != null) { return target == nestedScrollingChildRef.get() && (state != STATE_EXPANDED || super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY)); } else { return false; } } /** * @return whether the height of the expanded sheet is determined by the height of its contents, * or if it is expanded in two stages (half the height of the parent container, full height of * parent container). */ public boolean isFitToContents() { return fitToContents; } /** * Sets whether the height of the expanded sheet is determined by the height of its contents, or * if it is expanded in two stages (half the height of the parent container, full height of parent * container). Default value is true. * * @param fitToContents whether or not to fit the expanded sheet to its contents. */ public void setFitToContents(boolean fitToContents) { if (this.fitToContents == fitToContents) { return; } this.fitToContents = fitToContents; // If sheet is already laid out, recalculate the collapsed offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (viewRef != null) { calculateCollapsedOffset(); } // Fix incorrect expanded settings depending on whether or not we are fitting sheet to contents. setStateInternal((this.fitToContents && state == STATE_HALF_EXPANDED) ? STATE_EXPANDED : state); updateAccessibilityActions(); } /** * Sets the height of the bottom sheet when it is collapsed. * * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public void setPeekHeight(int peekHeight) { setPeekHeight(peekHeight, false); } /** * Sets the height of the bottom sheet when it is collapsed while optionally animating between the * old height and the new height. * * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline. * @param animate Whether to animate between the old height and the new height. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public final void setPeekHeight(int peekHeight, boolean animate) { boolean layout = false; if (peekHeight == PEEK_HEIGHT_AUTO) { if (!peekHeightAuto) { peekHeightAuto = true; layout = true; } } else if (peekHeightAuto || this.peekHeight != peekHeight) { peekHeightAuto = false; this.peekHeight = Math.max(0, peekHeight); layout = true; } // If sheet is already laid out, recalculate the collapsed offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (layout && viewRef != null) { updatePeekHeight(animate); } } private void updatePeekHeight(boolean animate) { calculateCollapsedOffset(); if (state == STATE_COLLAPSED) { V view = viewRef.get(); if (view != null) { if (animate) { settleToStatePendingLayout(state); } else { view.requestLayout(); } } } } /** * Gets the height of the bottom sheet when it is collapsed. * * @return The height of the collapsed bottom sheet in pixels, or {@link #PEEK_HEIGHT_AUTO} if the * sheet is configured to peek automatically at 16:9 ratio keyline * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight */ public int getPeekHeight() { return peekHeightAuto ? PEEK_HEIGHT_AUTO : peekHeight; } /** * Determines the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. The * material guidelines recommended a value of 0.5, which results in the sheet filling half of the * parent. The height of the BottomSheet will be smaller as this ratio is decreased and taller as * it is increased. The default value is 0.5. * * @param ratio a float between 0 and 1, representing the {@link #STATE_HALF_EXPANDED} ratio. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio */ public void setHalfExpandedRatio(@FloatRange(from = 0.0f, to = 1.0f) float ratio) { if ((ratio <= 0) || (ratio >= 1)) { throw new IllegalArgumentException("ratio must be a float value between 0 and 1"); } this.halfExpandedRatio = ratio; // If sheet is already laid out, recalculate the half expanded offset based on new setting. // Otherwise, let onLayoutChild handle this later. if (viewRef != null) { calculateHalfExpandedOffset(); } } /** * Gets the ratio for the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. * * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio */ @FloatRange(from = 0.0f, to = 1.0f) public float getHalfExpandedRatio() { return halfExpandedRatio; } /** * Determines the top offset of the BottomSheet in the {@link #STATE_EXPANDED} state when * fitsToContent is false. The default value is 0, which results in the sheet matching the * parent's top. * * @param offset an integer value greater than equal to 0, representing the {@link * #STATE_EXPANDED} offset. Value must not exceed the offset in the half expanded state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset */ public void setExpandedOffset(int offset) { if (offset < 0) { throw new IllegalArgumentException("offset must be greater than or equal to 0"); } this.expandedOffset = offset; } /** * Returns the current expanded offset. If {@code fitToContents} is true, it will automatically * pick the offset depending on the height of the content. * * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset */ public int getExpandedOffset() { return fitToContents ? fitToContentsOffset : expandedOffset; } /** * Sets whether this bottom sheet can hide when it is swiped down. * * @param hideable {@code true} to make this bottom sheet hideable. * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable */ public void setHideable(boolean hideable) { if (this.hideable != hideable) { this.hideable = hideable; if (!hideable && state == STATE_HIDDEN) { // Lift up to collapsed state setState(STATE_COLLAPSED); } updateAccessibilityActions(); } } /** * Gets whether this bottom sheet can hide when it is swiped down. * * @return {@code true} if this bottom sheet can hide. * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable */ public boolean isHideable() { return hideable; } /** * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it * is expanded once. Setting this to true has no effect unless the sheet is hideable. * * @param skipCollapsed True if the bottom sheet should skip the collapsed state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed */ public void setSkipCollapsed(boolean skipCollapsed) { this.skipCollapsed = skipCollapsed; } /** * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it * is expanded once. * * @return Whether the bottom sheet should skip the collapsed state. * @attr ref * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed */ public boolean getSkipCollapsed() { return skipCollapsed; } /** * Sets whether this bottom sheet is can be collapsed/expanded by dragging. Note: When disabling * dragging, an app will require to implement a custom way to expand/collapse the bottom sheet * * @param draggable {@code false} to prevent dragging the sheet to collapse and expand * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_draggable */ public void setDraggable(boolean draggable) { this.draggable = draggable; } public boolean isDraggable() { return draggable; } /** * Sets save flags to be preserved in bottomsheet on configuration change. * * @param flags bitwise int of {@link #SAVE_PEEK_HEIGHT}, {@link #SAVE_FIT_TO_CONTENTS}, {@link * #SAVE_HIDEABLE}, {@link #SAVE_SKIP_COLLAPSED}, {@link #SAVE_ALL} and {@link #SAVE_NONE}. * @see #getSaveFlags() * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags */ public void setSaveFlags(@SaveFlags int flags) { this.saveFlags = flags; } /** * Returns the save flags. * * @see #setSaveFlags(int) * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags */ @SaveFlags public int getSaveFlags() { return this.saveFlags; } /** * Sets a callback to be notified of bottom sheet events. * * @param callback The callback to notify when bottom sheet events occur. * @deprecated use {@link #addBottomSheetCallback(BottomSheetCallback)} and {@link * #removeBottomSheetCallback(BottomSheetCallback)} instead */ @Deprecated public void setBottomSheetCallback(BottomSheetCallback callback) { Log.w( TAG, "BottomSheetBehavior now supports multiple callbacks. `setBottomSheetCallback()` removes" + " all existing callbacks, including ones set internally by library authors, which" + " may result in unintended behavior. This may change in the future. Please use" + " `addBottomSheetCallback()` and `removeBottomSheetCallback()` instead to set your" + " own callbacks."); callbacks.clear(); if (callback != null) { callbacks.add(callback); } } /** * Adds a callback to be notified of bottom sheet events. * * @param callback The callback to notify when bottom sheet events occur. */ public void addBottomSheetCallback(@NonNull BottomSheetCallback callback) { if (!callbacks.contains(callback)) { callbacks.add(callback); } } /** * Removes a previously added callback. * * @param callback The callback to remove. */ public void removeBottomSheetCallback(@NonNull BottomSheetCallback callback) { callbacks.remove(callback); } /** * Sets the state of the bottom sheet. The bottom sheet will transition to that state with * animation. * * @param state One of {@link #STATE_COLLAPSED}, {@link #STATE_EXPANDED}, {@link #STATE_HIDDEN}, * or {@link #STATE_HALF_EXPANDED}. */ public void setState(@State int state) { if (state == this.state) { return; } if (viewRef == null) { // The view is not laid out yet; modify mState and let onLayoutChild handle it later if (state == STATE_COLLAPSED || state == STATE_EXPANDED || state == STATE_HALF_EXPANDED || (hideable && state == STATE_HIDDEN)) { this.state = state; } return; } settleToStatePendingLayout(state); } /** * Sets whether this bottom sheet should adjust it's position based on the system gesture area on * Android Q and above. * * <p>Note: the bottom sheet will only adjust it's position if it would be unable to be scrolled * upwards because the peekHeight is less than the gesture inset margins,(because that would cause * a gesture conflict), gesture navigation is enabled, and this {@code ignoreGestureInsetBottom} * flag is false. */ public void setGestureInsetBottomIgnored(boolean gestureInsetBottomIgnored) { this.gestureInsetBottomIgnored = gestureInsetBottomIgnored; } /** * Returns whether this bottom sheet should adjust it's position based on the system gesture area. */ public boolean isGestureInsetBottomIgnored() { return gestureInsetBottomIgnored; } private void settleToStatePendingLayout(@State int state) { final V child = viewRef.get(); if (child == null) { return; } // Start the animation; wait until a pending layout if there is one. ViewParent parent = child.getParent(); if (parent != null && parent.isLayoutRequested() && ViewCompat.isAttachedToWindow(child)) { final int finalState = state; child.post( new Runnable() { @Override public void run() { settleToState(child, finalState); } }); } else { settleToState(child, state); } } /** * Gets the current state of the bottom sheet. * * @return One of {@link #STATE_EXPANDED}, {@link #STATE_HALF_EXPANDED}, {@link #STATE_COLLAPSED}, * {@link #STATE_DRAGGING}, {@link #STATE_SETTLING}, or {@link #STATE_HALF_EXPANDED}. */ @State public int getState() { return state; } void setStateInternal(@State int state) { if (this.state == state) { return; } this.state = state; if (viewRef == null) { return; } View bottomSheet = viewRef.get(); if (bottomSheet == null) { return; } if (state == STATE_EXPANDED) { updateImportantForAccessibility(true); } else if (state == STATE_HALF_EXPANDED || state == STATE_HIDDEN || state == STATE_COLLAPSED) { updateImportantForAccessibility(false); } updateDrawableForTargetState(state); for (int i = 0; i < callbacks.size(); i++) { callbacks.get(i).onStateChanged(bottomSheet, state); } updateAccessibilityActions(); } private void updateDrawableForTargetState(@State int state) { if (state == STATE_SETTLING) { // Special case: we want to know which state we're settling to, so wait for another call. return; } boolean expand = state == STATE_EXPANDED; if (isShapeExpanded != expand) { isShapeExpanded = expand; if (materialShapeDrawable != null && interpolatorAnimator != null) { if (interpolatorAnimator.isRunning()) { interpolatorAnimator.reverse(); } else { float to = expand ? 0f : 1f; float from = 1f - to; interpolatorAnimator.setFloatValues(from, to); interpolatorAnimator.start(); } } } } private int calculatePeekHeight() { if (peekHeightAuto) { return Math.max(peekHeightMin, parentHeight - parentWidth * 9 / 16); } return peekHeight + (gestureInsetBottomIgnored ? 0 : gestureInsetBottom); } private void calculateCollapsedOffset() { int peek = calculatePeekHeight(); if (fitToContents) { collapsedOffset = Math.max(parentHeight - peek, fitToContentsOffset); } else { collapsedOffset = parentHeight - peek; } } private void calculateHalfExpandedOffset() { this.halfExpandedOffset = (int) (parentHeight * (1 - halfExpandedRatio)); } private void reset() { activePointerId = ViewDragHelper.INVALID_POINTER; if (velocityTracker != null) { velocityTracker.recycle(); velocityTracker = null; } } private void restoreOptionalState(@NonNull SavedState ss) { if (this.saveFlags == SAVE_NONE) { return; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_PEEK_HEIGHT) == SAVE_PEEK_HEIGHT) { this.peekHeight = ss.peekHeight; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_FIT_TO_CONTENTS) == SAVE_FIT_TO_CONTENTS) { this.fitToContents = ss.fitToContents; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_HIDEABLE) == SAVE_HIDEABLE) { this.hideable = ss.hideable; } if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_SKIP_COLLAPSED) == SAVE_SKIP_COLLAPSED) { this.skipCollapsed = ss.skipCollapsed; } } boolean shouldHide(@NonNull View child, float yvel) { if (skipCollapsed) { return true; } if (child.getTop() < collapsedOffset) { // It should not hide, but collapse. return false; } int peek = calculatePeekHeight(); final float newTop = child.getTop() + yvel * HIDE_FRICTION; return Math.abs(newTop - collapsedOffset) / (float) peek > HIDE_THRESHOLD; } @Nullable @VisibleForTesting View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; } private void createMaterialShapeDrawable( @NonNull Context context, AttributeSet attrs, boolean hasBackgroundTint) { this.createMaterialShapeDrawable(context, attrs, hasBackgroundTint, null); } private void createMaterialShapeDrawable( @NonNull Context context, AttributeSet attrs, boolean hasBackgroundTint, @Nullable ColorStateList bottomSheetColor) { if (this.shapeThemingEnabled) { this.shapeAppearanceModelDefault = ShapeAppearanceModel.builder(context, attrs, R.attr.bottomSheetStyle, DEF_STYLE_RES) .build(); this.materialShapeDrawable = new MaterialShapeDrawable(shapeAppearanceModelDefault); this.materialShapeDrawable.initializeElevationOverlay(context); if (hasBackgroundTint && bottomSheetColor != null) { materialShapeDrawable.setFillColor(bottomSheetColor); } else { // If the tint isn't set, use the theme default background color. TypedValue defaultColor = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.colorBackground, defaultColor, true); materialShapeDrawable.setTint(defaultColor.data); } } } private void createShapeValueAnimator() { interpolatorAnimator = ValueAnimator.ofFloat(0f, 1f); interpolatorAnimator.setDuration(CORNER_ANIMATION_DURATION); interpolatorAnimator.addUpdateListener( new AnimatorUpdateListener() { @Override public void onAnimationUpdate(@NonNull ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); if (materialShapeDrawable != null) { materialShapeDrawable.setInterpolation(value); } } }); } /** * Ensure the peek height is at least as large as the bottom gesture inset size so that the sheet * can always be dragged, but only when the inset is required by the system. */ private void setSystemGestureInsets(@NonNull View child) { if (VERSION.SDK_INT >= VERSION_CODES.Q && !isGestureInsetBottomIgnored() && !peekHeightAuto) { ViewUtils.doOnApplyWindowInsets( child, new ViewUtils.OnApplyWindowInsetsListener() { @Override public WindowInsetsCompat onApplyWindowInsets( View view, WindowInsetsCompat insets, RelativePadding initialPadding) { gestureInsetBottom = insets.getMandatorySystemGestureInsets().bottom; updatePeekHeight(/* animate= */ false); return insets; } }); } } private float getYVelocity() { if (velocityTracker == null) { return 0; } velocityTracker.computeCurrentVelocity(1000, maximumVelocity); return velocityTracker.getYVelocity(activePointerId); } void settleToState(@NonNull View child, int state) { int top; if (state == STATE_COLLAPSED) { top = collapsedOffset; } else if (state == STATE_HALF_EXPANDED) { top = halfExpandedOffset; if (fitToContents && top <= fitToContentsOffset) { // Skip to the expanded state if we would scroll past the height of the contents. state = STATE_EXPANDED; top = fitToContentsOffset; } } else if (state == STATE_EXPANDED) { top = getExpandedOffset(); } else if (hideable && state == STATE_HIDDEN) { top = parentHeight; } else { throw new IllegalArgumentException("Illegal state argument: " + state); } startSettlingAnimation(child, state, top, false); } void startSettlingAnimation(View child, int state, int top, boolean settleFromViewDragHelper) { boolean startedSettling = settleFromViewDragHelper ? viewDragHelper.settleCapturedViewAt(child.getLeft(), top) : viewDragHelper.smoothSlideViewTo(child, child.getLeft(), top); if (startedSettling) { setStateInternal(STATE_SETTLING); // STATE_SETTLING won't animate the material shape, so do that here with the target state. updateDrawableForTargetState(state); if (settleRunnable == null) { // If the singleton SettleRunnable instance has not been instantiated, create it. settleRunnable = new SettleRunnable(child, state); } // If the SettleRunnable has not been posted, post it with the correct state. if (settleRunnable.isPosted == false) { settleRunnable.targetState = state; ViewCompat.postOnAnimation(child, settleRunnable); settleRunnable.isPosted = true; } else { // Otherwise, if it has been posted, just update the target state. settleRunnable.targetState = state; } } else { setStateInternal(state); } } private final ViewDragHelper.Callback dragCallback = new ViewDragHelper.Callback() { @Override public boolean tryCaptureView(@NonNull View child, int pointerId) { if (state == STATE_DRAGGING) { return false; } if (touchingScrollingChild) { return false; } if (state == STATE_EXPANDED && activePointerId == pointerId) { View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null; if (scroll != null && scroll.canScrollVertically(-1)) { // Let the content scroll up return false; } } return viewRef != null && viewRef.get() == child; } @Override public void onViewPositionChanged( @NonNull View changedView, int left, int top, int dx, int dy) { dispatchOnSlide(top); } @Override public void onViewDragStateChanged(int state) { if (state == ViewDragHelper.STATE_DRAGGING && draggable) { setStateInternal(STATE_DRAGGING); } } private boolean releasedLow(@NonNull View child) { // Needs to be at least half way to the bottom. return child.getTop() > (parentHeight + getExpandedOffset()) / 2; } @Override public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) { int top; @State int targetState; if (yvel < 0) { // Moving up if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { int currentTop = releasedChild.getTop(); if (currentTop > halfExpandedOffset) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = expandedOffset; targetState = STATE_EXPANDED; } } } else if (hideable && shouldHide(releasedChild, yvel)) { // Hide if the view was either released low or it was a significant vertical swipe // otherwise settle to closest expanded state. if ((Math.abs(xvel) < Math.abs(yvel) && yvel > SIGNIFICANT_VEL_THRESHOLD) || releasedLow(releasedChild)) { top = parentHeight; targetState = STATE_HIDDEN; } else if (fitToContents) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else if (Math.abs(releasedChild.getTop() - expandedOffset) < Math.abs(releasedChild.getTop() - halfExpandedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else if (yvel == 0.f || Math.abs(xvel) > Math.abs(yvel)) { // If the Y velocity is 0 or the swipe was mostly horizontal indicated by the X velocity // being greater than the Y velocity, settle to the nearest correct height. int currentTop = releasedChild.getTop(); if (fitToContents) { if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) { top = fitToContentsOffset; targetState = STATE_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } else { if (currentTop < halfExpandedOffset) { if (currentTop < Math.abs(currentTop - collapsedOffset)) { top = expandedOffset; targetState = STATE_EXPANDED; } else { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } } else { if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } } else { // Moving Down if (fitToContents) { top = collapsedOffset; targetState = STATE_COLLAPSED; } else { // Settle to the nearest correct height. int currentTop = releasedChild.getTop(); if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) { top = halfExpandedOffset; targetState = STATE_HALF_EXPANDED; } else { top = collapsedOffset; targetState = STATE_COLLAPSED; } } } startSettlingAnimation(releasedChild, targetState, top, true); } @Override public int clampViewPositionVertical(@NonNull View child, int top, int dy) { return MathUtils.clamp( top, getExpandedOffset(), hideable ? parentHeight : collapsedOffset); } @Override public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) { return child.getLeft(); } @Override public int getViewVerticalDragRange(@NonNull View child) { if (hideable) { return parentHeight; } else { return collapsedOffset; } } }; void dispatchOnSlide(int top) { View bottomSheet = viewRef.get(); if (bottomSheet != null && !callbacks.isEmpty()) { float slideOffset = (top > collapsedOffset || collapsedOffset == getExpandedOffset()) ? (float) (collapsedOffset - top) / (parentHeight - collapsedOffset) : (float) (collapsedOffset - top) / (collapsedOffset - getExpandedOffset()); for (int i = 0; i < callbacks.size(); i++) { callbacks.get(i).onSlide(bottomSheet, slideOffset); } } } @VisibleForTesting int getPeekHeightMin() { return peekHeightMin; } /** * Disables the shaped corner {@link ShapeAppearanceModel} interpolation transition animations. * Will have no effect unless the sheet utilizes a {@link MaterialShapeDrawable} with set shape * theming properties. Only For use in UI testing. * * @hide */ @RestrictTo(LIBRARY_GROUP) @VisibleForTesting public void disableShapeAnimations() { // Sets the shape value animator to null, prevents animations from occuring during testing. interpolatorAnimator = null; } private class SettleRunnable implements Runnable { private final View view; private boolean isPosted; @State int targetState; SettleRunnable(View view, @State int targetState) { this.view = view; this.targetState = targetState; } @Override public void run() { if (viewDragHelper != null && viewDragHelper.continueSettling(true)) { ViewCompat.postOnAnimation(view, this); } else { setStateInternal(targetState); } this.isPosted = false; } } /** State persisted across instances */ protected static class SavedState extends AbsSavedState { @State final int state; int peekHeight; boolean fitToContents; boolean hideable; boolean skipCollapsed; public SavedState(@NonNull Parcel source) { this(source, null); } public SavedState(@NonNull Parcel source, ClassLoader loader) { super(source, loader); //noinspection ResourceType state = source.readInt(); peekHeight = source.readInt(); fitToContents = source.readInt() == 1; hideable = source.readInt() == 1; skipCollapsed = source.readInt() == 1; } public SavedState(Parcelable superState, @NonNull BottomSheetBehavior<?> behavior) { super(superState); this.state = behavior.state; this.peekHeight = behavior.peekHeight; this.fitToContents = behavior.fitToContents; this.hideable = behavior.hideable; this.skipCollapsed = behavior.skipCollapsed; } /** * This constructor does not respect flags: {@link BottomSheetBehavior#SAVE_PEEK_HEIGHT}, {@link * BottomSheetBehavior#SAVE_FIT_TO_CONTENTS}, {@link BottomSheetBehavior#SAVE_HIDEABLE}, {@link * BottomSheetBehavior#SAVE_SKIP_COLLAPSED}. It is as if {@link BottomSheetBehavior#SAVE_NONE} * were set. * * @deprecated Use {@link #SavedState(Parcelable, BottomSheetBehavior)} instead. */ @Deprecated public SavedState(Parcelable superstate, int state) { super(superstate); this.state = state; } @Override public void writeToParcel(@NonNull Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(state); out.writeInt(peekHeight); out.writeInt(fitToContents ? 1 : 0); out.writeInt(hideable ? 1 : 0); out.writeInt(skipCollapsed ? 1 : 0); } public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() { @NonNull @Override public SavedState createFromParcel(@NonNull Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Nullable @Override public SavedState createFromParcel(@NonNull Parcel in) { return new SavedState(in, null); } @NonNull @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * A utility function to get the {@link BottomSheetBehavior} associated with the {@code view}. * * @param view The {@link View} with {@link BottomSheetBehavior}. * @return The {@link BottomSheetBehavior} associated with the {@code view}. */ @NonNull @SuppressWarnings("unchecked") public static <V extends View> BottomSheetBehavior<V> from(@NonNull V view) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (!(params instanceof CoordinatorLayout.LayoutParams)) { throw new IllegalArgumentException("The view is not a child of CoordinatorLayout"); } CoordinatorLayout.Behavior<?> behavior = ((CoordinatorLayout.LayoutParams) params).getBehavior(); if (!(behavior instanceof BottomSheetBehavior)) { throw new IllegalArgumentException("The view is not associated with BottomSheetBehavior"); } return (BottomSheetBehavior<V>) behavior; } /** * Sets whether the BottomSheet should update the accessibility status of its {@link * CoordinatorLayout} siblings when expanded. * * <p>Set this to true if the expanded state of the sheet blocks access to siblings (e.g., when * the sheet expands over the full screen). */ public void setUpdateImportantForAccessibilityOnSiblings( boolean updateImportantForAccessibilityOnSiblings) { this.updateImportantForAccessibilityOnSiblings = updateImportantForAccessibilityOnSiblings; } private void updateImportantForAccessibility(boolean expanded) { if (viewRef == null) { return; } ViewParent viewParent = viewRef.get().getParent(); if (!(viewParent instanceof CoordinatorLayout)) { return; } CoordinatorLayout parent = (CoordinatorLayout) viewParent; final int childCount = parent.getChildCount(); if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) && expanded) { if (importantForAccessibilityMap == null) { importantForAccessibilityMap = new HashMap<>(childCount); } else { // The important for accessibility values of the child views have been saved already. return; } } for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); if (child == viewRef.get()) { continue; } if (expanded) { // Saves the important for accessibility value of the child view. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { importantForAccessibilityMap.put(child, child.getImportantForAccessibility()); } if (updateImportantForAccessibilityOnSiblings) { ViewCompat.setImportantForAccessibility( child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); } } else { if (updateImportantForAccessibilityOnSiblings && importantForAccessibilityMap != null && importantForAccessibilityMap.containsKey(child)) { // Restores the original important for accessibility value of the child view. ViewCompat.setImportantForAccessibility(child, importantForAccessibilityMap.get(child)); } } } if (!expanded) { importantForAccessibilityMap = null; } else if (updateImportantForAccessibilityOnSiblings) { // If the siblings of the bottom sheet have been set to not important for a11y, move the focus // to the bottom sheet when expanded. viewRef.get().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); } } private void updateAccessibilityActions() { if (viewRef == null) { return; } V child = viewRef.get(); if (child == null) { return; } ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_COLLAPSE); ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_EXPAND); ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_DISMISS); if (hideable && state != STATE_HIDDEN) { addAccessibilityActionForState(child, AccessibilityActionCompat.ACTION_DISMISS, STATE_HIDDEN); } switch (state) { case STATE_EXPANDED: { int nextState = fitToContents ? STATE_COLLAPSED : STATE_HALF_EXPANDED; addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_COLLAPSE, nextState); break; } case STATE_HALF_EXPANDED: { addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_COLLAPSE, STATE_COLLAPSED); addAccessibilityActionForState( child, AccessibilityActionCompat.ACTION_EXPAND, STATE_EXPANDED); break; } case STATE_COLLAPSED: { int nextState = fitToContents ? STATE_EXPANDED : STATE_HALF_EXPANDED; addAccessibilityActionForState(child, AccessibilityActionCompat.ACTION_EXPAND, nextState); break; } default: // fall out } } private void addAccessibilityActionForState( V child, AccessibilityActionCompat action, final int state) { ViewCompat.replaceAccessibilityAction( child, action, null, new AccessibilityViewCommand() { @Override public boolean perform(@NonNull View view, @Nullable CommandArguments arguments) { setState(state); return true; } }); } }
[BottomSheet] Fixed NullPointerException when calling updatePeekHeight with null viewRef PiperOrigin-RevId: 323107185
lib/java/com/google/android/material/bottomsheet/BottomSheetBehavior.java
[BottomSheet] Fixed NullPointerException when calling updatePeekHeight with null viewRef
Java
apache-2.0
acf5733a37b9c10319fcb64d761d5fcf0eab86f5
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
/* * Copyright 2008 Oracle Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.osgi.impl.bundle.jmx.framework; import java.io.IOException; import java.util.ArrayList; import javax.management.Notification; import javax.management.openmbean.TabularData; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.impl.bundle.jmx.Monitor; import org.osgi.jmx.codec.OSGiBundle; import org.osgi.jmx.codec.OSGiBundleEvent; import org.osgi.jmx.codec.Util; import org.osgi.jmx.framework.BundleStateMBean; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; /** * */ public class BundleState extends Monitor implements BundleStateMBean { public BundleState(BundleContext bc, StartLevel sl, PackageAdmin admin) { this.bc = bc; this.sl = sl; this.admin = admin; } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getBundleDependencies() */ public long[] getDependencies(long bundleIdentifier) throws IOException { return Util.getBundleDependencies(bundle(bundleIdentifier), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getBundles() */ public TabularData getBundles() throws IOException { try { ArrayList<OSGiBundle> bundles = new ArrayList<OSGiBundle>(); for (Bundle bundle : bc.getBundles()) { bundles.add(new OSGiBundle(bc, admin, sl, bundle)); } TabularData table = OSGiBundle.tableFrom(bundles); return table; } catch (Throwable e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getExportedPackages() */ public String[] getExportedPackages(long bundleId) throws IOException { ExportedPackage[] packages = admin.getExportedPackages(bundle(bundleId)); if (packages == null) { return new String[0]; } String[] ep = new String[packages.length]; for (int i = 0; i < packages.length; i++) { ep[i] = packages[i].getName() + ";" + packages[i].getVersion(); } return ep; } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getFragments() */ public long[] getFragments(long bundleId) throws IOException { return Util.getBundleFragments(bundle(bundleId), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getHeaders(long) */ public TabularData getHeaders(long bundleId) throws IOException { return OSGiBundle.headerTable(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getHosts(long) */ public long[] getHosts(long fragment) throws IOException { Bundle[] hosts = admin.getHosts(bundle(fragment)); if (hosts == null) { return new long[0]; } return Util.bundleIds(hosts); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getImportedPackages() */ public String[] getImportedPackages(long bundleId) throws IOException { return Util.getBundleImportedPackages(bundle(bundleId), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getLastModified(long) */ public long getLastModified(long bundleId) throws IOException { return bundle(bundleId).getLastModified(); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getRegisteredServices() */ public long[] getRegisteredServices(long bundleId) throws IOException { return Util.serviceIds(bundle(bundleId).getRegisteredServices()); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getRequiringBundles() */ public long[] getRequiringBundles(long bundleIdentifier) throws IOException { return Util.getBundlesRequiring(bundle(bundleIdentifier), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getServicesInUse() */ public long[] getServicesInUse(long bundleIdentifier) throws IOException { return Util.serviceIds(bundle(bundleIdentifier).getServicesInUse()); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getStartLevel(long) */ public int getStartLevel(long bundleId) throws IOException { return sl.getBundleStartLevel(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getState(long) */ public String getState(long bundleId) throws IOException { return Util.getBundleState(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getSymbolicName(long) */ public String getSymbolicName(long bundleId) throws IOException { return bundle(bundleId).getSymbolicName(); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isBundlePersistentlyStarted(long) */ public boolean isPersistentlyStarted(long bundleId) throws IOException { return Util.isBundlePersistentlyStarted(bundle(bundleId), sl); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isFragment(long) */ public boolean isFragment(long bundleId) throws IOException { return Util.isBundleFragment(bundle(bundleId), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isRemovalPending(long) */ public boolean isRemovalPending(long bundleId) throws IOException { return Util.isRequiredBundleRemovalPending(bundle(bundleId), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isRequired(long) */ public boolean isRequired(long bundleId) throws IOException { return Util.isBundleRequired(bundle(bundleId), bc, admin); } private Bundle bundle(long bundleId) { Bundle b = bc.getBundle(bundleId); if (b == null) { throw new IllegalArgumentException("Bundle with id: " + bundleId + " does not exist"); } return b; } /* * (non-Javadoc) * * @see org.osgi.jmx.Monitor#addListener() */ @Override protected void addListener() { bundleListener = getBundleListener(); bc.addBundleListener(bundleListener); } protected BundleListener getBundleListener() { return new BundleListener() { public void bundleChanged(BundleEvent bundleEvent) { Notification notification = new Notification(BUNDLE_EVENT_TYPE, objectName, sequenceNumber++); notification.setUserData(new OSGiBundleEvent(bundleEvent) .asCompositeData()); sendNotification(notification); } }; } /* * (non-Javadoc) * * @see org.osgi.jmx.Monitor#removeListener() */ @Override protected void removeListener() { if (bundleListener != null) { bc.removeBundleListener(bundleListener); } } protected BundleListener bundleListener; protected BundleContext bc; protected StartLevel sl; protected PackageAdmin admin; }
org.osgi.impl.bundle.jmx/src/org/osgi/impl/bundle/jmx/framework/BundleState.java
/* * Copyright 2008 Oracle Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.osgi.impl.bundle.jmx.framework; import java.io.IOException; import java.util.ArrayList; import javax.management.Notification; import javax.management.openmbean.TabularData; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.impl.bundle.jmx.Monitor; import org.osgi.jmx.codec.OSGiBundle; import org.osgi.jmx.codec.OSGiBundleEvent; import org.osgi.jmx.codec.Util; import org.osgi.jmx.framework.BundleStateMBean; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; /** * */ public class BundleState extends Monitor implements BundleStateMBean { public BundleState(BundleContext bc, StartLevel sl, PackageAdmin admin) { this.bc = bc; this.sl = sl; this.admin = admin; } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getBundleDependencies() */ public long[] getDependencies(long bundleIdentifier) throws IOException { return Util.getBundleDependencies(bundle(bundleIdentifier), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getBundles() */ public TabularData getBundles() throws IOException { try { ArrayList<OSGiBundle> bundles = new ArrayList<OSGiBundle>(); for (Bundle bundle : bc.getBundles()) { bundles.add(new OSGiBundle(bc, admin, sl, bundle)); } TabularData table = OSGiBundle.tableFrom(bundles); return table; } catch (Throwable e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getExportedPackages() */ public String[] getExportedPackages(long bundleId) throws IOException { ExportedPackage[] packages = admin .getExportedPackages(bundle(bundleId)); String[] ep = new String[packages.length]; for (int i = 0; i < packages.length; i++) { ep[i] = packages[i].getName() + ";" + packages[i].getVersion(); } return ep; } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getFragments() */ public long[] getFragments(long bundleId) throws IOException { return Util.getBundleFragments(bundle(bundleId), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getHeaders(long) */ public TabularData getHeaders(long bundleId) throws IOException { return OSGiBundle.headerTable(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getHosts(long) */ public long[] getHosts(long fragment) throws IOException { return Util.bundleIds(admin.getHosts(bundle(fragment))); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getImportedPackages() */ public String[] getImportedPackages(long bundleId) throws IOException { return Util.getBundleImportedPackages(bundle(bundleId), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getLastModified(long) */ public long getLastModified(long bundleId) throws IOException { return bundle(bundleId).getLastModified(); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getRegisteredServices() */ public long[] getRegisteredServices(long bundleId) throws IOException { return Util.serviceIds(bundle(bundleId).getRegisteredServices()); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getRequiringBundles() */ public long[] getRequiringBundles(long bundleIdentifier) throws IOException { return Util.getBundlesRequiring(bundle(bundleIdentifier), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getServicesInUse() */ public long[] getServicesInUse(long bundleIdentifier) throws IOException { return Util.serviceIds(bundle(bundleIdentifier).getServicesInUse()); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getStartLevel(long) */ public int getStartLevel(long bundleId) throws IOException { return sl.getBundleStartLevel(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getState(long) */ public String getState(long bundleId) throws IOException { return Util.getBundleState(bundle(bundleId)); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#getSymbolicName(long) */ public String getSymbolicName(long bundleId) throws IOException { return bundle(bundleId).getSymbolicName(); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isBundlePersistentlyStarted(long) */ public boolean isPersistentlyStarted(long bundleId) throws IOException { return Util.isBundlePersistentlyStarted(bundle(bundleId), sl); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isFragment(long) */ public boolean isFragment(long bundleId) throws IOException { return Util.isBundleFragment(bundle(bundleId), admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isRemovalPending(long) */ public boolean isRemovalPending(long bundleId) throws IOException { return Util.isRequiredBundleRemovalPending(bundle(bundleId), bc, admin); } /* * (non-Javadoc) * * @see org.osgi.jmx.core.BundleStateMBean#isRequired(long) */ public boolean isRequired(long bundleId) throws IOException { return Util.isBundleRequired(bundle(bundleId), bc, admin); } private Bundle bundle(long bundleId) { Bundle b = bc.getBundle(bundleId); if (b == null) { throw new IllegalArgumentException("Bundle with id: " + bundleId + " does not exist"); } return b; } /* * (non-Javadoc) * * @see org.osgi.jmx.Monitor#addListener() */ @Override protected void addListener() { bundleListener = getBundleListener(); bc.addBundleListener(bundleListener); } protected BundleListener getBundleListener() { return new BundleListener() { public void bundleChanged(BundleEvent bundleEvent) { Notification notification = new Notification(BUNDLE_EVENT_TYPE, objectName, sequenceNumber++); notification.setUserData(new OSGiBundleEvent(bundleEvent) .asCompositeData()); sendNotification(notification); } }; } /* * (non-Javadoc) * * @see org.osgi.jmx.Monitor#removeListener() */ @Override protected void removeListener() { if (bundleListener != null) { bc.removeBundleListener(bundleListener); } } protected BundleListener bundleListener; protected BundleContext bc; protected StartLevel sl; protected PackageAdmin admin; }
fix for Bug 1323 and fix another potential NPE
org.osgi.impl.bundle.jmx/src/org/osgi/impl/bundle/jmx/framework/BundleState.java
fix for Bug 1323 and fix another potential NPE
Java
apache-2.0
0c2d2252caf3cf625f6093185aedd36ac73b042b
0
flyway/flyway,flyway/flyway
/* * Copyright 2010-2020 Redgate Software Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flywaydb.core.internal.database.snowflake; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.api.logging.Log; import org.flywaydb.core.api.logging.LogFactory; import org.flywaydb.core.internal.database.base.Database; import org.flywaydb.core.internal.database.base.Table; import org.flywaydb.core.internal.database.mysql.MySQLDatabase; import org.flywaydb.core.internal.jdbc.JdbcConnectionFactory; import org.flywaydb.core.internal.jdbc.JdbcTemplate; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; public class SnowflakeDatabase extends Database<SnowflakeConnection> { private static final Log LOG = LogFactory.getLog(SnowflakeDatabase.class); /** * Whether quoted identifiers are treated in a case-insensitive way. Defaults to false. See * https://docs.snowflake.com/en/sql-reference/identifiers-syntax.html#controlling-case-using-the-quoted-identifiers-ignore-case-parameter */ private final boolean quotedIdentifiersIgnoreCase; /** * Creates a new instance. */ public SnowflakeDatabase(Configuration configuration, JdbcConnectionFactory jdbcConnectionFactory ) { super(configuration, jdbcConnectionFactory ); quotedIdentifiersIgnoreCase = getQuotedIdentifiersIgnoreCase(jdbcTemplate); if (quotedIdentifiersIgnoreCase) { LOG.warn("Current Flyway history table can't be used with QUOTED_IDENTIFIERS_IGNORE_CASE option on"); } } private static boolean getQuotedIdentifiersIgnoreCase(JdbcTemplate jdbcTemplate) { try { // Attempt query List<Map<String, String>> result = jdbcTemplate.queryForList("SHOW PARAMETERS LIKE 'QUOTED_IDENTIFIERS_IGNORE_CASE'"); Map<String, String> row = result.get(0); return "TRUE".equals(row.get("value").toUpperCase()); } catch (SQLException e) { LOG.warn("Could not query for parameter QUOTED_IDENTIFIERS_IGNORE_CASE."); return false; } } @Override protected SnowflakeConnection doGetConnection(Connection connection) { return new SnowflakeConnection(this, connection); } @Override public void ensureSupported() { ensureDatabaseIsRecentEnough("3.0"); ensureDatabaseNotOlderThanOtherwiseRecommendUpgradeToFlywayEdition("3", org.flywaydb.core.internal.license.Edition.ENTERPRISE); recommendFlywayUpgradeIfNecessaryForMajorVersion("4.2"); } @Override public String getRawCreateScript(Table table, boolean baseline) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name leading to SELECTs failing. return "CREATE TABLE " + table + " (\n" + quote("installed_rank") + " NUMBER(38,0) NOT NULL,\n" + quote("version") + " VARCHAR(50),\n" + quote("description") + " VARCHAR(200),\n" + quote("type") + " VARCHAR(20) NOT NULL,\n" + quote("script") + " VARCHAR(1000) NOT NULL,\n" + quote("checksum") + " NUMBER(38,0),\n" + quote("installed_by") + " VARCHAR(100) NOT NULL,\n" + quote("installed_on") + " TIMESTAMP_LTZ(9) NOT NULL DEFAULT CURRENT_TIMESTAMP(),\n" + quote("execution_time") + " NUMBER(38,0) NOT NULL,\n" + quote("success") + " BOOLEAN NOT NULL,\n" + "primary key (" + quote("installed_rank") + "));\n" + (baseline ? getBaselineStatement(table) + ";\n" : ""); } @Override public String getSelectStatement(Table table) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name. In data readers, the column name is case sensitive. return "SELECT " + quote("installed_rank") + "," + quote("version") + "," + quote("description") + "," + quote("type") + "," + quote("script") + "," + quote("checksum") + "," + quote("installed_on") + "," + quote("installed_by") + "," + quote("execution_time") + "," + quote("success") + " FROM " + table + " WHERE " + quote("installed_rank") + " > ?" + " ORDER BY " + quote("installed_rank"); } @Override public String getInsertStatement(Table table) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name. return "INSERT INTO " + table + " (" + quote("installed_rank") + ", " + quote("version") + ", " + quote("description") + ", " + quote("type") + ", " + quote("script") + ", " + quote("checksum") + ", " + quote("installed_by") + ", " + quote("execution_time") + ", " + quote("success") + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; } @Override public boolean supportsDdlTransactions() { return false; } @Override public boolean supportsChangingCurrentSchema() { return true; } @Override public String getBooleanTrue() { return "true"; } @Override public String getBooleanFalse() { return "false"; } @Override public String doQuote(String identifier) { return "\"" + identifier + "\""; } @Override public boolean catalogIsSchema() { return false; } }
flyway-core/src/main/java/org/flywaydb/core/internal/database/snowflake/SnowflakeDatabase.java
/* * Copyright 2010-2020 Redgate Software Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flywaydb.core.internal.database.snowflake; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.internal.database.base.Database; import org.flywaydb.core.internal.database.base.Table; import org.flywaydb.core.internal.jdbc.JdbcConnectionFactory; import java.sql.Connection; public class SnowflakeDatabase extends Database<SnowflakeConnection> { /** * Creates a new instance. */ public SnowflakeDatabase(Configuration configuration, JdbcConnectionFactory jdbcConnectionFactory ) { super(configuration, jdbcConnectionFactory ); } @Override protected SnowflakeConnection doGetConnection(Connection connection) { return new SnowflakeConnection(this, connection); } @Override public void ensureSupported() { ensureDatabaseIsRecentEnough("3.0"); ensureDatabaseNotOlderThanOtherwiseRecommendUpgradeToFlywayEdition("3", org.flywaydb.core.internal.license.Edition.ENTERPRISE); recommendFlywayUpgradeIfNecessaryForMajorVersion("4.2"); } @Override public String getRawCreateScript(Table table, boolean baseline) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name leading to SELECTs failing. return "CREATE TABLE " + table + " (\n" + quote("installed_rank") + " NUMBER(38,0) NOT NULL,\n" + quote("version") + " VARCHAR(50),\n" + quote("description") + " VARCHAR(200),\n" + quote("type") + " VARCHAR(20) NOT NULL,\n" + quote("script") + " VARCHAR(1000) NOT NULL,\n" + quote("checksum") + " NUMBER(38,0),\n" + quote("installed_by") + " VARCHAR(100) NOT NULL,\n" + quote("installed_on") + " TIMESTAMP_LTZ(9) NOT NULL DEFAULT CURRENT_TIMESTAMP(),\n" + quote("execution_time") + " NUMBER(38,0) NOT NULL,\n" + quote("success") + " BOOLEAN NOT NULL,\n" + "primary key (" + quote("installed_rank") + "));\n" + (baseline ? getBaselineStatement(table) + ";\n" : ""); } @Override public String getSelectStatement(Table table) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name. In data readers, the column name is case sensitive. return "SELECT " + quote("installed_rank") + "," + quote("version") + "," + quote("description") + "," + quote("type") + "," + quote("script") + "," + quote("checksum") + "," + quote("installed_on") + "," + quote("installed_by") + "," + quote("execution_time") + "," + quote("success") + " FROM " + table + " WHERE " + quote("installed_rank") + " > ?" + " ORDER BY " + quote("installed_rank"); } @Override public String getInsertStatement(Table table) { // CAUTION: Quotes are optional around column names without underscores; but without them, Snowflake will // uppercase the column name. return "INSERT INTO " + table + " (" + quote("installed_rank") + ", " + quote("version") + ", " + quote("description") + ", " + quote("type") + ", " + quote("script") + ", " + quote("checksum") + ", " + quote("installed_by") + ", " + quote("execution_time") + ", " + quote("success") + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; } @Override public boolean supportsDdlTransactions() { return false; } @Override public boolean supportsChangingCurrentSchema() { return true; } @Override public String getBooleanTrue() { return "true"; } @Override public String getBooleanFalse() { return "false"; } @Override public String doQuote(String identifier) { return "\"" + identifier + "\""; } @Override public boolean catalogIsSchema() { return false; } }
#2731 Snowflake: detect quoted-identifiers-ignore-case setting
flyway-core/src/main/java/org/flywaydb/core/internal/database/snowflake/SnowflakeDatabase.java
#2731 Snowflake: detect quoted-identifiers-ignore-case setting
Java
apache-2.0
d407ecb5e4a225f387cc9b27a558d9f5ee478266
0
kay-kim/mongo-java-driver,jsonking/mongo-java-driver,PSCGroup/mongo-java-driver,rozza/mongo-java-driver,gianpaj/mongo-java-driver,rozza/mongo-java-driver,jyemin/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver
/* * Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mongodb; import java.util.List; import static org.mongodb.OrderBy.ASC; /** * Represents an index to create on the database. Used as an argument in ensureIndex */ public final class Index implements ConvertibleToDocument { private final String name; /** * Ensures that the indexed key value is unique */ private final boolean unique; /** * Tells the unique index to drop duplicates silently when creating; only the first will be kept */ private final boolean dropDups; /** * Create the index in the background */ private final boolean background; /** * Create the index with the sparse option */ private final boolean sparse; /** * defines the time to live for documents in the collection */ private final int expireAfterSeconds; private final Document keys; private final Document extra; private Index(final String name, final boolean unique, final boolean dropDups, final boolean sparse, final boolean background, final int expireAfterSeconds, final Document keys, final Document extra) { this.name = name; this.unique = unique; this.dropDups = dropDups; this.sparse = sparse; this.background = background; this.expireAfterSeconds = expireAfterSeconds; this.keys = keys; this.extra = extra; } public static Builder builder() { return new Builder(); } public String getName() { return name; } @Override public Document toDocument() { final Document indexDetails = new Document(); indexDetails.append("name", name); indexDetails.append("key", keys); if (unique) { indexDetails.append("unique", unique); } if (sparse) { indexDetails.append("sparse", sparse); } if (dropDups) { indexDetails.append("dropDups", dropDups); } if (background) { indexDetails.append("background", background); } if (expireAfterSeconds != -1) { indexDetails.append("expireAfterSeconds", expireAfterSeconds); } indexDetails.putAll(extra); return indexDetails; } /** * Contains the pair that is the field name and the ordering value for each key of an index */ public static class OrderedKey implements Key<Integer> { private final String fieldName; private final OrderBy orderBy; public OrderedKey(final String fieldName, final OrderBy orderBy) { this.fieldName = fieldName; this.orderBy = orderBy; } @Override public String getFieldName() { return fieldName; } @Override public Integer getValue() { return orderBy.getIntRepresentation(); } } public static class GeoKey implements Key<String> { private final String fieldName; public GeoKey(final String fieldName) { this.fieldName = fieldName; } @Override public String getFieldName() { return fieldName; } @Override public String getValue() { return "2d"; } } public interface Key<T> { String getFieldName(); T getValue(); } public static class Builder { private String name; private boolean unique = false; private boolean dropDups = false; private boolean background = false; private boolean sparse = false; private int expireAfterSeconds = -1; private final Document keys = new Document(); private final Document extra = new Document(); private Builder() { } /** * Sets the name of the index. */ public Builder name(final String indexName) { this.name = indexName; return this; } /** * Ensures that the indexed key value is unique */ public Builder unique() { unique = true; return this; } public Builder unique(final boolean value) { this.unique = value; return this; } /** * Tells the unique index to drop duplicates silently when creating; only the first will be kept */ public Builder dropDups() { dropDups = true; return this; } public Builder dropDups(final boolean value) { this.dropDups = value; return this; } /** * Create the index in the background */ public Builder background() { background = true; return this; } public Builder background(final boolean value) { this.background = value; return this; } /** * Create the index with the sparse option */ public Builder sparse() { sparse = true; return this; } public Builder sparse(final boolean value) { this.sparse = value; return this; } /** * Defines the time to live for documents in the collection */ public Builder expireAfterSeconds(final int seconds) { expireAfterSeconds = seconds; return this; } public Builder addKey(final String key) { return addKey(key, ASC); } public Builder addKeys(final String... keyNames) { for (final String keyName : keyNames) { addKey(keyName); } return this; } public Builder addKey(final String key, final OrderBy orderBy) { keys.put(key, orderBy.getIntRepresentation()); return this; } public Builder addKey(final Key<?> key) { keys.put(key.getFieldName(), key.getValue()); return this; } public Builder addKeys(final Key<?>... newKeys) { for (final Key<?> key : newKeys) { addKey(key); } return this; } public Builder addKeys(final List<Key<?>> newKeys) { for (final Key<?> key : newKeys) { addKey(key); } return this; } public Builder extra(final String key, final Object value) { extra.put(key, value); return this; } /** * Convenience method to generate an index name from the set of fields it is over. * * @return a string representation of this index's fields */ private String generateIndexName() { final StringBuilder indexName = new StringBuilder(); for (final String keyNames : this.keys.keySet()) { if (indexName.length() != 0) { indexName.append('_'); } indexName.append(keyNames).append('_'); //is this ever anything other than an int? final Object ascOrDescValue = this.keys.get(keyNames); if (ascOrDescValue instanceof Number || ascOrDescValue instanceof String) { indexName.append(ascOrDescValue.toString().replace(' ', '_')); } } return indexName.toString(); } public Index build() { if (name == null) { name = generateIndexName(); } return new Index(name, unique, dropDups, sparse, background, expireAfterSeconds, keys, extra); } } }
driver/src/main/org/mongodb/Index.java
/* * Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mongodb; import java.util.List; import static org.mongodb.OrderBy.ASC; /** * Represents an index to create on the database. Used as an argument in ensureIndex */ public class Index implements ConvertibleToDocument { private final String name; /** * Ensures that the indexed key value is unique */ private final boolean unique; /** * Tells the unique index to drop duplicates silently when creating; only the first will be kept */ private final boolean dropDups; /** * Create the index in the background */ private final boolean background; /** * Create the index with the sparse option */ private final boolean sparse; /** * defines the time to live for documents in the collection */ private final int expireAfterSeconds; private final Document keys; private final Document extra; private Index(final String name, final boolean unique, final boolean dropDups, final boolean sparse, final boolean background, final int expireAfterSeconds, final Document keys, final Document extra) { this.name = name; this.unique = unique; this.dropDups = dropDups; this.sparse = sparse; this.background = background; this.expireAfterSeconds = expireAfterSeconds; this.keys = keys; this.extra = extra; } public static Builder builder() { return new Builder(); } public String getName() { return name; } @Override public Document toDocument() { final Document indexDetails = new Document(); indexDetails.append("name", name); indexDetails.append("key", keys); if (unique) { indexDetails.append("unique", unique); } if (sparse) { indexDetails.append("sparse", sparse); } if (dropDups) { indexDetails.append("dropDups", dropDups); } if (background) { indexDetails.append("background", background); } if (expireAfterSeconds != -1) { indexDetails.append("expireAfterSeconds", expireAfterSeconds); } indexDetails.putAll(extra); return indexDetails; } /** * Contains the pair that is the field name and the ordering value for each key of an index */ public static class OrderedKey implements Key<Integer> { private final String fieldName; private final OrderBy orderBy; public OrderedKey(final String fieldName, final OrderBy orderBy) { this.fieldName = fieldName; this.orderBy = orderBy; } @Override public String getFieldName() { return fieldName; } @Override public Integer getValue() { return orderBy.getIntRepresentation(); } } public static class GeoKey implements Key<String> { private final String fieldName; public GeoKey(final String fieldName) { this.fieldName = fieldName; } @Override public String getFieldName() { return fieldName; } @Override public String getValue() { return "2d"; } } public interface Key<T> { String getFieldName(); T getValue(); } public static class Builder { private String name; private boolean unique = false; private boolean dropDups = false; private boolean background = false; private boolean sparse = false; private int expireAfterSeconds = -1; private final Document keys = new Document(); private final Document extra = new Document(); private Builder() { } /** * Sets the name of the index. */ public Builder name(final String indexName) { this.name = indexName; return this; } /** * Ensures that the indexed key value is unique */ public Builder unique() { unique = true; return this; } public Builder unique(final boolean value) { this.unique = value; return this; } /** * Tells the unique index to drop duplicates silently when creating; only the first will be kept */ public Builder dropDups() { dropDups = true; return this; } public Builder dropDups(final boolean value) { this.dropDups = value; return this; } /** * Create the index in the background */ public Builder background() { background = true; return this; } public Builder background(final boolean value) { this.background = value; return this; } /** * Create the index with the sparse option */ public Builder sparse() { sparse = true; return this; } public Builder sparse(final boolean value) { this.sparse = value; return this; } /** * Defines the time to live for documents in the collection */ public Builder expireAfterSeconds(final int seconds) { expireAfterSeconds = seconds; return this; } public Builder addKey(final String key) { return addKey(key, ASC); } public Builder addKeys(final String... keyNames) { for (final String keyName : keyNames) { addKey(keyName); } return this; } public Builder addKey(final String key, final OrderBy orderBy) { keys.put(key, orderBy.getIntRepresentation()); return this; } public Builder addKey(final Key<?> key) { keys.put(key.getFieldName(), key.getValue()); return this; } public Builder addKeys(final Key<?>... newKeys) { for (final Key<?> key : newKeys) { addKey(key); } return this; } public Builder addKeys(final List<Key<?>> newKeys) { for (final Key<?> key : newKeys) { addKey(key); } return this; } public Builder extra(final String key, final Object value) { extra.put(key, value); return this; } /** * Convenience method to generate an index name from the set of fields it is over. * * @return a string representation of this index's fields */ private String generateIndexName() { final StringBuilder indexName = new StringBuilder(); for (final String keyNames : this.keys.keySet()) { if (indexName.length() != 0) { indexName.append('_'); } indexName.append(keyNames).append('_'); //is this ever anything other than an int? final Object ascOrDescValue = this.keys.get(keyNames); if (ascOrDescValue instanceof Number || ascOrDescValue instanceof String) { indexName.append(ascOrDescValue.toString().replace(' ', '_')); } } return indexName.toString(); } public Index build() { if (name == null) { name = generateIndexName(); } return new Index(name, unique, dropDups, sparse, background, expireAfterSeconds, keys, extra); } } }
made class final
driver/src/main/org/mongodb/Index.java
made class final
Java
apache-2.0
352d7a81feadcd65d58d590f5b2fa2e15fbf59eb
0
aesteve/vertx-web,InfoSec812/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,aesteve/vertx-web,InfoSec812/vertx-web,aesteve/vertx-web,vert-x3/vertx-web,InfoSec812/vertx-web,vert-x3/vertx-web,InfoSec812/vertx-web,InfoSec812/vertx-web,aesteve/vertx-web,InfoSec812/vertx-web,aesteve/vertx-web,vert-x3/vertx-web
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.handler; import java.io.File; import java.io.IOException; import java.util.Set; import org.junit.AfterClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.WebTestBase; import io.vertx.test.core.TestUtils; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class BodyHandlerTest extends WebTestBase { @Rule public TemporaryFolder tempUploads = new TemporaryFolder(); @Override public void setUp() throws Exception { super.setUp(); router.route().handler(BodyHandler.create()); } @AfterClass public static void oneTimeTearDown() { Vertx vertx = Vertx.vertx(); if (vertx.fileSystem().existsBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY)) { vertx.fileSystem().deleteRecursiveBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, true); } } @Test public void testGETWithBody() throws Exception { router.route().handler(rc -> { assertNotNull(rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.GET, "/", 200, "OK"); } @Test public void testHEADWithBody() throws Exception { router.route().handler(rc -> { assertNotNull(rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.HEAD, "/", 200, "OK"); } @Test public void testBodyBuffer() throws Exception { Buffer buff = TestUtils.randomBuffer(1000); router.route().handler(rc -> { assertEquals(buff, rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 200, "OK", null); } @Test public void testBodyString() throws Exception { String str = "sausages"; router.route().handler(rc -> { assertEquals(str, rc.getBodyAsString()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(str); }, 200, "OK", null); } @Test public void testBodyStringEncoding() throws Exception { String str = TestUtils.randomUnicodeString(100); String enc = "UTF-16"; router.route().handler(rc -> { assertEquals(str, rc.getBodyAsString(enc)); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(str, enc); }, 200, "OK", null); } @Test public void testBodyJson() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithNegativeContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, "-1"); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithEmptyContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, ""); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithHugeContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(Long.MAX_VALUE)); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyTooBig() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(5000)); Buffer buff = TestUtils.randomBuffer(10000); router.route().handler(rc -> fail("Should not be called")); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 413, "Request Entity Too Large", null); } @Test public void testBodyTooBig2() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(500)); Buffer buff = TestUtils.randomBuffer(1000); router.route().handler(rc -> fail("Should not be called")); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 413, "Request Entity Too Large", null); } @Test public void testFileUploadSmallUpload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 50); } @Test // This size (7990) has caused issues in the past so testing it public void testFileUpload7990Upload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 7990); } @Test public void testFileUploadLargeUpload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 20000); } @Test public void testFileUploadDefaultUploadsDir() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 5000); } @Test public void testFileUploadOtherUploadsDir() throws Exception { router.clear(); File dir = tempUploads.newFolder(); router.route().handler(BodyHandler.create().setUploadsDirectory(dir.getPath())); testFileUpload(dir.getPath(), 5000); } private void testFileUpload(String uploadsDir, int size) throws Exception { String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; Buffer fileData = TestUtils.randomBuffer(size); router.route().handler(rc -> { Set<FileUpload> fileUploads = rc.fileUploads(); assertNotNull(fileUploads); assertEquals(1, fileUploads.size()); FileUpload upload = fileUploads.iterator().next(); assertEquals(name, upload.name()); assertEquals(fileName, upload.fileName()); assertEquals(contentType, upload.contentType()); assertEquals("binary", upload.contentTransferEncoding()); assertEquals(fileData.length(), upload.size()); String uploadedFileName = upload.uploadedFileName(); assertTrue(uploadedFileName.startsWith(uploadsDir + File.separator)); Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName); assertEquals(fileData, uploaded); // the data is upload as HTML form, so the body should be empty Buffer rawBody = rc.getBody(); assertEquals(0, rawBody.length()); rc.response().end(); }); sendFileUploadRequest(fileData, 200, "OK"); } @Test public void testFileUploadTooBig() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(20000)); Buffer fileData = TestUtils.randomBuffer(50000); router.route().handler(rc -> fail("Should not be called")); sendFileUploadRequest(fileData, 413, "Request Entity Too Large"); } @Test public void testFileUploadTooBig2() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(20000)); Buffer fileData = TestUtils.randomBuffer(50000); router.route().handler(rc -> fail("Should not be called")); sendFileUploadRequest(fileData, 413, "Request Entity Too Large"); } @Test public void testFileUploadNoFileRemovalOnEnd() throws Exception { testFileUploadFileRemoval(rc -> rc.response().end(), false, 200, "OK"); } @Test public void testFileUploadFileRemovalOnEnd() throws Exception { testFileUploadFileRemoval(rc -> rc.response().end(), true, 200, "OK"); } @Test public void testFileUploadFileRemovalOnError() throws Exception { testFileUploadFileRemoval(rc -> { throw new IllegalStateException(); }, true, 500, "Internal Server Error"); } @Test public void testFileUploadFileRemovalIfAlreadyRemoved() throws Exception { testFileUploadFileRemoval(rc -> { vertx.fileSystem().deleteBlocking(rc.fileUploads().iterator().next().uploadedFileName()); rc.response().end(); }, true, 200, "OK"); } @Test public void testFileDeleteOnLargeUpload() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setDeleteUploadedFilesOnEnd(true) .setBodyLimit(10000) .setUploadsDirectory(uploadsDirectory)); router.route().handler(ctx -> { fail(); ctx.fail(500); }); sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, "Request Entity Too Large"); Thread.sleep(100); // wait until file is removed assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } @Test public void testFileUploadFileRemovalOnClientClosesConnection() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setUploadsDirectory(uploadsDirectory)); assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); io.vertx.core.http.HttpClientRequest req = client.request(HttpMethod.POST, "/", ctx -> {}); String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); req.headers().set("content-length", String.valueOf(buffer.length() + 50)); //partial upload req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() == 0; i--) { Thread.sleep(100); //wait for upload beginning } assertEquals(1, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); req.connection().close(); for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() != 0; i--) { Thread.sleep(100); //wait for upload being deleted } System.out.println(vertx.fileSystem().readDirBlocking(uploadsDirectory)); assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } private void testFileUploadFileRemoval(Handler<RoutingContext> requestHandler, boolean deletedUploadedFilesOnEnd, int statusCode, String statusMessage) throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd) .setUploadsDirectory(uploadsDirectory)); router.route().handler(requestHandler); sendFileUploadRequest(TestUtils.randomBuffer(50), statusCode, statusMessage); int uploadedFilesAfterEnd = deletedUploadedFilesOnEnd ? 0 : 1; assertWaitUntil(() -> uploadedFilesAfterEnd == vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } private void sendFileUploadRequest(Buffer fileData, int statusCode, String statusMessage) throws Exception { String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(fileData); String footer = "\r\n--" + boundary + "--\r\n"; buffer.appendString(footer); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.setChunked(true); req.write(buffer); }, statusCode, statusMessage, null); } @Test public void testFormURLEncoded() throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(3, attrs.size()); assertEquals("junit-testUserAlias", attrs.get("origin")); assertEquals("admin@foo.bar", attrs.get("login")); assertEquals("admin", attrs.get("pass word")); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer); }, 200, "OK", null); } @Test public void testFormContentTypeIgnoreCase() throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(1, attrs.size()); assertEquals("junit-testUserAlias", attrs.get("origin")); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("origin=junit-testUserAlias"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "ApPlIcAtIoN/x-WwW-fOrM-uRlEnCoDeD"); req.write(buffer); }, 200, "OK", null); } @Test public void testFormMultipartFormDataMergeAttributesDefault() throws Exception { testFormMultipartFormData(true); } @Test public void testFormMultipartFormDataMergeAttributes() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setMergeFormAttributes(true)); testFormMultipartFormData(true); } @Test public void testFormMultipartFormDataNoMergeAttributes() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setMergeFormAttributes(false)); testFormMultipartFormData(false); } @Test public void testMultiFileUpload() throws Exception { int uploads = 1000; router.route().handler(rc -> { assertEquals(uploads, rc.fileUploads().size()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); for (int i = 0; i < uploads; i++) { String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file" + i + "\"; filename=\"file" + i + "\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(4096*16)); buffer.appendString("\r\n"); } buffer.appendString("--" + boundary + "\r\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } private void testFormMultipartFormData(boolean mergeAttributes) throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(2, attrs.size()); assertEquals("Tim", attrs.get("attr1")); assertEquals("Julien", attrs.get("attr2")); MultiMap params = rc.request().params(); if (mergeAttributes) { assertNotNull(params); assertEquals(3, params.size()); assertEquals("Tim", params.get("attr1")); assertEquals("Julien", params.get("attr2")); assertEquals("foo", params.get("p1")); } else { assertNotNull(params); assertEquals(1, params.size()); assertEquals("foo", params.get("p1")); } rc.response().end(); }); testRequest(HttpMethod.POST, "/?p1=foo", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String str = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr1\"\r\n\r\nTim\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr2\"\r\n\r\nJulien\r\n" + "--" + boundary + "--\r\n"; buffer.appendString(str); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } @Test public void testMixedUploadAndForm() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setUploadsDirectory(uploadsDirectory)); router.route().handler(ctx -> { assertEquals(0, ctx.getBody().length()); assertEquals(1, ctx.fileUploads().size()); ctx.response().end(); }); String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); String footer = "\r\n--" + boundary + "--\r\n"; buffer.appendString(footer); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", ""); } @Test public void testNoUploadDirMultiPartFormData() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); Buffer fileData = TestUtils.randomBuffer(50); router.route().handler(rc -> { rc.response().end(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); } @Test public void testFormMultipartFormDataWithAllowedFilesUploadFalse1() throws Exception { testFormMultipartFormDataWithAllowedFilesUploadFalse(true); } @Test public void testFormMultipartFormDataWithAllowedFilesUploadFalse2() throws Exception { testFormMultipartFormDataWithAllowedFilesUploadFalse(false); } private void testFormMultipartFormDataWithAllowedFilesUploadFalse(boolean mergeAttributes) throws Exception { String fileName = "test.bin"; router.clear(); router.route().handler(BodyHandler.create(false).setMergeFormAttributes(mergeAttributes)).handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(2, attrs.size()); assertEquals("Tim", attrs.get("attr1")); assertEquals("Tommaso", attrs.get("attr2")); MultiMap params = rc.request().params(); assertEquals(0, rc.fileUploads().size()); if (mergeAttributes) { assertNotNull(params); assertEquals(3, params.size()); assertEquals("Tim", params.get("attr1")); assertEquals("Tommaso", params.get("attr2")); assertEquals("foo", params.get("p1")); } else { assertNotNull(params); assertEquals(1, params.size()); assertEquals("foo", params.get("p1")); assertEquals("Tim", rc.request().getFormAttribute("attr1")); assertEquals("Tommaso", rc.request().getFormAttribute("attr2")); } rc.response().end(); }); testRequest(HttpMethod.POST, "/?p1=foo", req -> { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr1\"\r\n\r\nTim\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr2\"\r\n\r\nTommaso\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); buffer.appendString("\r\n--" + boundary + "--\r\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } @Test public void testNoUploadDirFormURLEncoded() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); testFormURLEncoded(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); } @Test public void testBodyHandlerCreateTrueWorks() throws Exception { router.clear(); router.route().handler(BodyHandler.create(true)); testFormURLEncoded(); } @Test public void testSetHandleFileUploads() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); BodyHandler bodyHandler = BodyHandler.create().setUploadsDirectory(dirName).setHandleFileUploads(false); router.route().handler(bodyHandler); Buffer fileData = TestUtils.randomBuffer(50); Route route = router.route().handler(rc -> { rc.response().end(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); route.remove(); bodyHandler.setHandleFileUploads(true); router.route().handler(rc -> { rc.response().end(); assertTrue("Upload directory must be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); } @Test public void testRerouteWithHandleFileUploadsFalse() throws Exception { String fileName = "test.bin"; router.clear(); router.route().handler(BodyHandler.create(false).setMergeFormAttributes(true)); router.route("/toBeRerouted").handler(rc -> { rc.reroute("/rerouted"); }); router.route("/rerouted").handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(2, attrs.size()); assertEquals("Tim", attrs.get("attr1")); assertEquals("Tommaso", attrs.get("attr2")); MultiMap params = rc.request().params(); assertEquals(0, rc.fileUploads().size()); assertNotNull(params); assertEquals(2, params.size()); assertEquals("Tim", params.get("attr1")); assertEquals("Tommaso", params.get("attr2")); rc.response().end(); }); testRequest(HttpMethod.POST, "/toBeRerouted", req -> { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr1\"\r\n\r\nTim\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr2\"\r\n\r\nTommaso\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); buffer.appendString("\r\n--" + boundary + "--\r\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } private String getNotCreatedTemporaryFolderName() throws IOException { File dir = tempUploads.newFolder(); dir.delete(); return dir.getPath(); } }
vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.handler; import java.io.File; import java.io.IOException; import java.util.Set; import org.junit.AfterClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.WebTestBase; import io.vertx.test.core.TestUtils; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class BodyHandlerTest extends WebTestBase { @Rule public TemporaryFolder tempUploads = new TemporaryFolder(); @Override public void setUp() throws Exception { super.setUp(); router.route().handler(BodyHandler.create()); } @AfterClass public static void oneTimeTearDown() { Vertx vertx = Vertx.vertx(); if (vertx.fileSystem().existsBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY)) { vertx.fileSystem().deleteRecursiveBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, true); } } @Test public void testGETWithBody() throws Exception { router.route().handler(rc -> { assertNotNull(rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.GET, "/", 200, "OK"); } @Test public void testHEADWithBody() throws Exception { router.route().handler(rc -> { assertNotNull(rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.HEAD, "/", 200, "OK"); } @Test public void testBodyBuffer() throws Exception { Buffer buff = TestUtils.randomBuffer(1000); router.route().handler(rc -> { assertEquals(buff, rc.getBody()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 200, "OK", null); } @Test public void testBodyString() throws Exception { String str = "sausages"; router.route().handler(rc -> { assertEquals(str, rc.getBodyAsString()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(str); }, 200, "OK", null); } @Test public void testBodyStringEncoding() throws Exception { String str = TestUtils.randomUnicodeString(100); String enc = "UTF-16"; router.route().handler(rc -> { assertEquals(str, rc.getBodyAsString(enc)); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(str, enc); }, 200, "OK", null); } @Test public void testBodyJson() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithNegativeContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, "-1"); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithEmptyContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, ""); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyJsonWithHugeContentLength() throws Exception { JsonObject json = new JsonObject().put("foo", "bar").put("blah", 123); router.route().handler(rc -> { assertEquals(json, rc.getBodyAsJson()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(Long.MAX_VALUE)); req.write(json.encode()); }, 200, "OK", null); } @Test public void testBodyTooBig() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(5000)); Buffer buff = TestUtils.randomBuffer(10000); router.route().handler(rc -> fail("Should not be called")); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 413, "Request Entity Too Large", null); } @Test public void testBodyTooBig2() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(500)); Buffer buff = TestUtils.randomBuffer(1000); router.route().handler(rc -> fail("Should not be called")); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(buff); }, 413, "Request Entity Too Large", null); } @Test public void testFileUploadSmallUpload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 50); } @Test // This size (7990) has caused issues in the past so testing it public void testFileUpload7990Upload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 7990); } @Test public void testFileUploadLargeUpload() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 20000); } @Test public void testFileUploadDefaultUploadsDir() throws Exception { testFileUpload(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, 5000); } @Test public void testFileUploadOtherUploadsDir() throws Exception { router.clear(); File dir = tempUploads.newFolder(); router.route().handler(BodyHandler.create().setUploadsDirectory(dir.getPath())); testFileUpload(dir.getPath(), 5000); } private void testFileUpload(String uploadsDir, int size) throws Exception { String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; Buffer fileData = TestUtils.randomBuffer(size); router.route().handler(rc -> { Set<FileUpload> fileUploads = rc.fileUploads(); assertNotNull(fileUploads); assertEquals(1, fileUploads.size()); FileUpload upload = fileUploads.iterator().next(); assertEquals(name, upload.name()); assertEquals(fileName, upload.fileName()); assertEquals(contentType, upload.contentType()); assertEquals("binary", upload.contentTransferEncoding()); assertEquals(fileData.length(), upload.size()); String uploadedFileName = upload.uploadedFileName(); assertTrue(uploadedFileName.startsWith(uploadsDir + File.separator)); Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName); assertEquals(fileData, uploaded); // the data is upload as HTML form, so the body should be empty Buffer rawBody = rc.getBody(); assertEquals(0, rawBody.length()); rc.response().end(); }); sendFileUploadRequest(fileData, 200, "OK"); } @Test public void testFileUploadTooBig() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(20000)); Buffer fileData = TestUtils.randomBuffer(50000); router.route().handler(rc -> fail("Should not be called")); sendFileUploadRequest(fileData, 413, "Request Entity Too Large"); } @Test public void testFileUploadTooBig2() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setBodyLimit(20000)); Buffer fileData = TestUtils.randomBuffer(50000); router.route().handler(rc -> fail("Should not be called")); sendFileUploadRequest(fileData, 413, "Request Entity Too Large"); } @Test public void testFileUploadNoFileRemovalOnEnd() throws Exception { testFileUploadFileRemoval(rc -> rc.response().end(), false, 200, "OK"); } @Test public void testFileUploadFileRemovalOnEnd() throws Exception { testFileUploadFileRemoval(rc -> rc.response().end(), true, 200, "OK"); } @Test public void testFileUploadFileRemovalOnError() throws Exception { testFileUploadFileRemoval(rc -> { throw new IllegalStateException(); }, true, 500, "Internal Server Error"); } @Test public void testFileUploadFileRemovalIfAlreadyRemoved() throws Exception { testFileUploadFileRemoval(rc -> { vertx.fileSystem().deleteBlocking(rc.fileUploads().iterator().next().uploadedFileName()); rc.response().end(); }, true, 200, "OK"); } @Test public void testFileDeleteOnLargeUpload() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setDeleteUploadedFilesOnEnd(true) .setBodyLimit(10000) .setUploadsDirectory(uploadsDirectory)); router.route().handler(ctx -> { fail(); ctx.fail(500); }); sendFileUploadRequest(TestUtils.randomBuffer(20000), 413, "Request Entity Too Large"); Thread.sleep(100); // wait until file is removed assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } @Test public void testFileUploadFileRemovalOnClientClosesConnection() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setUploadsDirectory(uploadsDirectory)); assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); io.vertx.core.http.HttpClientRequest req = client.request(HttpMethod.POST, "/", ctx -> {}); String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); req.headers().set("content-length", String.valueOf(buffer.length() + 50)); //partial upload req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() == 0; i--) { Thread.sleep(100); //wait for upload beginning } assertEquals(1, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); req.connection().close(); for (int i = 100; i > 0 && vertx.fileSystem().readDirBlocking(uploadsDirectory).size() != 0; i--) { Thread.sleep(100); //wait for upload being deleted } System.out.println(vertx.fileSystem().readDirBlocking(uploadsDirectory)); assertEquals(0, vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } private void testFileUploadFileRemoval(Handler<RoutingContext> requestHandler, boolean deletedUploadedFilesOnEnd, int statusCode, String statusMessage) throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setDeleteUploadedFilesOnEnd(deletedUploadedFilesOnEnd) .setUploadsDirectory(uploadsDirectory)); router.route().handler(requestHandler); sendFileUploadRequest(TestUtils.randomBuffer(50), statusCode, statusMessage); int uploadedFilesAfterEnd = deletedUploadedFilesOnEnd ? 0 : 1; assertWaitUntil(() -> uploadedFilesAfterEnd == vertx.fileSystem().readDirBlocking(uploadsDirectory).size()); } private void sendFileUploadRequest(Buffer fileData, int statusCode, String statusMessage) throws Exception { String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(fileData); String footer = "\r\n--" + boundary + "--\r\n"; buffer.appendString(footer); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.setChunked(true); req.write(buffer); }, statusCode, statusMessage, null); } @Test public void testFormURLEncoded() throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(3, attrs.size()); assertEquals("junit-testUserAlias", attrs.get("origin")); assertEquals("admin@foo.bar", attrs.get("login")); assertEquals("admin", attrs.get("pass word")); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer); }, 200, "OK", null); } @Test public void testFormContentTypeIgnoreCase() throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(1, attrs.size()); assertEquals("junit-testUserAlias", attrs.get("origin")); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("origin=junit-testUserAlias"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "ApPlIcAtIoN/x-WwW-fOrM-uRlEnCoDeD"); req.write(buffer); }, 200, "OK", null); } @Test public void testFormMultipartFormDataMergeAttributesDefault() throws Exception { testFormMultipartFormData(true); } @Test public void testFormMultipartFormDataMergeAttributes() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setMergeFormAttributes(true)); testFormMultipartFormData(true); } @Test public void testFormMultipartFormDataNoMergeAttributes() throws Exception { router.clear(); router.route().handler(BodyHandler.create().setMergeFormAttributes(false)); testFormMultipartFormData(false); } @Test public void testMultiFileUpload() throws Exception { int uploads = 1000; router.route().handler(rc -> { assertEquals(uploads, rc.fileUploads().size()); rc.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); for (int i = 0; i < uploads; i++) { String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file" + i + "\"; filename=\"file" + i + "\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(4096*16)); buffer.appendString("\r\n"); } buffer.appendString("--" + boundary + "\r\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } private void testFormMultipartFormData(boolean mergeAttributes) throws Exception { router.route().handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(2, attrs.size()); assertEquals("Tim", attrs.get("attr1")); assertEquals("Julien", attrs.get("attr2")); MultiMap params = rc.request().params(); if (mergeAttributes) { assertNotNull(params); assertEquals(3, params.size()); assertEquals("Tim", params.get("attr1")); assertEquals("Julien", params.get("attr2")); assertEquals("foo", params.get("p1")); } else { assertNotNull(params); assertEquals(1, params.size()); assertEquals("foo", params.get("p1")); } rc.response().end(); }); testRequest(HttpMethod.POST, "/?p1=foo", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String str = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr1\"\r\n\r\nTim\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr2\"\r\n\r\nJulien\r\n" + "--" + boundary + "--\r\n"; buffer.appendString(str); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } @Test public void testMixedUploadAndForm() throws Exception { String uploadsDirectory = tempUploads.newFolder().getPath(); router.clear(); router.route().handler(BodyHandler.create() .setUploadsDirectory(uploadsDirectory)); router.route().handler(ctx -> { assertEquals(0, ctx.getBody().length()); assertEquals(1, ctx.fileUploads().size()); ctx.response().end(); }); String name = "somename"; String fileName = "somefile.dat"; String contentType = "application/octet-stream"; testRequest(HttpMethod.POST, "/", req -> { String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); String footer = "\r\n--" + boundary + "--\r\n"; buffer.appendString(footer); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", ""); } @Test public void testNoUploadDirMultiPartFormData() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); Buffer fileData = TestUtils.randomBuffer(50); router.route().handler(rc -> { rc.response().end(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); } @Test public void testFormMultipartFormDataWithAllowedFilesUploadFalse1() throws Exception { testFormMultipartFormDataWithAllowedFilesUploadFalse(true); } @Test public void testFormMultipartFormDataWithAllowedFilesUploadFalse2() throws Exception { testFormMultipartFormDataWithAllowedFilesUploadFalse(false); } private void testFormMultipartFormDataWithAllowedFilesUploadFalse(boolean mergeAttributes) throws Exception { String fileName = "test.bin"; router.clear(); router.route().handler(BodyHandler.create(false).setMergeFormAttributes(mergeAttributes)).handler(rc -> { MultiMap attrs = rc.request().formAttributes(); assertNotNull(attrs); assertEquals(2, attrs.size()); assertEquals("Tim", attrs.get("attr1")); assertEquals("Tommaso", attrs.get("attr2")); MultiMap params = rc.request().params(); assertEquals(0, rc.fileUploads().size()); if (mergeAttributes) { assertNotNull(params); assertEquals(3, params.size()); assertEquals("Tim", params.get("attr1")); assertEquals("Tommaso", params.get("attr2")); assertEquals("foo", params.get("p1")); } else { assertNotNull(params); assertEquals(1, params.size()); assertEquals("foo", params.get("p1")); assertEquals("Tim", rc.request().getFormAttribute("attr1")); assertEquals("Tommaso", rc.request().getFormAttribute("attr2")); } rc.response().end(); }); testRequest(HttpMethod.POST, "/?p1=foo", req -> { Buffer buffer = Buffer.buffer(); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; String header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr1\"\r\n\r\nTim\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"attr2\"\r\n\r\nTommaso\r\n" + "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: application/octet-stream\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n"; buffer.appendString(header); buffer.appendBuffer(TestUtils.randomBuffer(50)); buffer.appendString("\r\n--" + boundary + "--\r\n"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer); }, 200, "OK", null); } @Test public void testNoUploadDirFormURLEncoded() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); router.route().handler(BodyHandler.create(false).setUploadsDirectory(dirName)); testFormURLEncoded(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); } @Test public void testBodyHandlerCreateTrueWorks() throws Exception { router.clear(); router.route().handler(BodyHandler.create(true)); testFormURLEncoded(); } @Test public void testSetHandleFileUploads() throws Exception { String dirName = getNotCreatedTemporaryFolderName(); router.clear(); BodyHandler bodyHandler = BodyHandler.create().setUploadsDirectory(dirName).setHandleFileUploads(false); router.route().handler(bodyHandler); Buffer fileData = TestUtils.randomBuffer(50); Route route = router.route().handler(rc -> { rc.response().end(); assertFalse("Upload directory must not be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); route.remove(); bodyHandler.setHandleFileUploads(true); router.route().handler(rc -> { rc.response().end(); assertTrue("Upload directory must be created.", vertx.fileSystem().existsBlocking(dirName)); }); sendFileUploadRequest(fileData, 200, "OK"); } private String getNotCreatedTemporaryFolderName() throws IOException { File dir = tempUploads.newFolder(); dir.delete(); return dir.getPath(); } }
Added test for rerouting Signed-off-by: tnolli <addb5f477467ab6800a8e9705443449c0e8e8b7c@gmail.com>
vertx-web/src/test/java/io/vertx/ext/web/handler/BodyHandlerTest.java
Added test for rerouting
Java
apache-2.0
4a5506ef72c011939967ac808f3642aa4dd0df47
0
tuxarb/profiling
package app.model; import app.model.beans.Characteristic; import app.model.enums.DatabaseTypes; import app.utils.Log; import app.utils.Utils; import app.utils.exceptions.ClientProcessException; import app.utils.exceptions.WrongSelectedDatabaseException; import org.slf4j.Logger; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.Properties; import java.util.Scanner; import static app.utils.Utils.getUserCommandInfo; public class Model { private final Characteristic characteristic; private PointsList points; private long processId; private ProcessHandle task; private volatile boolean isTaskCompleted; private volatile boolean isDetailedTest; private int numberTests; private static final int DEFAULT_NUMBER_TESTS = 3; private static final PropertyRepository PROPERTY_REPOSITORY = PropertyRepository.getInstance(); private static final Logger LOG = Log.createLog(Model.class); public Model(final Characteristic characteristic) { this.characteristic = characteristic; } public void startTestForWindows() throws IOException, ClientProcessException { points = new PointsList(); BigInteger capacity = BigInteger.valueOf(0); long countIterations = 0; long currentTimeAfterStart = 0; long startTime = startTestAndGetStartTime(); Process process; Scanner scanner; while (task.isAlive()) { process = execute("tasklist /v /fo list /fi \"PID eq \"" + processId); scanner = new Scanner(process.getInputStream(), "cp866"); while (scanner.hasNext()) { String newLine = scanner.nextLine(); if (Utils.isMemoryLine(newLine.toLowerCase())) { capacity = capacity.add( BigInteger.valueOf(Utils.getNumberFromString(newLine)) ); currentTimeAfterStart = System.currentTimeMillis() - startTime; points.add(points.new Point(capacity, currentTimeAfterStart)); countIterations++; break; } } } checkCountOfIterationsOnZero(countIterations); computeAndSetResultingData(capacity, currentTimeAfterStart, countIterations); } public void startTestForLinuxOrMac() throws IOException, ClientProcessException { points = new PointsList(); BigInteger capacity = BigInteger.valueOf(0); long countIterations = 0; long currentTimeAfterStart = 0; long startTime = startTestAndGetStartTime(); Process process; Scanner scanner; while (task.isAlive()) { process = execute("ps -p " + processId + " -o rss"); scanner = new Scanner(process.getInputStream()); while (scanner.hasNext()) { String newLine = scanner.nextLine(); if (!newLine.matches("^\\D*")) { capacity = capacity.add( BigInteger.valueOf(Utils.getNumberFromString(newLine)) ); currentTimeAfterStart = System.currentTimeMillis() - startTime; points.add(points.new Point(capacity, currentTimeAfterStart)); countIterations++; break; } } } checkCountOfIterationsOnZero(countIterations); computeAndSetResultingData(capacity, currentTimeAfterStart, countIterations); } private void computeAndSetResultingData(BigInteger capacity, long time, long countIterations) { LOG.info(Log.RUNNING_CODE_ENDED); capacity = capacity.divide( BigInteger.valueOf(countIterations) ); long speed = 1000 * capacity.longValue() / time; points.computeSpeedForAllPoints(); setResultingData(capacity.longValue(), speed, time); LOG.info(Log.READING_PROCESS_ENDED); } private long startTestAndGetStartTime() throws ClientProcessException { boolean isScriptFile = false; String pathToProgram = PROPERTY_REPOSITORY.getProperties().getProperty("program_path"); if (pathToProgram.isEmpty()) { pathToProgram = PROPERTY_REPOSITORY.getProperties().getProperty("script_file_path"); if (pathToProgram.isEmpty()) { LOG.error(Log.EMPTY_PATH); throw new ClientProcessException(Log.EMPTY_PATH_MESSAGE); } isScriptFile = true; } long startTime = System.currentTimeMillis(); createAndRunUserProcess(pathToProgram, isScriptFile); return startTime; } private void createAndRunUserProcess(String pathToProgram, boolean isScriptFile) throws ClientProcessException { LOG.info(Log.READING_PROCESS_STARTED); try { execute(pathToProgram); if (isScriptFile) { long startTime = System.currentTimeMillis(); while (true) { if (ProcessHandle.current().descendants().count() == 2) { processId = ProcessHandle.current() .children() .findFirst() .orElseThrow(() -> new Exception(Log.SMALL_PROGRAM_ERROR)) .children() .findFirst() .orElseThrow(() -> new Exception(Log.SMALL_PROGRAM_ERROR)) .getPid(); break; } if (System.currentTimeMillis() - startTime > 700) { throw new Exception(Log.ERROR_WHEN_CREATING_USER_PROCESS_FROM_SCRIPT_FILE); } } } else { processId = ProcessHandle.current() .children() .findFirst() .orElseThrow(() -> new Exception(Log.ERROR_WHEN_CREATING_USER_PROCESS)) .getPid(); } task = ProcessHandle.of(processId) .orElseThrow(() -> new Exception(Log.PATH_TO_PROGRAM_INCORRECT)); } catch (Exception e) { killAllChildrenProcesses(); LOG.error(e.getMessage()); throw new ClientProcessException(); } new Thread(() -> LOG.info(Log.RUNNING_CODE_STARTED + getUserCommandInfo(task)) ).start(); } private Process execute(String command) throws IOException { return Runtime.getRuntime().exec(command); } private void checkCountOfIterationsOnZero(long countIterations) throws ClientProcessException { if (countIterations == 0) { LOG.error(Log.SMALL_PROGRAM_ERROR); throw new ClientProcessException(Log.SMALL_PROGRAM_ERROR); } } void setResultingData(long capacity, long speed, long runtime) { characteristic.setCapacity(Utils.formatNumber(capacity) + " kB"); characteristic.setSpeed(Utils.formatNumber(speed) + " kB/s"); String timeAsString = Utils.formatNumber(runtime); characteristic.setRuntime((runtime < 1000 ? "0," + timeAsString : timeAsString) + " s"); } public void exit() { LOG.debug(Log.CLOSING_APP); killAllChildrenProcesses(); System.exit(0); } private void killAllChildrenProcesses() { ProcessHandle.current() .descendants() .forEach(ProcessHandle::destroyForcibly); } public void writeToFile() throws IOException { Properties properties = PROPERTY_REPOSITORY.getProperties(); characteristic.setTaskName(properties.getProperty("program_name")); String pathToUserFolderForSaveResult = properties.getProperty("result_file_path"); app.model.FileWriter fileWriter = new app.model.FileWriter(characteristic, pathToUserFolderForSaveResult); fileWriter.write(); } public void writeToDatabase(DatabaseTypes type) throws IOException, WrongSelectedDatabaseException { DatabaseWriter dw = new DatabaseWriter(type); Properties properties = PROPERTY_REPOSITORY.getProperties(); dw.setUrl(properties.getProperty("url")); dw.setUsername(properties.getProperty("user")); dw.setPassword(properties.getProperty("password")); String programName = properties.getProperty("program_name"); if (!programName.isEmpty()) { characteristic.setTaskName(programName); } dw.initProperties(); dw.setSessionFactory(); try { dw.write(characteristic); } catch (Exception e) { LOG.error(Log.HIBERNATE_ERROR); throw new IOException(e); } } public void readPropertyFile(File file) throws Exception { PROPERTY_REPOSITORY.setPropertyFile(file); } public void completed() { this.isTaskCompleted = true; } public boolean isTaskCompleted() { return isTaskCompleted; } public void setTaskCompleted(boolean isCompleted) { this.isTaskCompleted = isCompleted; } public boolean isDetailedTest() { return isDetailedTest; } public void setDetailedTest(boolean detailedTest) { isDetailedTest = detailedTest; } public int getNumberTests() { return numberTests; } public void setNumberTests() { try { numberTests = Integer.valueOf( PROPERTY_REPOSITORY.getProperties().getProperty("number_tests") ); if (numberTests >= 2 && numberTests <= 999) { return; } LOG.warn(Log.NUMBER_TESTS_RANGE_EXCEPTION + DEFAULT_NUMBER_TESTS + "."); } catch (NumberFormatException e) { LOG.warn(Log.NUMBER_TESTS_FORMAT_EXCEPTION + DEFAULT_NUMBER_TESTS + "."); } numberTests = DEFAULT_NUMBER_TESTS; } public Characteristic getCharacteristic() { return characteristic; } public PropertyRepository getPropertyRepository() { return PROPERTY_REPOSITORY; } public PointsList getPoints() { return points; } }
src/main/java/app/model/Model.java
package app.model; import app.model.beans.Characteristic; import app.model.enums.DatabaseTypes; import app.utils.Log; import app.utils.Utils; import app.utils.exceptions.ClientProcessException; import app.utils.exceptions.WrongSelectedDatabaseException; import org.slf4j.Logger; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.Properties; import java.util.Scanner; import static app.utils.Utils.getUserCommandInfo; public class Model { private final Characteristic characteristic; private PointsList points; private long processId; private ProcessHandle task; private volatile boolean isTaskCompleted; private volatile boolean isDetailedTest; private int numberTests; private static final int DEFAULT_NUMBER_TESTS = 3; private static final PropertyRepository PROPERTY_REPOSITORY = PropertyRepository.getInstance(); private static final Logger LOG = Log.createLog(Model.class); public Model(final Characteristic characteristic) { this.characteristic = characteristic; } public void startTestForWindows() throws IOException, ClientProcessException { points = new PointsList(); BigInteger capacity = BigInteger.valueOf(0); long countIterations = 0; long startTime = startTestAndGetStartTime(); Process process; Scanner scanner; while (task.isAlive()) { process = execute("tasklist /v /fo list /fi \"PID eq \"" + processId); scanner = new Scanner(process.getInputStream(), "cp866"); while (scanner.hasNext()) { String newLine = scanner.nextLine(); if (Utils.isMemoryLine(newLine.toLowerCase())) { capacity = capacity.add( BigInteger.valueOf(Utils.getNumberFromString(newLine)) ); long currentTimeAfterStart = System.currentTimeMillis() - startTime; points.add(points.new Point(capacity, currentTimeAfterStart)); countIterations++; break; } } } checkCountOfIterationsOnZero(countIterations); long time = getTestTime(startTime); capacity = capacity.divide( BigInteger.valueOf(countIterations) ); long speed = 1000 * capacity.longValue() / time; points.computeSpeedForAllPoints(); setResultingData(capacity.longValue(), speed, time); LOG.info(Log.READING_PROCESS_ENDED); } public void startTestForLinuxOrMac() throws IOException, ClientProcessException { BigInteger capacity = BigInteger.valueOf(0); long countIterations = 0; long startTime = startTestAndGetStartTime(); Process process; Scanner scanner; while (task.isAlive()) { process = execute("ps -p " + processId + " -o rss"); scanner = new Scanner(process.getInputStream()); while (scanner.hasNext()) { String newLine = scanner.nextLine(); if (!newLine.matches("^\\D*")) { capacity = capacity.add( BigInteger.valueOf(Utils.getNumberFromString(newLine)) ); countIterations++; break; } } } checkCountOfIterationsOnZero(countIterations); long time = getTestTime(startTime); capacity = capacity.divide( BigInteger.valueOf(countIterations) ); long speed = 1000 * capacity.longValue() / time; setResultingData(capacity.longValue(), speed, time); LOG.info(Log.READING_PROCESS_ENDED); } private long startTestAndGetStartTime() throws ClientProcessException { boolean isScriptFile = false; String pathToProgram = PROPERTY_REPOSITORY.getProperties().getProperty("program_path"); if (pathToProgram.isEmpty()) { pathToProgram = PROPERTY_REPOSITORY.getProperties().getProperty("script_file_path"); if (pathToProgram.isEmpty()) { LOG.error(Log.EMPTY_PATH); throw new ClientProcessException(Log.EMPTY_PATH_MESSAGE); } isScriptFile = true; } long startTime = System.currentTimeMillis(); createAndRunUserProcess(pathToProgram, isScriptFile); return startTime; } private void createAndRunUserProcess(String pathToProgram, boolean isScriptFile) throws ClientProcessException { LOG.info(Log.READING_PROCESS_STARTED); try { execute(pathToProgram); if (isScriptFile) { long startTime = System.currentTimeMillis(); while (true) { if (ProcessHandle.current().descendants().count() == 2) { processId = ProcessHandle.current() .children() .findFirst() .orElseThrow(() -> new Exception(Log.SMALL_PROGRAM_ERROR)) .children() .findFirst() .orElseThrow(() -> new Exception(Log.SMALL_PROGRAM_ERROR)) .getPid(); break; } if (System.currentTimeMillis() - startTime > 700) { throw new Exception(Log.ERROR_WHEN_CREATING_USER_PROCESS_FROM_SCRIPT_FILE); } } } else { processId = ProcessHandle.current() .children() .findFirst() .orElseThrow(() -> new Exception(Log.ERROR_WHEN_CREATING_USER_PROCESS)) .getPid(); } task = ProcessHandle.of(processId) .orElseThrow(() -> new Exception(Log.PATH_TO_PROGRAM_INCORRECT)); } catch (Exception e) { killAllChildrenProcesses(); LOG.error(e.getMessage()); throw new ClientProcessException(); } new Thread(() -> LOG.info(Log.RUNNING_CODE_STARTED + getUserCommandInfo(task)) ).start(); } private Process execute(String command) throws IOException { return Runtime.getRuntime().exec(command); } private long getTestTime(long startTime) { LOG.info(Log.RUNNING_CODE_ENDED); return System.currentTimeMillis() - startTime; } private void checkCountOfIterationsOnZero(long countIterations) throws ClientProcessException { if (countIterations == 0) { LOG.error(Log.SMALL_PROGRAM_ERROR); throw new ClientProcessException(Log.SMALL_PROGRAM_ERROR); } } void setResultingData(long capacity, long speed, long runtime) { characteristic.setCapacity(Utils.formatNumber(capacity) + " kB"); characteristic.setSpeed(Utils.formatNumber(speed) + " kB/s"); String timeAsString = Utils.formatNumber(runtime); characteristic.setRuntime((runtime < 1000 ? "0," + timeAsString : timeAsString) + " s"); } public void exit() { LOG.debug(Log.CLOSING_APP); killAllChildrenProcesses(); System.exit(0); } private void killAllChildrenProcesses() { ProcessHandle.current() .descendants() .forEach(ProcessHandle::destroyForcibly); } public void writeToFile() throws IOException { Properties properties = PROPERTY_REPOSITORY.getProperties(); characteristic.setTaskName(properties.getProperty("program_name")); String pathToUserFolderForSaveResult = properties.getProperty("result_file_path"); app.model.FileWriter fileWriter = new app.model.FileWriter(characteristic, pathToUserFolderForSaveResult); fileWriter.write(); } public void writeToDatabase(DatabaseTypes type) throws IOException, WrongSelectedDatabaseException { DatabaseWriter dw = new DatabaseWriter(type); Properties properties = PROPERTY_REPOSITORY.getProperties(); dw.setUrl(properties.getProperty("url")); dw.setUsername(properties.getProperty("user")); dw.setPassword(properties.getProperty("password")); String programName = properties.getProperty("program_name"); if (!programName.isEmpty()) { characteristic.setTaskName(programName); } dw.initProperties(); dw.setSessionFactory(); try { dw.write(characteristic); } catch (Exception e) { LOG.error(Log.HIBERNATE_ERROR); throw new IOException(e); } } public void readPropertyFile(File file) throws Exception { PROPERTY_REPOSITORY.setPropertyFile(file); } public void completed() { this.isTaskCompleted = true; } public boolean isTaskCompleted() { return isTaskCompleted; } public void setTaskCompleted(boolean isCompleted) { this.isTaskCompleted = isCompleted; } public boolean isDetailedTest() { return isDetailedTest; } public void setDetailedTest(boolean detailedTest) { isDetailedTest = detailedTest; } public int getNumberTests() { return numberTests; } public void setNumberTests() { try { numberTests = Integer.valueOf( PROPERTY_REPOSITORY.getProperties().getProperty("number_tests") ); if (numberTests >= 2 && numberTests <= 999) { return; } LOG.warn(Log.NUMBER_TESTS_RANGE_EXCEPTION + DEFAULT_NUMBER_TESTS + "."); } catch (NumberFormatException e) { LOG.warn(Log.NUMBER_TESTS_FORMAT_EXCEPTION + DEFAULT_NUMBER_TESTS + "."); } numberTests = DEFAULT_NUMBER_TESTS; } public Characteristic getCharacteristic() { return characteristic; } public PropertyRepository getPropertyRepository() { return PROPERTY_REPOSITORY; } public PointsList getPoints() { return points; } }
refactored model.
src/main/java/app/model/Model.java
refactored model.
Java
apache-2.0
dd03e3e6b6270b1fb5aeb9500ae9181d88814f6c
0
sopeco/DynamicSpotter,CloudScale-Project/DynamicSpotter
/** * Copyright 2014 SAP AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spotter.measurement.jmsserver; import org.lpe.common.config.ConfigParameterDescription; import org.lpe.common.util.LpeSupportedTypes; import org.spotter.core.measurement.AbstractMeasurmentExtension; import org.spotter.core.measurement.IMeasurementController; /** * Extension for JMS server sampler. * * @author Alexander Wert * */ public class JmsServerMeasurementExtension extends AbstractMeasurmentExtension { private static final String EXTENSION_DESCRIPTION = "The jmsserver sampling measurement satellite adapter is used " + "to connect to the special sampling satellites for Java Messaging " + "Service (JMS) server. They sample more than the default sampling " + "satellites."; @Override public String getName() { return "measurement.satellite.adapter.sampling.jmsserver"; } @Override public IMeasurementController createExtensionArtifact() { return new JmsServerMeasurement(this); } private ConfigParameterDescription createSamplingDelayParameter() { ConfigParameterDescription samplingDelayParameter = new ConfigParameterDescription( JmsServerMeasurement.SAMPLING_DELAY, LpeSupportedTypes.Long); samplingDelayParameter.setMandatory(false); samplingDelayParameter.setAset(false); samplingDelayParameter.setDefaultValue(String.valueOf(JmsServerMeasurement.DEFAULT_DELAY)); samplingDelayParameter.setDescription("The sampling interval in milliseconds."); return samplingDelayParameter; } private ConfigParameterDescription createCollectorTypeParameter() { ConfigParameterDescription collectorTypeParameter = new ConfigParameterDescription( JmsServerMeasurement.COLLECTOR_TYPE_KEY, LpeSupportedTypes.String); collectorTypeParameter.setMandatory(true); collectorTypeParameter.setAset(false); collectorTypeParameter.setDescription("Type to use for data collector"); return collectorTypeParameter; } private ConfigParameterDescription createServerConnectionStringParameter() { ConfigParameterDescription collectorTypeParameter = new ConfigParameterDescription( JmsServerMeasurement.ACTIVE_MQJMX_URL, LpeSupportedTypes.String); collectorTypeParameter.setMandatory(true); collectorTypeParameter.setAset(false); collectorTypeParameter.setDescription("Connection string to the JMX interface of the massaging service."); return collectorTypeParameter; } @Override protected void initializeConfigurationParameters() { addConfigParameter(createSamplingDelayParameter()); addConfigParameter(createCollectorTypeParameter()); addConfigParameter(createServerConnectionStringParameter()); addConfigParameter(ConfigParameterDescription.createExtensionDescription(EXTENSION_DESCRIPTION)); } @Override public boolean testConnection(String host, String port) { return true; } @Override public boolean isRemoteExtension() { return false; } }
org.spotter.measurement/src/org/spotter/measurement/jmsserver/JmsServerMeasurementExtension.java
/** * Copyright 2014 SAP AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spotter.measurement.jmsserver; import org.lpe.common.config.ConfigParameterDescription; import org.lpe.common.util.LpeSupportedTypes; import org.spotter.core.measurement.AbstractMeasurmentExtension; import org.spotter.core.measurement.IMeasurementController; /** * Extension for JMS server sampler. * * @author Alexander Wert * */ public class JmsServerMeasurementExtension extends AbstractMeasurmentExtension { @Override public String getName() { return "measurement.sampler.jmsserver"; } @Override public IMeasurementController createExtensionArtifact() { return new JmsServerMeasurement(this); } private ConfigParameterDescription createSamplingDelayParameter() { ConfigParameterDescription samplingDelayParameter = new ConfigParameterDescription( JmsServerMeasurement.SAMPLING_DELAY, LpeSupportedTypes.Long); samplingDelayParameter.setMandatory(false); samplingDelayParameter.setAset(false); samplingDelayParameter.setDefaultValue(String.valueOf(JmsServerMeasurement.DEFAULT_DELAY)); samplingDelayParameter.setDescription("The sampling interval in milliseconds."); return samplingDelayParameter; } private ConfigParameterDescription createCollectorTypeParameter() { ConfigParameterDescription collectorTypeParameter = new ConfigParameterDescription( JmsServerMeasurement.COLLECTOR_TYPE_KEY, LpeSupportedTypes.String); collectorTypeParameter.setMandatory(true); collectorTypeParameter.setAset(false); collectorTypeParameter.setDescription("Type to use for data collector"); return collectorTypeParameter; } private ConfigParameterDescription createServerConnectionStringParameter() { ConfigParameterDescription collectorTypeParameter = new ConfigParameterDescription( JmsServerMeasurement.ACTIVE_MQJMX_URL, LpeSupportedTypes.String); collectorTypeParameter.setMandatory(true); collectorTypeParameter.setAset(false); collectorTypeParameter.setDescription("Connection string to the JMX interface of the massaging service."); return collectorTypeParameter; } @Override protected void initializeConfigurationParameters() { addConfigParameter(createSamplingDelayParameter()); addConfigParameter(createCollectorTypeParameter()); addConfigParameter(createServerConnectionStringParameter()); } @Override public boolean testConnection(String host, String port) { return true; } @Override public boolean isRemoteExtension() { return false; } }
Added extension information to the JMS server sampling satellite adapter. Change-Id: Ic74acef97db79347cd5cb8d930fe71ce47d800ae Signed-off-by: Peter Merkert <8fdbf00a17753bb84bfc0daace87836096fea880@sap.com>
org.spotter.measurement/src/org/spotter/measurement/jmsserver/JmsServerMeasurementExtension.java
Added extension information to the JMS server sampling satellite adapter.
Java
apache-2.0
028cf3e59f3de5191cf9bedef3678b3061d3408a
0
GerritCodeReview/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.query.account; import static com.google.common.truth.Truth.assertThat; import static java.util.stream.Collectors.toList; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.gerrit.extensions.api.GerritApi; import com.google.gerrit.extensions.api.accounts.Accounts.QueryRequest; import com.google.gerrit.extensions.client.ListAccountsOption; import com.google.gerrit.extensions.client.ProjectWatchInfo; import com.google.gerrit.extensions.common.AccountInfo; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.lifecycle.LifecycleManager; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountManager; import com.google.gerrit.server.account.AccountState; import com.google.gerrit.server.account.AuthRequest; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.schema.SchemaCreator; import com.google.gerrit.server.util.ManualRequestContext; import com.google.gerrit.server.util.OneOffRequestContext; import com.google.gerrit.server.util.RequestContext; import com.google.gerrit.server.util.ThreadLocalRequestContext; import com.google.gerrit.testutil.ConfigSuite; import com.google.gerrit.testutil.GerritServerTests; import com.google.gerrit.testutil.InMemoryDatabase; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.util.Providers; import org.eclipse.jgit.lib.Config; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; @Ignore public abstract class AbstractQueryAccountsTest extends GerritServerTests { @ConfigSuite.Default public static Config defaultConfig() { Config cfg = new Config(); cfg.setInt("index", null, "maxPages", 10); return cfg; } @Rule public final TestName testName = new TestName(); @Inject protected AccountCache accountCache; @Inject protected AccountManager accountManager; @Inject protected GerritApi gApi; @Inject protected IdentifiedUser.GenericFactory userFactory; @Inject private Provider<AnonymousUser> anonymousUser; @Inject protected InMemoryDatabase schemaFactory; @Inject protected SchemaCreator schemaCreator; @Inject protected ThreadLocalRequestContext requestContext; @Inject protected OneOffRequestContext oneOffRequestContext; @Inject protected InternalAccountQuery internalAccountQuery; @Inject protected AllProjectsName allProjects; protected LifecycleManager lifecycle; protected ReviewDb db; protected AccountInfo currentUserInfo; protected CurrentUser user; protected abstract Injector createInjector(); @Before public void setUpInjector() throws Exception { lifecycle = new LifecycleManager(); Injector injector = createInjector(); lifecycle.add(injector); injector.injectMembers(this); lifecycle.start(); db = schemaFactory.open(); schemaCreator.create(db); Account.Id userId = createAccount("user", "User", "user@example.com", true); user = userFactory.create(userId); requestContext.setContext(newRequestContext(userId)); currentUserInfo = gApi.accounts().id(userId.get()).get(); } protected RequestContext newRequestContext(Account.Id requestUserId) { final CurrentUser requestUser = userFactory.create(requestUserId); return new RequestContext() { @Override public CurrentUser getUser() { return requestUser; } @Override public Provider<ReviewDb> getReviewDbProvider() { return Providers.of(db); } }; } protected void setAnonymous() { requestContext.setContext(new RequestContext() { @Override public CurrentUser getUser() { return anonymousUser.get(); } @Override public Provider<ReviewDb> getReviewDbProvider() { return Providers.of(db); } }); } @After public void tearDownInjector() { if (lifecycle != null) { lifecycle.stop(); } requestContext.setContext(null); if (db != null) { db.close(); } InMemoryDatabase.drop(schemaFactory); } @Test public void byId() throws Exception { AccountInfo user = newAccount("user"); assertQuery("9999999"); assertQuery(currentUserInfo._accountId, currentUserInfo); assertQuery(user._accountId, user); } @Test public void bySelf() throws Exception { assertQuery("self", currentUserInfo); } @Test public void byEmail() throws Exception { AccountInfo user1 = newAccountWithEmail("user1", name("user1@example.com")); String domain = name("test.com"); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); String prefix = name("prefix"); AccountInfo user4 = newAccountWithEmail("user4", prefix + "user4@example.com"); AccountInfo user5 = newAccountWithEmail("user5", name("user5MixedCase@example.com")); assertQuery("notexisting@test.com"); assertQuery(currentUserInfo.email, currentUserInfo); assertQuery("email:" + currentUserInfo.email, currentUserInfo); assertQuery(user1.email, user1); assertQuery("email:" + user1.email, user1); assertQuery(domain, user2, user3); assertQuery("email:" + prefix, user4); assertQuery(user5.email, user5); assertQuery("email:" + user5.email, user5); assertQuery("email:" + user5.email.toUpperCase(), user5); } @Test public void byUsername() throws Exception { AccountInfo user1 = newAccount("myuser"); assertQuery("notexisting"); assertQuery("Not Existing"); assertQuery(user1.username, user1); assertQuery("username:" + user1.username, user1); assertQuery("username:" + user1.username.toUpperCase(), user1); } @Test public void isActive() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccount("user3", "user3@" + domain, false); AccountInfo user4 = newAccount("user4", "user4@" + domain, false); // by default only active accounts are returned assertQuery(domain, user1, user2); assertQuery("name:" + domain, user1, user2); assertQuery("is:active name:" + domain, user1, user2); assertQuery("is:inactive name:" + domain, user3, user4); } @Test public void byName() throws Exception { AccountInfo user1 = newAccountWithFullName("jdoe", "John Doe"); AccountInfo user2 = newAccountWithFullName("jroe", "Jane Roe"); AccountInfo user3 = newAccountWithFullName("user3", "Mr Selfish"); assertQuery("notexisting"); assertQuery("Not Existing"); assertQuery(quote(user1.name), user1); assertQuery("name:" + quote(user1.name), user1); assertQuery("John", user1); assertQuery("john", user1); assertQuery("Doe", user1); assertQuery("doe", user1); assertQuery("DOE", user1); assertQuery("Jo Do", user1); assertQuery("jo do", user1); assertQuery("self", currentUserInfo, user3); assertQuery("name:John", user1); assertQuery("name:john", user1); assertQuery("name:Doe", user1); assertQuery("name:doe", user1); assertQuery("name:DOE", user1); assertQuery("name:self", user3); assertQuery(quote(user2.name), user2); assertQuery("name:" + quote(user2.name), user2); } @Test public void byWatchedProject() throws Exception { Project.NameKey p = createProject(name("p")); Project.NameKey p2 = createProject(name("p2")); AccountInfo user1 = newAccountWithFullName("jdoe", "John Doe"); AccountInfo user2 = newAccountWithFullName("jroe", "Jane Roe"); AccountInfo user3 = newAccountWithFullName("user3", "Mr Selfish"); assertThat(internalAccountQuery.byWatchedProject(p)).isEmpty(); watch(user1, p, null); assertAccounts(internalAccountQuery.byWatchedProject(p), user1); watch(user2, p, "keyword"); assertAccounts(internalAccountQuery.byWatchedProject(p), user1, user2); watch(user3, p2, "keyword"); watch(user3, allProjects, "keyword"); assertAccounts(internalAccountQuery.byWatchedProject(p), user1, user2); assertAccounts(internalAccountQuery.byWatchedProject(p2), user3); assertAccounts(internalAccountQuery.byWatchedProject(allProjects), user3); } @Test public void withLimit() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); List<AccountInfo> result = assertQuery(domain, user1, user2, user3); assertThat(Iterables.getLast(result)._moreAccounts).isNull(); result = assertQuery(newQuery(domain).withLimit(2), result.subList(0, 2)); assertThat(Iterables.getLast(result)._moreAccounts).isTrue(); } @Test public void withStart() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); List<AccountInfo> result = assertQuery(domain, user1, user2, user3); assertQuery(newQuery(domain).withStart(1), result.subList(1, 3)); } @Test public void withDetails() throws Exception { AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true); List<AccountInfo> result = assertQuery(user1.username, user1); AccountInfo ai = result.get(0); assertThat(ai._accountId).isEqualTo(user1._accountId); assertThat(ai.name).isNull(); assertThat(ai.username).isNull(); assertThat(ai.email).isNull(); assertThat(ai.avatars).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1); ai = result.get(0); assertThat(ai._accountId).isEqualTo(user1._accountId); assertThat(ai.name).isEqualTo(user1.name); assertThat(ai.username).isEqualTo(user1.username); assertThat(ai.email).isEqualTo(user1.email); assertThat(ai.avatars).isNull(); } @Test public void withSecondaryEmails() throws Exception { AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true); String[] secondaryEmails = new String[] {"bar@example.com", "foo@example.com"}; addEmails(user1, secondaryEmails); List<AccountInfo> result = assertQuery(user1.username, user1); assertThat(result.get(0).secondaryEmails).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1); assertThat(result.get(0).secondaryEmails).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.ALL_EMAILS), user1); assertThat(result.get(0).secondaryEmails) .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder(); result = assertQuery(newQuery(user1.username).withOptions( ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS), user1); assertThat(result.get(0).secondaryEmails) .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder(); } @Test public void asAnonymous() throws Exception { AccountInfo user1 = newAccount("user1"); setAnonymous(); assertQuery("9999999"); assertQuery("self"); assertQuery("username:" + user1.username, user1); } protected AccountInfo newAccount(String username) throws Exception { return newAccountWithEmail(username, null); } protected AccountInfo newAccountWithEmail(String username, String email) throws Exception { return newAccount(username, email, true); } protected AccountInfo newAccountWithFullName(String username, String fullName) throws Exception { return newAccount(username, fullName, null, true); } protected AccountInfo newAccount(String username, String email, boolean active) throws Exception { return newAccount(username, null, email, active); } protected AccountInfo newAccount(String username, String fullName, String email, boolean active) throws Exception { String uniqueName = name(username); try { gApi.accounts().id(uniqueName).get(); fail("user " + uniqueName + " already exists"); } catch (ResourceNotFoundException e) { // expected: user does not exist yet } Account.Id id = createAccount(uniqueName, fullName, email, active); return gApi.accounts().id(id.get()).get(); } protected Project.NameKey createProject(String name) throws RestApiException { gApi.projects().create(name); return new Project.NameKey(name); } protected void watch(AccountInfo account, Project.NameKey project, String filter) throws RestApiException { List<ProjectWatchInfo> projectsToWatch = new ArrayList<>(); ProjectWatchInfo pwi = new ProjectWatchInfo(); pwi.project = project.get(); pwi.filter = filter; pwi.notifyAbandonedChanges = true; pwi.notifyNewChanges = true; pwi.notifyAllComments = true; projectsToWatch.add(pwi); gApi.accounts().id(account._accountId).setWatchedProjects(projectsToWatch); } protected String quote(String s) { return "\"" + s + "\""; } protected String name(String name) { if (name == null) { return null; } String suffix = testName.getMethodName().toLowerCase(); if (name.contains("@")) { return name + "." + suffix; } return name + "_" + suffix; } private Account.Id createAccount(String username, String fullName, String email, boolean active) throws Exception { try (ManualRequestContext ctx = oneOffRequestContext.open()) { Account.Id id = accountManager.authenticate(AuthRequest.forUser(username)).getAccountId(); if (email != null) { accountManager.link(id, AuthRequest.forEmail(email)); } Account a = db.accounts().get(id); a.setFullName(fullName); a.setPreferredEmail(email); a.setActive(active); db.accounts().update(ImmutableList.of(a)); accountCache.evict(id); return id; } } private void addEmails(AccountInfo account, String... emails) throws Exception { Account.Id id = new Account.Id(account._accountId); for (String email : emails) { accountManager.link(id, AuthRequest.forEmail(email)); } accountCache.evict(id); } protected QueryRequest newQuery(Object query) throws RestApiException { return gApi.accounts().query(query.toString()); } protected List<AccountInfo> assertQuery(Object query, AccountInfo... accounts) throws Exception { return assertQuery(newQuery(query), accounts); } protected List<AccountInfo> assertQuery(QueryRequest query, AccountInfo... accounts) throws Exception { return assertQuery(query, Arrays.asList(accounts)); } protected List<AccountInfo> assertQuery(QueryRequest query, List<AccountInfo> accounts) throws Exception { List<AccountInfo> result = query.get(); Iterable<Integer> ids = ids(result); assertThat(ids).named(format(query, result, accounts)) .containsExactlyElementsIn(ids(accounts)).inOrder(); return result; } protected void assertAccounts(List<AccountState> accounts, AccountInfo... expectedAccounts) { assertThat(accounts.stream().map(a -> a.getAccount().getId().get()) .collect(toList())) .containsExactlyElementsIn(Arrays.asList(expectedAccounts).stream() .map(a -> a._accountId).collect(toList())); } private String format(QueryRequest query, List<AccountInfo> actualIds, List<AccountInfo> expectedAccounts) { StringBuilder b = new StringBuilder(); b.append("query '").append(query.getQuery()) .append("' with expected accounts "); b.append(format(expectedAccounts)); b.append(" and result "); b.append(format(actualIds)); return b.toString(); } private String format(Iterable<AccountInfo> accounts) { StringBuilder b = new StringBuilder(); b.append("["); Iterator<AccountInfo> it = accounts.iterator(); while (it.hasNext()) { AccountInfo a = it.next(); b.append("{").append(a._accountId).append(", ").append("name=") .append(a.name).append(", ").append("email=").append(a.email) .append(", ").append("username=").append(a.username).append("}"); if (it.hasNext()) { b.append(", "); } } b.append("]"); return b.toString(); } protected static Iterable<Integer> ids(AccountInfo... accounts) { return ids(Arrays.asList(accounts)); } protected static Iterable<Integer> ids(List<AccountInfo> accounts) { return accounts.stream().map(a -> a._accountId).collect(toList()); } }
gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.query.account; import static com.google.common.truth.Truth.assertThat; import static java.util.stream.Collectors.toList; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.gerrit.extensions.api.GerritApi; import com.google.gerrit.extensions.api.accounts.Accounts.QueryRequest; import com.google.gerrit.extensions.client.ListAccountsOption; import com.google.gerrit.extensions.client.ProjectWatchInfo; import com.google.gerrit.extensions.common.AccountInfo; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.lifecycle.LifecycleManager; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountManager; import com.google.gerrit.server.account.AccountState; import com.google.gerrit.server.account.AuthRequest; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.schema.SchemaCreator; import com.google.gerrit.server.util.ManualRequestContext; import com.google.gerrit.server.util.OneOffRequestContext; import com.google.gerrit.server.util.RequestContext; import com.google.gerrit.server.util.ThreadLocalRequestContext; import com.google.gerrit.testutil.ConfigSuite; import com.google.gerrit.testutil.GerritServerTests; import com.google.gerrit.testutil.InMemoryDatabase; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.util.Providers; import org.eclipse.jgit.lib.Config; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; @Ignore public abstract class AbstractQueryAccountsTest extends GerritServerTests { @ConfigSuite.Default public static Config defaultConfig() { Config cfg = new Config(); cfg.setInt("index", null, "maxPages", 10); return cfg; } @Rule public final TestName testName = new TestName(); @Inject protected AccountCache accountCache; @Inject protected AccountManager accountManager; @Inject protected GerritApi gApi; @Inject protected IdentifiedUser.GenericFactory userFactory; @Inject private Provider<AnonymousUser> anonymousUser; @Inject protected InMemoryDatabase schemaFactory; @Inject protected SchemaCreator schemaCreator; @Inject protected ThreadLocalRequestContext requestContext; @Inject protected OneOffRequestContext oneOffRequestContext; @Inject protected InternalAccountQuery internalAccountQuery; @Inject protected AllProjectsName allProjects; protected LifecycleManager lifecycle; protected ReviewDb db; protected AccountInfo currentUserInfo; protected CurrentUser user; protected abstract Injector createInjector(); @Before public void setUpInjector() throws Exception { lifecycle = new LifecycleManager(); Injector injector = createInjector(); lifecycle.add(injector); injector.injectMembers(this); lifecycle.start(); db = schemaFactory.open(); schemaCreator.create(db); Account.Id userId = createAccount("user", "User", "user@example.com", true); user = userFactory.create(userId); requestContext.setContext(newRequestContext(userId)); currentUserInfo = gApi.accounts().id(userId.get()).get(); } protected RequestContext newRequestContext(Account.Id requestUserId) { final CurrentUser requestUser = userFactory.create(requestUserId); return new RequestContext() { @Override public CurrentUser getUser() { return requestUser; } @Override public Provider<ReviewDb> getReviewDbProvider() { return Providers.of(db); } }; } protected void setAnonymous() { requestContext.setContext(new RequestContext() { @Override public CurrentUser getUser() { return anonymousUser.get(); } @Override public Provider<ReviewDb> getReviewDbProvider() { return Providers.of(db); } }); } @After public void tearDownInjector() { if (lifecycle != null) { lifecycle.stop(); } requestContext.setContext(null); if (db != null) { db.close(); } InMemoryDatabase.drop(schemaFactory); } @Test public void byId() throws Exception { AccountInfo user = newAccount("user"); assertQuery("9999999"); assertQuery(currentUserInfo._accountId, currentUserInfo); assertQuery(user._accountId, user); } @Test public void bySelf() throws Exception { assertQuery("self", currentUserInfo); } @Test public void byEmail() throws Exception { AccountInfo user1 = newAccountWithEmail("user1", name("user1@example.com")); String domain = name("test.com"); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); String prefix = name("prefix"); AccountInfo user4 = newAccountWithEmail("user4", prefix + "user4@example.com"); AccountInfo user5 = newAccountWithEmail("user5", name("user5MixedCase@example.com")); assertQuery("notexisting@test.com"); assertQuery(currentUserInfo.email, currentUserInfo); assertQuery("email:" + currentUserInfo.email, currentUserInfo); assertQuery(user1.email, user1); assertQuery("email:" + user1.email, user1); assertQuery(domain, user2, user3); assertQuery("email:" + prefix, user4); assertQuery(user5.email, user5); assertQuery("email:" + user5.email, user5); assertQuery("email:" + user5.email.toUpperCase(), user5); } @Test public void byUsername() throws Exception { AccountInfo user1 = newAccount("myuser"); assertQuery("notexisting"); assertQuery("Not Existing"); assertQuery(user1.username, user1); assertQuery("username:" + user1.username, user1); assertQuery("username:" + user1.username.toUpperCase(), user1); } @Test public void isActive() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccount("user3", "user3@" + domain, false); AccountInfo user4 = newAccount("user4", "user4@" + domain, false); // by default only active accounts are returned assertQuery(domain, user1, user2); assertQuery("name:" + domain, user1, user2); assertQuery("is:active name:" + domain, user1, user2); assertQuery("is:inactive name:" + domain, user3, user4); } @Test public void byName() throws Exception { AccountInfo user1 = newAccountWithFullName("jdoe", "John Doe"); AccountInfo user2 = newAccountWithFullName("jroe", "Jane Roe"); AccountInfo user3 = newAccountWithFullName("user3", "Mr Selfish"); assertQuery("notexisting"); assertQuery("Not Existing"); assertQuery(quote(user1.name), user1); assertQuery("name:" + quote(user1.name), user1); assertQuery("John", user1); assertQuery("john", user1); assertQuery("Doe", user1); assertQuery("doe", user1); assertQuery("DOE", user1); assertQuery("Jo Do", user1); assertQuery("jo do", user1); assertQuery("self", currentUserInfo, user3); assertQuery("name:John", user1); assertQuery("name:john", user1); assertQuery("name:Doe", user1); assertQuery("name:doe", user1); assertQuery("name:DOE", user1); assertQuery("name:self", user3); assertQuery(quote(user2.name), user2); assertQuery("name:" + quote(user2.name), user2); } @Test public void byWatchedProject() throws Exception { Project.NameKey p = createProject(name("p")); Project.NameKey p2 = createProject(name("p2")); AccountInfo user1 = newAccountWithFullName("jdoe", "John Doe"); AccountInfo user2 = newAccountWithFullName("jroe", "Jane Roe"); AccountInfo user3 = newAccountWithFullName("user3", "Mr Selfish"); assertThat(internalAccountQuery.byWatchedProject(p).isEmpty()); watch(user1, p, null); assertAccounts(internalAccountQuery.byWatchedProject(p), user1); watch(user2, p, "keyword"); assertAccounts(internalAccountQuery.byWatchedProject(p), user1, user2); watch(user3, p2, "keyword"); watch(user3, allProjects, "keyword"); assertAccounts(internalAccountQuery.byWatchedProject(p), user1, user2); assertAccounts(internalAccountQuery.byWatchedProject(p2), user3); assertAccounts(internalAccountQuery.byWatchedProject(allProjects), user3); } @Test public void withLimit() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); List<AccountInfo> result = assertQuery(domain, user1, user2, user3); assertThat(Iterables.getLast(result)._moreAccounts).isNull(); result = assertQuery(newQuery(domain).withLimit(2), result.subList(0, 2)); assertThat(Iterables.getLast(result)._moreAccounts).isTrue(); } @Test public void withStart() throws Exception { String domain = name("test.com"); AccountInfo user1 = newAccountWithEmail("user1", "user1@" + domain); AccountInfo user2 = newAccountWithEmail("user2", "user2@" + domain); AccountInfo user3 = newAccountWithEmail("user3", "user3@" + domain); List<AccountInfo> result = assertQuery(domain, user1, user2, user3); assertQuery(newQuery(domain).withStart(1), result.subList(1, 3)); } @Test public void withDetails() throws Exception { AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true); List<AccountInfo> result = assertQuery(user1.username, user1); AccountInfo ai = result.get(0); assertThat(ai._accountId).isEqualTo(user1._accountId); assertThat(ai.name).isNull(); assertThat(ai.username).isNull(); assertThat(ai.email).isNull(); assertThat(ai.avatars).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1); ai = result.get(0); assertThat(ai._accountId).isEqualTo(user1._accountId); assertThat(ai.name).isEqualTo(user1.name); assertThat(ai.username).isEqualTo(user1.username); assertThat(ai.email).isEqualTo(user1.email); assertThat(ai.avatars).isNull(); } @Test public void withSecondaryEmails() throws Exception { AccountInfo user1 = newAccount("myuser", "My User", "my.user@example.com", true); String[] secondaryEmails = new String[] {"bar@example.com", "foo@example.com"}; addEmails(user1, secondaryEmails); List<AccountInfo> result = assertQuery(user1.username, user1); assertThat(result.get(0).secondaryEmails).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.DETAILS), user1); assertThat(result.get(0).secondaryEmails).isNull(); result = assertQuery( newQuery(user1.username).withOption(ListAccountsOption.ALL_EMAILS), user1); assertThat(result.get(0).secondaryEmails) .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder(); result = assertQuery(newQuery(user1.username).withOptions( ListAccountsOption.DETAILS, ListAccountsOption.ALL_EMAILS), user1); assertThat(result.get(0).secondaryEmails) .containsExactlyElementsIn(Arrays.asList(secondaryEmails)).inOrder(); } @Test public void asAnonymous() throws Exception { AccountInfo user1 = newAccount("user1"); setAnonymous(); assertQuery("9999999"); assertQuery("self"); assertQuery("username:" + user1.username, user1); } protected AccountInfo newAccount(String username) throws Exception { return newAccountWithEmail(username, null); } protected AccountInfo newAccountWithEmail(String username, String email) throws Exception { return newAccount(username, email, true); } protected AccountInfo newAccountWithFullName(String username, String fullName) throws Exception { return newAccount(username, fullName, null, true); } protected AccountInfo newAccount(String username, String email, boolean active) throws Exception { return newAccount(username, null, email, active); } protected AccountInfo newAccount(String username, String fullName, String email, boolean active) throws Exception { String uniqueName = name(username); try { gApi.accounts().id(uniqueName).get(); fail("user " + uniqueName + " already exists"); } catch (ResourceNotFoundException e) { // expected: user does not exist yet } Account.Id id = createAccount(uniqueName, fullName, email, active); return gApi.accounts().id(id.get()).get(); } protected Project.NameKey createProject(String name) throws RestApiException { gApi.projects().create(name); return new Project.NameKey(name); } protected void watch(AccountInfo account, Project.NameKey project, String filter) throws RestApiException { List<ProjectWatchInfo> projectsToWatch = new ArrayList<>(); ProjectWatchInfo pwi = new ProjectWatchInfo(); pwi.project = project.get(); pwi.filter = filter; pwi.notifyAbandonedChanges = true; pwi.notifyNewChanges = true; pwi.notifyAllComments = true; projectsToWatch.add(pwi); gApi.accounts().id(account._accountId).setWatchedProjects(projectsToWatch); } protected String quote(String s) { return "\"" + s + "\""; } protected String name(String name) { if (name == null) { return null; } String suffix = testName.getMethodName().toLowerCase(); if (name.contains("@")) { return name + "." + suffix; } return name + "_" + suffix; } private Account.Id createAccount(String username, String fullName, String email, boolean active) throws Exception { try (ManualRequestContext ctx = oneOffRequestContext.open()) { Account.Id id = accountManager.authenticate(AuthRequest.forUser(username)).getAccountId(); if (email != null) { accountManager.link(id, AuthRequest.forEmail(email)); } Account a = db.accounts().get(id); a.setFullName(fullName); a.setPreferredEmail(email); a.setActive(active); db.accounts().update(ImmutableList.of(a)); accountCache.evict(id); return id; } } private void addEmails(AccountInfo account, String... emails) throws Exception { Account.Id id = new Account.Id(account._accountId); for (String email : emails) { accountManager.link(id, AuthRequest.forEmail(email)); } accountCache.evict(id); } protected QueryRequest newQuery(Object query) throws RestApiException { return gApi.accounts().query(query.toString()); } protected List<AccountInfo> assertQuery(Object query, AccountInfo... accounts) throws Exception { return assertQuery(newQuery(query), accounts); } protected List<AccountInfo> assertQuery(QueryRequest query, AccountInfo... accounts) throws Exception { return assertQuery(query, Arrays.asList(accounts)); } protected List<AccountInfo> assertQuery(QueryRequest query, List<AccountInfo> accounts) throws Exception { List<AccountInfo> result = query.get(); Iterable<Integer> ids = ids(result); assertThat(ids).named(format(query, result, accounts)) .containsExactlyElementsIn(ids(accounts)).inOrder(); return result; } protected void assertAccounts(List<AccountState> accounts, AccountInfo... expectedAccounts) { assertThat(accounts.stream().map(a -> a.getAccount().getId().get()) .collect(toList())) .containsExactlyElementsIn(Arrays.asList(expectedAccounts).stream() .map(a -> a._accountId).collect(toList())); } private String format(QueryRequest query, List<AccountInfo> actualIds, List<AccountInfo> expectedAccounts) { StringBuilder b = new StringBuilder(); b.append("query '").append(query.getQuery()) .append("' with expected accounts "); b.append(format(expectedAccounts)); b.append(" and result "); b.append(format(actualIds)); return b.toString(); } private String format(Iterable<AccountInfo> accounts) { StringBuilder b = new StringBuilder(); b.append("["); Iterator<AccountInfo> it = accounts.iterator(); while (it.hasNext()) { AccountInfo a = it.next(); b.append("{").append(a._accountId).append(", ").append("name=") .append(a.name).append(", ").append("email=").append(a.email) .append(", ").append("username=").append(a.username).append("}"); if (it.hasNext()) { b.append(", "); } } b.append("]"); return b.toString(); } protected static Iterable<Integer> ids(AccountInfo... accounts) { return ids(Arrays.asList(accounts)); } protected static Iterable<Integer> ids(List<AccountInfo> accounts) { return accounts.stream().map(a -> a._accountId).collect(toList()); } }
Fix typo in AbstractQueryAccountsTest Change-Id: Iea65708f832b3225765a8c3428931bcec826daea
gerrit-server/src/test/java/com/google/gerrit/server/query/account/AbstractQueryAccountsTest.java
Fix typo in AbstractQueryAccountsTest
Java
apache-2.0
07db88a367282b50f13cf8df5bc64bda5e601275
0
MatthiasWinzeler/spring-security,djechelon/spring-security,yinhe402/spring-security,diegofernandes/spring-security,zhaoqin102/spring-security,spring-projects/spring-security,wkorando/spring-security,mounb/spring-security,chinazhaoht/spring-security,dsyer/spring-security,eddumelendez/spring-security,kazuki43zoo/spring-security,likaiwalkman/spring-security,ollie314/spring-security,zhaoqin102/spring-security,mrkingybc/spring-security,thomasdarimont/spring-security,spring-projects/spring-security,rwinch/spring-security,mrkingybc/spring-security,jgrandja/spring-security,raindev/spring-security,dsyer/spring-security,vitorgv/spring-security,pwheel/spring-security,wilkinsona/spring-security,panchenko/spring-security,mounb/spring-security,adairtaosy/spring-security,rwinch/spring-security,zgscwjm/spring-security,mparaz/spring-security,ractive/spring-security,mparaz/spring-security,ractive/spring-security,ollie314/spring-security,xingguang2013/spring-security,liuguohua/spring-security,chinazhaoht/spring-security,spring-projects/spring-security,zshift/spring-security,justinedelson/spring-security,chinazhaoht/spring-security,zhaoqin102/spring-security,driftman/spring-security,olezhuravlev/spring-security,wkorando/spring-security,rwinch/spring-security,Peter32/spring-security,Krasnyanskiy/spring-security,djechelon/spring-security,driftman/spring-security,follow99/spring-security,adairtaosy/spring-security,spring-projects/spring-security,Peter32/spring-security,Xcorpio/spring-security,liuguohua/spring-security,raindev/spring-security,fhanik/spring-security,ollie314/spring-security,zgscwjm/spring-security,yinhe402/spring-security,diegofernandes/spring-security,pkdevbox/spring-security,dsyer/spring-security,wilkinsona/spring-security,djechelon/spring-security,caiwenshu/spring-security,hippostar/spring-security,eddumelendez/spring-security,Peter32/spring-security,spring-projects/spring-security,xingguang2013/spring-security,raindev/spring-security,panchenko/spring-security,jmnarloch/spring-security,jmnarloch/spring-security,rwinch/spring-security,thomasdarimont/spring-security,hippostar/spring-security,fhanik/spring-security,eddumelendez/spring-security,hippostar/spring-security,zhaoqin102/spring-security,zgscwjm/spring-security,cyratech/spring-security,yinhe402/spring-security,dsyer/spring-security,zshift/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,panchenko/spring-security,Peter32/spring-security,ajdinhedzic/spring-security,driftman/spring-security,wilkinsona/spring-security,izeye/spring-security,olezhuravlev/spring-security,izeye/spring-security,Krasnyanskiy/spring-security,driftman/spring-security,pkdevbox/spring-security,forestqqqq/spring-security,Xcorpio/spring-security,diegofernandes/spring-security,zshift/spring-security,justinedelson/spring-security,rwinch/spring-security,djechelon/spring-security,forestqqqq/spring-security,mparaz/spring-security,fhanik/spring-security,ollie314/spring-security,hippostar/spring-security,dsyer/spring-security,thomasdarimont/spring-security,cyratech/spring-security,justinedelson/spring-security,MatthiasWinzeler/spring-security,zgscwjm/spring-security,caiwenshu/spring-security,yinhe402/spring-security,fhanik/spring-security,likaiwalkman/spring-security,pwheel/spring-security,vitorgv/spring-security,pwheel/spring-security,izeye/spring-security,olezhuravlev/spring-security,mrkingybc/spring-security,SanjayUser/SpringSecurityPro,pwheel/spring-security,mdeinum/spring-security,cyratech/spring-security,Krasnyanskiy/spring-security,ractive/spring-security,follow99/spring-security,olezhuravlev/spring-security,chinazhaoht/spring-security,mounb/spring-security,fhanik/spring-security,wkorando/spring-security,mrkingybc/spring-security,kazuki43zoo/spring-security,Xcorpio/spring-security,spring-projects/spring-security,adairtaosy/spring-security,jgrandja/spring-security,wkorando/spring-security,kazuki43zoo/spring-security,liuguohua/spring-security,liuguohua/spring-security,eddumelendez/spring-security,tekul/spring-security,zshift/spring-security,SanjayUser/SpringSecurityPro,forestqqqq/spring-security,vitorgv/spring-security,MatthiasWinzeler/spring-security,jmnarloch/spring-security,mdeinum/spring-security,vitorgv/spring-security,mparaz/spring-security,fhanik/spring-security,jgrandja/spring-security,tekul/spring-security,panchenko/spring-security,SanjayUser/SpringSecurityPro,caiwenshu/spring-security,jgrandja/spring-security,izeye/spring-security,ajdinhedzic/spring-security,likaiwalkman/spring-security,SanjayUser/SpringSecurityPro,eddumelendez/spring-security,wilkinsona/spring-security,ajdinhedzic/spring-security,follow99/spring-security,olezhuravlev/spring-security,spring-projects/spring-security,diegofernandes/spring-security,SanjayUser/SpringSecurityPro,forestqqqq/spring-security,xingguang2013/spring-security,Krasnyanskiy/spring-security,kazuki43zoo/spring-security,tekul/spring-security,ractive/spring-security,jmnarloch/spring-security,tekul/spring-security,pkdevbox/spring-security,caiwenshu/spring-security,rwinch/spring-security,cyratech/spring-security,djechelon/spring-security,xingguang2013/spring-security,justinedelson/spring-security,follow99/spring-security,mounb/spring-security,adairtaosy/spring-security,jgrandja/spring-security,mdeinum/spring-security,Xcorpio/spring-security,ajdinhedzic/spring-security,jgrandja/spring-security,kazuki43zoo/spring-security,raindev/spring-security,thomasdarimont/spring-security,pwheel/spring-security,mdeinum/spring-security,MatthiasWinzeler/spring-security,pkdevbox/spring-security
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.ui.webapp; import junit.framework.TestCase; import org.springframework.security.Authentication; import org.springframework.security.MockAuthenticationManager; import org.springframework.security.AuthenticationException; import org.springframework.security.ui.WebAuthenticationDetails; import org.springframework.mock.web.MockHttpServletRequest; import javax.servlet.ServletException; /** * Tests {@link AuthenticationProcessingFilter}. * * @author Ben Alex * @version $Id$ */ public class AuthenticationProcessingFilterTests extends TestCase { //~ Constructors =================================================================================================== public AuthenticationProcessingFilterTests() { } public AuthenticationProcessingFilterTests(String arg0) { super(arg0); } //~ Methods ======================================================================================================== public void testGetters() { AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); assertEquals("/j_spring_security_check", filter.getDefaultFilterProcessesUrl()); } public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.init(null); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); assertEquals("rod", request.getSession().getAttribute( AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)); assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); } public void testNullPasswordHandledGracefully() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); } public void testNullUsernameHandledGracefully() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); } public void testUsingDifferentParameterNamesWorksAsExpected() throws ServletException { AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.setUsernameParameter("x"); filter.setPasswordParameter("y"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("x", "rod"); request.addParameter("y", "koala"); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); } public void testSpacesAreTrimmedCorrectlyFromUsername() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod "); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertEquals("rod", result.getName()); } public void testFailedAuthenticationThrowsException() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(false)); try { filter.attemptAuthentication(request); fail("Expected AuthenticationException"); } catch (AuthenticationException e) { } // Check username has still been set assertEquals("rod", request.getSession().getAttribute( AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)); } /** * SEC-571 */ public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAllowSessionCreation(false); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.attemptAuthentication(request); assertNull(request.getSession(false)); } }
core/src/test/java/org/springframework/security/ui/webapp/AuthenticationProcessingFilterTests.java
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.ui.webapp; import junit.framework.TestCase; import org.springframework.security.Authentication; import org.springframework.security.MockAuthenticationManager; import org.springframework.security.AuthenticationException; import org.springframework.security.ui.WebAuthenticationDetails; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockFilterConfig; import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.ServletException; /** * Tests {@link AuthenticationProcessingFilter}. * * @author Ben Alex * @version $Id$ */ public class AuthenticationProcessingFilterTests extends TestCase { //~ Constructors =================================================================================================== public AuthenticationProcessingFilterTests() { } public AuthenticationProcessingFilterTests(String arg0) { super(arg0); } //~ Methods ======================================================================================================== public void testGetters() { AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); assertEquals("/j_spring_security_check", filter.getDefaultFilterProcessesUrl()); } public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.init(null); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); assertEquals("rod", request.getSession().getAttribute( AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)); assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); } public void testNullPasswordHandledGracefully() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); } public void testNullUsernameHandledGracefully() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); } public void testUsingDifferentParameterNamesWorksAsExpected() throws ServletException { AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.setUsernameParameter("x"); filter.setPasswordParameter("y"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("x", "rod"); request.addParameter("y", "koala"); Authentication result = filter.attemptAuthentication(request); assertTrue(result != null); assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); } public void testSpacesAreTrimmedCorrectlyFromUsername() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod "); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(true)); Authentication result = filter.attemptAuthentication(request); assertEquals("rod", result.getName()); } public void testFailedAuthenticationThrowsException() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAuthenticationManager(new MockAuthenticationManager(false)); try { filter.attemptAuthentication(request); fail("Expected AuthenticationException"); } catch (AuthenticationException e) { } // Check username has still been set assertEquals("rod", request.getSession().getAttribute( AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)); } /** * SEC-571 */ public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); AuthenticationProcessingFilter filter = new AuthenticationProcessingFilter(); filter.setAllowSessionCreation(false); filter.setAuthenticationManager(new MockAuthenticationManager(true)); filter.attemptAuthentication(request); assertNull(request.getSession(false)); } }
Import cleaning.
core/src/test/java/org/springframework/security/ui/webapp/AuthenticationProcessingFilterTests.java
Import cleaning.
Java
bsd-2-clause
ab45c93ca2988824dae55c6f58bf8655af6707f1
0
scifio/scifio
/* * #%L * SCIFIO library for reading and converting scientific file formats. * %% * Copyright (C) 2011 - 2016 Board of Regents of the University of * Wisconsin-Madison * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package io.scif.img; import static org.junit.Assert.assertEquals; import io.scif.config.SCIFIOConfig; import io.scif.config.SCIFIOConfig.ImgMode; import io.scif.io.ByteArrayHandle; import io.scif.services.LocationService; import java.io.File; import net.imagej.ImgPlus; import net.imglib2.RandomAccess; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.type.numeric.integer.UnsignedByteType; import org.junit.After; import org.junit.Test; import org.scijava.Context; /** * Tests for the {@link ImgSaver} class. * * @author Mark Hiner */ public class ImgSaverTest { private final String id = "testImg&lengths=512,512,2,3&axes=X,Y,Z,Time.fake"; private final String out = "test.tif"; private final Context ctx = new Context(); private final LocationService locationService = ctx.getService( LocationService.class); @After public void cleanup() { final File f = new File(out); if (f.exists()) f.delete(); } /** * Write an image to memory using the {@link ImgSaver} and verify that the * given {@link ImgPlus} is not corrupted during the process. */ @Test public void testImgPlusIntegrity() throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); final ByteArrayHandle bah = new ByteArrayHandle(); locationService.mapFile(out, bah); final SCIFIOImgPlus<?> openImg = o.openImgs(id, config).get(0); final String source = openImg.getSource(); s.saveImg(out, openImg); assertEquals(source, openImg.getSource()); } /** * Test that ImgSaver writes each plane of a multi-plane PlanarImg correctly */ @Test public void testPlanarPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane CellImg correctly */ @Test public void testCellPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.CELL); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane ArrayImg correctly */ @Test public void testArrayPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.ARRAY); testPlaneSavingForConfig(config); } // -- Helper methods -- private void testPlaneSavingForConfig(final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); // write the image SCIFIOImgPlus<UnsignedByteType> openImg = o.openImgs(id, new UnsignedByteType(), config).get(0); s.saveImg(out, openImg); // re-read the written image and check dimensions openImg = o.openImgs(out, new UnsignedByteType()).get(0); // fakes start with 10 0's, then pixel value == plane index.. // so we have to skip along the x-axis a bit final int[] pos = { 11, 0, 0 }; for (int i = 0; i < 5; i++) { pos[2] = i; final RandomAccess<UnsignedByteType> randomAccess = // openImg.randomAccess(); randomAccess.setPosition(pos); assertEquals(i, randomAccess.get().getRealDouble(), 0.0001); } } }
src/test/java/io/scif/img/ImgSaverTest.java
/* * #%L * SCIFIO library for reading and converting scientific file formats. * %% * Copyright (C) 2011 - 2016 Board of Regents of the University of * Wisconsin-Madison * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package io.scif.img; import static org.junit.Assert.assertEquals; import io.scif.config.SCIFIOConfig; import io.scif.config.SCIFIOConfig.ImgMode; import io.scif.io.ByteArrayHandle; import io.scif.services.LocationService; import java.io.File; import net.imagej.ImgPlus; import net.imglib2.RandomAccess; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.type.numeric.integer.UnsignedByteType; import org.junit.After; import org.junit.Test; import org.scijava.Context; /** * Tests for the {@link ImgSaver} class. * * @author Mark Hiner */ public class ImgSaverTest { private final String id = "testImg&lengths=512,512,2,3&axes=X,Y,Z,Time.fake"; private final String out = "test.tif"; private final Context ctx = new Context(); private final LocationService locationService = ctx.getService( LocationService.class); @After public void cleanup() { final File f = new File(out); if (f.exists()) f.delete(); } /** * Write an image to memory using the {@link ImgSaver} and verify that the * given {@link ImgPlus} is not corrupted during the process. */ @Test public void testImgPlusIntegrity() throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); final ByteArrayHandle bah = new ByteArrayHandle(); locationService.mapFile(out, bah); final SCIFIOImgPlus<?> openImg = o.openImgs(id, config).get(0); final String source = openImg.getSource(); s.saveImg(out, openImg); assertEquals(source, openImg.getSource()); } /** * Test that ImgSaver writes each plane of a multi-plane PlanarImg correctly */ @Test public void testPlanarPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.PLANAR); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane CellImg correctly */ @Test public void testSlowPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.CELL); testPlaneSavingForConfig(config); } /** * Test that ImgSaver writes each plane of a multi-plane ArrayImg correctly */ @Test public void testArrayPlaneSaving() throws ImgIOException, IncompatibleTypeException { final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes( ImgMode.ARRAY); testPlaneSavingForConfig(config); } // -- Helper methods -- private void testPlaneSavingForConfig(final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { final ImgOpener o = new ImgOpener(ctx); final ImgSaver s = new ImgSaver(ctx); // write the image SCIFIOImgPlus<UnsignedByteType> openImg = o.openImgs(id, new UnsignedByteType(), config).get(0); s.saveImg(out, openImg); // re-read the written image and check dimensions openImg = o.openImgs(out, new UnsignedByteType()).get(0); // fakes start with 10 0's, then pixel value == plane index.. // so we have to skip along the x-axis a bit final int[] pos = { 11, 0, 0 }; for (int i = 0; i < 5; i++) { pos[2] = i; final RandomAccess<UnsignedByteType> randomAccess = // openImg.randomAccess(); randomAccess.setPosition(pos); assertEquals(i, randomAccess.get().getRealDouble(), 0.0001); } } }
ImgSaverTest: name tests consistently
src/test/java/io/scif/img/ImgSaverTest.java
ImgSaverTest: name tests consistently
Java
bsd-2-clause
6bec915512f987f4a01385ef7463735cdc1ca25f
0
biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej
package imagej.core.tools; import imagej.data.Dataset; import imagej.util.ColorRGB; import java.util.Arrays; import net.imglib2.RandomAccess; import net.imglib2.meta.Axes; import net.imglib2.type.numeric.RealType; /** * This class, which does flood filling, is used by the FloodFillTool. It was * adapted from IJ1's FloodFiller class. That class implements the flood filling * code used by IJ1's macro language and IJ1's particle analyzer. The Wikipedia * article at "http://en.wikipedia.org/wiki/Flood_fill" has a good description * of the algorithm used here as well as examples in C and Java. * * @author Wayne Rasband * @author Barry DeZonia */ public class FloodFiller { private DrawingTool tool; private boolean isColor; private int colorAxis; private int uAxis; private int vAxis; private StackOfLongs uStack; private StackOfLongs vStack; /** * Constructs a FloodFiller from a given DrawingTool. The FloodFiller uses the * DrawingTool to fill a region of contiguous pixels in a plane of a Dataset. */ public FloodFiller(DrawingTool tool) { this.tool = tool; this.isColor = tool.getDataset().isRGBMerged(); if (isColor) this.colorAxis = tool.getDataset().getAxisIndex(Axes.CHANNEL); else this.colorAxis = -1; this.uAxis = -1; this.vAxis = -1; this.uStack = new StackOfLongs(); this.vStack = new StackOfLongs(); } /** * Does a 4-connected flood fill using the current fill/draw value. */ public void fill4(long u0, long v0, long[] position) { Dataset ds = tool.getDataset(); RandomAccess<? extends RealType<?>> accessor = ds.getImgPlus().randomAccess(); accessor.setPosition(position); uAxis = tool.getUAxis(); vAxis = tool.getVAxis(); long maxU = ds.dimension(uAxis); long maxV = ds.dimension(vAxis); ColorRGB origColor = getColor(accessor,u0,v0); Double origValue = getValue(accessor,u0,v0); uStack.clear(); vStack.clear(); push(u0, v0); while(!uStack.isEmpty()) { long u = popU(); long v = popV(); if (!matches(accessor,u,v,origColor,origValue)) continue; long u1 = u; long u2 = u; // find start of scan-line while (u1>=0 && matches(accessor,u1,v,origColor,origValue)) u1--; u1++; // find end of scan-line while (u2<maxU && matches(accessor,u2,v,origColor,origValue)) u2++; u2--; tool.drawLine(u1, v, u2, v); // fill scan-line boolean inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines above this one if (!inScanLine && v>0 && matches(accessor,i,v-1,origColor,origValue)) {push(i, v-1); inScanLine = true;} else if (inScanLine && v>0 && !matches(accessor,i,v-1,origColor,origValue)) inScanLine = false; } inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines below this one if (!inScanLine && v<maxV-1 && matches(accessor,i,v+1,origColor,origValue)) {push(i, v+1); inScanLine = true;} else if (inScanLine && v<maxV-1 && !matches(accessor,i,v+1,origColor,origValue)) inScanLine = false; } } //System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length); } /** * Does an 8-connected flood fill using the current fill/draw value. */ public void fill8(long u0, long v0, long[] position) { Dataset ds = tool.getDataset(); RandomAccess<? extends RealType<?>> accessor = ds.getImgPlus().randomAccess(); accessor.setPosition(position); uAxis = tool.getUAxis(); vAxis = tool.getVAxis(); long maxU = ds.dimension(uAxis); long maxV = ds.dimension(vAxis); ColorRGB origColor = getColor(accessor,u0,v0); Double origValue = getValue(accessor,u0,v0); uStack.clear(); vStack.clear(); push(u0, v0); while(!uStack.isEmpty()) { long u = popU(); long v = popV(); long u1 = u; long u2 = u; if (matches(accessor,u1,v,origColor,origValue)) { // find start of scan-line while (u1>=0 && matches(accessor,u1,v,origColor,origValue)) u1--; u1++; // find end of scan-line while (u2<maxU && matches(accessor,u2,v,origColor,origValue)) u2++; u2--; tool.drawLine(u1, v, u2, v); // fill scan-line } if (v > 0) { if (u1 > 0) { if (matches(accessor,u1-1,v-1,origColor,origValue)) { push(u1-1,v-1); } } if (u2 < maxU-1) { if (matches(accessor,u2+1,v-1,origColor,origValue)) { push(u2+1,v-1); } } } if (v < maxV-1) { if (u1 > 0) { if (matches(accessor,u1-1,v+1,origColor,origValue)) { push(u1-1,v+1); } } if (u2 < maxU-1) { if (matches(accessor,u2+1,v+1,origColor,origValue)) { push(u2+1,v+1); } } } boolean inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines above this one if (!inScanLine && v>0 && matches(accessor,i,v-1,origColor,origValue)) {push(i, v-1); inScanLine = true;} else if (inScanLine && v>0 && !matches(accessor,i,v-1,origColor,origValue)) inScanLine = false; } inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines below this one if (!inScanLine && v<maxV-1 && matches(accessor,i,v+1,origColor,origValue)) {push(i, v+1); inScanLine = true;} else if (inScanLine && v<maxV-1 && !matches(accessor,i,v+1,origColor,origValue)) inScanLine = false; } } //System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length); } // -- private helpers -- /** * Returns true if the current pixel located at the given (u,v) coordinates * is the same as the specified color or gray values. */ private boolean matches(RandomAccess<? extends RealType<?>> accessor, long u, long v, ColorRGB origColor, double origValue) { accessor.setPosition(u, uAxis); accessor.setPosition(v, vAxis); // are we interested in values? if (!isColor) { double val = accessor.get().getRealDouble(); return val == origValue; } // else interested in colors double component; accessor.setPosition(0,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getRed()) return false; accessor.setPosition(1,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getGreen()) return false; accessor.setPosition(2,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getBlue()) return false; return true; } /** * Gets the color of the pixel at the (u,v) coordinates of the UV plane of the * current DrawingTool. If the underlying Dataset is not color returns null. */ private ColorRGB getColor(RandomAccess<? extends RealType<?>> accessor, long u, long v) { if (!isColor) return null; accessor.setPosition(u,uAxis); accessor.setPosition(v,vAxis); accessor.setPosition(0,colorAxis); int r = (int) accessor.get().getRealDouble(); accessor.setPosition(1,colorAxis); int g = (int) accessor.get().getRealDouble(); accessor.setPosition(2,colorAxis); int b = (int) accessor.get().getRealDouble(); return new ColorRGB(r,g,b); } /** * Gets the gray value of the pixel at the (u,v) coordinates of the UV plane * of the current DrawingTool. If the underlying Dataset is not gray returns * Double.NaN. */ private double getValue(RandomAccess<? extends RealType<?>> accessor, long u, long v) { if (isColor) return Double.NaN; accessor.setPosition(u,uAxis); accessor.setPosition(v,vAxis); return accessor.get().getRealDouble(); } /** * Pushes the specified (u,v) point on the working stacks. */ private void push(long u, long v) { uStack.push(u); vStack.push(v); } /** Pops a U value of the working U stack. */ private long popU() { return uStack.pop(); } /** Pops a V value of the working V stack. */ private long popV() { return vStack.pop(); } /** * To minimize object creations/deletions we want a stack of primitives */ private class StackOfLongs { private int top; private long[] stack; public StackOfLongs() { top = -1; stack = new long[400]; } public boolean isEmpty() { return top < 0; } public void clear() { top = -1; } public void push(long value) { if (top == stack.length-1) stack = Arrays.copyOf(stack, stack.length*2); top++; stack[top] = value; } public long pop() { if (top < 0) throw new IllegalArgumentException("can't pop empty stack"); long value = stack[top]; top--; return value; } } }
core/tools/src/main/java/imagej/core/tools/FloodFiller.java
package imagej.core.tools; import imagej.data.Dataset; import imagej.util.ColorRGB; import java.util.Arrays; import net.imglib2.RandomAccess; import net.imglib2.meta.Axes; import net.imglib2.type.numeric.RealType; /** * This class, which does flood filling, is used by the FloodFillTool. It was * adapted from IJ1's FloodFiller class. That class implements the flood filling * code used by IJ1's macro language and IJ1's particle analyzer. The Wikipedia * article at "http://en.wikipedia.org/wiki/Flood_fill" has a good description * of the algorithm used here as well as examples in C and Java. * * @author Wayne Rasband * @author Barry DeZonia */ public class FloodFiller { private DrawingTool tool; private boolean isColor; private int colorAxis; private int uAxis; private int vAxis; private StackOfLongs uStack; private StackOfLongs vStack; /** * Constructs a FloodFiller from a given DrawingTool. The FloodFiller uses the * DrawingTool to fill a region of contiguous pixels in a plane of a Dataset. */ public FloodFiller(DrawingTool tool) { this.tool = tool; this.isColor = tool.getDataset().isRGBMerged(); if (isColor) this.colorAxis = tool.getDataset().getAxisIndex(Axes.CHANNEL); else this.colorAxis = -1; this.uAxis = -1; this.vAxis = -1; this.uStack = new StackOfLongs(); this.vStack = new StackOfLongs(); } /** * Does a 4-connected flood fill using the current fill/draw value. */ public void fill4(long u0, long v0, long[] position) { Dataset ds = tool.getDataset(); RandomAccess<? extends RealType<?>> accessor = ds.getImgPlus().randomAccess(); accessor.setPosition(position); uAxis = tool.getUAxis(); vAxis = tool.getVAxis(); long maxU = ds.dimension(uAxis); long maxV = ds.dimension(vAxis); ColorRGB origColor = getColor(accessor,u0,v0); Double origValue = getValue(accessor,u0,v0); uStack.clear(); vStack.clear(); push(u0, v0); while(!uStack.isEmpty()) { long u = popU(); long v = popV(); if (!matches(accessor,u,v,origColor,origValue)) continue; long u1 = u; long u2 = u; // find start of scan-line while (u1>=0 && matches(accessor,u1,v,origColor,origValue)) u1--; u1++; // find end of scan-line while (u2<maxU && matches(accessor,u2,v,origColor,origValue)) u2++; u2--; tool.drawLine(u1, v, u2, v); // fill scan-line boolean inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines above this one if (!inScanLine && v>0 && matches(accessor,i,v-1,origColor,origValue)) {push(i, v-1); inScanLine = true;} else if (inScanLine && v>0 && !matches(accessor,i,v-1,origColor,origValue)) inScanLine = false; } inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines below this one if (!inScanLine && v<maxV-1 && matches(accessor,i,v+1,origColor,origValue)) {push(i, v+1); inScanLine = true;} else if (inScanLine && v<maxV-1 && !matches(accessor,i,v+1,origColor,origValue)) inScanLine = false; } } //System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length); } /** * Does an 8-connected flood fill using the current fill/draw value. */ public void fill8(long u0, long v0, long[] position) { Dataset ds = tool.getDataset(); RandomAccess<? extends RealType<?>> accessor = ds.getImgPlus().randomAccess(); accessor.setPosition(position); uAxis = tool.getUAxis(); vAxis = tool.getVAxis(); long maxU = ds.dimension(uAxis); long maxV = ds.dimension(vAxis); ColorRGB origColor = getColor(accessor,u0,v0); Double origValue = getValue(accessor,u0,v0); uStack.clear(); vStack.clear(); push(u0, v0); while(!uStack.isEmpty()) { long u = popU(); long v = popV(); long u1 = u; long u2 = u; if (matches(accessor,u1,v,origColor,origValue)) { // find start of scan-line while (u1>=0 && matches(accessor,u1,v,origColor,origValue)) u1--; u1++; // find end of scan-line while (u2<maxU && matches(accessor,u2,v,origColor,origValue)) u2++; u2--; tool.drawLine(u1, v, u2, v); // fill scan-line } if (v > 0) { if (u1 > 0) { if (matches(accessor,u1-1,v-1,origColor,origValue)) { push(u1-1,v-1); } } if (u2 < maxU-1) { if (matches(accessor,u2+1,v-1,origColor,origValue)) { push(u2+1,v-1); } } } if (v < maxV-1) { if (u1 > 0) { if (matches(accessor,u1-1,v+1,origColor,origValue)) { push(u1-1,v+1); } } if (u2 < maxU-1) { if (matches(accessor,u2+1,v+1,origColor,origValue)) { push(u2+1,v+1); } } } boolean inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines above this one if (!inScanLine && v>0 && matches(accessor,i,v-1,origColor,origValue)) {push(i, v-1); inScanLine = true;} else if (inScanLine && v>0 && !matches(accessor,i,v-1,origColor,origValue)) inScanLine = false; } inScanLine = false; for (long i=u1; i<=u2; i++) { // find scan-lines below this one if (!inScanLine && v<maxV-1 && matches(accessor,i,v+1,origColor,origValue)) {push(i, v+1); inScanLine = true;} else if (inScanLine && v<maxV-1 && !matches(accessor,i,v+1,origColor,origValue)) inScanLine = false; } } //System.out.println("Stack allocated (but not necessarily used) "+uStack.stack.length); } // -- private helpers -- /** * Returns true if the current pixel located at the given (u,v) coordinates * is the same as the specified color or gray values. */ private boolean matches(RandomAccess<? extends RealType<?>> accessor, long u, long v, ColorRGB origColor, double origValue) { accessor.setPosition(u, uAxis); accessor.setPosition(v, vAxis); // are we interested in values? if (!isColor) { double val = accessor.get().getRealDouble(); return val == origValue; } // else interested in colors double component; accessor.setPosition(0,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getRed()) return false; accessor.setPosition(1,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getGreen()) return false; accessor.setPosition(2,colorAxis); component = accessor.get().getRealDouble(); if (component != origColor.getBlue()) return false; return true; } /** * Gets the color of the pixel at the (u,v) coordinates of the UV plane of the * current DrawingTool. If the underlying Dataset is not color returns null. */ private ColorRGB getColor(RandomAccess<? extends RealType<?>> accessor, long u, long v) { if (!isColor) return null; accessor.setPosition(u,uAxis); accessor.setPosition(v,vAxis); accessor.setPosition(0,colorAxis); int r = (int) accessor.get().getRealDouble(); accessor.setPosition(1,colorAxis); int g = (int) accessor.get().getRealDouble(); accessor.setPosition(2,colorAxis); int b = (int) accessor.get().getRealDouble(); return new ColorRGB(r,g,b); } /** * Gets the gray value of the pixel at the (u,v) coordinates of the UV plane * of the current DrawingTool. If the underlying Dataset is not gray returns * Double.NaN. */ private double getValue(RandomAccess<? extends RealType<?>> accessor, long u, long v) { if (isColor) return Double.NaN; accessor.setPosition(u,uAxis); accessor.setPosition(v,vAxis); return accessor.get().getRealDouble(); } /** * Pushes the specified (u,v) point on the working stacks. */ private void push(long u, long v) { uStack.push(u); vStack.push(v); } /** Pops a U value of the working U stack. */ private long popU() { return uStack.pop(); } /** Pops a V value of the working V stack. */ private long popV() { return vStack.pop(); } /** * To minimize object creations/deletions we want a stack of primitives */ private class StackOfLongs { private int top; private long[] stack; public StackOfLongs() { top = -1; stack = new long[100]; } public boolean isEmpty() { return top < 0; } public void clear() { top = -1; } public void push(long value) { if (top == stack.length-1) stack = Arrays.copyOf(stack, stack.length*2); top++; stack[top] = value; } public long pop() { if (top < 0) throw new IllegalArgumentException("can't pop empty stack"); long value = stack[top]; top--; return value; } } }
Increase size of internal stacks to minimize array reallocations This used to be revision r4700.
core/tools/src/main/java/imagej/core/tools/FloodFiller.java
Increase size of internal stacks to minimize array reallocations
Java
bsd-3-clause
bd9f54207311883058c9df04a46e1face70e5d93
0
NCIP/cadsr-formbuilder,NCIP/cadsr-formbuilder,NCIP/cadsr-formbuilder
package gov.nih.nci.cadsr.formloader.repository; import gov.nih.nci.cadsr.formloader.domain.FormCollection; import gov.nih.nci.cadsr.formloader.domain.FormDescriptor; import gov.nih.nci.cadsr.formloader.domain.ModuleDescriptor; import gov.nih.nci.cadsr.formloader.domain.QuestionDescriptor; import gov.nih.nci.cadsr.formloader.service.common.StaXParser; import gov.nih.nci.ncicb.cadsr.common.dto.AdminComponentTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.ContextTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DataElementTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DefinitionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObjectExt; import gov.nih.nci.ncicb.cadsr.common.dto.FormV2TransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.FormValidValueTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.InstructionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.ModuleTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.PermissibleValueV2TransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.QuestionChangeTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.QuestionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.RefdocTransferObjectExt; import gov.nih.nci.ncicb.cadsr.common.dto.ReferenceDocumentTransferObject; import gov.nih.nci.ncicb.cadsr.common.exception.DMLException; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCCollectionDAO; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormValidValueDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormValidValueInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCModuleDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCQuestionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCQuestionInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCReferenceDocumentDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCValueDomainDAOV2; import gov.nih.nci.ncicb.cadsr.common.resource.Context; import gov.nih.nci.ncicb.cadsr.common.resource.FormV2; import gov.nih.nci.ncicb.cadsr.common.resource.Instruction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public class FormLoaderRepositoryImpl implements FormLoaderRepository { private static Logger logger = Logger.getLogger(FormLoaderRepositoryImpl.class.getName()); static final int MAX_LONG_NAME_LENGTH = 255; public static final String COMPONENT_TYPE_FORM = "QUEST_CONTENT"; public static final String DEFAULT_WORKFLOW_STATUS = "DRAFT NEW"; public static final String DEFAULT_DEFINITION_TYPE = "Form Loader"; public static final String DEFAULT_DESIGNATION_TYPE = "Form Loader"; public static final String DEFAULT_CONTEXT_NAME = "NCIP"; public static final String DEFAULT_FORM_TYPE = "CRF"; public static final String DEFAULT_REFDOC_TYPE = "REFERENCE"; protected static final int MARK_TO_KEEP_IN_UPDATE = 99; JDBCFormDAOV2 formV2Dao; JDBCModuleDAOV2 moduleV2Dao; JDBCQuestionDAOV2 questionV2Dao; JDBCValueDomainDAOV2 valueDomainV2Dao; JDBCFormInstructionDAOV2 formInstructionV2Dao; JDBCQuestionInstructionDAOV2 questInstructionV2Dao; JDBCFormValidValueDAOV2 formValidValueV2Dao; JDBCFormValidValueInstructionDAOV2 formValidValueInstructionV2Dao; JDBCCollectionDAO collectionDao; JDBCReferenceDocumentDAOV2 referenceDocV2Dao; //These are loaded from database for validation purposes HashMap<String, String> conteNameSeqIdMap; List<String> definitionTypes; List<String> designationTypes; List<String> refdocTypes; List<String> workflowNames; /** * Gets Seq id, public id and version for forms with the given public ids * @param pubicIDList * @return */ @Transactional(readOnly=true) public List<FormV2> getFormsForPublicIDs(List<String> pubicIDList) { if (pubicIDList == null || pubicIDList.size() ==0) { logger.debug("getFormsForPublicIDs(): public id list is null or empty. Do nothing."); return null; } //Seq id, public id and version are set in the returned forms List<FormV2> formDtos = formV2Dao.getExistingVersionsForPublicIds(pubicIDList); logger.debug("getFormsForPublicIDs() returns " + formDtos.size() + " forms with " + pubicIDList.size() + " public ids"); return formDtos; } @Transactional(readOnly=true) public List<QuestionTransferObject> getQuestionsByPublicId(String publicId) { if (publicId == null || publicId.length() == 0) { logger.debug("getQuestionsByPublicId(): Question public id is null or empty. Unable to querry db."); return null; } int pubId = Integer.parseInt(publicId); List<QuestionTransferObject> questions = questionV2Dao.getQuestionsByPublicId(pubId); logger.debug("getQuestionsByPublicId(): Dao returns " + questions.size() + " questions."); return questions; } @Transactional(readOnly=true) public List<QuestionTransferObject> getQuestionsByPublicIds(List<String> publicIds) { if (publicIds == null || publicIds.size() == 0) { logger.debug("getQuestionsByPublicIds(): Question public id list is null or empty. Unable to querry db."); return null; } List<QuestionTransferObject> questions = questionV2Dao.getQuestionsByPublicIds(publicIds); logger.debug("getQuestionsByPublicId(): Dao returns " + questions.size() + " questions."); return questions; } @Transactional(readOnly=true) public List<DataElementTransferObject> getCDEByPublicId(String cdePublicId) { if (cdePublicId == null || cdePublicId.length() == 0) { logger.debug("getCDEByPublicId(): Question's CDE public id is null or empty. Unable to querry db."); return null; } List<DataElementTransferObject> des = questionV2Dao.getCdesByPublicId(cdePublicId); logger.debug("getCDEByPublicId(): Dao returns " + des.size() + " CDEs"); return des; } @Transactional(readOnly=true) public List<DataElementTransferObject> getCDEsByPublicIds(List<String> cdePublicIds) { if (cdePublicIds == null || cdePublicIds.size() == 0) { logger.debug("getCDEsByPublicIds(): cde public id list is null or empty. Unable to querry db."); return null; } List<DataElementTransferObject> des = questionV2Dao.getCdesByPublicIds(cdePublicIds); logger.debug("getCDEsByPublicIds(): Dao returns " + des.size() + " CDEs"); return des; } @Transactional(readOnly=true) public List<ReferenceDocumentTransferObject> getReferenceDocsForQuestionCde(String cdePublicId, String cdeVersion) { if (cdePublicId == null || cdePublicId.length() == 0) { logger.debug("getReferenceDocsForQuestionCde(): Question's CDE public id is null or empty. Unable to querry db."); return null; } if (cdeVersion == null || cdeVersion.length() == 0) { logger.debug("getReferenceDocsForQuestionCde(): Question CDE version is null or empty. Unable to querry db."); return null; } List<ReferenceDocumentTransferObject> deRefDocs = questionV2Dao.getAllReferenceDocumentsForDE( Integer.parseInt(cdePublicId), Float.parseFloat(cdeVersion)); logger.debug("getReferenceDocsForQuestionCde(): Dao returns " + deRefDocs.size() + " CDE reference docs."); return deRefDocs; } @Transactional(readOnly=true) public HashMap<String, List<ReferenceDocumentTransferObject>> getReferenceDocsByCdePublicIds(List<String> cdePublicIds) { if (cdePublicIds == null || cdePublicIds.size() == 0) { logger.debug("getReferenceDocsByCdePublicIds(): cde public id list is null or empty. Unable to querry db."); return null; } HashMap<String, List<ReferenceDocumentTransferObject>> deRefDocs = questionV2Dao.getReferenceDocumentsByCdePublicIds(cdePublicIds); logger.debug("getReferenceDocsByCdePublicIds(): Dao returns " + deRefDocs.size() + " CDE reference docs."); return deRefDocs; } @Transactional(readOnly=true) public List<PermissibleValueV2TransferObject> getValueDomainPermissibleValuesByVdId(String vdSeqId) { if (vdSeqId == null || vdSeqId.length() == 0) { logger.debug("getValueDomainBySeqId(): Value domain seq id is null or empty. Unable to querry db."); return null; } List<PermissibleValueV2TransferObject> pValues = valueDomainV2Dao.getPermissibleValuesByVdId(vdSeqId); String msg = "getValueDomainPermissibleValuesByVdId(): Dao returns "; if (pValues == null || pValues.size() == 0) msg += "a value domain obj with 0 permissible value."; else msg += "a value domain obj with " + pValues.size() + " permissible values"; logger.debug("msg"); return pValues; } @Transactional(readOnly=true) public HashMap<String, List<PermissibleValueV2TransferObject>> getPermissibleValuesByVdIds(List<String> vdSeqIds) { if (vdSeqIds == null || vdSeqIds.size() == 0) { logger.debug("getPermissibleValuesByVdIds(): vdSeqIds list is null or empty. Unable to querry db."); return null; } HashMap<String, List<PermissibleValueV2TransferObject>> pValues = valueDomainV2Dao.getPermissibleValuesByVdIds(vdSeqIds); String msg = "getPermissibleValuesByVdIds(): Dao returns "; if (pValues == null || pValues.size() == 0) msg += "a value domain obj with 0 permissible value."; else msg += "a value domain obj with " + pValues.size() + " permissible values"; logger.debug(msg); return pValues; } /** * To get the public id and version for the loaded forms * @param forms */ @Transactional(readOnly=true) public void setPublicIdVersionBySeqids(List<FormDescriptor> forms) { List<String> seqids = new ArrayList<String>(); for (FormDescriptor form : forms) { if (form.getLoadStatus() == FormDescriptor.STATUS_LOADED) seqids.add(form.getFormSeqId()); } if (seqids.size() == 0) return; HashMap<String, FormV2TransferObject> seqidMap = formV2Dao.getFormsBySeqids(seqids); for (FormDescriptor form : forms) { FormV2TransferObject formdto = seqidMap.get(form.getFormSeqId()); if (formdto != null) { form.setPublicId(String.valueOf(formdto.getPublicId())); form.setVersion(String.valueOf(formdto.getVersion())); } } } @Transactional(readOnly=true) public List<FormCollection> getAllLoadedCollections() { //first get collection headers List<FormCollection> colls = collectionDao.getAllLoadedCollections(); for (FormCollection coll : colls) { if (coll.getId().equals("E49101B2-1B48-BA26-E040-BB8921B61DC6")) { logger.debug("debug"); } List<String> formseqids = collectionDao.getAllFormSeqidsForCollection(coll.getId()); if (formseqids == null || formseqids.size() == 0) logger.warn("Collection " + coll.getId() + " doesn't have form seqids associated with it in database"); else { List<FormV2TransferObject> formdtos = this.formV2Dao.getFormHeadersBySeqids(formseqids); List<FormDescriptor> forms = translateIntoFormDescriptors(formdtos); coll.setForms(forms); } } return colls; } protected void retrievePublicIdForForm(String formSeqid, FormDescriptor form) { FormV2TransferObject formdto = this.formV2Dao.getFormPublicIdVersion(formSeqid); form.setPublicId(String.valueOf(formdto.getPublicId())); form.setVersion(String.valueOf(formdto.getVersion())); } protected void retrievePublicIdForQuestion(String questSeqid, QuestionDescriptor quest,QuestionTransferObject questdto) { QuestionTransferObject dto = this.questionV2Dao.getQuestionsPublicIdVersionBySeqid(questSeqid); quest.setPublicId(String.valueOf(dto.getPublicId())); quest.setVersion(String.valueOf(dto.getVersion())); questdto.setPublicId(dto.getPublicId()); questdto.setVersion(dto.getVersion()); } public JDBCFormDAOV2 getFormV2Dao() { return formV2Dao; } public void setFormV2Dao(JDBCFormDAOV2 formV2Dao) { this.formV2Dao = formV2Dao; } public JDBCModuleDAOV2 getModuleV2Dao() { return moduleV2Dao; } public void setModuleV2Dao(JDBCModuleDAOV2 moduleV2Dao) { this.moduleV2Dao = moduleV2Dao; } public JDBCQuestionDAOV2 getQuestionV2Dao() { return questionV2Dao; } public void setQuestionV2Dao(JDBCQuestionDAOV2 questionV2Dao) { this.questionV2Dao = questionV2Dao; } public JDBCValueDomainDAOV2 getValueDomainV2Dao() { return valueDomainV2Dao; } public void setValueDomainV2Dao(JDBCValueDomainDAOV2 valueDomainV2Dao) { this.valueDomainV2Dao = valueDomainV2Dao; } public JDBCFormInstructionDAOV2 getFormInstructionV2Dao() { return formInstructionV2Dao; } public void setFormInstructionV2Dao( JDBCFormInstructionDAOV2 formInstructionV2Dao) { this.formInstructionV2Dao = formInstructionV2Dao; } public JDBCQuestionInstructionDAOV2 getQuestInstructionV2Dao() { return questInstructionV2Dao; } public void setQuestInstructionV2Dao( JDBCQuestionInstructionDAOV2 questInstructionV2Dao) { this.questInstructionV2Dao = questInstructionV2Dao; } public JDBCFormValidValueDAOV2 getFormValidValueV2Dao() { return formValidValueV2Dao; } public void setFormValidValueV2Dao(JDBCFormValidValueDAOV2 formValidValueV2Dao) { this.formValidValueV2Dao = formValidValueV2Dao; } public JDBCFormValidValueInstructionDAOV2 getFormValidValueInstructionV2Dao() { return formValidValueInstructionV2Dao; } public void setFormValidValueInstructionV2Dao( JDBCFormValidValueInstructionDAOV2 formValidValueInstructionV2Dao) { this.formValidValueInstructionV2Dao = formValidValueInstructionV2Dao; } public JDBCCollectionDAO getCollectionDao() { return collectionDao; } public void setCollectionDao(JDBCCollectionDAO collectionDao) { this.collectionDao = collectionDao; } public JDBCReferenceDocumentDAOV2 getReferenceDocV2Dao() { return referenceDocV2Dao; } public void setReferenceDocV2Dao(JDBCReferenceDocumentDAOV2 referenceDocV2Dao) { this.referenceDocV2Dao = referenceDocV2Dao; } @Transactional(readOnly=true) public String getContextSeqIdByName(String contextName) { if (conteNameSeqIdMap == null) conteNameSeqIdMap = this.formV2Dao.getAllContextSeqIds(); return conteNameSeqIdMap.get(contextName); } @Transactional(readOnly=true) public boolean designationTypeExists(String designName) { if (designationTypes == null) designationTypes = this.formV2Dao.getAllDesignationTypes(); return designationTypes.contains(designName); } @Transactional(readOnly=true) public boolean refdocTypeExists(String refdocType) { if (this.refdocTypes == null) refdocTypes = this.formV2Dao.getAllRefdocTypes(); return refdocTypes.contains(refdocType); } /** * Create new form */ @Transactional public String createForm(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { String formSeqid = ""; try { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) return null; formSeqid = formV2Dao.createFormComponent(formdto); logger.debug("Created form. Seqid: " + formSeqid); //public id is created when new component is created //Need to go back to db for it retrievePublicIdForForm(formSeqid, form); formdto.setFormIdseq(formSeqid); form.setFormSeqId(formSeqid); //instructions createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions createModulesInForm(form, formdto); } catch (DMLException dbe) { logger.error(dbe.getMessage()); } return formSeqid; } /** * Create new form or new version of an existing form * <br><br> * This will first call the store procedure Sbrext_Form_Builder_Pkg.CRF_VERSION which will make a full copy * of the form with the same public id and an upgraded version number. Then it'll apply an update on the * copy with content from the xml. This is very inefficient. * <br><br> * Need to explore better way. Key quetions: how public id * is generated? Is it possible to insert new form row withough triggering a new public id generation. */ @Transactional public String createFormNewVersion(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { String formSeqid = ""; try { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) return null; formSeqid = formV2Dao.createNewFormVersionShellOnly(formdto.getFormIdseq(), formdto.getVersion(), "New version form by Form Loader", formdto.getCreatedBy()); logger.debug("Created new version for form. Seqid: " + formSeqid); formdto.setFormIdseq(formSeqid); form.setFormSeqId(formSeqid); int res = formV2Dao.updateFormComponent(formdto); if (res != 1) { logger.error("Error!! Failed to update form"); return null; } createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions updateModulesInForm(form, formdto); return form.getFormSeqId(); } catch (DMLException dbe) { logger.error(dbe.getMessage()); } return formSeqid; } @Transactional public String updateForm(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) { logger.error("Error!! Failed to translate xml form into FormTransferObject"); return null; } int res = formV2Dao.updateFormComponent(formdto); if (res != 1) { logger.error("Error!! Failed to update form"); return null; } createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions updateModulesInForm(form, formdto); return form.getFormSeqId(); } protected FormV2TransferObject translateIntoFormDTO(FormDescriptor form) { FormV2TransferObject formdto = new FormV2TransferObject(); String loadType = form.getLoadType(); if (FormDescriptor.LOAD_TYPE_NEW_VERSION.equals(loadType)) { float latest = this.formV2Dao.getMaxFormVersion(Integer.parseInt(form.getPublicId())); formdto.setVersion(new Float(latest + 1.0)); //TODO: is this the way to assign new version? formdto.setPublicId(Integer.parseInt(form.getPublicId())); formdto.setFormIdseq(form.getFormSeqId()); formdto.setAslName("DRAFT NEW"); formdto.setCreatedBy(form.getCreatedBy()); } else if (FormDescriptor.LOAD_TYPE_NEW.equals(loadType)) { formdto.setVersion(Float.valueOf("1.0")); formdto.setAslName("DRAFT NEW"); formdto.setCreatedBy(form.getCreatedBy()); } else if (FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(loadType)) { formdto.setVersion(Float.valueOf(form.getVersion())); formdto.setAslName(form.getWorkflowStatusName()); formdto.setModifiedBy(form.getModifiedBy()); String seqid = form.getFormSeqId(); //we got this when we queried on form public id //This should not happen if (seqid == null || seqid.length() == 0) { String msg = "Update form doesn't have a valid seqid. Unable to load."; form.addMessage(msg); form.setLoadStatus(FormDescriptor.STATUS_LOAD_FAILED); logger.error("Error with [" + form.getFormIdString() + "]: " + msg); return null; } formdto.setFormIdseq(seqid); } formdto.setLongName(form.getLongName()); formdto.setPreferredName(form.getLongName()); formdto.setFormType(form.getType()); formdto.setFormCategory(form.getCategoryName()); formdto.setPreferredDefinition(form.getPreferredDefinition()); String contextName = form.getContext(); if (contextName != null && contextName.length() > 0) { Context context = new ContextTransferObject(); context.setConteIdseq(this.getContextSeqIdByName(contextName)); formdto.setContext(context); formdto.setConteIdseq(this.getContextSeqIdByName(contextName)); } else { String msg = "Form doesn't have a valid context name. Unable to load"; form.addMessage(msg); form.setLoadStatus(FormDescriptor.STATUS_LOAD_FAILED); logger.error(form.getFormIdString() + ": " + msg); return null; } return formdto; } protected void createFormInstructions(FormDescriptor form, FormV2TransferObject formdto) { logger.debug("Creating instructions for form"); String instructString = form.getHeaderInstruction(); if (instructString == null || instructString.length() == 0) return; InstructionTransferObject formInstruction = createInstructionDto(formdto, instructString); if (formInstruction != null) formInstructionV2Dao.createInstruction(formInstruction, formdto.getFormIdseq()); instructString = form.getFooterInstruction(); formInstruction = createInstructionDto(formdto, instructString); if (formInstruction != null) formInstructionV2Dao.createFooterInstruction(formInstruction, formdto.getFormIdseq()); logger.debug("Done creating instructions for form"); } protected InstructionTransferObject createInstructionDto(AdminComponentTransferObject compdto, String instructionString) { InstructionTransferObject instruction = null; if (instructionString != null && instructionString.length() > 0) { instruction = new InstructionTransferObject(); instruction.setLongName(compdto.getLongName()); instruction.setPreferredDefinition(instructionString); instruction.setContext(compdto.getContext()); instruction.setAslName("DRAFT NEW"); instruction.setVersion(new Float(1.0)); instruction.setCreatedBy(compdto.getCreatedBy()); instruction.setDisplayOrder(1); } return instruction; } protected List<String> getCdeSeqIdsFromForm(FormDescriptor form) { return null; } protected void processFormdetails(FormDescriptor form, String xmlPathName, int currFormIdx) { logger.debug("Processing protocols, designations, refdocs and definitions for form"); StaXParser parser = new StaXParser(); parser.parseFormDetails(xmlPathName, form, currFormIdx); List<String> protoIds = parser.getProtocolIds(); processProtocols(form, protoIds); List<DesignationTransferObjectExt> designations = parser.getDesignations(); processDesignations(form, designations); List<RefdocTransferObjectExt> refdocs = parser.getRefdocs(); processRefdocs(form, refdocs); //TODO List<DefinitionTransferObject> definitions = parser.getDefinitions(); //TODO //processContactCommunications() logger.debug("Done processing protocols, designations, refdocs and definitions for form"); } /** * * @param form * @param refdocs */ @Transactional protected void processRefdocs(FormDescriptor form, List<RefdocTransferObjectExt> refdocs) { if (refdocs == null) { logger.error("Null refdocs list passed in to processRefdocs(). Do nothing"); return; } String formSeqid = form.getFormSeqId(); String contextSeqId = this.getContextSeqIdByName(form.getContext()); List existings = null; if (!form.getLoadType().equals(FormDescriptor.LOAD_TYPE_NEW)) { //2nd arg is not used in the actual query. existings = this.formV2Dao.getAllReferenceDocuments(form.getFormSeqId(), null); } //create ref docs int idx = 0; for (RefdocTransferObjectExt refdoc : refdocs) { String contextName = refdoc.getContextName(); String refdocContextSeqid = this.getContextSeqIdByName(contextName); if (refdocContextSeqid == null || refdocContextSeqid.length() == 0) { refdocContextSeqid = contextSeqId; contextName = form.getContext(); } ContextTransferObject con = new ContextTransferObject(contextName); con.setConteIdseq(refdocContextSeqid); refdoc.setContext(con); refdoc.setDisplayOrder(idx++); if (!this.refdocTypeExists(refdoc.getDocType())) { form.addMessage("Refdoc type [" + refdoc.getDocType() + "] is invalid. Use default type [REFERENCE]"); refdoc.setDocType(DEFAULT_REFDOC_TYPE); } if (existings != null && isExistingRefdoc(refdoc, existings)) { referenceDocV2Dao.updateReferenceDocument(refdoc); } else { this.referenceDocV2Dao.createReferenceDoc(refdoc, formSeqid); } } removeExtraRefdocsIfAny(existings); } /** * Compare a refdoc against a list from database, based on name and type. * @param currRefdoc * @param refdocs * @return */ protected boolean isExistingRefdoc(ReferenceDocumentTransferObject currRefdoc, List<ReferenceDocumentTransferObject> refdocs) { if (refdocs == null) { return false; } for (ReferenceDocumentTransferObject refdoc : refdocs) { if (refdoc.getDocName().equals(currRefdoc.getDocName()) && refdoc.getDocType().equals(currRefdoc.getDocType()) ) { refdoc.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); currRefdoc.setDocIDSeq(refdoc.getDocIdSeq()); return true; } } return false; } /** * Check a list of ref doc object that are previously marked and delete from database those are not marked as "KEEP" * * @param refdocs */ @Transactional protected void removeExtraRefdocsIfAny(List<ReferenceDocumentTransferObject> refdocs) { if (refdocs == null) { return; } for (ReferenceDocumentTransferObject refdoc : refdocs) { if (refdoc.getDisplayOrder() == MARK_TO_KEEP_IN_UPDATE) continue; logger.debug("Deleting refdoc [" + refdoc.getDocName() + "|" + refdoc.getDocType()); referenceDocV2Dao.deleteReferenceDocument(refdoc.getDocIdSeq()); } } /** * For new version and update form, if designation doesn't already exist, designate it to the context. For new form, * designate the form to the context. * @param form * @param designations */ @Transactional protected void processDesignations(FormDescriptor form, List<DesignationTransferObjectExt> designations) { if (designations == null) { logger.error("Null designation list passed in to processDesignations(). Do nothing"); return; } String formSeqid = form.getFormSeqId(); String contextSeqId = this.getContextSeqIdByName(form.getContext()); for (DesignationTransferObjectExt desig : designations) { if (form.getLoadType().equals(FormDescriptor.LOAD_TYPE_NEW)) { designateForm(formSeqid, contextSeqId, form.getCreatedBy(), desig); } else { //Check context name in designation elem from xml. If that's not valid, use form's String desigContext = desig.getContextName(); String desgContextSeqid = this.getContextSeqIdByName(desigContext); if (desgContextSeqid == null || desgContextSeqid.length() == 0) desgContextSeqid = contextSeqId; //validate the type, use default if neccessary String desigType = desig.getType(); if (!this.designationTypeExists(desigType)) { form.addMessage("Designation type [" + desigType + "] is invalid. Use default type [Form Loader]"); desig.setType(DEFAULT_DESIGNATION_TYPE); } List<DesignationTransferObject> existing = formV2Dao.getDesignationsForForm( formSeqid, desig.getName(), desig.getType(), desig.getLanguage()); if (existing == null || existing.size() == 0) { designateForm(formSeqid, contextSeqId, form.getCreatedBy(), desig); } } } } @Transactional protected int designateForm(String formSeqid, String contextSeqid, String createdby, DesignationTransferObjectExt desig) { List<String> ac_seqids = new ArrayList<String>(); ac_seqids.add(formSeqid); return formV2Dao.designate(contextSeqid, ac_seqids, createdby); } /** * 1. New form : add all listed protocols from xml to new form. * 2. New version and update form: add only if a protocol in xml doesn't already exist with the form. * * @param form * @param protoIds */ protected void processProtocols(FormDescriptor form, List<String> protoIds) { String formSeqid = form.getFormSeqId(); if (protoIds != null && protoIds.size() > 0) { HashMap<String, String> protoIdMap = formV2Dao.getProtocolSeqidsByIds(protoIds); List<String> protoSeqIds = markNoMatchProtoIds(form, protoIds, protoIdMap); for (String protoSeqid : protoSeqIds) { if (FormDescriptor.LOAD_TYPE_NEW.equals(form.getLoadType())) { formV2Dao.addFormProtocol(formSeqid, protoSeqid, form.getCreatedBy()); } else { if (!formV2Dao.formProtocolExists(formSeqid, protoSeqid)) formV2Dao.addFormProtocol(formSeqid, protoSeqid, form.getModifiedBy()); } } } } protected List<String> markNoMatchProtoIds(FormDescriptor form, List<String> protoIds, HashMap<String, String> protoIdMap) { List<String> protoSeqIds = new ArrayList<String>(); String nomatchids = ""; for (String protoId : protoIds) { String seqid = protoIdMap.get(protoId); if (seqid == null) nomatchids = (nomatchids.length() > 0) ? "," + protoId : protoId; else protoSeqIds.add(seqid); } if (nomatchids.length() > 0) form.addMessage("Protocol ids [" + nomatchids + "] with the form has no match in database."); return protoSeqIds; } @Transactional protected void createModulesInForm(FormDescriptor form, FormV2TransferObject formdto) { logger.debug("Start creating modules for form"); List<ModuleDescriptor> modules = form.getModules(); /* * Denise: * For a module and its questions in a form 1) If it's a new form or new version, use the form's createdBy 2) If it's an update form, check what's with module element in xml. a. If the module's createBy is valid, use it and apply that to all questions. b. If the module's createdBy is not valid, use form's createdBy and apply to all questions. */ for (ModuleDescriptor module : modules) { ModuleTransferObject moduledto = translateIntoModuleDTO(module, form, formdto); String moduleSeqid = moduleV2Dao.createModuleComponent(moduledto); logger.debug("Created a module with seqid: " + moduleSeqid); module.setModuleSeqId(moduleSeqid); moduledto.setIdseq(moduleSeqid); moduledto.setContext(formdto.getContext()); //TODO: do we need to go back to db to get module's public id? //Now, onto questions createQuestionsInModule(module, moduledto, form, formdto); } logger.debug("Done creating modules for form"); } @Transactional protected void createQuestionsInModule(ModuleDescriptor module, ModuleTransferObject moduledto, FormDescriptor form, FormV2TransferObject formdto) { List<QuestionDescriptor> questions = module.getQuestions(); logger.debug("Creating questions for module"); int idx = 0; for (QuestionDescriptor question : questions) { if (question.isSkip()) continue; QuestionTransferObject questdto = translateIntoQuestionDTO(question, form); questdto.setDisplayOrder(idx++); questdto.setContext(formdto.getContext()); questdto.setModule(moduledto); //better to call createQuestionComponents, which is not implement. QuestionTransferObject newQuestdto = (QuestionTransferObject)this.questionV2Dao.createQuestionComponent(questdto); String seqid = newQuestdto.getQuesIdseq(); logger.debug("Created a question: " + seqid); question.setQuestionSeqId(seqid); retrievePublicIdForQuestion(seqid, question, questdto); createQuestionInstruction(newQuestdto, moduledto, question.getInstruction()); createQuestionValidValues(question, form, newQuestdto, moduledto, formdto); } logger.debug("Done creating questions for module"); } /** * Create valid value for a newly created question. * * @param question question generated from xml * @param form form generated from xml * @param newQuestdto new question dto that just got created in db, with new seqid and public id * @param moduledto */ @Transactional protected void createQuestionValidValues(QuestionDescriptor question, FormDescriptor form, QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, FormV2TransferObject formdto) { List<QuestionDescriptor.ValidValue> validValues = question.getValidValues(); int idx = 0; for (QuestionDescriptor.ValidValue vValue : validValues) { if (vValue.isSkip()) continue; idx++; FormValidValueTransferObject fvv = translateIntoValidValueDto(vValue, newQuestdto, moduledto, formdto, idx); fvv.setDisplayOrder(idx); String vvSeqid = formValidValueV2Dao.createValidValue(fvv,newQuestdto.getQuesIdseq(),moduledto.getCreatedBy()); if (vvSeqid != null && vvSeqid.length() > 0) { formValidValueV2Dao.createValidValueAttributes(vvSeqid, vValue.getMeaningText(), vValue.getDescription(), moduledto.getCreatedBy()); String instr = vValue.getInstruction(); if (instr != null && instr.length() > 0) { InstructionTransferObject instrdto = createInstructionDto(fvv, instr); formValidValueInstructionV2Dao.createInstruction(instrdto, vvSeqid); } } logger.debug("Created new valid valid"); } } protected FormValidValueTransferObject translateIntoValidValueDto(QuestionDescriptor.ValidValue vValue, QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, FormV2TransferObject formdto, int displayOrder) { FormValidValueTransferObject fvv = new FormValidValueTransferObject(); fvv.setCreatedBy(moduledto.getCreatedBy()); fvv.setQuestion(newQuestdto); fvv.setVpIdseq(vValue.getVdPermissibleValueSeqid()); String preferredName = composeVVPreferredName(vValue, newQuestdto.getPublicId(), formdto.getPublicId(), formdto.getVersion(), displayOrder); fvv.setLongName(vValue.getValue()); fvv.setPreferredName(preferredName); fvv.setPreferredDefinition(vValue.getDescription()); fvv.setContext(moduledto.getContext()); fvv.setVersion(Float.valueOf("1.0")); fvv.setAslName("DRAFT NEW"); return fvv; } //PreferredName format: value meaning public id_quetionpublicid_form_public_id_version_<x> x = 1, 2, 3 protected String composeVVPreferredName(QuestionDescriptor.ValidValue vValue, int questPublicId, int formPublicId, float formversion, int displayorder) { return vValue.getPreferredName() + "_" + questPublicId + "_" + formPublicId + "v" + formversion + "_" + displayorder; } /** * Create new instruction for a question. * * Do nothing is instruction string is null or empty. * * @param newQuestdto * @param moduledto * @param instString */ protected void createQuestionInstruction(QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, String instString) { if (instString == null || instString.length() == 0) return; //Nothing to do String sizedUpInstr = instString; /* (Snippet copied from FormModuleEditAction (FB) * * Truncate instruction string to fit in LONG_NAME field (255 characters) * Refer to GF# 12379 for guidance on this */ if (sizedUpInstr.length() > MAX_LONG_NAME_LENGTH) { sizedUpInstr = sizedUpInstr.substring(0, MAX_LONG_NAME_LENGTH); } Instruction instr = new InstructionTransferObject(); instr.setLongName(sizedUpInstr); instr.setDisplayOrder(0); instr.setVersion(new Float(1)); instr.setAslName("DRAFT NEW"); instr.setContext(moduledto.getContext()); instr.setPreferredDefinition(instString); instr.setCreatedBy(moduledto.getCreatedBy()); newQuestdto.setInstruction(instr); questInstructionV2Dao.createInstruction(instr, newQuestdto.getQuesIdseq()); } /** * Check if question has existing instruction. If instruction found in db, update it. Otherwise, create new. * * Do nothing if instruction string is null or empty. * * @param questdto * @param moduledto * @param instString */ protected void updateQuestionInstruction(QuestionTransferObject questdto, ModuleTransferObject moduledto, String instString) { if (instString == null || instString.length() == 0) return; //Nothing to do List existings = questInstructionV2Dao.getInstructions(questdto.getQuesIdseq()); if (existings != null && existings.size() > 0) { String sizedUpInstr = instString; InstructionTransferObject existing = (InstructionTransferObject)existings.get(0); if (sizedUpInstr.length() > MAX_LONG_NAME_LENGTH) { sizedUpInstr = sizedUpInstr.substring(0, MAX_LONG_NAME_LENGTH); } Instruction instr = new InstructionTransferObject(); instr.setLongName(sizedUpInstr); instr.setPreferredDefinition(instString); instr.setModifiedBy(moduledto.getCreatedBy()); instr.setIdseq(existing.getIdseq()); questInstructionV2Dao.updateInstruction(instr); } else { createQuestionInstruction(questdto, moduledto, instString); } } protected QuestionTransferObject translateIntoQuestionDTO(QuestionDescriptor question, FormDescriptor form) { QuestionTransferObject questdto = new QuestionTransferObject(); String deSeqid = question.getCdeSeqId(); if (deSeqid != null && deSeqid.length() > 0) { DataElementTransferObject de = new DataElementTransferObject(); de.setDeIdseq(deSeqid); questdto.setDataElement(de); } if (!FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(form.getLoadType())) { questdto.setVersion(Float.valueOf("1.0")); questdto.setCreatedBy(form.getCreatedBy()); } else { questdto.setVersion(Float.valueOf(question.getVersion())); questdto.setModifiedBy(form.getModifiedBy()); } String pid = question.getPublicId(); if (pid != null && pid.length() > 0) questdto.setPublicId(Integer.parseInt(pid)); questdto.setEditable(question.isEditable()); questdto.setMandatory(question.isMandatory()); questdto.setDefaultValue(question.getDefaultValue()); questdto.setAslName("DRAFT NEW"); questdto.setLongName(question.getQuestionText()); //TODO: xsd doesn't have preferred def use question text now //Denise: if preferred def of data element if it's not null. Otherwise, use long name of data element. if No CDE, use question text questdto.setPreferredDefinition(question.getQuestionText()); return questdto; } protected ModuleTransferObject translateIntoModuleDTO(ModuleDescriptor module, FormDescriptor form, FormV2TransferObject formdto) { ModuleTransferObject moduleDto = new ModuleTransferObject(); moduleDto.setForm(formdto); moduleDto.setAslName("DRAFT NEW"); moduleDto.setLongName(module.getLongName()); if (!FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(form.getLoadType())) { moduleDto.setVersion(Float.valueOf("1.0")); moduleDto.setCreatedBy(formdto.getCreatedBy()); } else { moduleDto.setModifiedBy(form.getModifiedBy()); moduleDto.setPublicId(Integer.parseInt((module.getPublicId()))); moduleDto.setVersion(Float.parseFloat(module.getVersion())); } moduleDto.setContext(formdto.getContext()); moduleDto.setPreferredDefinition(module.getPreferredDefinition()); return moduleDto; } protected List<FormDescriptor> translateIntoFormDescriptors(List<FormV2TransferObject> formdtos) { List<FormDescriptor> forms = new ArrayList<FormDescriptor>(); if (formdtos == null) { logger.debug("Form dtos is null. Can't translater list into FormDescriptors"); return forms; } for (FormV2TransferObject dto : formdtos) { FormDescriptor form = new FormDescriptor(); form.setFormSeqId(dto.getFormIdseq()); form.setLongName(dto.getLongName()); form.setContext(dto.getContextName()); form.setModifiedBy(dto.getModifiedBy()); form.setCreatedBy(dto.getCreatedBy()); form.setProtocolName(dto.getProtocolLongName()); form.setPublicId(String.valueOf(dto.getPublicId())); form.setVersion(String.valueOf(dto.getVersion())); form.setType(dto.getFormType()); forms.add(form); } return forms; } /** * Update inlcudes adding new modules, updating existing ones and delete extra ones that are not in xml * * @param form * @param formdto */ @Transactional protected void updateModulesInForm(FormDescriptor form, FormV2TransferObject formdto) { List<ModuleDescriptor> modules = form.getModules(); List<ModuleTransferObject> existingModuledtos = this.formV2Dao.getModulesInAForm(formdto.getFormIdseq()); /* * Denise: * For a module and its questions in a form 1) If it's a new form or new version, use the form's createdBy 2) If it's an update form, check what's with module element in xml. a. If the module's createBy is valid, use it and apply that to all questions. b. If the module's createdBy is not valid, use form's createdBy and apply to all questions. */ int displayOrder = 0; for (ModuleDescriptor module : modules) { ModuleTransferObject moduledto = translateIntoModuleDTO(module, form, formdto); moduledto.setDisplayOrder(++displayOrder); String moduleSeqid = ""; if (isExistingModule(moduledto, existingModuledtos)) { int res = moduleV2Dao.updateModuleComponent(moduledto); //TODO: better understand spring sqlupdate return code updateQuestionsInModule(module, moduledto, form, formdto); } else { moduledto.setContext(formdto.getContext()); moduleSeqid = moduleV2Dao.createModuleComponent(moduledto); module.setModuleSeqId(moduleSeqid); moduledto.setIdseq(moduleSeqid); //Now, onto questions. Ignore version from xml. Start from 1.0 resetQeustionVersionInModule(module); // createQuestionsInModule(module, moduledto, form, formdto); } } //Find the existing modules to be deleted removeExtraModulesIfAny(existingModuledtos); } protected boolean isExistingModule(ModuleTransferObject currModule, List<ModuleTransferObject> existingModuledtos) { for (ModuleTransferObject moduledto : existingModuledtos) { if ((moduledto.getPublicId() == currModule.getPublicId()) && (moduledto.getVersion().floatValue() == currModule.getVersion().floatValue())) { currModule.setIdseq(moduledto.getIdseq()); currModule.setModuleIdseq(moduledto.getModuleIdseq()); //don't know how these are used moduledto.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); //use this to indicate module's taken return true; } } return false; } /** * Check the list to see if any is marked with MARK_FOR_DELETE. Delete the marked ones. * @param existingmoduledtos */ protected void removeExtraModulesIfAny(List<ModuleTransferObject> existingmoduledtos) { for (ModuleTransferObject moduledto : existingmoduledtos) { if (moduledto.getDisplayOrder() != MARK_TO_KEEP_IN_UPDATE) { logger.debug("Found a module to delete: [" + moduledto.getPublicId() + "|" + moduledto.getVersion() + "]"); this.moduleV2Dao.deleteModule(moduledto.getModuleIdseq()); } } } /** * Check a list of pre-processed existing questions from db. Delete those NOT marked as MARK_TO_KEEP_IN_UPDATE * @param questiondtos */ @Transactional protected void removeExtraQuestionsIfAny(List<QuestionTransferObject> questiondtos) { //Method copied from FormBuilderEJB for (QuestionTransferObject qdto : questiondtos) { if (qdto.getDisplayOrder() == MARK_TO_KEEP_IN_UPDATE) continue; String qSeqid = qdto.getQuesIdseq(); logger.debug("Found a question to delete: [" + qdto.getPublicId() + "|" + qdto.getVersion() + "|" + qSeqid); //delete question questionV2Dao.deleteQuestion(qdto.getQuesIdseq()); logger.debug("Done deleting question"); //delete instructions List instructions = this.questInstructionV2Dao.getInstructions(qSeqid); if (instructions != null && instructions.size() > 0) { logger.debug("Deleting instructions for question..."); for (int i = 0; i < instructions.size(); i++) { InstructionTransferObject instr = (InstructionTransferObject)instructions.get(i); this.questInstructionV2Dao.deleteInstruction(instr.getIdseq()); logger.debug("Deleted an instruction for question"); } } //delete valid values List<String> vvIds = this.formValidValueV2Dao.getValidValueSeqidsByQuestionSeqid(qSeqid); if (vvIds != null) { for (String vvid : vvIds) { //This calls remove_value sp which takes care of vv and instruction formValidValueV2Dao.deleteFormValidValue(vvid); } } } } /** * Reset all question versions to 1.0 in a module, mostly because we'll insert these questions * as new. * @param module */ protected void resetQeustionVersionInModule(ModuleDescriptor module) { List<QuestionDescriptor> questions = module.getQuestions(); for (QuestionDescriptor question : questions) { question.setVersion("1.0"); } } /** * * @param module * @param moduledto * @param form * @param formdto */ protected void updateQuestionsInModule(ModuleDescriptor module, ModuleTransferObject moduledto, FormDescriptor form, FormV2TransferObject formdto) { List<QuestionTransferObject> existingQuestiondtos = moduleV2Dao.getQuestionsInAModuleV2(moduledto.getModuleIdseq()); List<QuestionDescriptor> questions = module.getQuestions(); int idx = 0; for (QuestionDescriptor question : questions) { if (question.isSkip()) continue; QuestionTransferObject questdto = translateIntoQuestionDTO(question, form); questdto.setContext(formdto.getContext()); questdto.setModule(moduledto); //questdto.setModifiedBy(module.getModifiedBy()); //TODO: display order should come from xml? questdto.setDisplayOrder(idx++); QuestionTransferObject existingquestdto = getExistingQuestionDto(questdto, existingQuestiondtos); if (existingquestdto != null) { //existing question updateQuestion(question, questdto, existingquestdto, moduledto, formdto); } else { //better to call createQuestionComponents, which is not implemented. QuestionTransferObject newQuestdto = (QuestionTransferObject)this.questionV2Dao.createQuestionComponent(questdto); createQuestionInstruction(newQuestdto, moduledto, question.getInstruction()); createQuestionValidValues(question, form, newQuestdto, moduledto, formdto); } } removeExtraQuestionsIfAny(existingQuestiondtos); } /** * Determine if it's an existing question based on public id and version * @param currQuestiondto * @param existingQuestiondtos * @return */ protected QuestionTransferObject getExistingQuestionDto(QuestionTransferObject currQuestdto, List<QuestionTransferObject> existingQuestiondtos) { for (QuestionTransferObject quest : existingQuestiondtos) { if (currQuestdto.getPublicId() == quest.getPublicId() && currQuestdto.getVersion().floatValue() == quest.getVersion().floatValue()) { currQuestdto.setQuesIdseq(quest.getQuesIdseq()); currQuestdto.setIdseq(quest.getIdseq()); //Mark this as being update so we don't collect it to delete later. quest.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); return quest; } } return null; } /** * Update an existing question's various attributes. * @param question * @param questdto * @param moduledto */ @Transactional protected void updateQuestion(QuestionDescriptor question, QuestionTransferObject questdto, QuestionTransferObject existing, ModuleTransferObject moduledto, FormV2TransferObject formdto) { //What we could update in sbrext.Quest_contents_view_ext //display order, long name and asl name if (!questdto.getLongName().equals(existing.getLongName()) || questdto.getDisplayOrder() != existing.getDisplayOrder()) { int res = questionV2Dao.updateQuestionLongNameDispOrderDeIdseq(questdto); } //What we could update in sbrext.quest_attributes_ext //manditory, editable, default value QuestionChangeTransferObject qChangedto = new QuestionChangeTransferObject(); qChangedto.setDefaultValue(question.getDefaultValue()); qChangedto.setEditable(question.isEditable()); qChangedto.setMandatory(question.isMandatory()); qChangedto.setQuestionId(questdto.getQuesIdseq()); qChangedto.setQuestAttrChange(true); //update isEditable, isMandatory and default value questionV2Dao.updateQuestAttr(qChangedto, questdto.getModifiedBy().toUpperCase()); //what to do with isderived? updateQuestionInstruction(questdto, moduledto, question.getInstruction()); //For valid values, need to first compare what's in db updateQuestionValidValues(question, questdto, moduledto, formdto); } protected void updateQuestionValidValues(QuestionDescriptor question, QuestionTransferObject questdto, ModuleTransferObject moduledto, FormV2TransferObject formdto) { List<QuestionDescriptor.ValidValue> validValues = question.getValidValues(); List<FormValidValueTransferObject> existingVVs = questionV2Dao.getValidValues(questdto.getQuesIdseq()); /* * compare vv's long name, preferred definition and display order * * */ int idx = 0; for (QuestionDescriptor.ValidValue vValue : validValues) { FormValidValueTransferObject fvvdto = translateIntoValidValueDto(vValue, questdto, moduledto, formdto, idx); fvvdto.setDisplayOrder(idx++); if (isExistingValidValue(fvvdto, existingVVs)) { fvvdto.setModifiedBy(moduledto.getModifiedBy()); this.updateQuestionValidValue(fvvdto, vValue, questdto); } else { String vvSeqid = formValidValueV2Dao.createValidValue(fvvdto,questdto.getQuesIdseq(),moduledto.getCreatedBy()); if (vvSeqid != null && vvSeqid.length() > 0) { formValidValueV2Dao.createValidValueAttributes(vvSeqid, vValue.getMeaningText(), vValue.getDescription(), moduledto.getCreatedBy()); String instr = vValue.getInstruction(); if (instr != null && instr.length() > 0) { InstructionTransferObject instrdto = createInstructionDto(fvvdto, instr); formValidValueInstructionV2Dao.createInstruction(instrdto, vvSeqid); } } } } } protected boolean isExistingValidValue(FormValidValueTransferObject currVV, List<FormValidValueTransferObject> existingVVs) { for (FormValidValueTransferObject vv : existingVVs) { if (currVV.getLongName().equalsIgnoreCase((vv.getLongName())) && currVV.getPreferredDefinition().equalsIgnoreCase(vv.getPreferredDefinition())) { currVV.setIdseq(vv.getIdseq()); currVV.setValueIdseq(vv.getValueIdseq()); return true; } } return false; } protected void updateQuestionValidValue(FormValidValueTransferObject currVV, QuestionDescriptor.ValidValue vvXml, QuestionTransferObject questdto) { formValidValueV2Dao.updateDisplayOrder(currVV.getValueIdseq(), currVV.getDisplayOrder(), currVV.getModifiedBy()); String meaningText = vvXml.getMeaningText(); String description = vvXml.getDescription(); if (meaningText != null && meaningText.length() > 0 || description != null && description.length() > 0) formValidValueV2Dao.updateValueMeaning(currVV.getValueIdseq(), meaningText, description, currVV.getModifiedBy()); /* * */ String instruct = vvXml.getInstruction(); if (instruct != null && instruct.length() > 0) { Instruction instr = new InstructionTransferObject(); instr.setLongName(instruct); instr.setDisplayOrder(0); instr.setVersion(new Float(1)); instr.setAslName("DRAFT NEW"); instr.setContext(questdto.getContext()); instr.setPreferredDefinition(instruct); instr.setCreatedBy(questdto.getCreatedBy()); formValidValueInstructionV2Dao.createInstruction(instr, currVV.getValueIdseq()); } } @Transactional public String createFormCollectionRecords(FormCollection coll) { String collSeqid = collectionDao.createCollectionRecord(coll.getName(), coll.getDescription(), coll.getXmlFileName(), coll.getXmlPathOnServer(), coll.getCreatedBy()); if (collSeqid == null || collSeqid.length() == 0) { logger.error("Error!!! while creating record for collection: " + coll.getName() + " Uable to create form and collection mappings."); return null; } List<FormDescriptor> forms = coll.getForms(); for (FormDescriptor form : forms) { if (form.getLoadStatus() != FormDescriptor.STATUS_LOADED) continue; int res = collectionDao.createCollectionFormMappingRecord(collSeqid, form.getFormSeqId(), Integer.parseInt(form.getPublicId()), Float.parseFloat(form.getVersion()), form.getLoadType()); //TODO: check response value. int loatStatus = (res > 0) ? FormDescriptor.STATUS_LOADED : FormDescriptor.STATUS_LOAD_FAILED; } return collSeqid; } public boolean hasLoadFormRight(FormDescriptor form, String userName, String contextName) { String contextseqid = this.getContextSeqIdByName(contextName); if (userName == null || userName.length() == 0) { form.addMessage("User name is emppty. Unable to verify user load right"); return false; } if (contextseqid == null || contextseqid.length() == 0) { form.addMessage("Context name [" + contextName + "]is empty. Unable to verify user load right"); return false; } return this.formV2Dao.hasCreate(userName, COMPONENT_TYPE_FORM, contextseqid); } @Transactional(readOnly=true) public boolean definitionTypeValid(FormDescriptor form) { if (definitionTypes == null) { definitionTypes = this.formV2Dao.getAllDefinitionTypes(); } return false; } //@Transactional(readOnly=true) /* public void validateDesignationType(FormDescriptor form) { if (designationTypes == null) { designationTypes = this.formV2Dao.getAllDesignationTypes(); } if (designationTypeExists(form) return false; //return (designationTypes == null) ? false : designationTypes.contains(form.getd); } */ @Transactional(readOnly=true) public boolean refDocTypeValid(FormDescriptor form) { if (refdocTypes == null) { refdocTypes = this.formV2Dao.getAllRefdocTypes(); } return false; } @Transactional(readOnly=true) public void checkWorkflowStatusName(FormDescriptor form) { if (workflowNames == null) { workflowNames = this.formV2Dao.getAllWorkflowNames(); } String formWfName = form.getWorkflowStatusName(); if (!workflowNames.contains(formWfName)) { form.addMessage("Form's workflow status name invalid. Use default value Draft New"); form.setWorkflowStatusName(DEFAULT_WORKFLOW_STATUS); } } @Transactional public void unloadForm(FormDescriptor form) { String seqid = form.getFormSeqId(); if (seqid == null || seqid.length() == 0) { logger.debug("Form's seqid is invalid"); form.addMessage("Form's seqid is invalid. Unable to unload form"); form.setLoadStatus(FormDescriptor.STATUS_UNLOAD_FAILED); return; } int res = formV2Dao.updateWorkflowStatus(seqid, "RETIRED WITHDRAWN"); if (res <= 0) { form.addMessage("Failed to update form's workflow status. Unload failed"); form.setLoadStatus(FormDescriptor.STATUS_UNLOAD_FAILED); } else form.setLoadStatus(FormDescriptor.STATUS_UNLOADED); } }
software/FormLoader/src/gov/nih/nci/cadsr/formloader/repository/FormLoaderRepositoryImpl.java
package gov.nih.nci.cadsr.formloader.repository; import gov.nih.nci.cadsr.formloader.domain.FormCollection; import gov.nih.nci.cadsr.formloader.domain.FormDescriptor; import gov.nih.nci.cadsr.formloader.domain.ModuleDescriptor; import gov.nih.nci.cadsr.formloader.domain.QuestionDescriptor; import gov.nih.nci.cadsr.formloader.service.common.StaXParser; import gov.nih.nci.ncicb.cadsr.common.dto.AdminComponentTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.ContextTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DataElementTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DefinitionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObjectExt; import gov.nih.nci.ncicb.cadsr.common.dto.FormV2TransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.FormValidValueTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.InstructionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.ModuleTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.PermissibleValueV2TransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.QuestionChangeTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.QuestionTransferObject; import gov.nih.nci.ncicb.cadsr.common.dto.RefdocTransferObjectExt; import gov.nih.nci.ncicb.cadsr.common.dto.ReferenceDocumentTransferObject; import gov.nih.nci.ncicb.cadsr.common.exception.DMLException; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCCollectionDAO; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormValidValueDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormValidValueInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCModuleDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCQuestionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCQuestionInstructionDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCReferenceDocumentDAOV2; import gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCValueDomainDAOV2; import gov.nih.nci.ncicb.cadsr.common.resource.Context; import gov.nih.nci.ncicb.cadsr.common.resource.FormV2; import gov.nih.nci.ncicb.cadsr.common.resource.Instruction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public class FormLoaderRepositoryImpl implements FormLoaderRepository { private static Logger logger = Logger.getLogger(FormLoaderRepositoryImpl.class.getName()); static final int MAX_LONG_NAME_LENGTH = 255; public static final String COMPONENT_TYPE_FORM = "QUEST_CONTENT"; public static final String DEFAULT_WORKFLOW_STATUS = "DRAFT NEW"; public static final String DEFAULT_DEFINITION_TYPE = "Form Loader"; public static final String DEFAULT_DESIGNATION_TYPE = "Form Loader"; public static final String DEFAULT_CONTEXT_NAME = "NCIP"; public static final String DEFAULT_FORM_TYPE = "CRF"; public static final String DEFAULT_REFDOC_TYPE = "REFERENCE"; protected static final int MARK_TO_KEEP_IN_UPDATE = 99; JDBCFormDAOV2 formV2Dao; JDBCModuleDAOV2 moduleV2Dao; JDBCQuestionDAOV2 questionV2Dao; JDBCValueDomainDAOV2 valueDomainV2Dao; JDBCFormInstructionDAOV2 formInstructionV2Dao; JDBCQuestionInstructionDAOV2 questInstructionV2Dao; JDBCFormValidValueDAOV2 formValidValueV2Dao; JDBCFormValidValueInstructionDAOV2 formValidValueInstructionV2Dao; JDBCCollectionDAO collectionDao; JDBCReferenceDocumentDAOV2 referenceDocV2Dao; //These are loaded from database for validation purposes HashMap<String, String> conteNameSeqIdMap; List<String> definitionTypes; List<String> designationTypes; List<String> refdocTypes; List<String> workflowNames; /** * Gets Seq id, public id and version for forms with the given public ids * @param pubicIDList * @return */ @Transactional(readOnly=true) public List<FormV2> getFormsForPublicIDs(List<String> pubicIDList) { if (pubicIDList == null || pubicIDList.size() ==0) { logger.debug("getFormsForPublicIDs(): public id list is null or empty. Do nothing."); return null; } //Seq id, public id and version are set in the returned forms List<FormV2> formDtos = formV2Dao.getExistingVersionsForPublicIds(pubicIDList); logger.debug("getFormsForPublicIDs() returns " + formDtos.size() + " forms with " + pubicIDList.size() + " public ids"); return formDtos; } @Transactional(readOnly=true) public List<QuestionTransferObject> getQuestionsByPublicId(String publicId) { if (publicId == null || publicId.length() == 0) { logger.debug("getQuestionsByPublicId(): Question public id is null or empty. Unable to querry db."); return null; } int pubId = Integer.parseInt(publicId); List<QuestionTransferObject> questions = questionV2Dao.getQuestionsByPublicId(pubId); logger.debug("getQuestionsByPublicId(): Dao returns " + questions.size() + " questions."); return questions; } @Transactional(readOnly=true) public List<QuestionTransferObject> getQuestionsByPublicIds(List<String> publicIds) { if (publicIds == null || publicIds.size() == 0) { logger.debug("getQuestionsByPublicIds(): Question public id list is null or empty. Unable to querry db."); return null; } List<QuestionTransferObject> questions = questionV2Dao.getQuestionsByPublicIds(publicIds); logger.debug("getQuestionsByPublicId(): Dao returns " + questions.size() + " questions."); return questions; } @Transactional(readOnly=true) public List<DataElementTransferObject> getCDEByPublicId(String cdePublicId) { if (cdePublicId == null || cdePublicId.length() == 0) { logger.debug("getCDEByPublicId(): Question's CDE public id is null or empty. Unable to querry db."); return null; } List<DataElementTransferObject> des = questionV2Dao.getCdesByPublicId(cdePublicId); logger.debug("getCDEByPublicId(): Dao returns " + des.size() + " CDEs"); return des; } @Transactional(readOnly=true) public List<DataElementTransferObject> getCDEsByPublicIds(List<String> cdePublicIds) { if (cdePublicIds == null || cdePublicIds.size() == 0) { logger.debug("getCDEsByPublicIds(): cde public id list is null or empty. Unable to querry db."); return null; } List<DataElementTransferObject> des = questionV2Dao.getCdesByPublicIds(cdePublicIds); logger.debug("getCDEsByPublicIds(): Dao returns " + des.size() + " CDEs"); return des; } @Transactional(readOnly=true) public List<ReferenceDocumentTransferObject> getReferenceDocsForQuestionCde(String cdePublicId, String cdeVersion) { if (cdePublicId == null || cdePublicId.length() == 0) { logger.debug("getReferenceDocsForQuestionCde(): Question's CDE public id is null or empty. Unable to querry db."); return null; } if (cdeVersion == null || cdeVersion.length() == 0) { logger.debug("getReferenceDocsForQuestionCde(): Question CDE version is null or empty. Unable to querry db."); return null; } List<ReferenceDocumentTransferObject> deRefDocs = questionV2Dao.getAllReferenceDocumentsForDE( Integer.parseInt(cdePublicId), Float.parseFloat(cdeVersion)); logger.debug("getReferenceDocsForQuestionCde(): Dao returns " + deRefDocs.size() + " CDE reference docs."); return deRefDocs; } @Transactional(readOnly=true) public HashMap<String, List<ReferenceDocumentTransferObject>> getReferenceDocsByCdePublicIds(List<String> cdePublicIds) { if (cdePublicIds == null || cdePublicIds.size() == 0) { logger.debug("getReferenceDocsByCdePublicIds(): cde public id list is null or empty. Unable to querry db."); return null; } HashMap<String, List<ReferenceDocumentTransferObject>> deRefDocs = questionV2Dao.getReferenceDocumentsByCdePublicIds(cdePublicIds); logger.debug("getReferenceDocsByCdePublicIds(): Dao returns " + deRefDocs.size() + " CDE reference docs."); return deRefDocs; } @Transactional(readOnly=true) public List<PermissibleValueV2TransferObject> getValueDomainPermissibleValuesByVdId(String vdSeqId) { if (vdSeqId == null || vdSeqId.length() == 0) { logger.debug("getValueDomainBySeqId(): Value domain seq id is null or empty. Unable to querry db."); return null; } List<PermissibleValueV2TransferObject> pValues = valueDomainV2Dao.getPermissibleValuesByVdId(vdSeqId); String msg = "getValueDomainPermissibleValuesByVdId(): Dao returns "; if (pValues == null || pValues.size() == 0) msg += "a value domain obj with 0 permissible value."; else msg += "a value domain obj with " + pValues.size() + " permissible values"; logger.debug("msg"); return pValues; } @Transactional(readOnly=true) public HashMap<String, List<PermissibleValueV2TransferObject>> getPermissibleValuesByVdIds(List<String> vdSeqIds) { if (vdSeqIds == null || vdSeqIds.size() == 0) { logger.debug("getPermissibleValuesByVdIds(): vdSeqIds list is null or empty. Unable to querry db."); return null; } HashMap<String, List<PermissibleValueV2TransferObject>> pValues = valueDomainV2Dao.getPermissibleValuesByVdIds(vdSeqIds); String msg = "getPermissibleValuesByVdIds(): Dao returns "; if (pValues == null || pValues.size() == 0) msg += "a value domain obj with 0 permissible value."; else msg += "a value domain obj with " + pValues.size() + " permissible values"; logger.debug(msg); return pValues; } /** * To get the public id and version for the loaded forms * @param forms */ @Transactional(readOnly=true) public void setPublicIdVersionBySeqids(List<FormDescriptor> forms) { List<String> seqids = new ArrayList<String>(); for (FormDescriptor form : forms) { if (form.getLoadStatus() == FormDescriptor.STATUS_LOADED) seqids.add(form.getFormSeqId()); } if (seqids.size() == 0) return; HashMap<String, FormV2TransferObject> seqidMap = formV2Dao.getFormsBySeqids(seqids); for (FormDescriptor form : forms) { FormV2TransferObject formdto = seqidMap.get(form.getFormSeqId()); if (formdto != null) { form.setPublicId(String.valueOf(formdto.getPublicId())); form.setVersion(String.valueOf(formdto.getVersion())); } } } @Transactional(readOnly=true) public List<FormCollection> getAllLoadedCollections() { //first get collection headers List<FormCollection> colls = collectionDao.getAllLoadedCollections(); for (FormCollection coll : colls) { if (coll.getId().equals("E49101B2-1B48-BA26-E040-BB8921B61DC6")) { logger.debug("debug"); } List<String> formseqids = collectionDao.getAllFormSeqidsForCollection(coll.getId()); if (formseqids == null || formseqids.size() == 0) logger.warn("Collection " + coll.getId() + " doesn't have form seqids associated with it in database"); else { List<FormV2TransferObject> formdtos = this.formV2Dao.getFormHeadersBySeqids(formseqids); List<FormDescriptor> forms = translateIntoFormDescriptors(formdtos); coll.setForms(forms); } } return colls; } protected void retrievePublicIdForForm(String formSeqid, FormDescriptor form) { FormV2TransferObject formdto = this.formV2Dao.getFormPublicIdVersion(formSeqid); form.setPublicId(String.valueOf(formdto.getPublicId())); form.setVersion(String.valueOf(formdto.getVersion())); } protected void retrievePublicIdForQuestion(String questSeqid, QuestionDescriptor quest,QuestionTransferObject questdto) { QuestionTransferObject dto = this.questionV2Dao.getQuestionsPublicIdVersionBySeqid(questSeqid); quest.setPublicId(String.valueOf(dto.getPublicId())); quest.setVersion(String.valueOf(dto.getVersion())); questdto.setPublicId(dto.getPublicId()); questdto.setVersion(dto.getVersion()); } public JDBCFormDAOV2 getFormV2Dao() { return formV2Dao; } public void setFormV2Dao(JDBCFormDAOV2 formV2Dao) { this.formV2Dao = formV2Dao; } public JDBCModuleDAOV2 getModuleV2Dao() { return moduleV2Dao; } public void setModuleV2Dao(JDBCModuleDAOV2 moduleV2Dao) { this.moduleV2Dao = moduleV2Dao; } public JDBCQuestionDAOV2 getQuestionV2Dao() { return questionV2Dao; } public void setQuestionV2Dao(JDBCQuestionDAOV2 questionV2Dao) { this.questionV2Dao = questionV2Dao; } public JDBCValueDomainDAOV2 getValueDomainV2Dao() { return valueDomainV2Dao; } public void setValueDomainV2Dao(JDBCValueDomainDAOV2 valueDomainV2Dao) { this.valueDomainV2Dao = valueDomainV2Dao; } public JDBCFormInstructionDAOV2 getFormInstructionV2Dao() { return formInstructionV2Dao; } public void setFormInstructionV2Dao( JDBCFormInstructionDAOV2 formInstructionV2Dao) { this.formInstructionV2Dao = formInstructionV2Dao; } public JDBCQuestionInstructionDAOV2 getQuestInstructionV2Dao() { return questInstructionV2Dao; } public void setQuestInstructionV2Dao( JDBCQuestionInstructionDAOV2 questInstructionV2Dao) { this.questInstructionV2Dao = questInstructionV2Dao; } public JDBCFormValidValueDAOV2 getFormValidValueV2Dao() { return formValidValueV2Dao; } public void setFormValidValueV2Dao(JDBCFormValidValueDAOV2 formValidValueV2Dao) { this.formValidValueV2Dao = formValidValueV2Dao; } public JDBCFormValidValueInstructionDAOV2 getFormValidValueInstructionV2Dao() { return formValidValueInstructionV2Dao; } public void setFormValidValueInstructionV2Dao( JDBCFormValidValueInstructionDAOV2 formValidValueInstructionV2Dao) { this.formValidValueInstructionV2Dao = formValidValueInstructionV2Dao; } public JDBCCollectionDAO getCollectionDao() { return collectionDao; } public void setCollectionDao(JDBCCollectionDAO collectionDao) { this.collectionDao = collectionDao; } public JDBCReferenceDocumentDAOV2 getReferenceDocV2Dao() { return referenceDocV2Dao; } public void setReferenceDocV2Dao(JDBCReferenceDocumentDAOV2 referenceDocV2Dao) { this.referenceDocV2Dao = referenceDocV2Dao; } @Transactional(readOnly=true) public String getContextSeqIdByName(String contextName) { if (conteNameSeqIdMap == null) conteNameSeqIdMap = this.formV2Dao.getAllContextSeqIds(); return conteNameSeqIdMap.get(contextName); } @Transactional(readOnly=true) public boolean designationTypeExists(String designName) { if (designationTypes == null) designationTypes = this.formV2Dao.getAllDesignationTypes(); return designationTypes.contains(designName); } @Transactional(readOnly=true) public boolean refdocTypeExists(String refdocType) { if (this.refdocTypes == null) refdocTypes = this.formV2Dao.getAllRefdocTypes(); return refdocTypes.contains(refdocType); } /** * Create new form */ @Transactional public String createForm(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { String formSeqid = ""; try { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) return null; formSeqid = formV2Dao.createFormComponent(formdto); logger.debug("Created form. Seqid: " + formSeqid); //public id is created when new component is created //Need to go back to db for it retrievePublicIdForForm(formSeqid, form); formdto.setFormIdseq(formSeqid); form.setFormSeqId(formSeqid); //instructions createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions createModulesInForm(form, formdto); } catch (DMLException dbe) { logger.error(dbe.getMessage()); } return formSeqid; } /** * Create new form or new version of an existing form * <br><br> * This will first call the store procedure Sbrext_Form_Builder_Pkg.CRF_VERSION which will make a full copy * of the form with the same public id and an upgraded version number. Then it'll apply an update on the * copy with content from the xml. This is very inefficient. * <br><br> * Need to explore better way. Key quetions: how public id * is generated? Is it possible to insert new form row withough triggering a new public id generation. */ @Transactional public String createFormNewVersion(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { String formSeqid = ""; try { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) return null; formSeqid = formV2Dao.createNewFormVersion(formdto.getFormIdseq(), formdto.getVersion(), "New version form by Form Loader", formdto.getCreatedBy()); logger.debug("Created new version for form. Seqid: " + formSeqid); formdto.setFormIdseq(formSeqid); form.setFormSeqId(formSeqid); int res = formV2Dao.updateFormComponent(formdto); if (res != 1) { logger.error("Error!! Failed to update form"); return null; } createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions updateModulesInForm(form, formdto); return form.getFormSeqId(); } catch (DMLException dbe) { logger.error(dbe.getMessage()); } return formSeqid; } @Transactional public String updateForm(FormDescriptor form, String loggedinUser, String xmlPathName, int formIdx) { FormV2TransferObject formdto = translateIntoFormDTO(form); if (formdto == null) { logger.error("Error!! Failed to translate xml form into FormTransferObject"); return null; } int res = formV2Dao.updateFormComponent(formdto); if (res != 1) { logger.error("Error!! Failed to update form"); return null; } createFormInstructions(form, formdto); //designations, refdocs, definitions and contact communications processFormdetails(form, xmlPathName, formIdx); //Onto modules and questions updateModulesInForm(form, formdto); return form.getFormSeqId(); } protected FormV2TransferObject translateIntoFormDTO(FormDescriptor form) { FormV2TransferObject formdto = new FormV2TransferObject(); String loadType = form.getLoadType(); if (FormDescriptor.LOAD_TYPE_NEW_VERSION.equals(loadType)) { float latest = this.formV2Dao.getMaxFormVersion(Integer.parseInt(form.getPublicId())); formdto.setVersion(new Float(latest + 1.0)); //TODO: is this the way to assign new version? formdto.setPublicId(Integer.parseInt(form.getPublicId())); formdto.setFormIdseq(form.getFormSeqId()); formdto.setAslName("DRAFT NEW"); formdto.setCreatedBy(form.getCreatedBy()); } else if (FormDescriptor.LOAD_TYPE_NEW.equals(loadType)) { formdto.setVersion(Float.valueOf("1.0")); formdto.setAslName("DRAFT NEW"); formdto.setCreatedBy(form.getCreatedBy()); } else if (FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(loadType)) { formdto.setVersion(Float.valueOf(form.getVersion())); formdto.setAslName(form.getWorkflowStatusName()); formdto.setModifiedBy(form.getModifiedBy()); String seqid = form.getFormSeqId(); //we got this when we queried on form public id //This should not happen if (seqid == null || seqid.length() == 0) { String msg = "Update form doesn't have a valid seqid. Unable to load."; form.addMessage(msg); form.setLoadStatus(FormDescriptor.STATUS_LOAD_FAILED); logger.error("Error with [" + form.getFormIdString() + "]: " + msg); return null; } formdto.setFormIdseq(seqid); } formdto.setLongName(form.getLongName()); formdto.setPreferredName(form.getLongName()); formdto.setFormType(form.getType()); formdto.setFormCategory(form.getCategoryName()); formdto.setPreferredDefinition(form.getPreferredDefinition()); String contextName = form.getContext(); if (contextName != null && contextName.length() > 0) { Context context = new ContextTransferObject(); context.setConteIdseq(this.getContextSeqIdByName(contextName)); formdto.setContext(context); formdto.setConteIdseq(this.getContextSeqIdByName(contextName)); } else { String msg = "Form doesn't have a valid context name. Unable to load"; form.addMessage(msg); form.setLoadStatus(FormDescriptor.STATUS_LOAD_FAILED); logger.error(form.getFormIdString() + ": " + msg); return null; } return formdto; } protected void createFormInstructions(FormDescriptor form, FormV2TransferObject formdto) { logger.debug("Creating instructions for form"); String instructString = form.getHeaderInstruction(); if (instructString == null || instructString.length() == 0) return; InstructionTransferObject formInstruction = createInstructionDto(formdto, instructString); if (formInstruction != null) formInstructionV2Dao.createInstruction(formInstruction, formdto.getFormIdseq()); instructString = form.getFooterInstruction(); formInstruction = createInstructionDto(formdto, instructString); if (formInstruction != null) formInstructionV2Dao.createFooterInstruction(formInstruction, formdto.getFormIdseq()); logger.debug("Done creating instructions for form"); } protected InstructionTransferObject createInstructionDto(AdminComponentTransferObject compdto, String instructionString) { InstructionTransferObject instruction = null; if (instructionString != null && instructionString.length() > 0) { instruction = new InstructionTransferObject(); instruction.setLongName(compdto.getLongName()); instruction.setPreferredDefinition(instructionString); instruction.setContext(compdto.getContext()); instruction.setAslName("DRAFT NEW"); instruction.setVersion(new Float(1.0)); instruction.setCreatedBy(compdto.getCreatedBy()); instruction.setDisplayOrder(1); } return instruction; } protected List<String> getCdeSeqIdsFromForm(FormDescriptor form) { return null; } protected void processFormdetails(FormDescriptor form, String xmlPathName, int currFormIdx) { logger.debug("Processing protocols, designations, refdocs and definitions for form"); StaXParser parser = new StaXParser(); parser.parseFormDetails(xmlPathName, form, currFormIdx); List<String> protoIds = parser.getProtocolIds(); processProtocols(form, protoIds); List<DesignationTransferObjectExt> designations = parser.getDesignations(); processDesignations(form, designations); List<RefdocTransferObjectExt> refdocs = parser.getRefdocs(); processRefdocs(form, refdocs); //TODO List<DefinitionTransferObject> definitions = parser.getDefinitions(); //TODO //processContactCommunications() logger.debug("Done processing protocols, designations, refdocs and definitions for form"); } /** * * @param form * @param refdocs */ @Transactional protected void processRefdocs(FormDescriptor form, List<RefdocTransferObjectExt> refdocs) { if (refdocs == null) { logger.error("Null refdocs list passed in to processRefdocs(). Do nothing"); return; } String formSeqid = form.getFormSeqId(); String contextSeqId = this.getContextSeqIdByName(form.getContext()); List existings = null; if (!form.getLoadType().equals(FormDescriptor.LOAD_TYPE_NEW)) { //2nd arg is not used in the actual query. existings = this.formV2Dao.getAllReferenceDocuments(form.getFormSeqId(), null); } //create ref docs int idx = 0; for (RefdocTransferObjectExt refdoc : refdocs) { String contextName = refdoc.getContextName(); String refdocContextSeqid = this.getContextSeqIdByName(contextName); if (refdocContextSeqid == null || refdocContextSeqid.length() == 0) { refdocContextSeqid = contextSeqId; contextName = form.getContext(); } ContextTransferObject con = new ContextTransferObject(contextName); con.setConteIdseq(refdocContextSeqid); refdoc.setContext(con); refdoc.setDisplayOrder(idx++); if (!this.refdocTypeExists(refdoc.getDocType())) { form.addMessage("Refdoc type [" + refdoc.getDocType() + "] is invalid. Use default type [REFERENCE]"); refdoc.setDocType(DEFAULT_REFDOC_TYPE); } if (existings != null && isExistingRefdoc(refdoc, existings)) { referenceDocV2Dao.updateReferenceDocument(refdoc); } else { this.referenceDocV2Dao.createReferenceDoc(refdoc, formSeqid); } } removeExtraRefdocsIfAny(existings); } /** * Compare a refdoc against a list from database, based on name and type. * @param currRefdoc * @param refdocs * @return */ protected boolean isExistingRefdoc(ReferenceDocumentTransferObject currRefdoc, List<ReferenceDocumentTransferObject> refdocs) { if (refdocs == null) { return false; } for (ReferenceDocumentTransferObject refdoc : refdocs) { if (refdoc.getDocName().equals(currRefdoc.getDocName()) && refdoc.getDocType().equals(currRefdoc.getDocType()) ) { refdoc.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); currRefdoc.setDocIDSeq(refdoc.getDocIdSeq()); return true; } } return false; } /** * Check a list of ref doc object that are previously marked and delete from database those are not marked as "KEEP" * * @param refdocs */ @Transactional protected void removeExtraRefdocsIfAny(List<ReferenceDocumentTransferObject> refdocs) { if (refdocs == null) { return; } for (ReferenceDocumentTransferObject refdoc : refdocs) { if (refdoc.getDisplayOrder() == MARK_TO_KEEP_IN_UPDATE) continue; logger.debug("Deleting refdoc [" + refdoc.getDocName() + "|" + refdoc.getDocType()); referenceDocV2Dao.deleteReferenceDocument(refdoc.getDocIdSeq()); } } /** * For new version and update form, if designation doesn't already exist, designate it to the context. For new form, * designate the form to the context. * @param form * @param designations */ @Transactional protected void processDesignations(FormDescriptor form, List<DesignationTransferObjectExt> designations) { if (designations == null) { logger.error("Null designation list passed in to processDesignations(). Do nothing"); return; } String formSeqid = form.getFormSeqId(); String contextSeqId = this.getContextSeqIdByName(form.getContext()); for (DesignationTransferObjectExt desig : designations) { if (form.getLoadType().equals(FormDescriptor.LOAD_TYPE_NEW)) { designateForm(formSeqid, contextSeqId, form.getCreatedBy(), desig); } else { //Check context name in designation elem from xml. If that's not valid, use form's String desigContext = desig.getContextName(); String desgContextSeqid = this.getContextSeqIdByName(desigContext); if (desgContextSeqid == null || desgContextSeqid.length() == 0) desgContextSeqid = contextSeqId; //validate the type, use default if neccessary String desigType = desig.getType(); if (!this.designationTypeExists(desigType)) { form.addMessage("Designation type [" + desigType + "] is invalid. Use default type [Form Loader]"); desig.setType(DEFAULT_DESIGNATION_TYPE); } List<DesignationTransferObject> existing = formV2Dao.getDesignationsForForm( formSeqid, desig.getName(), desig.getType(), desig.getLanguage()); if (existing == null || existing.size() == 0) { designateForm(formSeqid, contextSeqId, form.getCreatedBy(), desig); } } } } @Transactional protected int designateForm(String formSeqid, String contextSeqid, String createdby, DesignationTransferObjectExt desig) { List<String> ac_seqids = new ArrayList<String>(); ac_seqids.add(formSeqid); return formV2Dao.designate(contextSeqid, ac_seqids, createdby); } /** * 1. New form : add all listed protocols from xml to new form. * 2. New version and update form: add only if a protocol in xml doesn't already exist with the form. * * @param form * @param protoIds */ protected void processProtocols(FormDescriptor form, List<String> protoIds) { String formSeqid = form.getFormSeqId(); if (protoIds != null && protoIds.size() > 0) { HashMap<String, String> protoIdMap = formV2Dao.getProtocolSeqidsByIds(protoIds); List<String> protoSeqIds = markNoMatchProtoIds(form, protoIds, protoIdMap); for (String protoSeqid : protoSeqIds) { if (FormDescriptor.LOAD_TYPE_NEW.equals(form.getLoadType())) { formV2Dao.addFormProtocol(formSeqid, protoSeqid, form.getCreatedBy()); } else { if (!formV2Dao.formProtocolExists(formSeqid, protoSeqid)) formV2Dao.addFormProtocol(formSeqid, protoSeqid, form.getModifiedBy()); } } } } protected List<String> markNoMatchProtoIds(FormDescriptor form, List<String> protoIds, HashMap<String, String> protoIdMap) { List<String> protoSeqIds = new ArrayList<String>(); String nomatchids = ""; for (String protoId : protoIds) { String seqid = protoIdMap.get(protoId); if (seqid == null) nomatchids = (nomatchids.length() > 0) ? "," + protoId : protoId; else protoSeqIds.add(seqid); } if (nomatchids.length() > 0) form.addMessage("Protocol ids [" + nomatchids + "] with the form has no match in database."); return protoSeqIds; } @Transactional protected void createModulesInForm(FormDescriptor form, FormV2TransferObject formdto) { logger.debug("Start creating modules for form"); List<ModuleDescriptor> modules = form.getModules(); /* * Denise: * For a module and its questions in a form 1) If it's a new form or new version, use the form's createdBy 2) If it's an update form, check what's with module element in xml. a. If the module's createBy is valid, use it and apply that to all questions. b. If the module's createdBy is not valid, use form's createdBy and apply to all questions. */ for (ModuleDescriptor module : modules) { ModuleTransferObject moduledto = translateIntoModuleDTO(module, form, formdto); String moduleSeqid = moduleV2Dao.createModuleComponent(moduledto); logger.debug("Created a module with seqid: " + moduleSeqid); module.setModuleSeqId(moduleSeqid); moduledto.setIdseq(moduleSeqid); moduledto.setContext(formdto.getContext()); //TODO: do we need to go back to db to get module's public id? //Now, onto questions createQuestionsInModule(module, moduledto, form, formdto); } logger.debug("Done creating modules for form"); } @Transactional protected void createQuestionsInModule(ModuleDescriptor module, ModuleTransferObject moduledto, FormDescriptor form, FormV2TransferObject formdto) { List<QuestionDescriptor> questions = module.getQuestions(); logger.debug("Creating questions for module"); int idx = 0; for (QuestionDescriptor question : questions) { if (question.isSkip()) continue; QuestionTransferObject questdto = translateIntoQuestionDTO(question, form); questdto.setDisplayOrder(idx++); questdto.setContext(formdto.getContext()); questdto.setModule(moduledto); //better to call createQuestionComponents, which is not implement. QuestionTransferObject newQuestdto = (QuestionTransferObject)this.questionV2Dao.createQuestionComponent(questdto); String seqid = newQuestdto.getQuesIdseq(); logger.debug("Created a question: " + seqid); question.setQuestionSeqId(seqid); retrievePublicIdForQuestion(seqid, question, questdto); createQuestionInstruction(newQuestdto, moduledto, question.getInstruction()); createQuestionValidValues(question, form, newQuestdto, moduledto, formdto); } logger.debug("Done creating questions for module"); } /** * Create valid value for a newly created question. * * @param question question generated from xml * @param form form generated from xml * @param newQuestdto new question dto that just got created in db, with new seqid and public id * @param moduledto */ @Transactional protected void createQuestionValidValues(QuestionDescriptor question, FormDescriptor form, QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, FormV2TransferObject formdto) { List<QuestionDescriptor.ValidValue> validValues = question.getValidValues(); int idx = 0; for (QuestionDescriptor.ValidValue vValue : validValues) { if (vValue.isSkip()) continue; idx++; FormValidValueTransferObject fvv = translateIntoValidValueDto(vValue, newQuestdto, moduledto, formdto, idx); fvv.setDisplayOrder(idx); String vvSeqid = formValidValueV2Dao.createValidValue(fvv,newQuestdto.getQuesIdseq(),moduledto.getCreatedBy()); if (vvSeqid != null && vvSeqid.length() > 0) { formValidValueV2Dao.createValidValueAttributes(vvSeqid, vValue.getMeaningText(), vValue.getDescription(), moduledto.getCreatedBy()); String instr = vValue.getInstruction(); if (instr != null && instr.length() > 0) { InstructionTransferObject instrdto = createInstructionDto(fvv, instr); formValidValueInstructionV2Dao.createInstruction(instrdto, vvSeqid); } } logger.debug("Created new valid valid"); } } protected FormValidValueTransferObject translateIntoValidValueDto(QuestionDescriptor.ValidValue vValue, QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, FormV2TransferObject formdto, int displayOrder) { FormValidValueTransferObject fvv = new FormValidValueTransferObject(); fvv.setCreatedBy(moduledto.getCreatedBy()); fvv.setQuestion(newQuestdto); fvv.setVpIdseq(vValue.getVdPermissibleValueSeqid()); String preferredName = composeVVPreferredName(vValue, newQuestdto.getPublicId(), formdto.getPublicId(), formdto.getVersion(), displayOrder); fvv.setLongName(vValue.getValue()); fvv.setPreferredName(preferredName); fvv.setPreferredDefinition(vValue.getDescription()); fvv.setContext(moduledto.getContext()); fvv.setVersion(Float.valueOf("1.0")); fvv.setAslName("DRAFT NEW"); return fvv; } //PreferredName format: value meaning public id_quetionpublicid_form_public_id_version_<x> x = 1, 2, 3 protected String composeVVPreferredName(QuestionDescriptor.ValidValue vValue, int questPublicId, int formPublicId, float formversion, int displayorder) { return vValue.getPreferredName() + "_" + questPublicId + "_" + formPublicId + "v" + formversion + "_" + displayorder; } /** * Create new instruction for a question. * * Do nothing is instruction string is null or empty. * * @param newQuestdto * @param moduledto * @param instString */ protected void createQuestionInstruction(QuestionTransferObject newQuestdto, ModuleTransferObject moduledto, String instString) { if (instString == null || instString.length() == 0) return; //Nothing to do String sizedUpInstr = instString; /* (Snippet copied from FormModuleEditAction (FB) * * Truncate instruction string to fit in LONG_NAME field (255 characters) * Refer to GF# 12379 for guidance on this */ if (sizedUpInstr.length() > MAX_LONG_NAME_LENGTH) { sizedUpInstr = sizedUpInstr.substring(0, MAX_LONG_NAME_LENGTH); } Instruction instr = new InstructionTransferObject(); instr.setLongName(sizedUpInstr); instr.setDisplayOrder(0); instr.setVersion(new Float(1)); instr.setAslName("DRAFT NEW"); instr.setContext(moduledto.getContext()); instr.setPreferredDefinition(instString); instr.setCreatedBy(moduledto.getCreatedBy()); newQuestdto.setInstruction(instr); questInstructionV2Dao.createInstruction(instr, newQuestdto.getQuesIdseq()); } /** * Check if question has existing instruction. If instruction found in db, update it. Otherwise, create new. * * Do nothing if instruction string is null or empty. * * @param questdto * @param moduledto * @param instString */ protected void updateQuestionInstruction(QuestionTransferObject questdto, ModuleTransferObject moduledto, String instString) { if (instString == null || instString.length() == 0) return; //Nothing to do List existings = questInstructionV2Dao.getInstructions(questdto.getQuesIdseq()); if (existings != null && existings.size() > 0) { String sizedUpInstr = instString; InstructionTransferObject existing = (InstructionTransferObject)existings.get(0); if (sizedUpInstr.length() > MAX_LONG_NAME_LENGTH) { sizedUpInstr = sizedUpInstr.substring(0, MAX_LONG_NAME_LENGTH); } Instruction instr = new InstructionTransferObject(); instr.setLongName(sizedUpInstr); instr.setPreferredDefinition(instString); instr.setModifiedBy(moduledto.getCreatedBy()); instr.setIdseq(existing.getIdseq()); questInstructionV2Dao.updateInstruction(instr); } else { createQuestionInstruction(questdto, moduledto, instString); } } protected QuestionTransferObject translateIntoQuestionDTO(QuestionDescriptor question, FormDescriptor form) { QuestionTransferObject questdto = new QuestionTransferObject(); String deSeqid = question.getCdeSeqId(); if (deSeqid != null && deSeqid.length() > 0) { DataElementTransferObject de = new DataElementTransferObject(); de.setDeIdseq(deSeqid); questdto.setDataElement(de); } if (!FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(form.getLoadType())) { questdto.setVersion(Float.valueOf("1.0")); questdto.setCreatedBy(form.getCreatedBy()); } else { questdto.setVersion(Float.valueOf(question.getVersion())); questdto.setModifiedBy(form.getModifiedBy()); } String pid = question.getPublicId(); if (pid != null && pid.length() > 0) questdto.setPublicId(Integer.parseInt(pid)); questdto.setEditable(question.isEditable()); questdto.setMandatory(question.isMandatory()); questdto.setDefaultValue(question.getDefaultValue()); questdto.setAslName("DRAFT NEW"); questdto.setLongName(question.getQuestionText()); //TODO: xsd doesn't have preferred def use question text now //Denise: if preferred def of data element if it's not null. Otherwise, use long name of data element. if No CDE, use question text questdto.setPreferredDefinition(question.getQuestionText()); return questdto; } protected ModuleTransferObject translateIntoModuleDTO(ModuleDescriptor module, FormDescriptor form, FormV2TransferObject formdto) { ModuleTransferObject moduleDto = new ModuleTransferObject(); moduleDto.setForm(formdto); moduleDto.setAslName("DRAFT NEW"); moduleDto.setLongName(module.getLongName()); if (!FormDescriptor.LOAD_TYPE_UPDATE_FORM.equals(form.getLoadType())) { moduleDto.setVersion(Float.valueOf("1.0")); moduleDto.setCreatedBy(formdto.getCreatedBy()); } else { moduleDto.setModifiedBy(form.getModifiedBy()); moduleDto.setPublicId(Integer.parseInt((module.getPublicId()))); moduleDto.setVersion(Float.parseFloat(module.getVersion())); } moduleDto.setContext(formdto.getContext()); moduleDto.setPreferredDefinition(module.getPreferredDefinition()); return moduleDto; } protected List<FormDescriptor> translateIntoFormDescriptors(List<FormV2TransferObject> formdtos) { List<FormDescriptor> forms = new ArrayList<FormDescriptor>(); if (formdtos == null) { logger.debug("Form dtos is null. Can't translater list into FormDescriptors"); return forms; } for (FormV2TransferObject dto : formdtos) { FormDescriptor form = new FormDescriptor(); form.setFormSeqId(dto.getFormIdseq()); form.setLongName(dto.getLongName()); form.setContext(dto.getContextName()); form.setModifiedBy(dto.getModifiedBy()); form.setCreatedBy(dto.getCreatedBy()); form.setProtocolName(dto.getProtocolLongName()); form.setPublicId(String.valueOf(dto.getPublicId())); form.setVersion(String.valueOf(dto.getVersion())); form.setType(dto.getFormType()); forms.add(form); } return forms; } /** * Update inlcudes adding new modules, updating existing ones and delete extra ones that are not in xml * * @param form * @param formdto */ @Transactional protected void updateModulesInForm(FormDescriptor form, FormV2TransferObject formdto) { List<ModuleDescriptor> modules = form.getModules(); List<ModuleTransferObject> existingModuledtos = this.formV2Dao.getModulesInAForm(formdto.getFormIdseq()); /* * Denise: * For a module and its questions in a form 1) If it's a new form or new version, use the form's createdBy 2) If it's an update form, check what's with module element in xml. a. If the module's createBy is valid, use it and apply that to all questions. b. If the module's createdBy is not valid, use form's createdBy and apply to all questions. */ int displayOrder = 0; for (ModuleDescriptor module : modules) { ModuleTransferObject moduledto = translateIntoModuleDTO(module, form, formdto); moduledto.setDisplayOrder(++displayOrder); String moduleSeqid = ""; if (isExistingModule(moduledto, existingModuledtos)) { int res = moduleV2Dao.updateModuleComponent(moduledto); //TODO: better understand spring sqlupdate return code updateQuestionsInModule(module, moduledto, form, formdto); } else { moduledto.setContext(formdto.getContext()); moduleSeqid = moduleV2Dao.createModuleComponent(moduledto); module.setModuleSeqId(moduleSeqid); moduledto.setIdseq(moduleSeqid); //Now, onto questions. Ignore version from xml. Start from 1.0 resetQeustionVersionInModule(module); // createQuestionsInModule(module, moduledto, form, formdto); } } //Find the existing modules to be deleted removeExtraModulesIfAny(existingModuledtos); } protected boolean isExistingModule(ModuleTransferObject currModule, List<ModuleTransferObject> existingModuledtos) { for (ModuleTransferObject moduledto : existingModuledtos) { if ((moduledto.getPublicId() == currModule.getPublicId()) && (moduledto.getVersion().floatValue() == currModule.getVersion().floatValue())) { currModule.setIdseq(moduledto.getIdseq()); currModule.setModuleIdseq(moduledto.getModuleIdseq()); //don't know how these are used moduledto.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); //use this to indicate module's taken return true; } } return false; } /** * Check the list to see if any is marked with MARK_FOR_DELETE. Delete the marked ones. * @param existingmoduledtos */ protected void removeExtraModulesIfAny(List<ModuleTransferObject> existingmoduledtos) { for (ModuleTransferObject moduledto : existingmoduledtos) { if (moduledto.getDisplayOrder() != MARK_TO_KEEP_IN_UPDATE) { logger.debug("Found a module to delete: [" + moduledto.getPublicId() + "|" + moduledto.getVersion() + "]"); this.moduleV2Dao.deleteModule(moduledto.getModuleIdseq()); } } } /** * Check a list of pre-processed existing questions from db. Delete those NOT marked as MARK_TO_KEEP_IN_UPDATE * @param questiondtos */ @Transactional protected void removeExtraQuestionsIfAny(List<QuestionTransferObject> questiondtos) { //Method copied from FormBuilderEJB for (QuestionTransferObject qdto : questiondtos) { if (qdto.getDisplayOrder() == MARK_TO_KEEP_IN_UPDATE) continue; String qSeqid = qdto.getQuesIdseq(); logger.debug("Found a question to delete: [" + qdto.getPublicId() + "|" + qdto.getVersion() + "|" + qSeqid); //delete question questionV2Dao.deleteQuestion(qdto.getQuesIdseq()); logger.debug("Done deleting question"); //delete instructions List instructions = this.questInstructionV2Dao.getInstructions(qSeqid); if (instructions != null && instructions.size() > 0) { logger.debug("Deleting instructions for question..."); for (int i = 0; i < instructions.size(); i++) { InstructionTransferObject instr = (InstructionTransferObject)instructions.get(i); this.questInstructionV2Dao.deleteInstruction(instr.getIdseq()); logger.debug("Deleted an instruction for question"); } } //delete valid values List<String> vvIds = this.formValidValueV2Dao.getValidValueSeqidsByQuestionSeqid(qSeqid); if (vvIds != null) { for (String vvid : vvIds) { //This calls remove_value sp which takes care of vv and instruction formValidValueV2Dao.deleteFormValidValue(vvid); } } } } /** * Reset all question versions to 1.0 in a module, mostly because we'll insert these questions * as new. * @param module */ protected void resetQeustionVersionInModule(ModuleDescriptor module) { List<QuestionDescriptor> questions = module.getQuestions(); for (QuestionDescriptor question : questions) { question.setVersion("1.0"); } } /** * * @param module * @param moduledto * @param form * @param formdto */ protected void updateQuestionsInModule(ModuleDescriptor module, ModuleTransferObject moduledto, FormDescriptor form, FormV2TransferObject formdto) { List<QuestionTransferObject> existingQuestiondtos = moduleV2Dao.getQuestionsInAModuleV2(moduledto.getModuleIdseq()); List<QuestionDescriptor> questions = module.getQuestions(); int idx = 0; for (QuestionDescriptor question : questions) { if (question.isSkip()) continue; QuestionTransferObject questdto = translateIntoQuestionDTO(question, form); questdto.setContext(formdto.getContext()); questdto.setModule(moduledto); //questdto.setModifiedBy(module.getModifiedBy()); //TODO: display order should come from xml? questdto.setDisplayOrder(idx++); QuestionTransferObject existingquestdto = getExistingQuestionDto(questdto, existingQuestiondtos); if (existingquestdto != null) { //existing question updateQuestion(question, questdto, existingquestdto, moduledto, formdto); } else { //better to call createQuestionComponents, which is not implemented. QuestionTransferObject newQuestdto = (QuestionTransferObject)this.questionV2Dao.createQuestionComponent(questdto); createQuestionInstruction(newQuestdto, moduledto, question.getInstruction()); createQuestionValidValues(question, form, newQuestdto, moduledto, formdto); } } removeExtraQuestionsIfAny(existingQuestiondtos); } /** * Determine if it's an existing question based on public id and version * @param currQuestiondto * @param existingQuestiondtos * @return */ protected QuestionTransferObject getExistingQuestionDto(QuestionTransferObject currQuestdto, List<QuestionTransferObject> existingQuestiondtos) { for (QuestionTransferObject quest : existingQuestiondtos) { if (currQuestdto.getPublicId() == quest.getPublicId() && currQuestdto.getVersion().floatValue() == quest.getVersion().floatValue()) { currQuestdto.setQuesIdseq(quest.getQuesIdseq()); currQuestdto.setIdseq(quest.getIdseq()); //Mark this as being update so we don't collect it to delete later. quest.setDisplayOrder(MARK_TO_KEEP_IN_UPDATE); return quest; } } return null; } /** * Update an existing question's various attributes. * @param question * @param questdto * @param moduledto */ @Transactional protected void updateQuestion(QuestionDescriptor question, QuestionTransferObject questdto, QuestionTransferObject existing, ModuleTransferObject moduledto, FormV2TransferObject formdto) { //What we could update in sbrext.Quest_contents_view_ext //display order, long name and asl name if (!questdto.getLongName().equals(existing.getLongName()) || questdto.getDisplayOrder() != existing.getDisplayOrder()) { int res = questionV2Dao.updateQuestionLongNameDispOrderDeIdseq(questdto); } //What we could update in sbrext.quest_attributes_ext //manditory, editable, default value QuestionChangeTransferObject qChangedto = new QuestionChangeTransferObject(); qChangedto.setDefaultValue(question.getDefaultValue()); qChangedto.setEditable(question.isEditable()); qChangedto.setMandatory(question.isMandatory()); qChangedto.setQuestionId(questdto.getQuesIdseq()); qChangedto.setQuestAttrChange(true); //update isEditable, isMandatory and default value questionV2Dao.updateQuestAttr(qChangedto, questdto.getModifiedBy().toUpperCase()); //what to do with isderived? updateQuestionInstruction(questdto, moduledto, question.getInstruction()); //For valid values, need to first compare what's in db updateQuestionValidValues(question, questdto, moduledto, formdto); } protected void updateQuestionValidValues(QuestionDescriptor question, QuestionTransferObject questdto, ModuleTransferObject moduledto, FormV2TransferObject formdto) { List<QuestionDescriptor.ValidValue> validValues = question.getValidValues(); List<FormValidValueTransferObject> existingVVs = questionV2Dao.getValidValues(questdto.getQuesIdseq()); /* * compare vv's long name, preferred definition and display order * * */ int idx = 0; for (QuestionDescriptor.ValidValue vValue : validValues) { FormValidValueTransferObject fvvdto = translateIntoValidValueDto(vValue, questdto, moduledto, formdto, idx); fvvdto.setDisplayOrder(idx++); if (isExistingValidValue(fvvdto, existingVVs)) { fvvdto.setModifiedBy(moduledto.getModifiedBy()); this.updateQuestionValidValue(fvvdto, vValue, questdto); } else { String vvSeqid = formValidValueV2Dao.createValidValue(fvvdto,questdto.getQuesIdseq(),moduledto.getCreatedBy()); if (vvSeqid != null && vvSeqid.length() > 0) { formValidValueV2Dao.createValidValueAttributes(vvSeqid, vValue.getMeaningText(), vValue.getDescription(), moduledto.getCreatedBy()); String instr = vValue.getInstruction(); if (instr != null && instr.length() > 0) { InstructionTransferObject instrdto = createInstructionDto(fvvdto, instr); formValidValueInstructionV2Dao.createInstruction(instrdto, vvSeqid); } } } } } protected boolean isExistingValidValue(FormValidValueTransferObject currVV, List<FormValidValueTransferObject> existingVVs) { for (FormValidValueTransferObject vv : existingVVs) { if (currVV.getLongName().equalsIgnoreCase((vv.getLongName())) && currVV.getPreferredDefinition().equalsIgnoreCase(vv.getPreferredDefinition())) { currVV.setIdseq(vv.getIdseq()); currVV.setValueIdseq(vv.getValueIdseq()); return true; } } return false; } protected void updateQuestionValidValue(FormValidValueTransferObject currVV, QuestionDescriptor.ValidValue vvXml, QuestionTransferObject questdto) { formValidValueV2Dao.updateDisplayOrder(currVV.getValueIdseq(), currVV.getDisplayOrder(), currVV.getModifiedBy()); String meaningText = vvXml.getMeaningText(); String description = vvXml.getDescription(); if (meaningText != null && meaningText.length() > 0 || description != null && description.length() > 0) formValidValueV2Dao.updateValueMeaning(currVV.getValueIdseq(), meaningText, description, currVV.getModifiedBy()); /* * */ String instruct = vvXml.getInstruction(); if (instruct != null && instruct.length() > 0) { Instruction instr = new InstructionTransferObject(); instr.setLongName(instruct); instr.setDisplayOrder(0); instr.setVersion(new Float(1)); instr.setAslName("DRAFT NEW"); instr.setContext(questdto.getContext()); instr.setPreferredDefinition(instruct); instr.setCreatedBy(questdto.getCreatedBy()); formValidValueInstructionV2Dao.createInstruction(instr, currVV.getValueIdseq()); } } @Transactional public String createFormCollectionRecords(FormCollection coll) { String collSeqid = collectionDao.createCollectionRecord(coll.getName(), coll.getDescription(), coll.getXmlFileName(), coll.getXmlPathOnServer(), coll.getCreatedBy()); if (collSeqid == null || collSeqid.length() == 0) { logger.error("Error!!! while creating record for collection: " + coll.getName() + " Uable to create form and collection mappings."); return null; } List<FormDescriptor> forms = coll.getForms(); for (FormDescriptor form : forms) { if (form.getLoadStatus() != FormDescriptor.STATUS_LOADED) continue; int res = collectionDao.createCollectionFormMappingRecord(collSeqid, form.getFormSeqId(), Integer.parseInt(form.getPublicId()), Float.parseFloat(form.getVersion()), form.getLoadType()); //TODO: check response value. int loatStatus = (res > 0) ? FormDescriptor.STATUS_LOADED : FormDescriptor.STATUS_LOAD_FAILED; } return collSeqid; } public boolean hasLoadFormRight(FormDescriptor form, String userName, String contextName) { String contextseqid = this.getContextSeqIdByName(contextName); if (userName == null || userName.length() == 0) { form.addMessage("User name is emppty. Unable to verify user load right"); return false; } if (contextseqid == null || contextseqid.length() == 0) { form.addMessage("Context name [" + contextName + "]is empty. Unable to verify user load right"); return false; } return this.formV2Dao.hasCreate(userName, COMPONENT_TYPE_FORM, contextseqid); } @Transactional(readOnly=true) public boolean definitionTypeValid(FormDescriptor form) { if (definitionTypes == null) { definitionTypes = this.formV2Dao.getAllDefinitionTypes(); } return false; } //@Transactional(readOnly=true) /* public void validateDesignationType(FormDescriptor form) { if (designationTypes == null) { designationTypes = this.formV2Dao.getAllDesignationTypes(); } if (designationTypeExists(form) return false; //return (designationTypes == null) ? false : designationTypes.contains(form.getd); } */ @Transactional(readOnly=true) public boolean refDocTypeValid(FormDescriptor form) { if (refdocTypes == null) { refdocTypes = this.formV2Dao.getAllRefdocTypes(); } return false; } @Transactional(readOnly=true) public void checkWorkflowStatusName(FormDescriptor form) { if (workflowNames == null) { workflowNames = this.formV2Dao.getAllWorkflowNames(); } String formWfName = form.getWorkflowStatusName(); if (!workflowNames.contains(formWfName)) { form.addMessage("Form's workflow status name invalid. Use default value Draft New"); form.setWorkflowStatusName(DEFAULT_WORKFLOW_STATUS); } } @Transactional public void unloadForm(FormDescriptor form) { String seqid = form.getFormSeqId(); if (seqid == null || seqid.length() == 0) { logger.debug("Form's seqid is invalid"); form.addMessage("Form's seqid is invalid. Unable to unload form"); form.setLoadStatus(FormDescriptor.STATUS_UNLOAD_FAILED); return; } int res = formV2Dao.updateWorkflowStatus(seqid, "RETIRED WITHDRAWN"); if (res <= 0) { form.addMessage("Failed to update form's workflow status. Unload failed"); form.setLoadStatus(FormDescriptor.STATUS_UNLOAD_FAILED); } else form.setLoadStatus(FormDescriptor.STATUS_UNLOADED); } }
When creating new version, call sp crf_version_shell to make shallow copy of the form.
software/FormLoader/src/gov/nih/nci/cadsr/formloader/repository/FormLoaderRepositoryImpl.java
When creating new version, call sp crf_version_shell to make shallow copy of the form.
Java
apache-2.0
4a8c2368daab67792956f8c72c1359fb33136ec1
0
apache/isis,oscarbou/isis,estatio/isis,apache/isis,sanderginn/isis,apache/isis,apache/isis,niv0/isis,incodehq/isis,oscarbou/isis,niv0/isis,incodehq/isis,incodehq/isis,oscarbou/isis,estatio/isis,sanderginn/isis,niv0/isis,sanderginn/isis,incodehq/isis,apache/isis,oscarbou/isis,sanderginn/isis,estatio/isis,estatio/isis,apache/isis,niv0/isis
core/metamodel/src/main/java/org/apache/isis/core/commons/jmx/JmxBeanServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.core.commons.jmx; import java.lang.management.ManagementFactory; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JmxBeanServer { private static final Logger LOG = LoggerFactory.getLogger(JmxBeanServer.class); private static JmxBeanServer instance; private final MBeanServer server; private JmxBeanServer() { server = ManagementFactory.getPlatformMBeanServer(); instance = this; } public static JmxBeanServer getInstance() { if (instance == null) { LOG.info("JMX bean server created"); instance = new JmxBeanServer(); } return instance; } public void register(final String name, final Object object) { try { final ObjectName objectName = new ObjectName("Isis:name=" + name); server.registerMBean(object, objectName); LOG.info(name + " JMX mbean registered: " + object); } catch (final MalformedObjectNameException | NullPointerException | MBeanRegistrationException | NotCompliantMBeanException e) { throw new RuntimeException(e); } catch (final InstanceAlreadyExistsException e) { LOG.info(name + " JMX mbean already registered: " + object); } } } // Copyright (c) Naked Objects Group Ltd.
ISIS-1429: removing unused JmxBeanServer
core/metamodel/src/main/java/org/apache/isis/core/commons/jmx/JmxBeanServer.java
ISIS-1429: removing unused JmxBeanServer
Java
apache-2.0
94a8be0931946dc233a9047a64842f63246b27c6
0
weige211/jenkins
Main.java
public class Main { public static void main(String[] args) { System.out.println("Helloworld"); // TODO Auto-generated method stub } }
add null
Main.java
add null
Java
mit
e191df956b868ddee3e00fcd8bc2f229211e802f
0
swaldman/ethereumj,swaldman/ethereumj
package org.ethereum.config; import java.lang.reflect.Constructor; import org.slf4j.Logger; import static org.ethereum.config.KeysDefaults.*; /** * To write a config plugin, override the {@link #getLocalOrNull}, * and provide a public constructor that accepts a fallback ConfigPlugin * for its sole argument. * * Objects provided should be put into the types expected for the key. * * @see KeysDefaults#expectedTypes() and {@link #attemptCoerceValueForKey} */ public abstract class ConfigPlugin implements ConfigSource { protected final static Logger logger = KeysDefaults.getConfigPluginLogger(); protected final static ConfigPlugin fromPluginPath( String pluginPath ) { String[] classNames = parsePluginPath( pluginPath ); ConfigPlugin head = ConfigPlugin.NULL; for ( int i = classNames.length; --i >= 0; ) { String className = classNames[i]; try { head = instantiatePlugin( className, head ); logger.info( "Loaded config plugin '{}'.", className ); } catch ( Exception e ) { if ( logger.isWarnEnabled() ) { logger.warn("Could not instantiate a plugin of type '" + className + "'. Skipping...", e); } } } return head; } protected static String vmPluginPath() { String replacePath = System.getProperty(SYSPROP_PLUGIN_PATH_REPLACE); String appendPath = System.getProperty(SYSPROP_PLUGIN_PATH_APPEND); String prependPath = System.getProperty(SYSPROP_PLUGIN_PATH_PREPEND); String path = ( replacePath == null ? DEFAULT_PLUGIN_PATH : replacePath ); // base path if ( appendPath != null ) path = path + "," + appendPath; if ( prependPath != null ) path = prependPath + "," + path; return path; } final static String[] parsePluginPath( String pluginPath ) { return pluginPath.split("\\s*,\\s*"); } final static ConfigPlugin instantiatePlugin( String fqcn, ConfigPlugin fallback ) throws Exception { Class clz = Class.forName( fqcn ); return instantiatePlugin( clz, fallback ); } final static ConfigPlugin instantiatePlugin( Class clz, ConfigPlugin fallback ) throws Exception { Constructor<ConfigPlugin> ctor = clz.getConstructor( ConfigPlugin.class ); return ctor.newInstance( fallback ); } private final static ConfigPlugin NULL = new ConfigPlugin(null) { protected Object getLocalOrNull( String key ) { return null; } @Override boolean matchesTail( String[] classNames, int index ) { return classNames.length == index; } @Override StringBuilder appendPathTail( StringBuilder in, boolean first ) { return in; } }; private ConfigPlugin fallback; protected ConfigPlugin( ConfigPlugin fallback ) { this.fallback = fallback; } protected Object attemptCoerceValueForKey( String value, String key ) { Class<?> type = TYPES.get( key ); Object out; if ( type == Boolean.class ) { out = Boolean.valueOf( value ); } else if ( type == Integer.class ) { out = Integer.valueOf( value ); } else if ( type == String.class ) { out = value; } else { if ( logger.isWarnEnabled() ) { logger.warn("Cannot coerce String to {} for key '{}'. Left as String. [{}]", type, key, this.getClass().getSimpleName()); } out = value; } return out; } boolean matchesTail( String[] classNames, int index ) { if ( index < classNames.length ) return this.getClass().getName().equals( classNames[index] ) && fallback.matchesTail( classNames, index + 1 ); else return false; } boolean matches( String[] classNames ) { return matchesTail( classNames, 0 ); } StringBuilder appendPathTail( StringBuilder in, boolean first ) { if (! first) in.append(", "); in.append( this.getClass().getName() ); return fallback.appendPathTail( in, false ); } String path() { StringBuilder sb = new StringBuilder(); return appendPathTail( sb, true ).toString(); } /* * * Abstract, protected methods * */ protected abstract Object getLocalOrNull( String key ); public final Object getOrNull( String key ) { Object out = getLocalOrNull( key ); return ( out == null ? fallback.getLocalOrNull( key ) : out ); } }
ethereumj-core/src/main/java/org/ethereum/config/ConfigPlugin.java
package org.ethereum.config; import java.lang.reflect.Constructor; import org.slf4j.Logger; import static org.ethereum.config.KeysDefaults.*; public abstract class ConfigPlugin implements ConfigSource { protected final static Logger logger = KeysDefaults.getConfigPluginLogger(); protected final static ConfigPlugin fromPluginPath( String pluginPath ) { String[] classNames = parsePluginPath( pluginPath ); ConfigPlugin head = ConfigPlugin.NULL; for ( int i = classNames.length; --i >= 0; ) { String className = classNames[i]; try { head = instantiatePlugin( className, head ); logger.info( "Loaded config plugin '{}'.", className ); } catch ( Exception e ) { if ( logger.isWarnEnabled() ) { logger.warn("Could not instantiate a plugin of type '" + className + "'. Skipping...", e); } } } return head; } protected static String vmPluginPath() { String replacePath = System.getProperty(SYSPROP_PLUGIN_PATH_REPLACE); String appendPath = System.getProperty(SYSPROP_PLUGIN_PATH_APPEND); String prependPath = System.getProperty(SYSPROP_PLUGIN_PATH_PREPEND); String path = ( replacePath == null ? DEFAULT_PLUGIN_PATH : replacePath ); // base path if ( appendPath != null ) path = path + "," + appendPath; if ( prependPath != null ) path = prependPath + "," + path; return path; } final static String[] parsePluginPath( String pluginPath ) { return pluginPath.split("\\s*,\\s*"); } final static ConfigPlugin instantiatePlugin( String fqcn, ConfigPlugin fallback ) throws Exception { Class clz = Class.forName( fqcn ); return instantiatePlugin( clz, fallback ); } final static ConfigPlugin instantiatePlugin( Class clz, ConfigPlugin fallback ) throws Exception { Constructor<ConfigPlugin> ctor = clz.getConstructor( ConfigPlugin.class ); return ctor.newInstance( fallback ); } private final static ConfigPlugin NULL = new ConfigPlugin(null) { protected Object getLocalOrNull( String key ) { return null; } @Override boolean matchesTail( String[] classNames, int index ) { return classNames.length == index; } @Override StringBuilder appendPathTail( StringBuilder in, boolean first ) { return in; } }; private ConfigPlugin fallback; protected ConfigPlugin( ConfigPlugin fallback ) { this.fallback = fallback; } protected Object attemptCoerceValueForKey( String value, String key ) { Class<?> type = TYPES.get( key ); Object out; if ( type == Boolean.class ) { out = Boolean.valueOf( value ); } else if ( type == Integer.class ) { out = Integer.valueOf( value ); } else if ( type == String.class ) { out = value; } else { if ( logger.isWarnEnabled() ) { logger.warn("Cannot coerce String to {} for key '{}'. Left as String. [{}]", type, key, this.getClass().getSimpleName()); } out = value; } return out; } boolean matchesTail( String[] classNames, int index ) { if ( index < classNames.length ) return this.getClass().getName().equals( classNames[index] ) && fallback.matchesTail( classNames, index + 1 ); else return false; } boolean matches( String[] classNames ) { return matchesTail( classNames, 0 ); } StringBuilder appendPathTail( StringBuilder in, boolean first ) { if (! first) in.append(", "); in.append( this.getClass().getName() ); return fallback.appendPathTail( in, false ); } String path() { StringBuilder sb = new StringBuilder(); return appendPathTail( sb, true ).toString(); } /* * * Abstract, protected methods * */ protected abstract Object getLocalOrNull( String key ); public final Object getOrNull( String key ) { Object out = getLocalOrNull( key ); return ( out == null ? fallback.getLocalOrNull( key ) : out ); } }
Added doc comments to ConfigPlugin.
ethereumj-core/src/main/java/org/ethereum/config/ConfigPlugin.java
Added doc comments to ConfigPlugin.
Java
mit
6f64d3ba1df8a06c2c966f7c59a69553ffacad17
0
aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.ServerSocket; import javax.swing.*; // import com.sun.tools.attach.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); add(new JScrollPane(new JTree())); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } // private static final IAppInstanceCounter counter = new JVMDescriptorInstanceCounter(); private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } // if (counter.getInstanceCount() > 1) { // JOptionPane.showMessageDialog(null, "An instance of the application is already running..."); // return; // } SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop(); // Java Swing Hacks #68 try (ServerSocket ignored = new ServerSocket(38_765)) { JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { loop.exit(); } }); loop.enter(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "An instance of the application is already running..."); } } } // // Attach API // // http://d.hatena.ne.jp/Kazzz/20071221/p1 // interface IAppInstanceCounter { // int getInstanceCount(); // } // // class JVMDescriptorInstanceCounter implements IAppInstanceCounter { // private final String mainClassName; // protected JVMDescriptorInstanceCounter() { // StackTraceElement[] traces = Thread.currentThread().getStackTrace(); // mainClassName = traces[traces.length-1].getClassName(); // // System.out.println(mainClassName); // } // public int getInstanceCount() { // return FinderUtil.findAll( // VirtualMachine.list(), // new IPredicate<VirtualMachineDescriptor>() { // @Override public boolean evaluate(VirtualMachineDescriptor input) { // return input.displayName().equals(mainClassName); // } // }).size(); // } // } // // interface IPredicate<T> { // boolean evaluate(T input); // } // // final class FinderUtil { // public static final <T> List<T> findAll(List<T> list, IPredicate<T> match) { // List<T> temp = new ArrayList<>(); // for (T t: list) { // if (match.evaluate(t)) { // temp.add(t); // } // } // return temp; // } // } // class PseudoFileSemaphoreCounter implements IAppInstanceCounter { // private PseudoFileSemaphore semaphore; // private int launchLimit; // protected PseudoFileSemaphoreCounter(String appName, int launchLimit) { // this.semaphore = new PseudoFileSemaphore(appName, launchLimit); // this.launchLimit = launchLimit; // Runtime.getRuntime().addShutdownHook(new Thread(() -> semaphore.release())); // } // // @Override public int getInstanceCount() { // int result = this.semaphore.tryAcquire(); // return result != 0 ? result : this.launchLimit + 1; // } // }
SingleInstanceApplication/src/java/example/MainPanel.java
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.ServerSocket; import javax.swing.*; // import com.sun.tools.attach.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); add(new JScrollPane(new JTree())); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } // private static final IAppInstanceCounter counter = new JVMDescriptorInstanceCounter(); private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } // if (counter.getInstanceCount() > 1) { // JOptionPane.showMessageDialog(null, "An instance of the application is already running..."); // return; // } SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop(); // Java Swing Hacks #68 try (ServerSocket socket = new ServerSocket(38_765)) { JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { loop.exit(); } }); loop.enter(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "An instance of the application is already running..."); } } } // // Attach API // // http://d.hatena.ne.jp/Kazzz/20071221/p1 // interface IAppInstanceCounter { // int getInstanceCount(); // } // // class JVMDescriptorInstanceCounter implements IAppInstanceCounter { // private final String mainclassName; // protected JVMDescriptorInstanceCounter() { // StackTraceElement[] traces = Thread.currentThread().getStackTrace(); // mainclassName = traces[traces.length-1].getClassName(); // // System.out.println(mainclassName); // } // public int getInstanceCount() { // return FinderUtil.findAll( // VirtualMachine.list(), // new IPredicate<VirtualMachineDescriptor>() { // @Override public boolean evaluate(VirtualMachineDescriptor input) { // return input.displayName().equals(mainclassName); // } // }).size(); // } // } // // interface IPredicate<T> { // boolean evaluate(T input); // } // // final class FinderUtil { // public static final <T> List<T> findAll(List<T> list, IPredicate<T> match) { // List<T> temp = new ArrayList<>(); // for (T t: list) { // if (match.evaluate(t)) { // temp.add(t); // } // } // return temp; // } // } // class PseudoFileSemaphoreCounter implements IAppInstanceCounter { // private PseudoFileSemaphore semaphore; // private int launchLimit; // protected PseudoFileSemaphoreCounter(String appName, int launchLimit) { // this.semaphore = new PseudoFileSemaphore(appName, launchLimit); // this.launchLimit = launchLimit; // Runtime.getRuntime().addShutdownHook(new Thread(() -> semaphore.release())); // } // @Override public int getInstanceCount() { // int result = this.semaphore.tryAcquire(); // return result != 0 ? result : this.launchLimit + 1; // } // }
refactor: variable 'socket' is never used
SingleInstanceApplication/src/java/example/MainPanel.java
refactor: variable 'socket' is never used
Java
mit
6294f98c557e9384e8a8195d2fd38ae46905af5e
0
nfleet/java-sdk
package fi.cosky.sdk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import com.google.gson.*; import org.apache.commons.codec.binary.Base64; /* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ /** * API-class to handle the communication between SDK-user and CO-SKY * optimization's REST-API. */ public class API { private String baseUrl; private String ClientKey; private String ClientSecret; private ApiData apiData; private TokenData tokenData; private boolean timed; private ObjectCache objectCache; private boolean retry; private boolean useMimeTypes; private MimeTypeHelper helper; static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'").create(); public API(String baseUrl) { this.baseUrl = baseUrl; this.objectCache = new ObjectCache(); this.timed = false; this.retry = true; this.useMimeTypes = true; //change this when production will support mimetypes. this.helper = new MimeTypeHelper(); //Delete-Verb causes connection to keep something somewhere that causes the next request to fail. //this hopefully helps with that. System.setProperty("http.keepAlive", "false"); } private boolean authenticate() { return authenticate(this.ClientKey, this.ClientSecret); } public boolean authenticate(String username, String password) { this.ClientKey = username; this.ClientSecret = password; System.out.println("Authenticating API with username: " +username + " and pass: " + password); try { ResponseData result = navigate(ResponseData.class, getAuthLink()); if (result == null || result.getItems() != null) { System.out.println("Could not authenticate, please check credentials"); return false; } TokenData authenticationData = navigate(TokenData.class, result.getLocation()); this.tokenData = authenticationData; } catch (Exception e) { System.out.println( e.toString()); return false; } return true; } /** * * @param tClass return type. * @param l navigation link * @return object of type tClass * @throws NFleetRequestException when there is data validation problems * @throws IOException when there is problems with infrastructure (connection etc..) */ public <T extends BaseData> T navigate(Class<T> tClass, Link l) throws IOException { return navigate(tClass, l, null); } @SuppressWarnings("unchecked") public <T extends BaseData> T navigate(Class<T> tClass, Link l, HashMap<String, String> queryParameters) throws IOException { Object result; long start = 0; long end; if (isTimed()) { start = System.currentTimeMillis(); } if (tClass.equals(TokenData.class)) { result = sendRequest(l, tClass, null); return (T) result; } if (l.getRel().equals("authenticate")) { HashMap<String, String> headers = new HashMap<String, String>(); String authorization = "Basic " + Base64.encodeBase64String((this.ClientKey + ":" + this.ClientSecret).getBytes()); headers.put("authorization", authorization); result = sendRequestWithAddedHeaders(Verb.POST, this.baseUrl + l.getUri(), tClass, null, headers); return (T) result; } String uri = l.getUri(); if (l.getMethod().equals("GET") && queryParameters != null && !queryParameters.isEmpty()) { StringBuilder sb = new StringBuilder(uri + "?"); for (String key : queryParameters.keySet()) { sb.append(key + "=" + queryParameters.get(key) + "&"); } sb.deleteCharAt(sb.length() - 1); uri = sb.toString(); } if (l.getMethod().equals("GET") && !uri.contains(":")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("PUT")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("POST")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("DELETE")) { result = sendRequest(l, tClass, new Object()); } else { result = sendRequest(l, tClass, null); } if (isTimed()) { end = System.currentTimeMillis(); long time = end - start; System.out.println("Method " + l.getMethod() + " on " + l.getUri() + " doing " + l.getRel() + " took " + time + " ms."); } return (T) result; } /** * Navigate method for sending data * @param tClass return type. * @param l navigation link * @param object object to send * @return object of type tClass * @throws NFleetRequestException when there is problems with data validation, exception contains list of the errors. * @throws IOException when there is problems with infrastructure ( connection etc.. ) */ @SuppressWarnings("unchecked") public <T extends BaseData> T navigate(Class<T> tClass, Link l, Object object) throws IOException { long start = 0; long end; if (isTimed()) { start = System.currentTimeMillis(); } Object result = sendRequest(l, tClass, object); if (isTimed()) { end = System.currentTimeMillis(); long time = end - start; System.out.println("Method " + l.getMethod() + " on " + l.getUri() + " took " + time + " ms."); } return (T) result; } public Link getRoot() { return new Link("self", baseUrl, "GET","", true); } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress; BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER ) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired " + connection.getResponseMessage()); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if( authenticate() ) { System.out.println("Authenticated again"); return sendRequest(l, tClass, object); } } else throw new IOException("Could not authenticate"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR ) { String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; } private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass, Object object, HashMap<String, String> headers) throws IOException { URL serverAddress; HttpURLConnection connection; BufferedReader br; String result = ""; try { serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setInstanceFollowRedirects(false); boolean doOutput = doOutput(verb); connection.setDoOutput(doOutput); connection.setRequestMethod(method(verb)); connection.setRequestProperty("Authorization", headers.get("authorization")); connection.addRequestProperty("Accept", "application/json"); if (doOutput){ connection.addRequestProperty("Content-Length", "0"); OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream()); os.write(""); os.flush(); os.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { Link location = parseLocationLinkFromString(connection.getHeaderField("Location")); Link l = new Link("self", "/tokens", "GET","", true); ArrayList<Link> links = new ArrayList<Link>(); links.add(l); links.add(location); ResponseData data = new ResponseData(); data.setLocation(location); data.setLinks(links); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired: " + connection.getResponseMessage()); if ( retry && this.tokenData != null ) { retry = false; this.tokenData = null; if( authenticate() ) { System.out.println("Authenticated again"); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } System.out.println("Could not authenticate"); } else throw new IOException("Could not authenticate"); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + verb); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR ) { String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } return (T) gson.fromJson(result, tClass); } private Link getAuthLink() { return new Link("authenticate", "/tokens", "POST", "", true); } private String method(Verb verb) { switch (verb) { case GET: return "GET"; case PUT: return "PUT"; case POST: return "POST"; case DELETE: return "DELETE"; case PATCH: return "PATCH"; } return ""; } private Link parseLocationLinkFromString(String s) { //Azure emulator hack if (s.contains("82")) s = s.replace("82", "81"); if (s.contains("/tokens")) return new Link("location", s, "GET","", true); else s = s.substring(s.lastIndexOf("/users")); return new Link("location", s, "GET", "", true); } private boolean doOutput(Verb verb) { switch (verb) { case GET: case DELETE: return false; default: return true; } } private boolean doOutput(String verb) { switch (verb) { case "GET": case "DELETE": return false; default: return true; } } private enum Verb { GET, PUT, POST, DELETE, PATCH } private <T> void addMimeTypeAcceptToRequest(Object object, Class<T> tClass, HttpURLConnection connection) { Field f = null; StringTokenizer st = null; StringBuilder sb = null; Field[] fields = null; try { fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals("MimeType")) f = field; } if (f == null) { connection.setRequestProperty("Accept", "application/json"); return; } String type = null; f.setAccessible(true); type = f.get(tClass).toString(); if (type != null) { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } } catch (Exception e) { } } private <T> void addMimeTypeContentTypeToRequest(Object object, Class<T> tClass, HttpURLConnection connection) { Field f = null; StringTokenizer st = null; StringBuilder sb = null; Field[] fields = null; try { fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals("MimeType")) f = field; } if (f == null) { connection.setRequestProperty("Content-Type", "application/json"); return; } String type = null; f.setAccessible(true); type = f.get(object).toString(); if (type != null) { connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } catch (Exception e) { } } private void addVersionNumberToHeader(Object object, String url, HttpURLConnection connection) { Field f = null; Object fromCache = null; if (objectCache.containsUri(url)) { try { fromCache = objectCache.getObject(url); f = fromCache.getClass().getDeclaredField("VersionNumber"); } catch (NoSuchFieldException e) { // Object does not have versionnumber. } if (f != null) { f.setAccessible(true); int versionNumber = 0; try { versionNumber = f.getInt(fromCache); } catch (IllegalAccessException e) { } connection.setRequestProperty("If-None-Match", versionNumber + ""); } } } private String readErrorStreamAndCloseConnection(HttpURLConnection connection) { InputStream stream = connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String s; try { while ((s = br.readLine()) != null) { sb.append(s); } } catch (IOException e) { e.printStackTrace(); } String body = sb.toString(); connection.disconnect(); return body; } private String readDataFromConnection(HttpURLConnection connection) { InputStream is = null; BufferedReader br = null; StringBuilder sb = null; try { is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String eTag = null; if ((eTag = connection.getHeaderField("ETag")) != null) { sb.insert(sb.lastIndexOf("}"), ",\"VersionNumber\":" + eTag + ""); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public TokenData getTokenData() { return this.tokenData; } public void setTokenData(TokenData data) { tokenData = data; } public ApiData getApiData() { return apiData; } public void setApiData(ApiData apiData) { this.apiData = apiData; } public boolean isTimed() { return timed; } public void setTimed(boolean timed) { this.timed = timed; } }
fi/cosky/sdk/API.java
package fi.cosky.sdk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import com.google.gson.*; import org.apache.commons.codec.binary.Base64; /* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ /** * API-class to handle the communication between SDK-user and CO-SKY * optimization's REST-API. */ public class API { private String baseUrl; private String ClientKey; private String ClientSecret; private ApiData apiData; private TokenData tokenData; private boolean timed; private ObjectCache objectCache; private boolean retry; private boolean useMimeTypes; private MimeTypeHelper helper; static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'").create(); public API(String baseUrl) { this.baseUrl = baseUrl; this.objectCache = new ObjectCache(); this.timed = false; this.retry = true; this.useMimeTypes = false; //change this when production will support mimetypes. this.helper = new MimeTypeHelper(); //Delete-Verb causes connection to keep something somewhere that causes the next request to fail. //this hopefully helps with that. System.setProperty("http.keepAlive", "false"); } private boolean authenticate() { return authenticate(this.ClientKey, this.ClientSecret); } public boolean authenticate(String username, String password) { this.ClientKey = username; this.ClientSecret = password; System.out.println("Authenticating API with username: " +username + " and pass: " + password); try { ResponseData result = navigate(ResponseData.class, getAuthLink()); if (result == null || result.getItems() != null) { System.out.println("Could not authenticate, please check credentials"); return false; } TokenData authenticationData = navigate(TokenData.class, result.getLocation()); this.tokenData = authenticationData; } catch (Exception e) { System.out.println( e.toString()); return false; } return true; } /** * * @param tClass return type. * @param l navigation link * @return object of type tClass * @throws NFleetRequestException when there is data validation problems * @throws IOException when there is problems with infrastructure (connection etc..) */ public <T extends BaseData> T navigate(Class<T> tClass, Link l) throws IOException { return navigate(tClass, l, null); } @SuppressWarnings("unchecked") public <T extends BaseData> T navigate(Class<T> tClass, Link l, HashMap<String, String> queryParameters) throws IOException { Object result; long start = 0; long end; if (isTimed()) { start = System.currentTimeMillis(); } if (tClass.equals(TokenData.class)) { result = sendRequest(l, tClass, null); return (T) result; } if (l.getRel().equals("authenticate")) { HashMap<String, String> headers = new HashMap<String, String>(); String authorization = "Basic " + Base64.encodeBase64String((this.ClientKey + ":" + this.ClientSecret).getBytes()); headers.put("authorization", authorization); result = sendRequestWithAddedHeaders(Verb.POST, this.baseUrl + l.getUri(), tClass, null, headers); return (T) result; } String uri = l.getUri(); if (l.getMethod().equals("GET") && queryParameters != null && !queryParameters.isEmpty()) { StringBuilder sb = new StringBuilder(uri + "?"); for (String key : queryParameters.keySet()) { sb.append(key + "=" + queryParameters.get(key) + "&"); } sb.deleteCharAt(sb.length() - 1); uri = sb.toString(); } if (l.getMethod().equals("GET") && !uri.contains(":")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("PUT")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("POST")) { result = sendRequest(l, tClass, null); } else if (l.getMethod().equals("DELETE")) { result = sendRequest(l, tClass, new Object()); } else { result = sendRequest(l, tClass, null); } if (isTimed()) { end = System.currentTimeMillis(); long time = end - start; System.out.println("Method " + l.getMethod() + " on " + l.getUri() + " doing " + l.getRel() + " took " + time + " ms."); } return (T) result; } /** * Navigate method for sending data * @param tClass return type. * @param l navigation link * @param object object to send * @return object of type tClass * @throws NFleetRequestException when there is problems with data validation, exception contains list of the errors. * @throws IOException when there is problems with infrastructure ( connection etc.. ) */ @SuppressWarnings("unchecked") public <T extends BaseData> T navigate(Class<T> tClass, Link l, Object object) throws IOException { long start = 0; long end; if (isTimed()) { start = System.currentTimeMillis(); } Object result = sendRequest(l, tClass, object); if (isTimed()) { end = System.currentTimeMillis(); long time = end - start; System.out.println("Method " + l.getMethod() + " on " + l.getUri() + " took " + time + " ms."); } return (T) result; } public Link getRoot() { return new Link("self", baseUrl, "GET","", true); } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress; BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER ) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired " + connection.getResponseMessage()); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if( authenticate() ) { System.out.println("Authenticated again"); return sendRequest(l, tClass, object); } } else throw new IOException("Could not authenticate"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR ) { String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; } private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass, Object object, HashMap<String, String> headers) throws IOException { URL serverAddress; HttpURLConnection connection; BufferedReader br; String result = ""; try { serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setInstanceFollowRedirects(false); boolean doOutput = doOutput(verb); connection.setDoOutput(doOutput); connection.setRequestMethod(method(verb)); connection.setRequestProperty("Authorization", headers.get("authorization")); connection.addRequestProperty("Accept", "application/json"); if (doOutput){ connection.addRequestProperty("Content-Length", "0"); OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream()); os.write(""); os.flush(); os.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { Link location = parseLocationLinkFromString(connection.getHeaderField("Location")); Link l = new Link("self", "/tokens", "GET","", true); ArrayList<Link> links = new ArrayList<Link>(); links.add(l); links.add(location); ResponseData data = new ResponseData(); data.setLocation(location); data.setLinks(links); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired: " + connection.getResponseMessage()); if ( retry && this.tokenData != null ) { retry = false; this.tokenData = null; if( authenticate() ) { System.out.println("Authenticated again"); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } System.out.println("Could not authenticate"); } else throw new IOException("Could not authenticate"); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + verb); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR ) { String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } return (T) gson.fromJson(result, tClass); } private Link getAuthLink() { return new Link("authenticate", "/tokens", "POST", "", true); } private String method(Verb verb) { switch (verb) { case GET: return "GET"; case PUT: return "PUT"; case POST: return "POST"; case DELETE: return "DELETE"; case PATCH: return "PATCH"; } return ""; } private Link parseLocationLinkFromString(String s) { //Azure emulator hack if (s.contains("82")) s = s.replace("82", "81"); if (s.contains("/tokens")) return new Link("location", s, "GET","", true); else s = s.substring(s.lastIndexOf("/users")); return new Link("location", s, "GET", "", true); } private boolean doOutput(Verb verb) { switch (verb) { case GET: case DELETE: return false; default: return true; } } private boolean doOutput(String verb) { switch (verb) { case "GET": case "DELETE": return false; default: return true; } } private enum Verb { GET, PUT, POST, DELETE, PATCH } private <T> void addMimeTypeAcceptToRequest(Object object, Class<T> tClass, HttpURLConnection connection) { Field f = null; StringTokenizer st = null; StringBuilder sb = null; Field[] fields = null; try { fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals("MimeType")) f = field; } if (f == null) { connection.setRequestProperty("Accept", "application/json"); return; } String type = null; f.setAccessible(true); type = f.get(tClass).toString(); if (type != null) { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } } catch (Exception e) { } } private <T> void addMimeTypeContentTypeToRequest(Object object, Class<T> tClass, HttpURLConnection connection) { Field f = null; StringTokenizer st = null; StringBuilder sb = null; Field[] fields = null; try { fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields(); for (Field field : fields) { if (field.getName().equals("MimeType")) f = field; } if (f == null) { connection.setRequestProperty("Content-Type", "application/json"); return; } String type = null; f.setAccessible(true); type = f.get(object).toString(); if (type != null) { connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } catch (Exception e) { } } private void addVersionNumberToHeader(Object object, String url, HttpURLConnection connection) { Field f = null; Object fromCache = null; if (objectCache.containsUri(url)) { try { fromCache = objectCache.getObject(url); f = fromCache.getClass().getDeclaredField("VersionNumber"); } catch (NoSuchFieldException e) { // Object does not have versionnumber. } if (f != null) { f.setAccessible(true); int versionNumber = 0; try { versionNumber = f.getInt(fromCache); } catch (IllegalAccessException e) { } connection.setRequestProperty("If-None-Match", versionNumber + ""); } } } private String readErrorStreamAndCloseConnection(HttpURLConnection connection) { InputStream stream = connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String s; try { while ((s = br.readLine()) != null) { sb.append(s); } } catch (IOException e) { e.printStackTrace(); } String body = sb.toString(); connection.disconnect(); return body; } private String readDataFromConnection(HttpURLConnection connection) { InputStream is = null; BufferedReader br = null; StringBuilder sb = null; try { is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String eTag = null; if ((eTag = connection.getHeaderField("ETag")) != null) { sb.insert(sb.lastIndexOf("}"), ",\"VersionNumber\":" + eTag + ""); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public TokenData getTokenData() { return this.tokenData; } public void setTokenData(TokenData data) { tokenData = data; } public ApiData getApiData() { return apiData; } public void setApiData(ApiData apiData) { this.apiData = apiData; } public boolean isTimed() { return timed; } public void setTimed(boolean timed) { this.timed = timed; } }
SDK now sends the mime types as test-api supports them.
fi/cosky/sdk/API.java
SDK now sends the mime types as test-api supports them.
Java
mit
073d5bd112a73b5827203d174550fc7d3f543122
0
sanman00/SpongeCommon,SpongePowered/SpongeCommon,SpongePowered/Sponge,Grinch/SpongeCommon,sanman00/SpongeCommon,SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,JBYoshi/SpongeCommon,Grinch/SpongeCommon,JBYoshi/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.world.gen; import com.flowpowered.math.vector.Vector3i; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkGenerator; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.world.SerializationBehaviors; import org.spongepowered.api.world.storage.ChunkDataStream; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.api.world.storage.WorldStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.config.SpongeConfig; import org.spongepowered.common.event.tracking.CauseTracker; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.phase.TrackingPhases; import org.spongepowered.common.event.tracking.phase.entity.EntityPhase; import org.spongepowered.common.event.tracking.phase.generation.GenerationPhase; import org.spongepowered.common.event.tracking.phase.plugin.PluginPhase; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.world.IMixinAnvilChunkLoader; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer; import org.spongepowered.common.util.CachedLong2ObjectMap; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.world.SpongeEmptyChunk; import org.spongepowered.common.world.storage.SpongeChunkDataStream; import org.spongepowered.common.world.storage.WorldStorageUtil; import java.util.Iterator; import java.util.Optional; import java.util.concurrent.CompletableFuture; @Mixin(ChunkProviderServer.class) public abstract class MixinChunkProviderServer implements WorldStorage, IMixinChunkProviderServer { private SpongeEmptyChunk EMPTY_CHUNK; private boolean denyChunkRequests = true; private boolean forceChunkRequests = false; private long chunkUnloadDelay = 15000; private int maxChunkUnloads = 100; @Shadow @Final public WorldServer world; @Shadow @Final private IChunkLoader chunkLoader; @Shadow public IChunkGenerator chunkGenerator; @SuppressWarnings({"unchecked", "rawtypes"}) @Shadow @Final @Mutable public Long2ObjectMap<Chunk> id2ChunkMap = new CachedLong2ObjectMap(); @Shadow public abstract Chunk getLoadedChunk(int x, int z); @Shadow public abstract Chunk loadChunk(int x, int z); @Shadow public abstract Chunk loadChunkFromFile(int x, int z); @Shadow public abstract Chunk provideChunk(int x, int z); @Shadow public abstract void saveChunkExtraData(Chunk chunkIn); @Shadow public abstract void saveChunkData(Chunk chunkIn); @Inject(method = "<init>", at = @At("RETURN")) private void onConstruct(WorldServer worldObjIn, IChunkLoader chunkLoaderIn, IChunkGenerator chunkGeneratorIn, CallbackInfo ci) { EMPTY_CHUNK = new SpongeEmptyChunk(worldObjIn, 0, 0); SpongeConfig<?> spongeConfig = SpongeHooks.getActiveConfig(worldObjIn); ((IMixinWorldServer) worldObjIn).setActiveConfig(spongeConfig); this.denyChunkRequests = spongeConfig.getConfig().getWorld().getDenyChunkRequests(); this.chunkUnloadDelay = spongeConfig.getConfig().getWorld().getChunkUnloadDelay() * 1000; this.maxChunkUnloads = spongeConfig.getConfig().getWorld().getMaxChunkUnloads(); } @Override public ChunkDataStream getGeneratedChunks() { if (!(this.chunkLoader instanceof IMixinAnvilChunkLoader)) { throw new UnsupportedOperationException("unknown chunkLoader"); } return new SpongeChunkDataStream(((IMixinAnvilChunkLoader) this.chunkLoader).getWorldDir()); } @Override public CompletableFuture<Boolean> doesChunkExist(Vector3i chunkCoords) { return WorldStorageUtil.doesChunkExist(this.world, this.chunkLoader, chunkCoords); } @Override public CompletableFuture<Optional<DataContainer>> getChunkData(Vector3i chunkCoords) { return WorldStorageUtil.getChunkData(this.world, this.chunkLoader, chunkCoords); } @Override public WorldProperties getWorldProperties() { return (WorldProperties) this.world.getWorldInfo(); } /** * @author blood - October 25th, 2016 * @reason Removes usage of droppedChunksSet in favor of unloaded flag. * * @param chunkIn The chunk to queue */ @Overwrite public void queueUnload(Chunk chunkIn) { if (!((IMixinChunk) chunkIn).isPersistedChunk() && this.world.provider.canDropChunk(chunkIn.xPosition, chunkIn.zPosition)) { // Sponge - we avoid using the queue and simply check the unloaded flag during unloads //this.droppedChunksSet.add(Long.valueOf(ChunkPos.asLong(chunkIn.xPosition, chunkIn.zPosition))); chunkIn.unloadQueued = true; } } // split from loadChunk to avoid 2 lookups with our inject private Chunk loadChunkForce(int x, int z) { Chunk chunk = this.loadChunkFromFile(x, z); if (chunk != null) { this.id2ChunkMap.put(ChunkPos.asLong(x, z), chunk); chunk.onChunkLoad(); chunk.populateChunk((ChunkProviderServer)(Object) this, this.chunkGenerator); } return chunk; } @Redirect(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/gen/ChunkProviderServer;loadChunk(II)Lnet/minecraft/world/chunk/Chunk;")) public Chunk onProvideChunkHead(ChunkProviderServer chunkProviderServer, int x, int z) { if (!this.denyChunkRequests || this.forceChunkRequests) { return this.loadChunk(x, z); } Chunk chunk = this.getLoadedChunk(x, z); if (chunk == null && this.canDenyChunkRequest()) { return EMPTY_CHUNK; } if (chunk == null) { chunk = this.loadChunkForce(x, z); } return chunk; } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/ChunkPos;asLong(II)J")) public void onProvideChunkStart(int x, int z, CallbackInfoReturnable<Chunk> cir) { if (CauseTracker.ENABLED) { final CauseTracker causeTracker = ((IMixinWorldServer) this.world).getCauseTracker(); causeTracker.switchToPhase(GenerationPhase.State.TERRAIN_GENERATION, PhaseContext.start() .addCaptures() .complete()); } } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;populateChunk(Lnet/minecraft/world/chunk/IChunkProvider;Lnet/minecraft/world/chunk/IChunkGenerator;)V", shift = Shift.AFTER)) public void onProvideChunkEnd(int x, int z, CallbackInfoReturnable<Chunk> ci) { if (CauseTracker.ENABLED) { ((IMixinWorldServer) this.world).getCauseTracker().completePhase(); } } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/crash/CrashReport;makeCrashReport(Ljava/lang/Throwable;Ljava/lang/String;)Lnet/minecraft/crash/CrashReport;")) public void onError(CallbackInfoReturnable<Chunk> ci) { if (CauseTracker.ENABLED) { ((IMixinWorldServer) this.world).getCauseTracker().completePhase(); } } private boolean canDenyChunkRequest() { if (CauseTracker.ENABLED) { final CauseTracker causeTracker = ((IMixinWorldServer) this.world).getCauseTracker(); final IPhaseState currentState = causeTracker.getCurrentState(); // States that cannot deny chunks if (currentState == TickPhase.Tick.PLAYER || currentState == TickPhase.Tick.DIMENSION || currentState == EntityPhase.State.CHANGING_TO_DIMENSION || currentState == EntityPhase.State.LEAVING_DIMENSION) { return false; } // States that can deny chunks if (currentState == GenerationPhase.State.WORLD_SPAWNER_SPAWNING || currentState == PluginPhase.Listener.PRE_WORLD_TICK_LISTENER) { return true; } // Phases that can deny chunks if (currentState.getPhase() == TrackingPhases.BLOCK || currentState.getPhase() == TrackingPhases.ENTITY || currentState.getPhase() == TrackingPhases.TICK) { return true; } } return false; } @Override public void setMaxChunkUnloads(int maxUnloads) { this.maxChunkUnloads = maxUnloads; } @Override public void setForceChunkRequests(boolean flag) { this.forceChunkRequests = flag; } @Override public void setDenyChunkRequests(boolean flag) { this.denyChunkRequests = flag; } @Override public long getChunkUnloadDelay() { return this.chunkUnloadDelay; } /** * @author blood - October 20th, 2016 * @reason Refactors entire method to not use the droppedChunksSet by * simply looping through all loaded chunks and determining whether it * can unload or not. * * @return true if unload queue was processed */ @Overwrite public boolean tick() { if (!this.world.disableLevelSaving) { ((IMixinWorldServer) this.world).getTimingsHandler().doChunkUnload.startTiming(); Iterator<Chunk> iterator = this.id2ChunkMap.values().iterator(); int chunksUnloaded = 0; long now = System.currentTimeMillis(); while (chunksUnloaded < this.maxChunkUnloads && iterator.hasNext()) { Chunk chunk = iterator.next(); IMixinChunk spongeChunk = (IMixinChunk) chunk; if (chunk != null && chunk.unloadQueued && !spongeChunk.isPersistedChunk()) { if (this.getChunkUnloadDelay() > 0) { if ((now - spongeChunk.getScheduledForUnload()) < this.chunkUnloadDelay) { continue; } spongeChunk.setScheduledForUnload(-1); } chunk.onChunkUnload(); this.saveChunkData(chunk); this.saveChunkExtraData(chunk); iterator.remove(); chunksUnloaded++; } } ((IMixinWorldServer) this.world).getTimingsHandler().doChunkUnload.stopTiming(); } this.chunkLoader.chunkTick(); return false; } // Copy of getLoadedChunk without marking chunk active. // This allows the chunk to unload if currently queued. @Override public Chunk getLoadedChunkWithoutMarkingActive(int x, int z){ long i = ChunkPos.asLong(x, z); Chunk chunk = this.id2ChunkMap.get(i); return chunk; } @Inject(method = "canSave", at = @At("HEAD"), cancellable = true) public void onCanSave(CallbackInfoReturnable<Boolean> cir) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { cir.setReturnValue(false); } } @Inject(method = "saveChunkData", at = @At("HEAD"), cancellable = true) public void onSaveChunkData(Chunk chunkIn, CallbackInfo ci) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { ci.cancel(); } } @Inject(method = "saveExtraData", at = @At("HEAD"), cancellable = true) public void onSaveExtraData(CallbackInfo ci) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { ci.cancel(); } } }
src/main/java/org/spongepowered/common/mixin/core/world/gen/MixinChunkProviderServer.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.world.gen; import com.flowpowered.math.vector.Vector3i; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkGenerator; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.world.SerializationBehaviors; import org.spongepowered.api.world.storage.ChunkDataStream; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.api.world.storage.WorldStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.config.SpongeConfig; import org.spongepowered.common.event.tracking.CauseTracker; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.phase.TrackingPhases; import org.spongepowered.common.event.tracking.phase.entity.EntityPhase; import org.spongepowered.common.event.tracking.phase.generation.GenerationPhase; import org.spongepowered.common.event.tracking.phase.plugin.PluginPhase; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.interfaces.IMixinChunk; import org.spongepowered.common.interfaces.world.IMixinAnvilChunkLoader; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.interfaces.world.gen.IMixinChunkProviderServer; import org.spongepowered.common.util.CachedLong2ObjectMap; import org.spongepowered.common.util.SpongeHooks; import org.spongepowered.common.world.SpongeEmptyChunk; import org.spongepowered.common.world.storage.SpongeChunkDataStream; import org.spongepowered.common.world.storage.WorldStorageUtil; import java.util.Iterator; import java.util.Optional; import java.util.concurrent.CompletableFuture; @Mixin(ChunkProviderServer.class) public abstract class MixinChunkProviderServer implements WorldStorage, IMixinChunkProviderServer { private SpongeEmptyChunk EMPTY_CHUNK; private boolean denyChunkRequests = true; private boolean forceChunkRequests = false; private long chunkUnloadDelay = 15000; private int maxChunkUnloads = 100; @Shadow @Final public WorldServer world; @Shadow @Final private IChunkLoader chunkLoader; @Shadow public IChunkGenerator chunkGenerator; @SuppressWarnings({"unchecked", "rawtypes"}) @Shadow @Final @Mutable public Long2ObjectMap<Chunk> id2ChunkMap = new CachedLong2ObjectMap(); @Shadow public abstract Chunk getLoadedChunk(int x, int z); @Shadow public abstract Chunk loadChunk(int x, int z); @Shadow public abstract Chunk loadChunkFromFile(int x, int z); @Shadow public abstract Chunk provideChunk(int x, int z); @Shadow public abstract void saveChunkExtraData(Chunk chunkIn); @Shadow public abstract void saveChunkData(Chunk chunkIn); @Inject(method = "<init>", at = @At("RETURN")) private void onConstruct(WorldServer worldObjIn, IChunkLoader chunkLoaderIn, IChunkGenerator chunkGeneratorIn, CallbackInfo ci) { EMPTY_CHUNK = new SpongeEmptyChunk(worldObjIn, 0, 0); SpongeConfig<?> spongeConfig = SpongeHooks.getActiveConfig(worldObjIn); ((IMixinWorldServer) worldObjIn).setActiveConfig(spongeConfig); this.denyChunkRequests = spongeConfig.getConfig().getWorld().getDenyChunkRequests(); this.chunkUnloadDelay = spongeConfig.getConfig().getWorld().getChunkUnloadDelay() * 1000; this.maxChunkUnloads = spongeConfig.getConfig().getWorld().getMaxChunkUnloads(); } @Override public ChunkDataStream getGeneratedChunks() { if (!(this.chunkLoader instanceof IMixinAnvilChunkLoader)) { throw new UnsupportedOperationException("unknown chunkLoader"); } return new SpongeChunkDataStream(((IMixinAnvilChunkLoader) this.chunkLoader).getWorldDir()); } @Override public CompletableFuture<Boolean> doesChunkExist(Vector3i chunkCoords) { return WorldStorageUtil.doesChunkExist(this.world, this.chunkLoader, chunkCoords); } @Override public CompletableFuture<Optional<DataContainer>> getChunkData(Vector3i chunkCoords) { return WorldStorageUtil.getChunkData(this.world, this.chunkLoader, chunkCoords); } @Override public WorldProperties getWorldProperties() { return (WorldProperties) this.world.getWorldInfo(); } /** * @author blood - October 25th, 2016 * @reason Removes usage of droppedChunksSet in favor of unloaded flag. * * @param chunkIn The chunk to queue */ @Overwrite public void queueUnload(Chunk chunkIn) { if (!((IMixinChunk) chunkIn).isPersistedChunk() && this.world.provider.canDropChunk(chunkIn.xPosition, chunkIn.zPosition)) { // Sponge - we avoid using the queue and simply check the unloaded flag during unloads //this.droppedChunksSet.add(Long.valueOf(ChunkPos.asLong(chunkIn.xPosition, chunkIn.zPosition))); chunkIn.unloadQueued = true; } } // split from loadChunk to avoid 2 lookups with our inject private Chunk loadChunkForce(int x, int z) { Chunk chunk = this.loadChunkFromFile(x, z); if (chunk != null) { this.id2ChunkMap.put(ChunkPos.asLong(x, z), chunk); chunk.onChunkLoad(); chunk.populateChunk((ChunkProviderServer)(Object) this, this.chunkGenerator); } return chunk; } @Redirect(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/gen/ChunkProviderServer;loadChunk(II)Lnet/minecraft/world/chunk/Chunk;")) public Chunk onProvideChunkHead(ChunkProviderServer chunkProviderServer, int x, int z) { if (!this.denyChunkRequests || this.forceChunkRequests) { return this.loadChunk(x, z); } Chunk chunk = this.getLoadedChunk(x, z); if (chunk == null && this.canDenyChunkRequest()) { return EMPTY_CHUNK; } if (chunk == null) { chunk = this.loadChunkForce(x, z); } return chunk; } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/ChunkPos;asLong(II)J")) public void onProvideChunkStart(int x, int z, CallbackInfoReturnable<Chunk> cir) { if (CauseTracker.ENABLED) { final CauseTracker causeTracker = ((IMixinWorldServer) this.world).getCauseTracker(); causeTracker.switchToPhase(GenerationPhase.State.TERRAIN_GENERATION, PhaseContext.start() .addCaptures() .complete()); } } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;populateChunk(Lnet/minecraft/world/chunk/IChunkProvider;Lnet/minecraft/world/chunk/IChunkGenerator;)V", shift = Shift.AFTER)) public void onProvideChunkEnd(int x, int z, CallbackInfoReturnable<Chunk> ci) { if (CauseTracker.ENABLED) { ((IMixinWorldServer) this.world).getCauseTracker().completePhase(); } } @Inject(method = "provideChunk", at = @At(value = "INVOKE", target = "Lnet/minecraft/crash/CrashReport;makeCrashReport(Ljava/lang/Throwable;Ljava/lang/String;)Lnet/minecraft/crash/CrashReport;")) public void onError(CallbackInfoReturnable<Chunk> ci) { if (CauseTracker.ENABLED) { ((IMixinWorldServer) this.worldObj).getCauseTracker().completePhase(); } } private boolean canDenyChunkRequest() { if (CauseTracker.ENABLED) { final CauseTracker causeTracker = ((IMixinWorldServer) this.world).getCauseTracker(); final IPhaseState currentState = causeTracker.getCurrentState(); // States that cannot deny chunks if (currentState == TickPhase.Tick.PLAYER || currentState == TickPhase.Tick.DIMENSION || currentState == EntityPhase.State.CHANGING_TO_DIMENSION || currentState == EntityPhase.State.LEAVING_DIMENSION) { return false; } // States that can deny chunks if (currentState == GenerationPhase.State.WORLD_SPAWNER_SPAWNING || currentState == PluginPhase.Listener.PRE_WORLD_TICK_LISTENER) { return true; } // Phases that can deny chunks if (currentState.getPhase() == TrackingPhases.BLOCK || currentState.getPhase() == TrackingPhases.ENTITY || currentState.getPhase() == TrackingPhases.TICK) { return true; } } return false; } @Override public void setMaxChunkUnloads(int maxUnloads) { this.maxChunkUnloads = maxUnloads; } @Override public void setForceChunkRequests(boolean flag) { this.forceChunkRequests = flag; } @Override public void setDenyChunkRequests(boolean flag) { this.denyChunkRequests = flag; } @Override public long getChunkUnloadDelay() { return this.chunkUnloadDelay; } /** * @author blood - October 20th, 2016 * @reason Refactors entire method to not use the droppedChunksSet by * simply looping through all loaded chunks and determining whether it * can unload or not. * * @return true if unload queue was processed */ @Overwrite public boolean tick() { if (!this.world.disableLevelSaving) { ((IMixinWorldServer) this.world).getTimingsHandler().doChunkUnload.startTiming(); Iterator<Chunk> iterator = this.id2ChunkMap.values().iterator(); int chunksUnloaded = 0; long now = System.currentTimeMillis(); while (chunksUnloaded < this.maxChunkUnloads && iterator.hasNext()) { Chunk chunk = iterator.next(); IMixinChunk spongeChunk = (IMixinChunk) chunk; if (chunk != null && chunk.unloadQueued && !spongeChunk.isPersistedChunk()) { if (this.getChunkUnloadDelay() > 0) { if ((now - spongeChunk.getScheduledForUnload()) < this.chunkUnloadDelay) { continue; } spongeChunk.setScheduledForUnload(-1); } chunk.onChunkUnload(); this.saveChunkData(chunk); this.saveChunkExtraData(chunk); iterator.remove(); chunksUnloaded++; } } ((IMixinWorldServer) this.world).getTimingsHandler().doChunkUnload.stopTiming(); } this.chunkLoader.chunkTick(); return false; } // Copy of getLoadedChunk without marking chunk active. // This allows the chunk to unload if currently queued. @Override public Chunk getLoadedChunkWithoutMarkingActive(int x, int z){ long i = ChunkPos.asLong(x, z); Chunk chunk = this.id2ChunkMap.get(i); return chunk; } @Inject(method = "canSave", at = @At("HEAD"), cancellable = true) public void onCanSave(CallbackInfoReturnable<Boolean> cir) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { cir.setReturnValue(false); } } @Inject(method = "saveChunkData", at = @At("HEAD"), cancellable = true) public void onSaveChunkData(Chunk chunkIn, CallbackInfo ci) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { ci.cancel(); } } @Inject(method = "saveExtraData", at = @At("HEAD"), cancellable = true) public void onSaveExtraData(CallbackInfo ci) { if (((WorldProperties)this.world.getWorldInfo()).getSerializationBehavior() == SerializationBehaviors.NONE) { ci.cancel(); } } }
Update MixinChunkProviderServer for bleeding changes
src/main/java/org/spongepowered/common/mixin/core/world/gen/MixinChunkProviderServer.java
Update MixinChunkProviderServer for bleeding changes
Java
mit
92a25d5938cc8692b9413e304f4f84dc8dd33edd
0
ktrnka/droidling,ktrnka/droidling,ktrnka/droidling
package com.github.ktrnka.droidling; import static com.github.ktrnka.droidling.Tokenizer.isNonword; import static com.github.ktrnka.droidling.Tokenizer.messageEnd; import static com.github.ktrnka.droidling.Tokenizer.messageStart; import static com.github.ktrnka.droidling.Tokenizer.nospacePunctPattern; import static com.github.ktrnka.droidling.Tokenizer.tokenize; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.regex.Matcher; /** * Statistics about a homogeneous corpus, such as a single person's sent or received messages. * Contains stats like unigrams, bigrams, trigrams, number of messages, message lengths, etc. * @author keith.trnka * */ public class CorpusStats { private int messages; private int filteredWords; private int unfilteredWords; private int chars; private int filteredWordLength; private HashMap<String,int[]> unigrams; public HashMap<String, int[]> getUnigrams() { return unigrams; } private int unigramTotal; private HashMap<String,HashMap<String, int[]>> bigrams; private int bigramTotal; private HashMap<String,HashMap<String,HashMap<String, int[]>>> trigrams; private int trigramTotal; /** * parameter for absolute discounting */ public static final double D = 0.3; public CorpusStats() { messages = 0; filteredWords = 0; unfilteredWords = 0; chars = 0; filteredWordLength = 0; unigrams = new HashMap<String,int[]>(); bigrams = new HashMap<String,HashMap<String, int[]>>(); trigrams = new HashMap<String,HashMap<String,HashMap<String, int[]>>>(); unigramTotal = 0; bigramTotal = 0; trigramTotal = 0; } /** * Train from the specified text message. * * TODO: There are OutOfMemory crash bugs that can be triggered from this in put calls to HashMap when it doubles in size * @param message */ public void train(String message) { messages++; chars += message.length(); message = message.toLowerCase(); ArrayList<String> tokens = new ArrayList<String>(); tokens.add(messageStart); tokens.addAll(tokenize(message)); tokens.add(messageEnd); // update the ngrams! String previous = null, ppWord = null; for (String token : tokens) { // TODO: change this to truecasing //token = token.toLowerCase(); // unigrams if (unigrams.containsKey(token)) unigrams.get(token)[0]++; else unigrams.put(token, new int[] { 1 }); // OutOfMemory error here in the put call at HashMap.doubleCapacity unigramTotal++; unfilteredWords++; // filtered unigram stats // TODO: compute this from the distribution at the end (faster) if (!isNonword(token)) { filteredWords++; filteredWordLength += token.length(); } // bigrams if (previous != null) { if (!bigrams.containsKey(previous)) bigrams.put(previous, new HashMap<String, int[]>()); if (!bigrams.get(previous).containsKey(token)) bigrams.get(previous).put(token, new int[] { 1 }); else bigrams.get(previous).get(token)[0]++; bigramTotal++; // trigrams if (ppWord != null) { if (!trigrams.containsKey(ppWord)) trigrams.put(ppWord, new HashMap<String,HashMap<String, int[]>>()); // OutOfMemory error here in the put call at HashMap.doubleCapacity HashMap<String,HashMap<String, int[]>> bigramSubdist = trigrams.get(ppWord); if (!bigramSubdist.containsKey(previous)) bigramSubdist.put(previous, new HashMap<String, int[]>()); HashMap<String,int[]> dist = bigramSubdist.get(previous); if (!dist.containsKey(token)) dist.put(token, new int[] { 1 }); else dist.get(token)[0]++; trigramTotal++; } } // move the history back ppWord = previous; previous = token; } } public int getMessages() { return messages; } public double getCharsPerMessage() { return chars / (double)messages; } public double getWordsPerMessage() { return filteredWords / (double)messages; } public double getWordLength() { return filteredWordLength / (double) filteredWords; } public int getFilteredWords() { return filteredWords; } /** * Unigram probability (smoothed) */ public double getProb(String word) { if (unigrams.containsKey(word)) { int count = unigrams.get(word)[0]; return (count - D) / unigramTotal; } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / unigramTotal; } } /** * Bigram joint probability (smoothed) */ public double getProb(String word1, String word2) { if (bigrams.containsKey(word1) && bigrams.get(word1).containsKey(word2)) { int count = bigrams.get(word1).get(word2)[0]; return (count - D) / bigramTotal; } else { // we discounted bigrams.size() of them, estimating bigrams.size() unknown words return D / bigramTotal; } } /** * Unigram probability (smoothed) minus any counts in subtractThis */ public double getProb(String word, CorpusStats subtractThis) { if (unigrams.containsKey(word)) { int count = unigrams.get(word)[0]; if (subtractThis.unigrams.containsKey(word)) count -= subtractThis.unigrams.get(word)[0]; if (count == 0) { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (unigramTotal - subtractThis.unigramTotal); } else { return (count - D) / (unigramTotal - subtractThis.unigramTotal); } } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (unigramTotal - subtractThis.unigramTotal); } } /** * Bigram joint probability (smoothed) minus any counts in subtractThis */ public double getProb(String word1, String word2, CorpusStats subtractThis) { if (bigrams.containsKey(word1) && bigrams.get(word1).containsKey(word2)) { int count = bigrams.get(word1).get(word2)[0]; if (subtractThis.bigrams.containsKey(word1) && subtractThis.bigrams.get(word1).containsKey(word2)) count -= subtractThis.bigrams.get(word1).get(word2)[0]; if (count == 0) { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (bigramTotal - subtractThis.bigramTotal); } else { return (count - D) / (bigramTotal - subtractThis.bigramTotal); } } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (bigramTotal - subtractThis.bigramTotal); } } /** * Compute Jaccard coefficient over the full (unfiltered) vocabulary, which * is size(intersection)/size(union) * @param other * @return */ public double computeUnigramJaccard(CorpusStats other) { int intersection = 0; int union = 0; union = unigrams.size(); for (String word : unigrams.keySet()) { if (other.unigrams.containsKey(word)) intersection++; } for (String word : other.unigrams.keySet()) if (!unigrams.containsKey(word)) union++; return intersection / (double) union; } /** * Assuming that the person measured in a and b are related, determine the interesting * terms that are unique to this association. */ public static ArrayList<String> computeRelationshipTerms(CorpusStats a, CorpusStats aSuperset, CorpusStats b, CorpusStats bSuperset) { // find unigrams in both, score them final HashMap<String,int[]> candidates = new HashMap<String,int[]>(); for (String word : a.unigrams.keySet()) if (b.unigrams.containsKey(word)) if (!isNonword(word)) candidates.put(word, new int[] { (int)(100 * Math.log(a.getProb(word) / aSuperset.getProb(word, a))) + (int)(100 * Math.log(b.getProb(word) / bSuperset.getProb(word, b))) }); // find bigrams in both, score them for (String prev : a.bigrams.keySet()) if (b.bigrams.containsKey(prev) && !isNonword(prev)) for (String word : a.bigrams.get(prev).keySet()) if (b.bigrams.get(prev).containsKey(word) && !isNonword(word)) candidates.put(prev + " " + word, new int[] { (int)(100 * Math.log(a.getProb(prev, word) / aSuperset.getProb(prev, word, a))) + (int)(100 * Math.log(b.getProb(prev, word) / bSuperset.getProb(prev, word, b))) }); ArrayList<String> candidateList = new ArrayList<String>(candidates.keySet()); Collections.sort(candidateList, new Comparator<String>() { public int compare(String lhs, String rhs) { return candidates.get(rhs)[0] - candidates.get(lhs)[0]; } }); // basic ngram folding for (int i = 0; i < 10 && i < candidateList.size(); i++) { String[] tokens = candidateList.get(i).split(" "); if (tokens.length == 2) { candidates.get(tokens[0])[0] = 0; candidates.get(tokens[1])[0] = 0; } } // resort (should be fast - mostly in order) Collections.sort(candidateList, new Comparator<String>() { public int compare(String lhs, String rhs) { return candidates.get(rhs)[0] - candidates.get(lhs)[0]; } }); // TODO: find an efficient way to remove any elements that have zero or negative score return candidateList; } /** * Generate the single most probable message according to the trigram model. * If it's not built from much data, it's probably an exact message. * @return */ public String generateBestMessage(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; if (ppWord == null || !useTrigrams) distribution = bigrams.get(prev); else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); } String bestWord = null; int bestFreq = 0; for (String word : distribution.keySet()) if (bestFreq == 0 || bestFreq < distribution.get(word)[0]) { bestWord = word; bestFreq = distribution.get(word)[0]; } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } StringBuilder b = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) if (i == 0) b.append(tokens.get(i)); else { Matcher m = nospacePunctPattern.matcher(tokens.get(i)); if (!m.matches()) b.append(" "); b.append(tokens.get(i)); } return b.toString(); } public String generateRandomMessage(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; int total; if (ppWord == null || !useTrigrams) { distribution = bigrams.get(prev); total = unigrams.get(prev)[0]; } else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); total = bigrams.get(ppWord).get(prev)[0]; } // generate a rand, scale to total int target = (int)(total * Math.random()); int seenFrequency = 0; String bestWord = null; for (String word : distribution.keySet()) { seenFrequency += distribution.get(word)[0]; if (seenFrequency > target) { bestWord = word; break; } } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } StringBuilder b = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) if (i == 0) b.append(tokens.get(i)); else { Matcher m = nospacePunctPattern.matcher(tokens.get(i)); if (!m.matches()) b.append(" "); b.append(tokens.get(i)); } return b.toString(); } public ArrayList<String> generateRandomMessageTokens(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; int total; if (ppWord == null || !useTrigrams) { distribution = bigrams.get(prev); total = unigrams.get(prev)[0]; } else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); total = bigrams.get(ppWord).get(prev)[0]; } // generate a rand, scale to total int target = (int)(total * Math.random()); int seenFrequency = 0; String bestWord = null; for (String word : distribution.keySet()) { seenFrequency += distribution.get(word)[0]; if (seenFrequency > target) { bestWord = word; break; } } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } return tokens; } /** * Generate N random messages according to the trigram/bigram model. * @param N * @return */ public ArrayList<String> generateRandomMessages(int N) { ArrayList<String> messages = new ArrayList<String>(); for (int i = 0; i < N; i++) { messages.add(generateRandomMessage(false)); } return messages; } /** * Generate a set of messages of size M, then select the N most probable. * @param N The number of messages you want * @param M The number to pick N from (if you pick too many, you'll likely get similar messages, but too few and they'll be too random) * @return The most probable subset of the messages. */ public ArrayList<String> generateSemiRandom(int N, int M) { ArrayList<ArrayList<String>> messages = new ArrayList<ArrayList<String>>(); // generate M for (int i = 0; i < M; i++) { messages.add(generateRandomMessageTokens(false)); } // score them all // sort // pick the top assert(false); return null; } }
src/com/github/ktrnka/droidling/CorpusStats.java
package com.github.ktrnka.droidling; import static com.github.ktrnka.droidling.Tokenizer.isNonword; import static com.github.ktrnka.droidling.Tokenizer.messageEnd; import static com.github.ktrnka.droidling.Tokenizer.messageStart; import static com.github.ktrnka.droidling.Tokenizer.nospacePunctPattern; import static com.github.ktrnka.droidling.Tokenizer.tokenize; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.regex.Matcher; /** * Statistics about a homogeneous corpus, such as a single person's sent or received messages. * Contains stats like unigrams, bigrams, trigrams, number of messages, message lengths, etc. * @author keith.trnka * */ public class CorpusStats { private int messages; private int filteredWords; private int unfilteredWords; private int chars; private int filteredWordLength; private HashMap<String,int[]> unigrams; public HashMap<String, int[]> getUnigrams() { return unigrams; } private int unigramTotal; private HashMap<String,HashMap<String, int[]>> bigrams; private int bigramTotal; private HashMap<String,HashMap<String,HashMap<String, int[]>>> trigrams; private int trigramTotal; /** * parameter for absolute discounting */ public static final double D = 0.3; public CorpusStats() { messages = 0; filteredWords = 0; unfilteredWords = 0; chars = 0; filteredWordLength = 0; unigrams = new HashMap<String,int[]>(); bigrams = new HashMap<String,HashMap<String, int[]>>(); trigrams = new HashMap<String,HashMap<String,HashMap<String, int[]>>>(); unigramTotal = 0; bigramTotal = 0; trigramTotal = 0; } public void train(String message) { messages++; chars += message.length(); message = message.toLowerCase(); ArrayList<String> tokens = new ArrayList<String>(); tokens.add(messageStart); tokens.addAll(tokenize(message)); tokens.add(messageEnd); // update the ngrams! String previous = null, ppWord = null; for (String token : tokens) { // TODO: change this to truecasing //token = token.toLowerCase(); // unigrams if (unigrams.containsKey(token)) unigrams.get(token)[0]++; else unigrams.put(token, new int[] { 1 }); unigramTotal++; unfilteredWords++; // filtered unigram stats // TODO: compute this from the distribution at the end (faster) if (!isNonword(token)) { filteredWords++; filteredWordLength += token.length(); } // bigrams if (previous != null) { if (!bigrams.containsKey(previous)) bigrams.put(previous, new HashMap<String, int[]>()); if (!bigrams.get(previous).containsKey(token)) bigrams.get(previous).put(token, new int[] { 1 }); else bigrams.get(previous).get(token)[0]++; bigramTotal++; // trigrams if (ppWord != null) { if (!trigrams.containsKey(ppWord)) trigrams.put(ppWord, new HashMap<String,HashMap<String, int[]>>()); HashMap<String,HashMap<String, int[]>> bigramSubdist = trigrams.get(ppWord); if (!bigramSubdist.containsKey(previous)) bigramSubdist.put(previous, new HashMap<String, int[]>()); HashMap<String,int[]> dist = bigramSubdist.get(previous); if (!dist.containsKey(token)) dist.put(token, new int[] { 1 }); else dist.get(token)[0]++; trigramTotal++; } } // move the history back ppWord = previous; previous = token; } } public int getMessages() { return messages; } public double getCharsPerMessage() { return chars / (double)messages; } public double getWordsPerMessage() { return filteredWords / (double)messages; } public double getWordLength() { return filteredWordLength / (double) filteredWords; } public int getFilteredWords() { return filteredWords; } /** * Unigram probability (smoothed) */ public double getProb(String word) { if (unigrams.containsKey(word)) { int count = unigrams.get(word)[0]; return (count - D) / unigramTotal; } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / unigramTotal; } } /** * Bigram joint probability (smoothed) */ public double getProb(String word1, String word2) { if (bigrams.containsKey(word1) && bigrams.get(word1).containsKey(word2)) { int count = bigrams.get(word1).get(word2)[0]; return (count - D) / bigramTotal; } else { // we discounted bigrams.size() of them, estimating bigrams.size() unknown words return D / bigramTotal; } } /** * Unigram probability (smoothed) minus any counts in subtractThis */ public double getProb(String word, CorpusStats subtractThis) { if (unigrams.containsKey(word)) { int count = unigrams.get(word)[0]; if (subtractThis.unigrams.containsKey(word)) count -= subtractThis.unigrams.get(word)[0]; if (count == 0) { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (unigramTotal - subtractThis.unigramTotal); } else { return (count - D) / (unigramTotal - subtractThis.unigramTotal); } } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (unigramTotal - subtractThis.unigramTotal); } } /** * Bigram joint probability (smoothed) minus any counts in subtractThis */ public double getProb(String word1, String word2, CorpusStats subtractThis) { if (bigrams.containsKey(word1) && bigrams.get(word1).containsKey(word2)) { int count = bigrams.get(word1).get(word2)[0]; if (subtractThis.bigrams.containsKey(word1) && subtractThis.bigrams.get(word1).containsKey(word2)) count -= subtractThis.bigrams.get(word1).get(word2)[0]; if (count == 0) { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (bigramTotal - subtractThis.bigramTotal); } else { return (count - D) / (bigramTotal - subtractThis.bigramTotal); } } else { // we discounted unigrams.size() of them, estimating unigrams.size() unknown words return D / (bigramTotal - subtractThis.bigramTotal); } } /** * Compute Jaccard coefficient over the full (unfiltered) vocabulary, which * is size(intersection)/size(union) * @param other * @return */ public double computeUnigramJaccard(CorpusStats other) { int intersection = 0; int union = 0; union = unigrams.size(); for (String word : unigrams.keySet()) { if (other.unigrams.containsKey(word)) intersection++; } for (String word : other.unigrams.keySet()) if (!unigrams.containsKey(word)) union++; return intersection / (double) union; } /** * Assuming that the person measured in a and b are related, determine the interesting * terms that are unique to this association. */ public static ArrayList<String> computeRelationshipTerms(CorpusStats a, CorpusStats aSuperset, CorpusStats b, CorpusStats bSuperset) { // find unigrams in both, score them final HashMap<String,int[]> candidates = new HashMap<String,int[]>(); for (String word : a.unigrams.keySet()) if (b.unigrams.containsKey(word)) if (!isNonword(word)) candidates.put(word, new int[] { (int)(100 * Math.log(a.getProb(word) / aSuperset.getProb(word, a))) + (int)(100 * Math.log(b.getProb(word) / bSuperset.getProb(word, b))) }); // find bigrams in both, score them for (String prev : a.bigrams.keySet()) if (b.bigrams.containsKey(prev) && !isNonword(prev)) for (String word : a.bigrams.get(prev).keySet()) if (b.bigrams.get(prev).containsKey(word) && !isNonword(word)) candidates.put(prev + " " + word, new int[] { (int)(100 * Math.log(a.getProb(prev, word) / aSuperset.getProb(prev, word, a))) + (int)(100 * Math.log(b.getProb(prev, word) / bSuperset.getProb(prev, word, b))) }); ArrayList<String> candidateList = new ArrayList<String>(candidates.keySet()); Collections.sort(candidateList, new Comparator<String>() { public int compare(String lhs, String rhs) { return candidates.get(rhs)[0] - candidates.get(lhs)[0]; } }); // basic ngram folding for (int i = 0; i < 10 && i < candidateList.size(); i++) { String[] tokens = candidateList.get(i).split(" "); if (tokens.length == 2) { candidates.get(tokens[0])[0] = 0; candidates.get(tokens[1])[0] = 0; } } // resort (should be fast - mostly in order) Collections.sort(candidateList, new Comparator<String>() { public int compare(String lhs, String rhs) { return candidates.get(rhs)[0] - candidates.get(lhs)[0]; } }); // TODO: find an efficient way to remove any elements that have zero or negative score return candidateList; } /** * Generate the single most probable message according to the trigram model. * If it's not built from much data, it's probably an exact message. * @return */ public String generateBestMessage(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; if (ppWord == null || !useTrigrams) distribution = bigrams.get(prev); else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); } String bestWord = null; int bestFreq = 0; for (String word : distribution.keySet()) if (bestFreq == 0 || bestFreq < distribution.get(word)[0]) { bestWord = word; bestFreq = distribution.get(word)[0]; } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } StringBuilder b = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) if (i == 0) b.append(tokens.get(i)); else { Matcher m = nospacePunctPattern.matcher(tokens.get(i)); if (!m.matches()) b.append(" "); b.append(tokens.get(i)); } return b.toString(); } public String generateRandomMessage(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; int total; if (ppWord == null || !useTrigrams) { distribution = bigrams.get(prev); total = unigrams.get(prev)[0]; } else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); total = bigrams.get(ppWord).get(prev)[0]; } // generate a rand, scale to total int target = (int)(total * Math.random()); int seenFrequency = 0; String bestWord = null; for (String word : distribution.keySet()) { seenFrequency += distribution.get(word)[0]; if (seenFrequency > target) { bestWord = word; break; } } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } StringBuilder b = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) if (i == 0) b.append(tokens.get(i)); else { Matcher m = nospacePunctPattern.matcher(tokens.get(i)); if (!m.matches()) b.append(" "); b.append(tokens.get(i)); } return b.toString(); } public ArrayList<String> generateRandomMessageTokens(boolean useTrigrams) { ArrayList<String> tokens = new ArrayList<String>(); String ppWord = null, prev = messageStart; while (tokens.size() < 40) { // load the best trigram (or bigram if none available) HashMap<String, int[]> distribution; int total; if (ppWord == null || !useTrigrams) { distribution = bigrams.get(prev); total = unigrams.get(prev)[0]; } else { HashMap<String,HashMap<String, int[]>> bigramDist = trigrams.get(ppWord); distribution = bigramDist.get(prev); total = bigrams.get(ppWord).get(prev)[0]; } // generate a rand, scale to total int target = (int)(total * Math.random()); int seenFrequency = 0; String bestWord = null; for (String word : distribution.keySet()) { seenFrequency += distribution.get(word)[0]; if (seenFrequency > target) { bestWord = word; break; } } if (bestWord.equals(messageEnd)) break; tokens.add(bestWord); // advance ppWord = prev; prev = bestWord; } return tokens; } /** * Generate N random messages according to the trigram/bigram model. * @param N * @return */ public ArrayList<String> generateRandomMessages(int N) { ArrayList<String> messages = new ArrayList<String>(); for (int i = 0; i < N; i++) { messages.add(generateRandomMessage(false)); } return messages; } /** * Generate a set of messages of size M, then select the N most probable. * @param N The number of messages you want * @param M The number to pick N from (if you pick too many, you'll likely get similar messages, but too few and they'll be too random) * @return The most probable subset of the messages. */ public ArrayList<String> generateSemiRandom(int N, int M) { ArrayList<ArrayList<String>> messages = new ArrayList<ArrayList<String>>(); // generate M for (int i = 0; i < M; i++) { messages.add(generateRandomMessageTokens(false)); } // score them all // sort // pick the top assert(false); return null; } }
Noted OutOfMemory error locations. Looked through the crash reports and noted where the errors are being thrown. There isn't a really clear fallback mechanism though. I plan to see if I can add more detailed info to the error for reporting.
src/com/github/ktrnka/droidling/CorpusStats.java
Noted OutOfMemory error locations.
Java
mit
59f97946efacb39429b1c56b7fa92684ade59754
0
mhogrefe/wheels
package mho.wheels.misc; import org.jetbrains.annotations.NotNull; import org.junit.Test; import static mho.wheels.misc.FloatingPointUtils.predecessor; import static mho.wheels.misc.FloatingPointUtils.successor; import static mho.wheels.testing.Testing.aeq; import static org.junit.Assert.*; public strictfp class FloatingPointUtilsTest { @Test public void testIsNegativeZero_float() { assertFalse(FloatingPointUtils.isNegativeZero(0.0f)); assertTrue(FloatingPointUtils.isNegativeZero(-0.0f)); assertFalse(FloatingPointUtils.isNegativeZero(1.0f)); assertFalse(FloatingPointUtils.isNegativeZero(-1.0f)); assertFalse(FloatingPointUtils.isNegativeZero(Float.NaN)); assertFalse(FloatingPointUtils.isNegativeZero(Float.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isNegativeZero(Float.NEGATIVE_INFINITY)); } @Test public void testIsNegativeZero_double() { assertFalse(FloatingPointUtils.isNegativeZero(0.0)); assertTrue(FloatingPointUtils.isNegativeZero(-0.0)); assertFalse(FloatingPointUtils.isNegativeZero(1.0)); assertFalse(FloatingPointUtils.isNegativeZero(-1.0)); assertFalse(FloatingPointUtils.isNegativeZero(Double.NaN)); assertFalse(FloatingPointUtils.isNegativeZero(Double.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isNegativeZero(Double.NEGATIVE_INFINITY)); } @Test public void testIsPositiveZero_float() { assertTrue(FloatingPointUtils.isPositiveZero(0.0f)); assertFalse(FloatingPointUtils.isPositiveZero(-0.0f)); assertFalse(FloatingPointUtils.isPositiveZero(1.0f)); assertFalse(FloatingPointUtils.isPositiveZero(-1.0f)); assertFalse(FloatingPointUtils.isPositiveZero(Float.NaN)); assertFalse(FloatingPointUtils.isPositiveZero(Float.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isPositiveZero(Float.NEGATIVE_INFINITY)); } @Test public void testIsPositiveZero_double() { assertTrue(FloatingPointUtils.isPositiveZero(0.0)); assertFalse(FloatingPointUtils.isPositiveZero(-0.0)); assertFalse(FloatingPointUtils.isPositiveZero(1.0)); assertFalse(FloatingPointUtils.isPositiveZero(-1.0)); assertFalse(FloatingPointUtils.isPositiveZero(Double.NaN)); assertFalse(FloatingPointUtils.isPositiveZero(Double.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isPositiveZero(Double.NEGATIVE_INFINITY)); } private static void successor_float_helper(float x, @NotNull String output) { aeq(successor(x), output); } private static void successor_float_fail_helper(float f) { try { successor(f); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSuccessor_float() { successor_float_helper(1.0f, "1.0000001"); successor_float_helper(1e20f, "1.0000001E20"); successor_float_helper(-1.0f, "-0.99999994"); successor_float_helper(-1e20f, "-9.999999E19"); successor_float_helper((float) Math.PI, "3.141593"); successor_float_helper((float) Math.sqrt(2), "1.4142137"); successor_float_helper((float) -Math.PI, "-3.1415925"); successor_float_helper((float) -Math.sqrt(2), "-1.4142134"); successor_float_helper(0.0f, "1.4E-45"); successor_float_helper(-0.0f, "1.4E-45"); successor_float_helper(Float.MIN_VALUE, "2.8E-45"); successor_float_helper(Float.MIN_NORMAL, "1.1754945E-38"); successor_float_helper(-Float.MIN_VALUE, "-0.0"); successor_float_helper(-Float.MIN_NORMAL, "-1.1754942E-38"); successor_float_helper(Float.MAX_VALUE, "Infinity"); successor_float_helper(-Float.MAX_VALUE, "-3.4028233E38"); successor_float_helper(Float.NEGATIVE_INFINITY, "-3.4028235E38"); successor_float_fail_helper(Float.POSITIVE_INFINITY); successor_float_fail_helper(Float.NaN); } private static void predecessor_float_helper(float x, @NotNull String output) { aeq(predecessor(x), output); } private static void predecessor_float_fail_helper(float f) { try { predecessor(f); fail(); } catch (ArithmeticException ignored) {} } @Test public void testPredecessor_float() { predecessor_float_helper(1.0f, "0.99999994"); predecessor_float_helper(1e20f, "9.999999E19"); predecessor_float_helper(-1.0f, "-1.0000001"); predecessor_float_helper(-1e20f, "-1.0000001E20"); predecessor_float_helper((float) Math.PI, "3.1415925"); predecessor_float_helper((float) Math.sqrt(2), "1.4142134"); predecessor_float_helper((float) -Math.PI, "-3.141593"); predecessor_float_helper((float) -Math.sqrt(2), "-1.4142137"); predecessor_float_helper(0.0f, "-1.4E-45"); predecessor_float_helper(-0.0f, "-1.4E-45"); predecessor_float_helper(Float.MIN_VALUE, "0.0"); predecessor_float_helper(Float.MIN_NORMAL, "1.1754942E-38"); predecessor_float_helper(-Float.MIN_VALUE, "-2.8E-45"); predecessor_float_helper(-Float.MIN_NORMAL, "-1.1754945E-38"); predecessor_float_helper(Float.MAX_VALUE, "3.4028233E38"); predecessor_float_helper(-Float.MAX_VALUE, "-Infinity"); predecessor_float_helper(Float.POSITIVE_INFINITY, "3.4028235E38"); predecessor_float_fail_helper(Float.NEGATIVE_INFINITY); predecessor_float_fail_helper(Float.NaN); } private static void successor_double_helper(double x, @NotNull String output) { aeq(successor(x), output); } private static void successor_double_fail_helper(double d) { try { successor(d); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSuccessor_double() { successor_double_helper(1.0, "1.0000000000000002"); successor_double_helper(1e20, "1.0000000000000002E20"); successor_double_helper(-1.0, "-0.9999999999999999"); successor_double_helper(-1e20, "-9.999999999999998E19"); successor_double_helper(Math.PI, "3.1415926535897936"); successor_double_helper(Math.sqrt(2), "1.4142135623730954"); successor_double_helper(-Math.PI, "-3.1415926535897927"); successor_double_helper(-Math.sqrt(2), "-1.414213562373095"); successor_double_helper(0.0, "4.9E-324"); successor_double_helper(-0.0, "4.9E-324"); successor_double_helper(Double.MIN_VALUE, "1.0E-323"); successor_double_helper(Double.MIN_NORMAL, "2.225073858507202E-308"); successor_double_helper(-Double.MIN_VALUE, "-0.0"); successor_double_helper(-Double.MIN_NORMAL, "-2.225073858507201E-308"); successor_double_helper(Double.MAX_VALUE, "Infinity"); successor_double_helper(-Double.MAX_VALUE, "-1.7976931348623155E308"); successor_double_helper(Double.NEGATIVE_INFINITY, "-1.7976931348623157E308"); successor_double_fail_helper(Double.POSITIVE_INFINITY); successor_double_fail_helper(Double.NaN); } private static void predecessor_double_helper(double x, @NotNull String output) { aeq(predecessor(x), output); } private static void predecessor_double_fail_helper(double d) { try { predecessor(d); fail(); } catch (ArithmeticException ignored) {} } @Test public void testPredecessor_double() { predecessor_double_helper(1.0, "0.9999999999999999"); predecessor_double_helper(1e20, "9.999999999999998E19"); predecessor_double_helper(-1.0, "-1.0000000000000002"); predecessor_double_helper(-1e20, "-1.0000000000000002E20"); predecessor_double_helper(Math.PI, "3.1415926535897927"); predecessor_double_helper(Math.sqrt(2), "1.414213562373095"); predecessor_double_helper(-Math.PI, "-3.1415926535897936"); predecessor_double_helper(-Math.sqrt(2), "-1.4142135623730954"); predecessor_double_helper(0.0, "-4.9E-324"); predecessor_double_helper(-0.0, "-4.9E-324"); predecessor_double_helper(Double.MIN_VALUE, "0.0"); predecessor_double_helper(Double.MIN_NORMAL, "2.225073858507201E-308"); predecessor_double_helper(-Double.MIN_VALUE, "-1.0E-323"); predecessor_double_helper(-Double.MIN_NORMAL, "-2.225073858507202E-308"); predecessor_double_helper(Double.MAX_VALUE, "1.7976931348623155E308"); predecessor_double_helper(-Double.MAX_VALUE, "-Infinity"); predecessor_double_helper(Double.POSITIVE_INFINITY, "1.7976931348623157E308"); predecessor_double_fail_helper(Double.NEGATIVE_INFINITY); predecessor_double_fail_helper(Double.NaN); } }
src/test/java/mho/wheels/misc/FloatingPointUtilsTest.java
package mho.wheels.misc; import org.jetbrains.annotations.NotNull; import org.junit.Test; import static mho.wheels.misc.FloatingPointUtils.predecessor; import static mho.wheels.misc.FloatingPointUtils.successor; import static mho.wheels.testing.Testing.aeq; import static org.junit.Assert.*; public strictfp class FloatingPointUtilsTest { @Test public void testIsNegativeZero_float() { assertFalse(FloatingPointUtils.isNegativeZero(0.0f)); assertTrue(FloatingPointUtils.isNegativeZero(-0.0f)); assertFalse(FloatingPointUtils.isNegativeZero(1.0f)); assertFalse(FloatingPointUtils.isNegativeZero(-1.0f)); assertFalse(FloatingPointUtils.isNegativeZero(Float.NaN)); assertFalse(FloatingPointUtils.isNegativeZero(Float.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isNegativeZero(Float.NEGATIVE_INFINITY)); } @Test public void testIsNegativeZero_double() { assertFalse(FloatingPointUtils.isNegativeZero(0.0)); assertTrue(FloatingPointUtils.isNegativeZero(-0.0)); assertFalse(FloatingPointUtils.isNegativeZero(1.0)); assertFalse(FloatingPointUtils.isNegativeZero(-1.0)); assertFalse(FloatingPointUtils.isNegativeZero(Double.NaN)); assertFalse(FloatingPointUtils.isNegativeZero(Double.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isNegativeZero(Double.NEGATIVE_INFINITY)); } @Test public void testIsPositiveZero_float() { assertTrue(FloatingPointUtils.isPositiveZero(0.0f)); assertFalse(FloatingPointUtils.isPositiveZero(-0.0f)); assertFalse(FloatingPointUtils.isPositiveZero(1.0f)); assertFalse(FloatingPointUtils.isPositiveZero(-1.0f)); assertFalse(FloatingPointUtils.isPositiveZero(Float.NaN)); assertFalse(FloatingPointUtils.isPositiveZero(Float.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isPositiveZero(Float.NEGATIVE_INFINITY)); } @Test public void testIsPositiveZero_double() { assertTrue(FloatingPointUtils.isPositiveZero(0.0)); assertFalse(FloatingPointUtils.isPositiveZero(-0.0)); assertFalse(FloatingPointUtils.isPositiveZero(1.0)); assertFalse(FloatingPointUtils.isPositiveZero(-1.0)); assertFalse(FloatingPointUtils.isPositiveZero(Double.NaN)); assertFalse(FloatingPointUtils.isPositiveZero(Double.POSITIVE_INFINITY)); assertFalse(FloatingPointUtils.isPositiveZero(Double.NEGATIVE_INFINITY)); } private static void successor_float_helper(float x, @NotNull String output) { aeq(successor(x), output); } @Test public void testSuccessor_float() { successor_float_helper(1.0f, "1.0000001"); successor_float_helper(1e20f, "1.0000001E20"); successor_float_helper(-1.0f, "-0.99999994"); successor_float_helper(-1e20f, "-9.999999E19"); successor_float_helper((float) Math.PI, "3.141593"); successor_float_helper((float) Math.sqrt(2), "1.4142137"); successor_float_helper((float) -Math.PI, "-3.1415925"); successor_float_helper((float) -Math.sqrt(2), "-1.4142134"); successor_float_helper(0.0f, "1.4E-45"); successor_float_helper(-0.0f, "1.4E-45"); successor_float_helper(Float.MIN_VALUE, "2.8E-45"); successor_float_helper(Float.MIN_NORMAL, "1.1754945E-38"); successor_float_helper(-Float.MIN_VALUE, "-0.0"); successor_float_helper(-Float.MIN_NORMAL, "-1.1754942E-38"); successor_float_helper(Float.MAX_VALUE, "Infinity"); successor_float_helper(-Float.MAX_VALUE, "-3.4028233E38"); successor_float_helper(Float.NEGATIVE_INFINITY, "-3.4028235E38"); try { successor(Float.POSITIVE_INFINITY); fail(); } catch (ArithmeticException ignored) {} try { successor(Float.NaN); fail(); } catch (ArithmeticException ignored) {} } private static void predecessor_float_helper(float x, @NotNull String output) { aeq(predecessor(x), output); } @Test public void testPredecessor_float() { predecessor_float_helper(1.0f, "0.99999994"); predecessor_float_helper(1e20f, "9.999999E19"); predecessor_float_helper(-1.0f, "-1.0000001"); predecessor_float_helper(-1e20f, "-1.0000001E20"); predecessor_float_helper((float) Math.PI, "3.1415925"); predecessor_float_helper((float) Math.sqrt(2), "1.4142134"); predecessor_float_helper((float) -Math.PI, "-3.141593"); predecessor_float_helper((float) -Math.sqrt(2), "-1.4142137"); predecessor_float_helper(0.0f, "-1.4E-45"); predecessor_float_helper(-0.0f, "-1.4E-45"); predecessor_float_helper(Float.MIN_VALUE, "0.0"); predecessor_float_helper(Float.MIN_NORMAL, "1.1754942E-38"); predecessor_float_helper(-Float.MIN_VALUE, "-2.8E-45"); predecessor_float_helper(-Float.MIN_NORMAL, "-1.1754945E-38"); predecessor_float_helper(Float.MAX_VALUE, "3.4028233E38"); predecessor_float_helper(-Float.MAX_VALUE, "-Infinity"); predecessor_float_helper(Float.POSITIVE_INFINITY, "3.4028235E38"); try { predecessor(Float.NEGATIVE_INFINITY); fail(); } catch (ArithmeticException ignored) {} try { predecessor(Float.NaN); fail(); } catch (ArithmeticException ignored) {} } private static void successor_double_helper(double x, @NotNull String output) { aeq(successor(x), output); } @Test public void testSuccessor_double() { successor_double_helper(1.0, "1.0000000000000002"); successor_double_helper(1e20, "1.0000000000000002E20"); successor_double_helper(-1.0, "-0.9999999999999999"); successor_double_helper(-1e20, "-9.999999999999998E19"); successor_double_helper(Math.PI, "3.1415926535897936"); successor_double_helper(Math.sqrt(2), "1.4142135623730954"); successor_double_helper(-Math.PI, "-3.1415926535897927"); successor_double_helper(-Math.sqrt(2), "-1.414213562373095"); successor_double_helper(0.0, "4.9E-324"); successor_double_helper(-0.0, "4.9E-324"); successor_double_helper(Double.MIN_VALUE, "1.0E-323"); successor_double_helper(Double.MIN_NORMAL, "2.225073858507202E-308"); successor_double_helper(-Double.MIN_VALUE, "-0.0"); successor_double_helper(-Double.MIN_NORMAL, "-2.225073858507201E-308"); successor_double_helper(Double.MAX_VALUE, "Infinity"); successor_double_helper(-Double.MAX_VALUE, "-1.7976931348623155E308"); successor_double_helper(Double.NEGATIVE_INFINITY, "-1.7976931348623157E308"); try { successor(Double.POSITIVE_INFINITY); fail(); } catch (ArithmeticException ignored) {} try { successor(Double.NaN); fail(); } catch (ArithmeticException ignored) {} } private static void predecessor_double_helper(double x, @NotNull String output) { aeq(predecessor(x), output); } @Test public void testPredecessor_double() { predecessor_double_helper(1.0, "0.9999999999999999"); predecessor_double_helper(1e20, "9.999999999999998E19"); predecessor_double_helper(-1.0, "-1.0000000000000002"); predecessor_double_helper(-1e20, "-1.0000000000000002E20"); predecessor_double_helper(Math.PI, "3.1415926535897927"); predecessor_double_helper(Math.sqrt(2), "1.414213562373095"); predecessor_double_helper(-Math.PI, "-3.1415926535897936"); predecessor_double_helper(-Math.sqrt(2), "-1.4142135623730954"); predecessor_double_helper(0.0, "-4.9E-324"); predecessor_double_helper(-0.0, "-4.9E-324"); predecessor_double_helper(Double.MIN_VALUE, "0.0"); predecessor_double_helper(Double.MIN_NORMAL, "2.225073858507201E-308"); predecessor_double_helper(-Double.MIN_VALUE, "-1.0E-323"); predecessor_double_helper(-Double.MIN_NORMAL, "-2.225073858507202E-308"); predecessor_double_helper(Double.MAX_VALUE, "1.7976931348623155E308"); predecessor_double_helper(-Double.MAX_VALUE, "-Infinity"); predecessor_double_helper(Double.POSITIVE_INFINITY, "1.7976931348623157E308"); try { predecessor(Double.NEGATIVE_INFINITY); fail(); } catch (ArithmeticException ignored) {} try { predecessor(Double.NaN); fail(); } catch (ArithmeticException ignored) {} } }
added some test helpers
src/test/java/mho/wheels/misc/FloatingPointUtilsTest.java
added some test helpers
Java
mit
af0756dca102fb85cfe9dc9874fddad87faae663
0
dag10/Soapy,dag10/Soapy,dag10/Soapy,dag10/Soapy,dag10/Soapy
package net.drewgottlieb.soapy; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.os.Binder; import android.os.IBinder; import android.util.Log; import com.hoho.android.usbserial.driver.UsbSerialDriver; import com.hoho.android.usbserial.driver.UsbSerialPort; import com.hoho.android.usbserial.driver.UsbSerialProber; import com.hoho.android.usbserial.util.SerialInputOutputManager; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MessageIndexFormatException extends Exception { public MessageIndexFormatException(String msg) { super("Invalid message format. No index found in \"" + msg + "\"."); } } class MessageValueFormatException extends Exception { public MessageValueFormatException(String msg) { super("Invalid message format. No value found in \"" + msg + "\"."); } } public class ArduinoService extends Service { public static final String RFID_INTENT = "new.drewgottlieb.RFID_INTENT"; public static final String DOOR_INTENT = "new.drewgottlieb.DOOR_INTENT"; public static final String CONNECTED_INTENT = "new.drewgottlieb.CONNECTED_INTENT"; public static final String DISCONNECTED_INTENT = "new.drewgottlieb.DISCONNECTED_INTENT"; private static String TAG = "ArduinoService"; public class ArduinoBinder extends Binder { ArduinoService getService() { return ArduinoService.this; } } private boolean connected = false; private final ArduinoBinder mBinder = new ArduinoBinder(); private List<Byte> buffer = new ArrayList<>(); private boolean readingMessage = false; private boolean[] lampStatus = new boolean[2]; private UsbSerialPort port; private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private SerialInputOutputManager serialIoManager; private final SerialInputOutputManager.Listener listener = new SerialInputOutputManager.Listener() { @Override public void onNewData(byte[] bytes) { onRead(bytes); } @Override public void onRunError(Exception e) { Log.w(TAG, "Arduino disconnected. Serial listener stopped due to error: " + e.getMessage()); disconnect(); } }; public ArduinoService() { } private static int getMessageIndex(String msg) throws MessageIndexFormatException { int startIdx = msg.indexOf('['); if (startIdx < 0) { throw new MessageIndexFormatException(msg); } int endIdx = msg.indexOf(']', startIdx); if (endIdx < 0) { throw new MessageIndexFormatException(msg); } try { return Integer.parseInt(msg.substring(startIdx + 1, endIdx)); } catch (NumberFormatException e) { throw new MessageIndexFormatException(msg); } } private static String getMessageValue(String msg) throws MessageValueFormatException { int idx = msg.indexOf(": "); if (idx < 0 || msg.length() < idx + 3) { throw new MessageValueFormatException(msg); } return msg.substring(idx + 2); } private void handleReceivedString(String str) { Log.i(TAG, "Received: \"" + str + "\""); if (str.startsWith("door[")) { int doorId; boolean closed; try { doorId = getMessageIndex(str); closed = "closed".equals(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse door message; " + e.getMessage()); return; } setLamp(doorId, closed); Intent intent = new Intent(); intent.setAction(DOOR_INTENT); intent.putExtra("index", doorId); intent.putExtra("closed", closed); sendBroadcast(intent); } else if (str.startsWith("rfid[")) { int rfidId; String rfid; try { rfidId = getMessageIndex(str); rfid = getMessageValue(str); } catch (Exception e) { Log.e(TAG, "Failed to parse rfid message; " + e.getMessage()); return; } Intent intent = new Intent(); intent.setAction(RFID_INTENT); intent.putExtra("index", rfidId); intent.putExtra("rfid", rfid); sendBroadcast(intent); } else if (str.startsWith("num_doors:")) { int numDoors; try { numDoors = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_doors; " + e.getMessage()); return; } // TODO: Save number of doors } else if (str.startsWith("num_rfids:")) { int numRfids; try { numRfids = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_rfids; " + e.getMessage()); return; } // TODO: Save number of RFID scanners } else if (str.startsWith("num_lamps:")) { int numLamps; try { numLamps = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_lamps; " + e.getMessage()); return; } // TODO: Save number of lamps } } protected void handleCompletedBuffer() { if (buffer == null || buffer.isEmpty()) { Log.e(TAG, "Can't handle empty message buffer."); return; } int size = buffer.size() - 1; byte[] bufArr = new byte[size]; byte check = 0; for (int i = 0; i < size; i++) { bufArr[i] = buffer.get(i); check = (byte) (check ^ bufArr[i]); } // Verify checksum of data if (check != buffer.get(size)) { String failedString; try { failedString = new String(bufArr, "UTF-8"); } catch (UnsupportedEncodingException e) { failedString = "<failed to decode UTF-8>"; } Log.e(TAG, "Checksum mismatch! Sending poll request. (String: \"" + failedString + "\", Expected: " + buffer.get(size) + ", Computed: " + check); sendMessage("poll"); return; } try { handleReceivedString(new String(bufArr, "UTF-8")); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Failed to read arduino string."); } } public void onRead(byte[] data) { for (int i = 0; i < data.length; i++) { byte b = data[i]; if (b == 0x02) { buffer.clear(); readingMessage = true; } else if (b == 0x03) { if (!readingMessage) { continue; } handleCompletedBuffer(); readingMessage = false; } else { buffer.add(b); } } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onCreate() { connect(); } @Override public void onDestroy() { Log.i(TAG, "The arduino service was destroyed."); disconnect(); } private void sendMessage(String str) { if (!connected) { Log.w(TAG, "Tried to send message to Arduino but no connection found. (\"" + str + "\")"); return; } Log.i(TAG, "Sending: \"" + str + "\""); str += "\n"; byte[] buf = str.getBytes(); try { port.write(buf, buf.length); } catch (IOException e) { Log.e(TAG, "Failed to write message to Arduino: " + e.getMessage()); } } private void sendInitialPackets() { for (int i = 0; i < lampStatus.length; i++) { sendLamp(i); } sendMessage("poll"); } private void setLamp(int lampId, boolean on) { if (lampStatus[lampId] != on) { lampStatus[lampId] = on; sendLamp(lampId); } } private void sendLamp(int lampId) { sendMessage("lamp[" + lampId + "]: " + (lampStatus[lampId] ? "on" : "off")); } private void disconnect() { if (serialIoManager != null) { serialIoManager.stop(); serialIoManager = null; } if (port != null) { try { port.close(); } catch (IOException e) { // nothing } port = null; } connected = false; Intent intent = new Intent(); intent.setAction(DISCONNECTED_INTENT); sendBroadcast(intent); } public void connect() { if (connected) { return; } UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers( manager); if (availableDrivers.isEmpty()) { Log.w(TAG, "No available USB drivers found."); return; } UsbSerialDriver driver = availableDrivers.get(0); UsbDeviceConnection conn = manager.openDevice(driver.getDevice()); if (conn == null) { Log.e(TAG, "Failed to open USB connection. Possible permissions issue."); return; } List<UsbSerialPort> ports = driver.getPorts(); if (ports.isEmpty()) { Log.e(TAG, "USB driver has no ports."); conn.close(); return; } port = ports.get(0); try { port.open(conn); port.setParameters( 9600, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); } catch (IOException e) { Log.e(TAG, "IOException when opening port with connection: " + e.getMessage()); try { port.close(); } catch (IOException e2) { // nothing } port = null; return; } Log.i(TAG, "Opened connection with serial device: " + port.getClass().getSimpleName()); serialIoManager = new SerialInputOutputManager(port, listener); executorService.submit(serialIoManager); connected = true; // after 2 seconds, send initial messages to arduino. new Timer().schedule(new TimerTask() { @Override public void run() { sendInitialPackets(); Intent intent = new Intent(); intent.setAction(CONNECTED_INTENT); sendBroadcast(intent); } }, 3000); } }
Android/app/src/main/java/net/drewgottlieb/soapy/ArduinoService.java
package net.drewgottlieb.soapy; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.os.Binder; import android.os.IBinder; import android.util.Log; import com.hoho.android.usbserial.driver.UsbSerialDriver; import com.hoho.android.usbserial.driver.UsbSerialPort; import com.hoho.android.usbserial.driver.UsbSerialProber; import com.hoho.android.usbserial.util.SerialInputOutputManager; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MessageIndexFormatException extends Exception { public MessageIndexFormatException(String msg) { super("Invalid message format. No index found in \"" + msg + "\"."); } } class MessageValueFormatException extends Exception { public MessageValueFormatException(String msg) { super("Invalid message format. No value found in \"" + msg + "\"."); } } public class ArduinoService extends Service { public static final String RFID_INTENT = "new.drewgottlieb.RFID_INTENT"; public static final String DOOR_INTENT = "new.drewgottlieb.DOOR_INTENT"; public static final String CONNECTED_INTENT = "new.drewgottlieb.CONNECTED_INTENT"; public static final String DISCONNECTED_INTENT = "new.drewgottlieb.DISCONNECTED_INTENT"; private static String TAG = "ArduinoService"; public class ArduinoBinder extends Binder { ArduinoService getService() { return ArduinoService.this; } } private boolean connected = false; private final ArduinoBinder mBinder = new ArduinoBinder(); private List<Byte> buffer = new ArrayList<>(); private boolean readingMessage = false; private boolean[] lampStatus = new boolean[2]; private UsbSerialPort port; private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private SerialInputOutputManager serialIoManager; private final SerialInputOutputManager.Listener listener = new SerialInputOutputManager.Listener() { @Override public void onNewData(byte[] bytes) { onRead(bytes); } @Override public void onRunError(Exception e) { Log.w(TAG, "Arduino disconnected. Serial listener stopped due to error: " + e.getMessage()); disconnect(); } }; public ArduinoService() { } private static int getMessageIndex(String msg) throws MessageIndexFormatException { int startIdx = msg.indexOf('['); if (startIdx < 0) { throw new MessageIndexFormatException(msg); } int endIdx = msg.indexOf(']', startIdx); if (endIdx < 0) { throw new MessageIndexFormatException(msg); } try { return Integer.parseInt(msg.substring(startIdx + 1, endIdx)); } catch (NumberFormatException e) { throw new MessageIndexFormatException(msg); } } private static String getMessageValue(String msg) throws MessageValueFormatException { int idx = msg.indexOf(": "); if (idx < 0 || msg.length() < idx + 3) { throw new MessageValueFormatException(msg); } return msg.substring(idx + 2); } private void handleReceivedString(String str) { Log.i(TAG, "Received: \"" + str + "\""); if (str.startsWith("door[")) { int doorId; boolean closed; try { doorId = getMessageIndex(str); closed = "closed".equals(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse door message; " + e.getMessage()); return; } setLamp(doorId, closed); Intent intent = new Intent(); intent.setAction(DOOR_INTENT); intent.putExtra("index", doorId); intent.putExtra("closed", closed); sendBroadcast(intent); } else if (str.startsWith("rfid[")) { int rfidId; String rfid; try { rfidId = getMessageIndex(str); rfid = getMessageValue(str); } catch (Exception e) { Log.e(TAG, "Failed to parse rfid message; " + e.getMessage()); return; } Intent intent = new Intent(); intent.setAction(RFID_INTENT); intent.putExtra("index", rfidId); intent.putExtra("rfid", rfid); sendBroadcast(intent); } else if (str.startsWith("num_doors:")) { int numDoors; try { numDoors = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_doors; " + e.getMessage()); return; } // TODO: Save number of doors } else if (str.startsWith("num_rfids:")) { int numRfids; try { numRfids = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_rfids; " + e.getMessage()); return; } // TODO: Save number of RFID scanners } else if (str.startsWith("num_lamps:")) { int numLamps; try { numLamps = Integer.parseInt(getMessageValue(str)); } catch (Exception e) { Log.e(TAG, "Failed to parse num_lamps; " + e.getMessage()); return; } // TODO: Save number of lamps } } protected void handleCompletedBuffer() { if (buffer == null || buffer.isEmpty()) { Log.e(TAG, "Can't handle empty message buffer."); return; } int size = buffer.size() - 1; byte[] bufArr = new byte[size]; byte check = 0; for (int i = 0; i < size; i++) { bufArr[i] = buffer.get(i); check = (byte) (check ^ bufArr[i]); } // Verify checksum of data if (check != buffer.get(size)) { String failedString; try { failedString = new String(bufArr, "UTF-8"); } catch (UnsupportedEncodingException e) { failedString = "<failed to decode UTF-8>"; } Log.e(TAG, "Checksum mismatch! Sending poll request. (String: \"" + failedString + "\", Expected: " + buffer.get(size) + ", Computed: " + check); sendMessage("poll"); return; } try { handleReceivedString(new String(bufArr, "UTF-8")); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Failed to read arduino string."); } } public void onRead(byte[] data) { for (int i = 0; i < data.length; i++) { byte b = data[i]; if (b == 0x02) { buffer.clear(); readingMessage = true; } else if (b == 0x03) { if (!readingMessage) { continue; } handleCompletedBuffer(); readingMessage = false; } else { buffer.add(b); } } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onCreate() { connect(); } @Override public void onDestroy() { Log.i(TAG, "The arduino service was destroyed."); disconnect(); } private void sendMessage(String str) { if (!connected) { Log.w(TAG, "Tried to send message to Arduino but no connection found. (\"" + str + "\")"); return; } Log.i(TAG, "Sending: \"" + str + "\""); str += "\n"; byte[] buf = str.getBytes(); try { port.write(buf, buf.length); } catch (IOException e) { Log.e(TAG, "Failed to write message to Arduino: " + e.getMessage()); } } private void sendInitialPackets() { for (int i = 0; i < lampStatus.length; i++) { sendLamp(i); } sendMessage("poll"); } private void setLamp(int lampId, boolean on) { if (lampStatus[lampId] != on) { lampStatus[lampId] = on; sendLamp(lampId); } } private void sendLamp(int lampId) { sendMessage("lamp[" + lampId + "]: " + (lampStatus[lampId] ? "on" : "off")); } private void disconnect() { if (serialIoManager != null) { serialIoManager.stop(); serialIoManager = null; } if (port != null) { try { port.close(); } catch (IOException e) { // nothing } port = null; } connected = false; Intent intent = new Intent(); intent.setAction(DISCONNECTED_INTENT); sendBroadcast(intent); } public void connect() { if (connected) { return; } UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers( manager); if (availableDrivers.isEmpty()) { Log.w(TAG, "No available USB drivers found."); return; } UsbSerialDriver driver = availableDrivers.get(0); UsbDeviceConnection conn = manager.openDevice(driver.getDevice()); if (conn == null) { Log.e(TAG, "Failed to open USB connection. Possible permissions issue."); return; } List<UsbSerialPort> ports = driver.getPorts(); if (ports.isEmpty()) { Log.e(TAG, "USB driver has no ports."); conn.close(); return; } port = ports.get(0); try { port.open(conn); port.setParameters( 9600, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); } catch (IOException e) { Log.e(TAG, "IOException when opening port with connection: " + e.getMessage()); try { port.close(); } catch (IOException e2) { // nothing } port = null; return; } Log.i(TAG, "Opened connection with serial device: " + port.getClass().getSimpleName()); serialIoManager = new SerialInputOutputManager(port, listener); executorService.submit(serialIoManager); connected = true; // after 2 seconds, send initial messages to arduino. new Timer().schedule(new TimerTask() { @Override public void run() { sendInitialPackets(); Intent intent = new Intent(); intent.setAction(CONNECTED_INTENT); sendBroadcast(intent); } }, 2000); } }
Android: Send initial poll to arduino after 3 seconds instead of 2.
Android/app/src/main/java/net/drewgottlieb/soapy/ArduinoService.java
Android: Send initial poll to arduino after 3 seconds instead of 2.
Java
mpl-2.0
666c22cd74114863dd83485b9b5bac81074e81d2
0
yonadev/yona-app-android,yonadev/yona-app-android,yonadev/yona-app-android,yonadev/yona-app-android
/* * Copyright (c) 2016 Stichting Yona Foundation * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * */ package nu.yona.app.api.manager.impl; import android.content.Context; import android.text.TextUtils; import android.util.Log; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import nu.yona.app.R; import nu.yona.app.YonaApplication; import nu.yona.app.api.db.DatabaseHelper; import nu.yona.app.api.manager.APIManager; import nu.yona.app.api.manager.ActivityManager; import nu.yona.app.api.manager.dao.ActivityTrackerDAO; import nu.yona.app.api.manager.network.ActivityNetworkImpl; import nu.yona.app.api.model.Activity; import nu.yona.app.api.model.ActivityCategories; import nu.yona.app.api.model.AppActivity; import nu.yona.app.api.model.Day; import nu.yona.app.api.model.DayActivities; import nu.yona.app.api.model.DayActivity; import nu.yona.app.api.model.Embedded; import nu.yona.app.api.model.EmbeddedYonaActivity; import nu.yona.app.api.model.ErrorMessage; import nu.yona.app.api.model.Href; import nu.yona.app.api.model.Message; import nu.yona.app.api.model.Properties; import nu.yona.app.api.model.TimeZoneSpread; import nu.yona.app.api.model.User; import nu.yona.app.api.model.WeekActivity; import nu.yona.app.api.model.WeekDayActivity; import nu.yona.app.api.model.YonaActivityCategories; import nu.yona.app.api.model.YonaBuddy; import nu.yona.app.api.model.YonaDayActivityOverview; import nu.yona.app.api.model.YonaGoal; import nu.yona.app.api.model.YonaMessage; import nu.yona.app.api.model.YonaWeekActivityOverview; import nu.yona.app.customview.graph.GraphUtils; import nu.yona.app.enums.ChartTypeEnum; import nu.yona.app.enums.GoalsEnum; import nu.yona.app.enums.WeekDayEnum; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.utils.AppConstant; import nu.yona.app.utils.AppUtils; import nu.yona.app.utils.DateUtility; /** * Created by kinnarvasa on 06/06/16. */ public class ActivityManagerImpl implements ActivityManager { private final ActivityNetworkImpl activityNetwork; private final ActivityTrackerDAO activityTrackerDAO; private final Context mContext; private final int maxSpreadTime = 15; private final SimpleDateFormat sdf = new SimpleDateFormat(AppConstant.YONA_DATE_FORMAT, Locale.getDefault()); /** * Instantiates a new Activity manager. * * @param context the context */ public ActivityManagerImpl(Context context) { activityNetwork = new ActivityNetworkImpl(); activityTrackerDAO = new ActivityTrackerDAO(DatabaseHelper.getInstance(context)); mContext = context; } @Override public void getDaysActivity(boolean loadMore, boolean isBuddyFlow, Href url, DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getDayActivityList() == null || embeddedYonaActivity.getDayActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getDayActivityList() != null && embeddedYonaActivity.getDayActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; //User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (url != null && !TextUtils.isEmpty(url.getHref())) { getDailyActivity(url.getHref(), isBuddyFlow, AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList()); } } private void getDetailOfEachSpread() { List<DayActivity> dayActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList(); for (final DayActivity dayActivity : dayActivities) { if (dayActivity.getTimeZoneSpread() == null || (dayActivity.getTimeZoneSpread() != null && dayActivity.getTimeZoneSpread().size() == 0) || dayActivity.getChartTypeEnum() == ChartTypeEnum.TIME_FRAME_CONTROL) { APIManager.getInstance().getActivityManager().getDayDetailActivity(dayActivity.getLinks().getYonaDayDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof DayActivity) { try { DayActivity resultActivity = generateTimeZoneSpread((DayActivity) result); List<DayActivity> dayActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList(); for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getYonaDayDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { dayActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList().set(i, updateLinks(dayActivityList.get(i), resultActivity)); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { } }); } } } private void getDetailOfEachWeekSpread() { List<WeekActivity> weekActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList(); for (final WeekActivity weekActivity : weekActivities) { if (weekActivity.getTimeZoneSpread() == null || (weekActivity.getTimeZoneSpread() != null && weekActivity.getTimeZoneSpread().size() == 0)) { APIManager.getInstance().getActivityManager().getWeeksDetailActivity(weekActivity.getLinks().getWeekDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof WeekActivity) { try { WeekActivity resultActivity = generateTimeZoneSpread((WeekActivity) result); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity() != null) { List<WeekActivity> weekActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList(); for (int i = 0; i < weekActivityList.size(); i++) { try { if (weekActivityList.get(i).getLinks().getWeekDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { weekActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); weekActivityList.set(i, updateLinks(weekActivityList.get(i), resultActivity)); weekActivityList.get(i).setTotalActivityDurationMinutes(resultActivity.getTotalActivityDurationMinutes()); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { //if error, we don't worry for now. } }); } } } @Override public void getDayDetailActivity(String url, final DataLoadListener listener) { try { if (!TextUtils.isEmpty(url)) { activityNetwork.getDayDetailActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), new DataLoadListener() { @Override public void onDataLoad(Object result) { updateDayActivity((DayActivity) result, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } @Override public void getWeeksActivity(boolean loadMore, boolean isBuddyFlow, Href href, DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getWeekActivityList() == null || embeddedYonaActivity.getWeekActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getWeekActivityList() != null && embeddedYonaActivity.getWeekActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; if (href != null && !TextUtils.isEmpty(href.getHref())) { getWeeksActivity(href.getHref(), isBuddyFlow, AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList()); } } @Override public void getWeeksDetailActivity(String url, final DataLoadListener listener) { activityNetwork.getWeeksDetailActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), new DataLoadListener() { @Override public void onDataLoad(Object result) { updateWeekActivity((WeekActivity) result, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } public void postActivityToDB(String applicationName, Date startDate, Date endDate) { try { activityTrackerDAO.saveActivities(getAppActivity(applicationName, startDate, endDate)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } private void postActivityOnServer(final AppActivity activity, final boolean fromDB) { User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getLinks() != null && user.getLinks().getYonaAppActivity() != null && !TextUtils.isEmpty(user.getLinks().getYonaAppActivity().getHref())) { activityNetwork.postAppActivity(user.getLinks().getYonaAppActivity().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), activity, new DataLoadListener() { @Override public void onDataLoad(Object result) { //on success nothing to do, as it is posted on server. if (fromDB) { activityTrackerDAO.clearActivities(); } } @Override public void onError(Object errorMessage) { //on failure, we need to store data in database to resend next time. if (!fromDB) { activityTrackerDAO.saveActivities(activity.getActivities()); } } }); } } public void postAllDBActivities() { List<Activity> activityList = activityTrackerDAO.getActivities(); if (activityList != null && activityList.size() > 0) { AppActivity appActivity = new AppActivity(); appActivity.setDeviceDateTime(DateUtility.getLongFormatDate(new Date())); appActivity.setActivities(activityList); postActivityOnServer(appActivity, true); } } public void getWithBuddyActivity(boolean loadMore, final DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getDayActivityList() == null || embeddedYonaActivity.getDayActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getDayActivityList() != null && embeddedYonaActivity.getDayActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getLinks() != null && user.getLinks().getYonaDailyActivityReports() != null && !TextUtils.isEmpty(user.getLinks().getYonaDailyActivityReports().getHref())) { getWithBuddyActivity(user.getLinks().getDailyActivityReportsWithBuddies().getHref(), AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList()); } } public void getComments(List<DayActivity> dayActivityList, int position, final DataLoadListener listener) { int pageNo = 0; DayActivity dayActivity = dayActivityList.get(position); if (dayActivity != null) { if (dayActivity.getComments() != null && dayActivity.getComments().getPage() != null) { if (dayActivity.getComments().getPage().getNumber() + 1 == dayActivity.getComments().getPage().getTotalPages()) { listener.onDataLoad(dayActivityList); } else { pageNo = dayActivity.getComments().getPage().getNumber() + 1; getCommentsFromServer(dayActivityList, dayActivity, pageNo, listener); } } else { getCommentsFromServer(dayActivityList, dayActivity, pageNo, listener); } } } public void getCommentsForWeek(List<WeekActivity> weekActivityList, int position, final DataLoadListener listener) { int pageNo = 0; WeekActivity weekActivity = weekActivityList.get(position); if (weekActivity != null) { if (weekActivity.getComments() != null && weekActivity.getComments().getPage() != null) { if (weekActivity.getComments().getPage().getNumber() + 1 == weekActivity.getComments().getPage().getTotalPages()) { listener.onDataLoad(weekActivityList); } else if (weekActivity.getComments().getEmbedded() != null) { pageNo = weekActivity.getComments().getPage().getNumber() + 1; getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } else { getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } } else { getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } } } @Override public void addComment(DayActivity dayActivity, String comment, DataLoadListener listener) { Message message = new Message(); message.setMessage(comment); if (dayActivity != null && dayActivity.getLinks() != null) { if (dayActivity.getLinks().getAddComment() != null) { doAddComment(dayActivity.getLinks().getAddComment().getHref(), message, listener); } else if (dayActivity.getLinks().getReplyComment() != null) { Properties properties = new Properties(); properties.setMessage(message); reply(dayActivity.getLinks().getReplyComment().getHref(), properties, listener); } } } @Override public void addComment(WeekActivity weekActivity, String comment, DataLoadListener listener) { Message message = new Message(); message.setMessage(comment); if (weekActivity != null && weekActivity.getLinks() != null) { if (weekActivity.getLinks().getAddComment() != null) { doAddComment(weekActivity.getLinks().getAddComment().getHref(), message, listener); } else if (weekActivity.getLinks().getReplyComment() != null) { Properties properties = new Properties(); properties.setMessage(message); reply(weekActivity.getLinks().getReplyComment().getHref(), properties, listener); } } } private void reply(String url, Properties properties, final DataLoadListener listener) { activityNetwork.replyComment(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), properties, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof YonaMessage) { listener.onDataLoad(result); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } private void doAddComment(String url, Message message, final DataLoadListener listener) { activityNetwork.addComment(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), message, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof YonaMessage) { listener.onDataLoad(result); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } private void getCommentsFromServerForWeek(final List<WeekActivity> weekActivityList, final WeekActivity weekActivity, int pageNo, final DataLoadListener listener) { if (weekActivity.getLinks() != null && weekActivity.getLinks().getYonaMessages() != null && !TextUtils.isEmpty(weekActivity.getLinks().getYonaMessages().getHref())) { activityNetwork.getComments(weekActivity.getLinks().getYonaMessages().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), pageNo, AppConstant.PAGE_SIZE, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { EmbeddedYonaActivity embeddedYonaActivity = (EmbeddedYonaActivity) result; if (weekActivity.getComments() == null) { weekActivity.setComments(embeddedYonaActivity); } else { if (embeddedYonaActivity.getEmbedded() != null && embeddedYonaActivity.getEmbedded().getYonaMessages() != null) { weekActivity.getComments().getEmbedded().getYonaMessages().addAll(embeddedYonaActivity.getEmbedded().getYonaMessages()); weekActivity.getComments().setPage(embeddedYonaActivity.getEmbedded().getPage()); } } updateWeekActivityList(weekActivityList, weekActivity, listener); } else { listener.onError(new ErrorMessage(YonaApplication.getAppContext().getString(R.string.no_data_found))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } } private void getCommentsFromServer(final List<DayActivity> dayActivityList, final DayActivity dayActivity, int pageNo, final DataLoadListener listener) { if (dayActivity.getLinks() != null && dayActivity.getLinks().getYonaMessages() != null && !TextUtils.isEmpty(dayActivity.getLinks().getYonaMessages().getHref())) { activityNetwork.getComments(dayActivity.getLinks().getYonaMessages().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), pageNo, AppConstant.PAGE_SIZE, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { EmbeddedYonaActivity embeddedYonaActivity = (EmbeddedYonaActivity) result; if (dayActivity.getComments() == null) { dayActivity.setComments(embeddedYonaActivity); } else { if (dayActivity != null && dayActivity.getComments() != null && dayActivity.getComments().getEmbedded() != null && dayActivity.getComments().getEmbedded().getYonaMessages() != null && embeddedYonaActivity.getEmbedded() != null && embeddedYonaActivity.getEmbedded().getYonaMessages() != null) { dayActivity.getComments().getEmbedded().getYonaMessages().addAll(embeddedYonaActivity.getEmbedded().getYonaMessages()); dayActivity.getComments().setPage(embeddedYonaActivity.getEmbedded().getPage()); } } updateDayActivityList(dayActivityList, dayActivity, listener); } else { listener.onError(new ErrorMessage(YonaApplication.getAppContext().getString(R.string.no_data_found))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } } private void updateWeekActivityList(List<WeekActivity> weekActivityList, WeekActivity weekActivity, DataLoadListener listener) { if (weekActivityList != null) { for (int i = 0; i < weekActivityList.size(); i++) { try { if (weekActivityList.get(i).getLinks().getSelf().getHref().equals(weekActivity.getLinks().getSelf().getHref())) { weekActivityList.set(i, weekActivity); listener.onDataLoad(weekActivityList); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } } } private void updateDayActivityList(List<DayActivity> dayActivityList, DayActivity dayActivity, DataLoadListener listener) { for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getSelf().getHref().equals(dayActivity.getLinks().getSelf().getHref())) { dayActivityList.set(i, dayActivity); listener.onDataLoad(dayActivityList); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } } private Activity getAppActivity(String applicationName, Date startDate, Date endDate) { Activity activity = new Activity(); activity.setApplication(applicationName); activity.setStartTime(DateUtility.getLongFormatDate(startDate)); activity.setEndTime(DateUtility.getLongFormatDate(endDate)); return activity; } private void getWeeksActivity(String url, final boolean isbuddyFlow, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { if (!TextUtils.isEmpty(url)) { activityNetwork.getWeeksActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { filterAndUpdateWeekData((EmbeddedYonaActivity) result, isbuddyFlow, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } private void getDailyActivity(String url, final boolean isbuddyFlow, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { activityNetwork.getDaysActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { filterAndUpdateDailyData((EmbeddedYonaActivity) result, isbuddyFlow, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.dataparseerror))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } private void filterAndUpdateWeekData(EmbeddedYonaActivity embeddedYonaActivity, boolean isbuddyFlow, DataLoadListener listener) { List<WeekActivity> weekActivities = new ArrayList<>(); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedWeekActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaWeekActivityOverview> yonaDayActivityOverviews = embedded.getYonaWeekActivityOverviews(); List<WeekActivity> thisWeekActivities; for (YonaWeekActivityOverview overview : yonaDayActivityOverviews) { thisWeekActivities = new ArrayList<>(); List<WeekActivity> overviewWeekActivities = overview.getWeekActivities(); for (WeekActivity activity : overviewWeekActivities) { YonaGoal goal = getYonaGoal(isbuddyFlow, activity.getLinks().getYonaGoal()); if (goal != null) { activity.setYonaGoal(goal); if (activity.getYonaGoal() != null) { activity.setChartTypeEnum(ChartTypeEnum.WEEK_SCORE_CONTROL); } try { activity.setStickyTitle(DateUtility.getRetriveWeek(overview.getDate())); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } activity.setDate(overview.getDate()); activity = getWeekDayActivity(activity); thisWeekActivities.add(activity); } } weekActivities.addAll(sortWeekActivity(thisWeekActivities)); } if (embeddedYonaActivity.getWeekActivityList() == null) { embeddedYonaActivity.setWeekActivityList(weekActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList().addAll(weekActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().setPage(embeddedYonaActivity.getPage()); } getDetailOfEachWeekSpread(); listener.onDataLoad(embeddedYonaActivity); } } private void updateWeekActivity(WeekActivity weekActivity, DataLoadListener listener) { YonaGoal currentYonaGoal = findYonaGoal(weekActivity.getLinks().getYonaGoal()) != null ? findYonaGoal(weekActivity.getLinks().getYonaGoal()) : findYonaBuddyGoal(weekActivity.getLinks().getYonaGoal()); if (currentYonaGoal != null) { weekActivity.setYonaGoal(currentYonaGoal); if (weekActivity.getYonaGoal() != null) { weekActivity.setChartTypeEnum(ChartTypeEnum.WEEK_SCORE_CONTROL); } try { weekActivity.setStickyTitle(DateUtility.getRetriveWeek(weekActivity.getDate())); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } weekActivity.setDate(weekActivity.getDate()); weekActivity = getWeekDayActivity(weekActivity); } WeekActivity resultActivity = generateTimeZoneSpread(weekActivity); try { if (weekActivity != null && weekActivity.getLinks() != null && weekActivity.getLinks().getWeekDetails() != null && !TextUtils.isEmpty(weekActivity.getLinks().getWeekDetails().getHref()) && resultActivity != null && resultActivity.getLinks() != null && resultActivity.getLinks().getSelf() != null && !TextUtils.isEmpty(resultActivity.getLinks().getSelf().getHref()) && weekActivity.getLinks().getWeekDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { weekActivity.setTimeZoneSpread(resultActivity.getTimeZoneSpread()); weekActivity.setTotalActivityDurationMinutes(resultActivity.getTotalActivityDurationMinutes()); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } if (listener != null) { listener.onDataLoad(weekActivity); } } private WeekActivity getWeekDayActivity(WeekActivity activity) { List<WeekDayActivity> mWeekDayActivityList = new ArrayList<>(); Iterator calDates = DateUtility.getWeekDay(activity.getDate()).entrySet().iterator(); int i = 0; boolean isCurrentDateReached = false; int mAccomplishedGoalCount = 0; WeekDayEnum weekDayEnum = null; int color = GraphUtils.COLOR_WHITE_THREE; while (calDates.hasNext()) { Map.Entry pair = (Map.Entry) calDates.next(); Calendar calendar = Calendar.getInstance(); DayActivities dayActivity = activity.getDayActivities(); WeekDayActivity weekDayActivity = new WeekDayActivity(); switch (i) { case 0: weekDayEnum = WeekDayEnum.SUNDAY; color = getColor(dayActivity.getSUNDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getSUNDAY()); break; case 1: weekDayEnum = WeekDayEnum.MONDAY; color = getColor(dayActivity.getMONDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getMONDAY()); break; case 2: weekDayEnum = WeekDayEnum.TUESDAY; color = getColor(dayActivity.getTUESDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getTUESDAY()); break; case 3: weekDayEnum = WeekDayEnum.WEDNESDAY; color = getColor(dayActivity.getWEDNESDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getWEDNESDAY()); break; case 4: weekDayEnum = WeekDayEnum.THURSDAY; color = getColor(dayActivity.getTHURSDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getTHURSDAY()); break; case 5: weekDayEnum = WeekDayEnum.FRIDAY; color = getColor(dayActivity.getFRIDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getFRIDAY()); break; case 6: weekDayEnum = WeekDayEnum.SATURDAY; color = getColor(dayActivity.getSATURDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getSATURDAY()); break; default: break; } if (activity.getLinks() != null && activity.getLinks().getYonaDayDetails() != null && !TextUtils.isEmpty(activity.getLinks().getYonaDayDetails().getHref())) { weekDayActivity.setUrl(activity.getLinks().getYonaDayDetails().getHref()); } weekDayActivity.setWeekDayEnum(weekDayEnum); weekDayActivity.setColor(color); weekDayActivity.setDay(pair.getKey().toString()); weekDayActivity.setDate(pair.getValue().toString()); if (!isCurrentDateReached) { isCurrentDateReached = DateUtility.DAY_NO_FORMAT.format(calendar.getTime()).equals(pair.getValue().toString()); } i++; mWeekDayActivityList.add(weekDayActivity); } activity.setWeekDayActivity(mWeekDayActivityList); activity.setTotalAccomplishedGoal(mAccomplishedGoalCount); return activity; } /** * Get the Accomplished number on base on day he has achieved or not * * @param day * @return */ private int getGoalAccomplished(Day day) { return (day != null && day.getGoalAccomplished()) ? 1 : 0; } /** * Get the color of week Circle , * if goal has achieved then its Green, * if goal not achieved then its Pink, * else if its future date or not added that goal before date of created then its Grey * * @param day * @return */ private int getColor(Day day) { if (day != null) { if (day.getGoalAccomplished()) { return GraphUtils.COLOR_GREEN; } else { return GraphUtils.COLOR_PINK; } } return GraphUtils.COLOR_WHITE_THREE; } private void filterAndUpdateDailyData(EmbeddedYonaActivity embeddedYonaActivity, boolean isBuddyFlow, DataLoadListener listener) { List<DayActivity> dayActivities = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat(AppConstant.YONA_DATE_FORMAT, Locale.getDefault()); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedDayActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaDayActivityOverview> yonaDayActivityOverviews = embedded.getYonaDayActivityOverviews(); for (YonaDayActivityOverview overview : yonaDayActivityOverviews) { List<DayActivity> overviewDayActivities = overview.getDayActivities(); List<DayActivity> updatedOverviewDayActivities = new ArrayList<>(); for (DayActivity activity : overviewDayActivities) { activity.setYonaGoal(getYonaGoal(isBuddyFlow, activity.getLinks().getYonaGoal())); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = overview.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); Log.e(NotificationManagerImpl.class.getName(), "DateFormat " + e); } if (activity.getYonaGoal() != null && activity.getYonaGoal() != null && !activity.getYonaGoal().isHistoryItem()) { updatedOverviewDayActivities.add(generateTimeZoneSpread(activity)); } } dayActivities.addAll(sortDayActivity(updatedOverviewDayActivities)); } if (embeddedYonaActivity.getDayActivityList() == null) { embeddedYonaActivity.setDayActivityList(dayActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList().addAll(dayActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().setPage(embeddedYonaActivity.getPage()); } getDetailOfEachSpread(); listener.onDataLoad(embeddedYonaActivity); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.no_data_found))); } } private List<DayActivity> sortDayActivity(List<DayActivity> overviewDayActiivties) { Collections.sort(overviewDayActiivties, new Comparator<DayActivity>() { public int compare(DayActivity o1, DayActivity o2) { if (!TextUtils.isEmpty(o1.getYonaGoal().getActivityCategoryName()) && !TextUtils.isEmpty(o2.getYonaGoal().getActivityCategoryName())) { return o1.getYonaGoal().getActivityCategoryName().compareTo(o2.getYonaGoal().getActivityCategoryName()); } return 0; } }); return overviewDayActiivties; } private List<WeekActivity> sortWeekActivity(List<WeekActivity> overviewDayActiivties) { Collections.sort(overviewDayActiivties, new Comparator<WeekActivity>() { public int compare(WeekActivity o1, WeekActivity o2) { if (!TextUtils.isEmpty(o1.getYonaGoal().getActivityCategoryName()) && !TextUtils.isEmpty(o2.getYonaGoal().getActivityCategoryName())) { return o1.getYonaGoal().getActivityCategoryName().compareTo(o2.getYonaGoal().getActivityCategoryName()); } return 0; } }); return overviewDayActiivties; } private YonaGoal getYonaGoal(boolean isBuddyFlow, Href url) { if (!isBuddyFlow) { return findYonaGoal(url); } else { return findYonaBuddyGoal(url); } } private YonaGoal findYonaGoal(Href goalHref) { if (YonaApplication.getEventChangeManager().getDataState().getUser() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded().getYonaGoals() != null) { List<YonaGoal> yonaGoals = YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded().getYonaGoals(); for (YonaGoal goal : yonaGoals) { if (goal.getLinks().getSelf().getHref().equals(goalHref.getHref())) { goal.setActivityCategoryName(getActivityCategory(goal)); goal.setNickName(YonaApplication.getEventChangeManager().getDataState().getUser().getNickname()); return goal; } } } return null; } public YonaBuddy findYonaBuddy(Href yonaBuddy) { User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getEmbedded() != null && user.getEmbedded().getYonaBuddies() != null && user.getEmbedded().getYonaBuddies().getEmbedded() != null && user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies() != null) { List<YonaBuddy> yonaBuddies = user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies(); for (YonaBuddy buddy : yonaBuddies) { if (buddy != null && buddy.getLinks() != null && buddy.getLinks().getSelf() != null && buddy.getLinks().getSelf().getHref().equals(yonaBuddy.getHref())) { return buddy; } } } return null; } private YonaGoal findYonaBuddyGoal(Href goalHref) { User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getEmbedded() != null && user.getEmbedded().getYonaBuddies() != null && user.getEmbedded().getYonaBuddies().getEmbedded() != null && user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies() != null) { List<YonaBuddy> yonaBuddies = user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies(); for (YonaBuddy buddy : yonaBuddies) { if (buddy != null && buddy.getEmbedded() != null && buddy.getEmbedded().getYonaGoals() != null && buddy.getEmbedded().getYonaGoals().getEmbedded() != null && buddy.getEmbedded().getYonaGoals().getEmbedded().getYonaGoals() != null) { List<YonaGoal> yonaGoals = buddy.getEmbedded().getYonaGoals().getEmbedded().getYonaGoals(); for (YonaGoal goal : yonaGoals) { if (goal.getLinks().getSelf().getHref().equals(goalHref.getHref())) { goal.setActivityCategoryName(getActivityCategory(goal)); goal.setNickName(buddy.getNickname()); return goal; } } } } } return null; } private String getActivityCategory(YonaGoal goal) { ActivityCategories categories = APIManager.getInstance().getActivityCategoryManager().getListOfActivityCategories(); if (categories != null) { List<YonaActivityCategories> categoriesList = categories.getEmbeddedActivityCategories().getYonaActivityCategories(); for (YonaActivityCategories yonaActivityCategories : categoriesList) { if (yonaActivityCategories.get_links().getSelf().getHref().equals(goal.getLinks().getYonaActivityCategory().getHref())) { return yonaActivityCategories.getName(); } } } return null; } private DayActivity generateTimeZoneSpread(DayActivity activity) { if (activity.getSpread() != null) { List<Integer> spreadsList = activity.getSpread(); List<Integer> spreadCellsList; boolean isBudgetGoal = false; if (activity.getYonaGoal() != null && activity.getYonaGoal().getSpreadCells() != null) { isBudgetGoal = activity.getYonaGoal().getType().equals(GoalsEnum.BUDGET_GOAL.getActionString()) && activity.getYonaGoal().getMaxDurationMinutes() != 0; spreadCellsList = activity.getYonaGoal().getSpreadCells(); } else { spreadCellsList = new ArrayList<>(); } List<TimeZoneSpread> timeZoneSpreadList = new ArrayList<>(); for (int i = 0; i < spreadsList.size(); i++) { setTimeZoneSpread(i, spreadsList.get(i), timeZoneSpreadList, spreadCellsList.contains(i) || isBudgetGoal); } activity.setTimeZoneSpread(timeZoneSpreadList); } return activity; } private void setTimeZoneSpread(int index, int spreadListValue, List<TimeZoneSpread> timeZoneSpreadList, boolean allowed) { TimeZoneSpread timeZoneSpread = new TimeZoneSpread(); timeZoneSpread.setIndex(index); timeZoneSpread.setAllowed(allowed); if (spreadListValue > 0) { if (allowed) { timeZoneSpread.setColor(GraphUtils.COLOR_BLUE); } else { timeZoneSpread.setColor(GraphUtils.COLOR_PINK); } timeZoneSpread.setUsedValue(spreadListValue); // ex. set 10 min as blue used during allowed time. timeZoneSpreadList.add(timeZoneSpread); //Now create remaining time's other object: if (spreadListValue < maxSpreadTime) { TimeZoneSpread secondSpread = new TimeZoneSpread(); secondSpread.setIndex(index); secondSpread.setAllowed(allowed); timeZoneSpreadList.add(addToArray(allowed, secondSpread, maxSpreadTime - spreadListValue)); } } else { timeZoneSpreadList.add(addToArray(allowed, timeZoneSpread, maxSpreadTime - spreadListValue)); } } private TimeZoneSpread addToArray(boolean allowed, TimeZoneSpread timeZoneSpread, int usage) { if (allowed) { timeZoneSpread.setColor(GraphUtils.COLOR_GREEN); } else { timeZoneSpread.setColor(GraphUtils.COLOR_WHITE_THREE); } timeZoneSpread.setUsedValue(usage); // out of 15 mins, if 10 min used, so here we need to show 5 min as green return timeZoneSpread; } private WeekActivity generateTimeZoneSpread(WeekActivity activity) { if (activity.getSpread() != null) { List<Integer> spreadsList = activity.getSpread(); List<Integer> spreadCellsList; if (activity.getYonaGoal() != null && activity.getYonaGoal().getSpreadCells() != null) { spreadCellsList = activity.getYonaGoal().getSpreadCells(); } else { spreadCellsList = new ArrayList<>(); } List<TimeZoneSpread> timeZoneSpreadList = new ArrayList<>(); for (int i = 0; i < spreadsList.size(); i++) { setTimeZoneSpread(i, spreadsList.get(i), timeZoneSpreadList, spreadCellsList.contains(i)); } activity.setTimeZoneSpread(timeZoneSpreadList); } return activity; } private void getWithBuddyActivity(String url, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { activityNetwork.getWithBuddyActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { filterAndUpdateWithBuddyData((EmbeddedYonaActivity) result, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.dataparseerror))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } //TOD0 modify this method private void filterAndUpdateWithBuddyData(EmbeddedYonaActivity embeddedYonaActivity, DataLoadListener listener) { List<DayActivity> dayActivities = new ArrayList<>(); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedWithBuddyActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaDayActivityOverview> yonaDayActivityOverviews = embedded.getYonaDayActivityOverviews(); for (YonaDayActivityOverview overview : yonaDayActivityOverviews) { List<DayActivity> overviewDayActivities = overview.getDayActivities(); List<DayActivity> updatedOverviewDayActivities = new ArrayList<>(); for (DayActivity activities : overviewDayActivities) { if (activities != null && activities.getDayActivitiesForUsers() != null) { for (DayActivity activity : activities.getDayActivitiesForUsers()) { activity.setYonaGoal(getYonaGoal(activity.getLinks().getYonaUser() != null ? false : true, activity.getLinks().getYonaGoal())); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = overview.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } if (activity.getYonaGoal() != null && activity.getYonaGoal() != null && !activity.getYonaGoal().isHistoryItem()) { updatedOverviewDayActivities.add(generateTimeZoneSpread(activity)); } } } } dayActivities.addAll(sortDayActivity(updatedOverviewDayActivities)); } if (embeddedYonaActivity.getDayActivityList() == null) { embeddedYonaActivity.setDayActivityList(dayActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList().addAll(dayActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().setPage(embeddedYonaActivity.getPage()); } getBuddyDetailOfEachSpread(); listener.onDataLoad(embeddedYonaActivity); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.no_data_found))); } } private void updateDayActivity(DayActivity activity, DataLoadListener listener) { YonaGoal currentYonaGoal = findYonaGoal(activity.getLinks().getYonaGoal()) != null ? findYonaGoal(activity.getLinks().getYonaGoal()) : findYonaBuddyGoal(activity.getLinks().getYonaGoal()); activity.setYonaGoal(currentYonaGoal); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = activity.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { Log.e(NotificationManagerImpl.class.getName(), "DateFormat " + e); } listener.onDataLoad(generateTimeZoneSpread(activity)); } private void getBuddyDetailOfEachSpread() { final List<DayActivity> dayActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList(); for (final DayActivity dayActivity : dayActivities) { if (dayActivity.getTimeZoneSpread() == null || (dayActivity.getTimeZoneSpread() != null && dayActivity.getTimeZoneSpread().size() == 0)) { APIManager.getInstance().getActivityManager().getDayDetailActivity(dayActivity.getLinks().getYonaDayDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof DayActivity) { try { DayActivity resultActivity = generateTimeZoneSpread((DayActivity) result); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity() != null) { List<DayActivity> dayActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList(); if (dayActivityList != null) { for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getYonaDayDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { dayActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); dayActivityList.set(i, updateLinks(dayActivityList.get(i), resultActivity)); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { // we are not worry as of now here } }); } } } private DayActivity updateLinks(DayActivity actualActivity, DayActivity resultActivity) { if (resultActivity.getLinks() != null) { if (resultActivity.getLinks().getSelf() != null) { actualActivity.getLinks().setSelf(resultActivity.getLinks().getSelf()); } if (resultActivity.getLinks().getEdit() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getEdit()); } if (resultActivity.getLinks().getReplyComment() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getReplyComment()); } if (resultActivity.getLinks().getYonaMessages() != null) { actualActivity.getLinks().setYonaMessages(resultActivity.getLinks().getYonaMessages()); } if (resultActivity.getLinks().getYonaUser() != null) { actualActivity.getLinks().setYonaUser(resultActivity.getLinks().getYonaUser()); } if (resultActivity.getLinks().getYonaDayDetails() != null) { actualActivity.getLinks().setYonaDayDetails(resultActivity.getLinks().getYonaDayDetails()); } if (resultActivity.getLinks().getYonaBuddy() != null) { actualActivity.getLinks().setYonaBuddy(resultActivity.getLinks().getYonaBuddy()); } if (resultActivity.getLinks().getAddComment() != null) { actualActivity.getLinks().setAddComment(resultActivity.getLinks().getAddComment()); } } return actualActivity; } private WeekActivity updateLinks(WeekActivity actualActivity, WeekActivity resultActivity) { if (resultActivity.getLinks() != null) { if (resultActivity.getLinks().getSelf() != null) { actualActivity.getLinks().setSelf(resultActivity.getLinks().getSelf()); } if (resultActivity.getLinks().getEdit() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getEdit()); } if (resultActivity.getLinks().getReplyComment() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getReplyComment()); } if (resultActivity.getLinks().getYonaMessages() != null) { actualActivity.getLinks().setYonaMessages(resultActivity.getLinks().getYonaMessages()); } if (resultActivity.getLinks().getYonaUser() != null) { actualActivity.getLinks().setYonaUser(resultActivity.getLinks().getYonaUser()); } if (resultActivity.getLinks().getYonaDayDetails() != null) { actualActivity.getLinks().setYonaDayDetails(resultActivity.getLinks().getYonaDayDetails()); } if (resultActivity.getLinks().getYonaBuddy() != null) { actualActivity.getLinks().setYonaBuddy(resultActivity.getLinks().getYonaBuddy()); } if (resultActivity.getLinks().getAddComment() != null) { actualActivity.getLinks().setAddComment(resultActivity.getLinks().getAddComment()); } } return actualActivity; } }
app/src/main/java/nu/yona/app/api/manager/impl/ActivityManagerImpl.java
/* * Copyright (c) 2016 Stichting Yona Foundation * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * */ package nu.yona.app.api.manager.impl; import android.content.Context; import android.text.TextUtils; import android.util.Log; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import nu.yona.app.R; import nu.yona.app.YonaApplication; import nu.yona.app.api.db.DatabaseHelper; import nu.yona.app.api.manager.APIManager; import nu.yona.app.api.manager.ActivityManager; import nu.yona.app.api.manager.dao.ActivityTrackerDAO; import nu.yona.app.api.manager.network.ActivityNetworkImpl; import nu.yona.app.api.model.Activity; import nu.yona.app.api.model.ActivityCategories; import nu.yona.app.api.model.AppActivity; import nu.yona.app.api.model.Day; import nu.yona.app.api.model.DayActivities; import nu.yona.app.api.model.DayActivity; import nu.yona.app.api.model.Embedded; import nu.yona.app.api.model.EmbeddedYonaActivity; import nu.yona.app.api.model.ErrorMessage; import nu.yona.app.api.model.Href; import nu.yona.app.api.model.Message; import nu.yona.app.api.model.Properties; import nu.yona.app.api.model.TimeZoneSpread; import nu.yona.app.api.model.User; import nu.yona.app.api.model.WeekActivity; import nu.yona.app.api.model.WeekDayActivity; import nu.yona.app.api.model.YonaActivityCategories; import nu.yona.app.api.model.YonaBuddy; import nu.yona.app.api.model.YonaDayActivityOverview; import nu.yona.app.api.model.YonaGoal; import nu.yona.app.api.model.YonaMessage; import nu.yona.app.api.model.YonaWeekActivityOverview; import nu.yona.app.customview.graph.GraphUtils; import nu.yona.app.enums.ChartTypeEnum; import nu.yona.app.enums.GoalsEnum; import nu.yona.app.enums.WeekDayEnum; import nu.yona.app.listener.DataLoadListener; import nu.yona.app.utils.AppConstant; import nu.yona.app.utils.AppUtils; import nu.yona.app.utils.DateUtility; /** * Created by kinnarvasa on 06/06/16. */ public class ActivityManagerImpl implements ActivityManager { private final ActivityNetworkImpl activityNetwork; private final ActivityTrackerDAO activityTrackerDAO; private final Context mContext; private final int maxSpreadTime = 15; private final SimpleDateFormat sdf = new SimpleDateFormat(AppConstant.YONA_DATE_FORMAT, Locale.getDefault()); /** * Instantiates a new Activity manager. * * @param context the context */ public ActivityManagerImpl(Context context) { activityNetwork = new ActivityNetworkImpl(); activityTrackerDAO = new ActivityTrackerDAO(DatabaseHelper.getInstance(context)); mContext = context; } @Override public void getDaysActivity(boolean loadMore, boolean isBuddyFlow, Href url, DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getDayActivityList() == null || embeddedYonaActivity.getDayActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getDayActivityList() != null && embeddedYonaActivity.getDayActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; //User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (url != null && !TextUtils.isEmpty(url.getHref())) { getDailyActivity(url.getHref(), isBuddyFlow, AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList()); } } private void getDetailOfEachSpread() { List<DayActivity> dayActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList(); for (final DayActivity dayActivity : dayActivities) { if (dayActivity.getTimeZoneSpread() == null || (dayActivity.getTimeZoneSpread() != null && dayActivity.getTimeZoneSpread().size() == 0) || dayActivity.getChartTypeEnum() == ChartTypeEnum.TIME_FRAME_CONTROL) { APIManager.getInstance().getActivityManager().getDayDetailActivity(dayActivity.getLinks().getYonaDayDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof DayActivity) { try { DayActivity resultActivity = generateTimeZoneSpread((DayActivity) result); List<DayActivity> dayActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList(); for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getYonaDayDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { dayActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList().set(i, updateLinks(dayActivityList.get(i), resultActivity)); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { } }); } } } private void getDetailOfEachWeekSpread() { List<WeekActivity> weekActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList(); for (final WeekActivity weekActivity : weekActivities) { if (weekActivity.getTimeZoneSpread() == null || (weekActivity.getTimeZoneSpread() != null && weekActivity.getTimeZoneSpread().size() == 0)) { APIManager.getInstance().getActivityManager().getWeeksDetailActivity(weekActivity.getLinks().getWeekDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof WeekActivity) { try { WeekActivity resultActivity = generateTimeZoneSpread((WeekActivity) result); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity() != null) { List<WeekActivity> weekActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList(); for (int i = 0; i < weekActivityList.size(); i++) { try { if (weekActivityList.get(i).getLinks().getWeekDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { weekActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); weekActivityList.set(i, updateLinks(weekActivityList.get(i), resultActivity)); weekActivityList.get(i).setTotalActivityDurationMinutes(resultActivity.getTotalActivityDurationMinutes()); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { //if error, we don't worry for now. } }); } } } @Override public void getDayDetailActivity(String url, final DataLoadListener listener) { try { if (!TextUtils.isEmpty(url)) { activityNetwork.getDayDetailActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), new DataLoadListener() { @Override public void onDataLoad(Object result) { updateDayActivity((DayActivity) result, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } @Override public void getWeeksActivity(boolean loadMore, boolean isBuddyFlow, Href href, DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getWeekActivityList() == null || embeddedYonaActivity.getWeekActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getWeekActivityList() != null && embeddedYonaActivity.getWeekActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; if (href != null && !TextUtils.isEmpty(href.getHref())) { getWeeksActivity(href.getHref(), isBuddyFlow, AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList()); } } @Override public void getWeeksDetailActivity(String url, final DataLoadListener listener) { activityNetwork.getWeeksDetailActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), new DataLoadListener() { @Override public void onDataLoad(Object result) { updateWeekActivity((WeekActivity) result, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } public void postActivityToDB(String applicationName, Date startDate, Date endDate) { try { activityTrackerDAO.saveActivities(getAppActivity(applicationName, startDate, endDate)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } private void postActivityOnServer(final AppActivity activity, final boolean fromDB) { activityNetwork.postAppActivity(YonaApplication.getEventChangeManager().getDataState().getUser().getLinks().getYonaAppActivity().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), activity, new DataLoadListener() { @Override public void onDataLoad(Object result) { //on success nothing to do, as it is posted on server. if (fromDB) { activityTrackerDAO.clearActivities(); } } @Override public void onError(Object errorMessage) { //on failure, we need to store data in database to resend next time. if (!fromDB) { activityTrackerDAO.saveActivities(activity.getActivities()); } } }); } public void postAllDBActivities() { List<Activity> activityList = activityTrackerDAO.getActivities(); if (activityList != null && activityList.size() > 0) { AppActivity appActivity = new AppActivity(); appActivity.setDeviceDateTime(DateUtility.getLongFormatDate(new Date())); appActivity.setActivities(activityList); postActivityOnServer(appActivity, true); } } public void getWithBuddyActivity(boolean loadMore, final DataLoadListener listener) { EmbeddedYonaActivity embeddedYonaActivity = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity(); if (loadMore || embeddedYonaActivity == null || embeddedYonaActivity.getDayActivityList() == null || embeddedYonaActivity.getDayActivityList().size() == 0) { int pageNo = (embeddedYonaActivity != null && embeddedYonaActivity.getPage() != null && embeddedYonaActivity.getDayActivityList() != null && embeddedYonaActivity.getDayActivityList().size() > 0) ? embeddedYonaActivity.getPage().getNumber() + 1 : 0; User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getLinks() != null && user.getLinks().getYonaDailyActivityReports() != null && !TextUtils.isEmpty(user.getLinks().getYonaDailyActivityReports().getHref())) { getWithBuddyActivity(user.getLinks().getDailyActivityReportsWithBuddies().getHref(), AppConstant.PAGE_SIZE, pageNo, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } else { listener.onDataLoad(YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList()); } } public void getComments(List<DayActivity> dayActivityList, int position, final DataLoadListener listener) { int pageNo = 0; DayActivity dayActivity = dayActivityList.get(position); if (dayActivity != null) { if (dayActivity.getComments() != null && dayActivity.getComments().getPage() != null) { if (dayActivity.getComments().getPage().getNumber() + 1 == dayActivity.getComments().getPage().getTotalPages()) { listener.onDataLoad(dayActivityList); } else { pageNo = dayActivity.getComments().getPage().getNumber() + 1; getCommentsFromServer(dayActivityList, dayActivity, pageNo, listener); } } else { getCommentsFromServer(dayActivityList, dayActivity, pageNo, listener); } } } public void getCommentsForWeek(List<WeekActivity> weekActivityList, int position, final DataLoadListener listener) { int pageNo = 0; WeekActivity weekActivity = weekActivityList.get(position); if (weekActivity != null) { if (weekActivity.getComments() != null && weekActivity.getComments().getPage() != null) { if (weekActivity.getComments().getPage().getNumber() + 1 == weekActivity.getComments().getPage().getTotalPages()) { listener.onDataLoad(weekActivityList); } else if (weekActivity.getComments().getEmbedded() != null) { pageNo = weekActivity.getComments().getPage().getNumber() + 1; getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } else { getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } } else { getCommentsFromServerForWeek(weekActivityList, weekActivity, pageNo, listener); } } } @Override public void addComment(DayActivity dayActivity, String comment, DataLoadListener listener) { Message message = new Message(); message.setMessage(comment); if (dayActivity != null && dayActivity.getLinks() != null) { if (dayActivity.getLinks().getAddComment() != null) { doAddComment(dayActivity.getLinks().getAddComment().getHref(), message, listener); } else if (dayActivity.getLinks().getReplyComment() != null) { Properties properties = new Properties(); properties.setMessage(message); reply(dayActivity.getLinks().getReplyComment().getHref(), properties, listener); } } } @Override public void addComment(WeekActivity weekActivity, String comment, DataLoadListener listener) { Message message = new Message(); message.setMessage(comment); if (weekActivity != null && weekActivity.getLinks() != null) { if (weekActivity.getLinks().getAddComment() != null) { doAddComment(weekActivity.getLinks().getAddComment().getHref(), message, listener); } else if (weekActivity.getLinks().getReplyComment() != null) { Properties properties = new Properties(); properties.setMessage(message); reply(weekActivity.getLinks().getReplyComment().getHref(), properties, listener); } } } private void reply(String url, Properties properties, final DataLoadListener listener) { activityNetwork.replyComment(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), properties, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof YonaMessage) { listener.onDataLoad(result); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } private void doAddComment(String url, Message message, final DataLoadListener listener) { activityNetwork.addComment(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), message, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof YonaMessage) { listener.onDataLoad(result); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } private void getCommentsFromServerForWeek(final List<WeekActivity> weekActivityList, final WeekActivity weekActivity, int pageNo, final DataLoadListener listener) { if (weekActivity.getLinks() != null && weekActivity.getLinks().getYonaMessages() != null && !TextUtils.isEmpty(weekActivity.getLinks().getYonaMessages().getHref())) { activityNetwork.getComments(weekActivity.getLinks().getYonaMessages().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), pageNo, AppConstant.PAGE_SIZE, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { EmbeddedYonaActivity embeddedYonaActivity = (EmbeddedYonaActivity) result; if (weekActivity.getComments() == null) { weekActivity.setComments(embeddedYonaActivity); } else { if (embeddedYonaActivity.getEmbedded() != null && embeddedYonaActivity.getEmbedded().getYonaMessages() != null) { weekActivity.getComments().getEmbedded().getYonaMessages().addAll(embeddedYonaActivity.getEmbedded().getYonaMessages()); weekActivity.getComments().setPage(embeddedYonaActivity.getEmbedded().getPage()); } } updateWeekActivityList(weekActivityList, weekActivity, listener); } else { listener.onError(new ErrorMessage(YonaApplication.getAppContext().getString(R.string.no_data_found))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } } private void getCommentsFromServer(final List<DayActivity> dayActivityList, final DayActivity dayActivity, int pageNo, final DataLoadListener listener) { if (dayActivity.getLinks() != null && dayActivity.getLinks().getYonaMessages() != null && !TextUtils.isEmpty(dayActivity.getLinks().getYonaMessages().getHref())) { activityNetwork.getComments(dayActivity.getLinks().getYonaMessages().getHref(), YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), pageNo, AppConstant.PAGE_SIZE, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { EmbeddedYonaActivity embeddedYonaActivity = (EmbeddedYonaActivity) result; if (dayActivity.getComments() == null) { dayActivity.setComments(embeddedYonaActivity); } else { if (dayActivity != null && dayActivity.getComments() != null && dayActivity.getComments().getEmbedded() != null && dayActivity.getComments().getEmbedded().getYonaMessages() != null && embeddedYonaActivity.getEmbedded() != null && embeddedYonaActivity.getEmbedded().getYonaMessages() != null) { dayActivity.getComments().getEmbedded().getYonaMessages().addAll(embeddedYonaActivity.getEmbedded().getYonaMessages()); dayActivity.getComments().setPage(embeddedYonaActivity.getEmbedded().getPage()); } } updateDayActivityList(dayActivityList, dayActivity, listener); } else { listener.onError(new ErrorMessage(YonaApplication.getAppContext().getString(R.string.no_data_found))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } } private void updateWeekActivityList(List<WeekActivity> weekActivityList, WeekActivity weekActivity, DataLoadListener listener) { if (weekActivityList != null) { for (int i = 0; i < weekActivityList.size(); i++) { try { if (weekActivityList.get(i).getLinks().getSelf().getHref().equals(weekActivity.getLinks().getSelf().getHref())) { weekActivityList.set(i, weekActivity); listener.onDataLoad(weekActivityList); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } } } private void updateDayActivityList(List<DayActivity> dayActivityList, DayActivity dayActivity, DataLoadListener listener) { for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getSelf().getHref().equals(dayActivity.getLinks().getSelf().getHref())) { dayActivityList.set(i, dayActivity); listener.onDataLoad(dayActivityList); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } } private Activity getAppActivity(String applicationName, Date startDate, Date endDate) { Activity activity = new Activity(); activity.setApplication(applicationName); activity.setStartTime(DateUtility.getLongFormatDate(startDate)); activity.setEndTime(DateUtility.getLongFormatDate(endDate)); return activity; } private void getWeeksActivity(String url, final boolean isbuddyFlow, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { if (!TextUtils.isEmpty(url)) { activityNetwork.getWeeksActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { filterAndUpdateWeekData((EmbeddedYonaActivity) result, isbuddyFlow, listener); } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.urlnotfound))); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } private void getDailyActivity(String url, final boolean isbuddyFlow, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { activityNetwork.getDaysActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { filterAndUpdateDailyData((EmbeddedYonaActivity) result, isbuddyFlow, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.dataparseerror))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } private void filterAndUpdateWeekData(EmbeddedYonaActivity embeddedYonaActivity, boolean isbuddyFlow, DataLoadListener listener) { List<WeekActivity> weekActivities = new ArrayList<>(); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedWeekActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaWeekActivityOverview> yonaDayActivityOverviews = embedded.getYonaWeekActivityOverviews(); List<WeekActivity> thisWeekActivities; for (YonaWeekActivityOverview overview : yonaDayActivityOverviews) { thisWeekActivities = new ArrayList<>(); List<WeekActivity> overviewWeekActivities = overview.getWeekActivities(); for (WeekActivity activity : overviewWeekActivities) { YonaGoal goal = getYonaGoal(isbuddyFlow, activity.getLinks().getYonaGoal()); if (goal != null) { activity.setYonaGoal(goal); if (activity.getYonaGoal() != null) { activity.setChartTypeEnum(ChartTypeEnum.WEEK_SCORE_CONTROL); } try { activity.setStickyTitle(DateUtility.getRetriveWeek(overview.getDate())); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } activity.setDate(overview.getDate()); activity = getWeekDayActivity(activity); thisWeekActivities.add(activity); } } weekActivities.addAll(sortWeekActivity(thisWeekActivities)); } if (embeddedYonaActivity.getWeekActivityList() == null) { embeddedYonaActivity.setWeekActivityList(weekActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().getWeekActivityList().addAll(weekActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWeekActivity().setPage(embeddedYonaActivity.getPage()); } getDetailOfEachWeekSpread(); listener.onDataLoad(embeddedYonaActivity); } } private void updateWeekActivity(WeekActivity weekActivity, DataLoadListener listener) { YonaGoal currentYonaGoal = findYonaGoal(weekActivity.getLinks().getYonaGoal()) != null ? findYonaGoal(weekActivity.getLinks().getYonaGoal()) : findYonaBuddyGoal(weekActivity.getLinks().getYonaGoal()); if (currentYonaGoal != null) { weekActivity.setYonaGoal(currentYonaGoal); if (weekActivity.getYonaGoal() != null) { weekActivity.setChartTypeEnum(ChartTypeEnum.WEEK_SCORE_CONTROL); } try { weekActivity.setStickyTitle(DateUtility.getRetriveWeek(weekActivity.getDate())); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } weekActivity.setDate(weekActivity.getDate()); weekActivity = getWeekDayActivity(weekActivity); } WeekActivity resultActivity = generateTimeZoneSpread(weekActivity); try { if (weekActivity != null && weekActivity.getLinks() != null && weekActivity.getLinks().getWeekDetails() != null && !TextUtils.isEmpty(weekActivity.getLinks().getWeekDetails().getHref()) && resultActivity != null && resultActivity.getLinks() != null && resultActivity.getLinks().getSelf() != null && !TextUtils.isEmpty(resultActivity.getLinks().getSelf().getHref()) && weekActivity.getLinks().getWeekDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { weekActivity.setTimeZoneSpread(resultActivity.getTimeZoneSpread()); weekActivity.setTotalActivityDurationMinutes(resultActivity.getTotalActivityDurationMinutes()); } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } if (listener != null) { listener.onDataLoad(weekActivity); } } private WeekActivity getWeekDayActivity(WeekActivity activity) { List<WeekDayActivity> mWeekDayActivityList = new ArrayList<>(); Iterator calDates = DateUtility.getWeekDay(activity.getDate()).entrySet().iterator(); int i = 0; boolean isCurrentDateReached = false; int mAccomplishedGoalCount = 0; WeekDayEnum weekDayEnum = null; int color = GraphUtils.COLOR_WHITE_THREE; while (calDates.hasNext()) { Map.Entry pair = (Map.Entry) calDates.next(); Calendar calendar = Calendar.getInstance(); DayActivities dayActivity = activity.getDayActivities(); WeekDayActivity weekDayActivity = new WeekDayActivity(); switch (i) { case 0: weekDayEnum = WeekDayEnum.SUNDAY; color = getColor(dayActivity.getSUNDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getSUNDAY()); break; case 1: weekDayEnum = WeekDayEnum.MONDAY; color = getColor(dayActivity.getMONDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getMONDAY()); break; case 2: weekDayEnum = WeekDayEnum.TUESDAY; color = getColor(dayActivity.getTUESDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getTUESDAY()); break; case 3: weekDayEnum = WeekDayEnum.WEDNESDAY; color = getColor(dayActivity.getWEDNESDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getWEDNESDAY()); break; case 4: weekDayEnum = WeekDayEnum.THURSDAY; color = getColor(dayActivity.getTHURSDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getTHURSDAY()); break; case 5: weekDayEnum = WeekDayEnum.FRIDAY; color = getColor(dayActivity.getFRIDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getFRIDAY()); break; case 6: weekDayEnum = WeekDayEnum.SATURDAY; color = getColor(dayActivity.getSATURDAY()); mAccomplishedGoalCount = mAccomplishedGoalCount + getGoalAccomplished(dayActivity.getSATURDAY()); break; default: break; } if (activity.getLinks() != null && activity.getLinks().getYonaDayDetails() != null && !TextUtils.isEmpty(activity.getLinks().getYonaDayDetails().getHref())) { weekDayActivity.setUrl(activity.getLinks().getYonaDayDetails().getHref()); } weekDayActivity.setWeekDayEnum(weekDayEnum); weekDayActivity.setColor(color); weekDayActivity.setDay(pair.getKey().toString()); weekDayActivity.setDate(pair.getValue().toString()); if (!isCurrentDateReached) { isCurrentDateReached = DateUtility.DAY_NO_FORMAT.format(calendar.getTime()).equals(pair.getValue().toString()); } i++; mWeekDayActivityList.add(weekDayActivity); } activity.setWeekDayActivity(mWeekDayActivityList); activity.setTotalAccomplishedGoal(mAccomplishedGoalCount); return activity; } /** * Get the Accomplished number on base on day he has achieved or not * * @param day * @return */ private int getGoalAccomplished(Day day) { return (day != null && day.getGoalAccomplished()) ? 1 : 0; } /** * Get the color of week Circle , * if goal has achieved then its Green, * if goal not achieved then its Pink, * else if its future date or not added that goal before date of created then its Grey * * @param day * @return */ private int getColor(Day day) { if (day != null) { if (day.getGoalAccomplished()) { return GraphUtils.COLOR_GREEN; } else { return GraphUtils.COLOR_PINK; } } return GraphUtils.COLOR_WHITE_THREE; } private void filterAndUpdateDailyData(EmbeddedYonaActivity embeddedYonaActivity, boolean isBuddyFlow, DataLoadListener listener) { List<DayActivity> dayActivities = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat(AppConstant.YONA_DATE_FORMAT, Locale.getDefault()); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedDayActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaDayActivityOverview> yonaDayActivityOverviews = embedded.getYonaDayActivityOverviews(); for (YonaDayActivityOverview overview : yonaDayActivityOverviews) { List<DayActivity> overviewDayActivities = overview.getDayActivities(); List<DayActivity> updatedOverviewDayActivities = new ArrayList<>(); for (DayActivity activity : overviewDayActivities) { activity.setYonaGoal(getYonaGoal(isBuddyFlow, activity.getLinks().getYonaGoal())); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = overview.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); Log.e(NotificationManagerImpl.class.getName(), "DateFormat " + e); } if (activity.getYonaGoal() != null && activity.getYonaGoal() != null && !activity.getYonaGoal().isHistoryItem()) { updatedOverviewDayActivities.add(generateTimeZoneSpread(activity)); } } dayActivities.addAll(sortDayActivity(updatedOverviewDayActivities)); } if (embeddedYonaActivity.getDayActivityList() == null) { embeddedYonaActivity.setDayActivityList(dayActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().getDayActivityList().addAll(dayActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedDayActivity().setPage(embeddedYonaActivity.getPage()); } getDetailOfEachSpread(); listener.onDataLoad(embeddedYonaActivity); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.no_data_found))); } } private List<DayActivity> sortDayActivity(List<DayActivity> overviewDayActiivties) { Collections.sort(overviewDayActiivties, new Comparator<DayActivity>() { public int compare(DayActivity o1, DayActivity o2) { if (!TextUtils.isEmpty(o1.getYonaGoal().getActivityCategoryName()) && !TextUtils.isEmpty(o2.getYonaGoal().getActivityCategoryName())) { return o1.getYonaGoal().getActivityCategoryName().compareTo(o2.getYonaGoal().getActivityCategoryName()); } return 0; } }); return overviewDayActiivties; } private List<WeekActivity> sortWeekActivity(List<WeekActivity> overviewDayActiivties) { Collections.sort(overviewDayActiivties, new Comparator<WeekActivity>() { public int compare(WeekActivity o1, WeekActivity o2) { if (!TextUtils.isEmpty(o1.getYonaGoal().getActivityCategoryName()) && !TextUtils.isEmpty(o2.getYonaGoal().getActivityCategoryName())) { return o1.getYonaGoal().getActivityCategoryName().compareTo(o2.getYonaGoal().getActivityCategoryName()); } return 0; } }); return overviewDayActiivties; } private YonaGoal getYonaGoal(boolean isBuddyFlow, Href url) { if (!isBuddyFlow) { return findYonaGoal(url); } else { return findYonaBuddyGoal(url); } } private YonaGoal findYonaGoal(Href goalHref) { if (YonaApplication.getEventChangeManager().getDataState().getUser() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded() != null && YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded().getYonaGoals() != null) { List<YonaGoal> yonaGoals = YonaApplication.getEventChangeManager().getDataState().getUser().getEmbedded().getYonaGoals().getEmbedded().getYonaGoals(); for (YonaGoal goal : yonaGoals) { if (goal.getLinks().getSelf().getHref().equals(goalHref.getHref())) { goal.setActivityCategoryName(getActivityCategory(goal)); goal.setNickName(YonaApplication.getEventChangeManager().getDataState().getUser().getNickname()); return goal; } } } return null; } public YonaBuddy findYonaBuddy(Href yonaBuddy) { User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getEmbedded() != null && user.getEmbedded().getYonaBuddies() != null && user.getEmbedded().getYonaBuddies().getEmbedded() != null && user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies() != null) { List<YonaBuddy> yonaBuddies = user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies(); for (YonaBuddy buddy : yonaBuddies) { if (buddy != null && buddy.getLinks() != null && buddy.getLinks().getSelf() != null && buddy.getLinks().getSelf().getHref().equals(yonaBuddy.getHref())) { return buddy; } } } return null; } private YonaGoal findYonaBuddyGoal(Href goalHref) { User user = YonaApplication.getEventChangeManager().getDataState().getUser(); if (user != null && user.getEmbedded() != null && user.getEmbedded().getYonaBuddies() != null && user.getEmbedded().getYonaBuddies().getEmbedded() != null && user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies() != null) { List<YonaBuddy> yonaBuddies = user.getEmbedded().getYonaBuddies().getEmbedded().getYonaBuddies(); for (YonaBuddy buddy : yonaBuddies) { if (buddy != null && buddy.getEmbedded() != null && buddy.getEmbedded().getYonaGoals() != null && buddy.getEmbedded().getYonaGoals().getEmbedded() != null && buddy.getEmbedded().getYonaGoals().getEmbedded().getYonaGoals() != null) { List<YonaGoal> yonaGoals = buddy.getEmbedded().getYonaGoals().getEmbedded().getYonaGoals(); for (YonaGoal goal : yonaGoals) { if (goal.getLinks().getSelf().getHref().equals(goalHref.getHref())) { goal.setActivityCategoryName(getActivityCategory(goal)); goal.setNickName(buddy.getNickname()); return goal; } } } } } return null; } private String getActivityCategory(YonaGoal goal) { ActivityCategories categories = APIManager.getInstance().getActivityCategoryManager().getListOfActivityCategories(); if (categories != null) { List<YonaActivityCategories> categoriesList = categories.getEmbeddedActivityCategories().getYonaActivityCategories(); for (YonaActivityCategories yonaActivityCategories : categoriesList) { if (yonaActivityCategories.get_links().getSelf().getHref().equals(goal.getLinks().getYonaActivityCategory().getHref())) { return yonaActivityCategories.getName(); } } } return null; } private DayActivity generateTimeZoneSpread(DayActivity activity) { if (activity.getSpread() != null) { List<Integer> spreadsList = activity.getSpread(); List<Integer> spreadCellsList; boolean isBudgetGoal = false; if (activity.getYonaGoal() != null && activity.getYonaGoal().getSpreadCells() != null) { isBudgetGoal = activity.getYonaGoal().getType().equals(GoalsEnum.BUDGET_GOAL.getActionString()) && activity.getYonaGoal().getMaxDurationMinutes() != 0; spreadCellsList = activity.getYonaGoal().getSpreadCells(); } else { spreadCellsList = new ArrayList<>(); } List<TimeZoneSpread> timeZoneSpreadList = new ArrayList<>(); for (int i = 0; i < spreadsList.size(); i++) { setTimeZoneSpread(i, spreadsList.get(i), timeZoneSpreadList, spreadCellsList.contains(i) || isBudgetGoal); } activity.setTimeZoneSpread(timeZoneSpreadList); } return activity; } private void setTimeZoneSpread(int index, int spreadListValue, List<TimeZoneSpread> timeZoneSpreadList, boolean allowed) { TimeZoneSpread timeZoneSpread = new TimeZoneSpread(); timeZoneSpread.setIndex(index); timeZoneSpread.setAllowed(allowed); if (spreadListValue > 0) { if (allowed) { timeZoneSpread.setColor(GraphUtils.COLOR_BLUE); } else { timeZoneSpread.setColor(GraphUtils.COLOR_PINK); } timeZoneSpread.setUsedValue(spreadListValue); // ex. set 10 min as blue used during allowed time. timeZoneSpreadList.add(timeZoneSpread); //Now create remaining time's other object: if (spreadListValue < maxSpreadTime) { TimeZoneSpread secondSpread = new TimeZoneSpread(); secondSpread.setIndex(index); secondSpread.setAllowed(allowed); timeZoneSpreadList.add(addToArray(allowed, secondSpread, maxSpreadTime - spreadListValue)); } } else { timeZoneSpreadList.add(addToArray(allowed, timeZoneSpread, maxSpreadTime - spreadListValue)); } } private TimeZoneSpread addToArray(boolean allowed, TimeZoneSpread timeZoneSpread, int usage) { if (allowed) { timeZoneSpread.setColor(GraphUtils.COLOR_GREEN); } else { timeZoneSpread.setColor(GraphUtils.COLOR_WHITE_THREE); } timeZoneSpread.setUsedValue(usage); // out of 15 mins, if 10 min used, so here we need to show 5 min as green return timeZoneSpread; } private WeekActivity generateTimeZoneSpread(WeekActivity activity) { if (activity.getSpread() != null) { List<Integer> spreadsList = activity.getSpread(); List<Integer> spreadCellsList; if (activity.getYonaGoal() != null && activity.getYonaGoal().getSpreadCells() != null) { spreadCellsList = activity.getYonaGoal().getSpreadCells(); } else { spreadCellsList = new ArrayList<>(); } List<TimeZoneSpread> timeZoneSpreadList = new ArrayList<>(); for (int i = 0; i < spreadsList.size(); i++) { setTimeZoneSpread(i, spreadsList.get(i), timeZoneSpreadList, spreadCellsList.contains(i)); } activity.setTimeZoneSpread(timeZoneSpreadList); } return activity; } private void getWithBuddyActivity(String url, int itemsPerPage, int pageNo, final DataLoadListener listener) { try { activityNetwork.getWithBuddyActivity(url, YonaApplication.getEventChangeManager().getSharedPreference().getYonaPassword(), itemsPerPage, pageNo, new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof EmbeddedYonaActivity) { filterAndUpdateWithBuddyData((EmbeddedYonaActivity) result, listener); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.dataparseerror))); } } @Override public void onError(Object errorMessage) { if (errorMessage instanceof ErrorMessage) { listener.onError(errorMessage); } else { listener.onError(new ErrorMessage(errorMessage.toString())); } } }); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), listener); } } //TOD0 modify this method private void filterAndUpdateWithBuddyData(EmbeddedYonaActivity embeddedYonaActivity, DataLoadListener listener) { List<DayActivity> dayActivities = new ArrayList<>(); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity() == null) { YonaApplication.getEventChangeManager().getDataState().setEmbeddedWithBuddyActivity(embeddedYonaActivity); } if (embeddedYonaActivity != null) { if (embeddedYonaActivity.getEmbedded() != null) { Embedded embedded = embeddedYonaActivity.getEmbedded(); List<YonaDayActivityOverview> yonaDayActivityOverviews = embedded.getYonaDayActivityOverviews(); for (YonaDayActivityOverview overview : yonaDayActivityOverviews) { List<DayActivity> overviewDayActivities = overview.getDayActivities(); List<DayActivity> updatedOverviewDayActivities = new ArrayList<>(); for (DayActivity activities : overviewDayActivities) { if (activities != null && activities.getDayActivitiesForUsers() != null) { for (DayActivity activity : activities.getDayActivitiesForUsers()) { activity.setYonaGoal(getYonaGoal(activity.getLinks().getYonaUser() != null ? false : true, activity.getLinks().getYonaGoal())); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = overview.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } if (activity.getYonaGoal() != null && activity.getYonaGoal() != null && !activity.getYonaGoal().isHistoryItem()) { updatedOverviewDayActivities.add(generateTimeZoneSpread(activity)); } } } } dayActivities.addAll(sortDayActivity(updatedOverviewDayActivities)); } if (embeddedYonaActivity.getDayActivityList() == null) { embeddedYonaActivity.setDayActivityList(dayActivities); } else { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList().addAll(dayActivities); } } if (embeddedYonaActivity.getPage() != null) { YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().setPage(embeddedYonaActivity.getPage()); } getBuddyDetailOfEachSpread(); listener.onDataLoad(embeddedYonaActivity); } else { listener.onError(new ErrorMessage(mContext.getString(R.string.no_data_found))); } } private void updateDayActivity(DayActivity activity, DataLoadListener listener) { YonaGoal currentYonaGoal = findYonaGoal(activity.getLinks().getYonaGoal()) != null ? findYonaGoal(activity.getLinks().getYonaGoal()) : findYonaBuddyGoal(activity.getLinks().getYonaGoal()); activity.setYonaGoal(currentYonaGoal); if (activity.getYonaGoal() != null) { if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.BUDGET_GOAL) { if (activity.getYonaGoal().getMaxDurationMinutes() == 0) { activity.setChartTypeEnum(ChartTypeEnum.NOGO_CONTROL); } else { activity.setChartTypeEnum(ChartTypeEnum.TIME_BUCKET_CONTROL); } } else if (GoalsEnum.fromName(activity.getYonaGoal().getType()) == GoalsEnum.TIME_ZONE_GOAL) { activity.setChartTypeEnum(ChartTypeEnum.TIME_FRAME_CONTROL); } } String createdTime = activity.getDate(); try { Calendar futureCalendar = Calendar.getInstance(); futureCalendar.setTime(sdf.parse(createdTime)); activity.setStickyTitle(DateUtility.getRelativeDate(futureCalendar)); } catch (Exception e) { Log.e(NotificationManagerImpl.class.getName(), "DateFormat " + e); } listener.onDataLoad(generateTimeZoneSpread(activity)); } private void getBuddyDetailOfEachSpread() { final List<DayActivity> dayActivities = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList(); for (final DayActivity dayActivity : dayActivities) { if (dayActivity.getTimeZoneSpread() == null || (dayActivity.getTimeZoneSpread() != null && dayActivity.getTimeZoneSpread().size() == 0)) { APIManager.getInstance().getActivityManager().getDayDetailActivity(dayActivity.getLinks().getYonaDayDetails().getHref(), new DataLoadListener() { @Override public void onDataLoad(Object result) { if (result instanceof DayActivity) { try { DayActivity resultActivity = generateTimeZoneSpread((DayActivity) result); if (YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity() != null) { List<DayActivity> dayActivityList = YonaApplication.getEventChangeManager().getDataState().getEmbeddedWithBuddyActivity().getDayActivityList(); if (dayActivityList != null) { for (int i = 0; i < dayActivityList.size(); i++) { try { if (dayActivityList.get(i).getLinks().getYonaDayDetails().getHref().equals(resultActivity.getLinks().getSelf().getHref())) { dayActivityList.get(i).setTimeZoneSpread(resultActivity.getTimeZoneSpread()); dayActivityList.set(i, updateLinks(dayActivityList.get(i), resultActivity)); break; } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } } } catch (Exception e) { AppUtils.throwException(ActivityManagerImpl.class.getSimpleName(), e, Thread.currentThread(), null); } } } @Override public void onError(Object errorMessage) { // we are not worry as of now here } }); } } } private DayActivity updateLinks(DayActivity actualActivity, DayActivity resultActivity) { if (resultActivity.getLinks() != null) { if (resultActivity.getLinks().getSelf() != null) { actualActivity.getLinks().setSelf(resultActivity.getLinks().getSelf()); } if (resultActivity.getLinks().getEdit() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getEdit()); } if (resultActivity.getLinks().getReplyComment() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getReplyComment()); } if (resultActivity.getLinks().getYonaMessages() != null) { actualActivity.getLinks().setYonaMessages(resultActivity.getLinks().getYonaMessages()); } if (resultActivity.getLinks().getYonaUser() != null) { actualActivity.getLinks().setYonaUser(resultActivity.getLinks().getYonaUser()); } if (resultActivity.getLinks().getYonaDayDetails() != null) { actualActivity.getLinks().setYonaDayDetails(resultActivity.getLinks().getYonaDayDetails()); } if (resultActivity.getLinks().getYonaBuddy() != null) { actualActivity.getLinks().setYonaBuddy(resultActivity.getLinks().getYonaBuddy()); } if (resultActivity.getLinks().getAddComment() != null) { actualActivity.getLinks().setAddComment(resultActivity.getLinks().getAddComment()); } } return actualActivity; } private WeekActivity updateLinks(WeekActivity actualActivity, WeekActivity resultActivity) { if (resultActivity.getLinks() != null) { if (resultActivity.getLinks().getSelf() != null) { actualActivity.getLinks().setSelf(resultActivity.getLinks().getSelf()); } if (resultActivity.getLinks().getEdit() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getEdit()); } if (resultActivity.getLinks().getReplyComment() != null) { actualActivity.getLinks().setEdit(resultActivity.getLinks().getReplyComment()); } if (resultActivity.getLinks().getYonaMessages() != null) { actualActivity.getLinks().setYonaMessages(resultActivity.getLinks().getYonaMessages()); } if (resultActivity.getLinks().getYonaUser() != null) { actualActivity.getLinks().setYonaUser(resultActivity.getLinks().getYonaUser()); } if (resultActivity.getLinks().getYonaDayDetails() != null) { actualActivity.getLinks().setYonaDayDetails(resultActivity.getLinks().getYonaDayDetails()); } if (resultActivity.getLinks().getYonaBuddy() != null) { actualActivity.getLinks().setYonaBuddy(resultActivity.getLinks().getYonaBuddy()); } if (resultActivity.getLinks().getAddComment() != null) { actualActivity.getLinks().setAddComment(resultActivity.getLinks().getAddComment()); } } return actualActivity; } }
Handle url check in posting app activity Handle url check in posting app activity Signed-off-by: Kinnar Vasa <7e1ed76899879a0d8732c30e94b9e94691b30172@mobiquityinc.com>
app/src/main/java/nu/yona/app/api/manager/impl/ActivityManagerImpl.java
Handle url check in posting app activity
Java
agpl-3.0
7e0717a8a84604b272f3c548cafc3486dcd54b60
0
d3b-center/pedcbioportal,shrumit/cbioportal-gsoc-final,IntersectAustralia/cbioportal,IntersectAustralia/cbioportal,kalletlak/cbioportal,inodb/cbioportal,onursumer/cbioportal,IntersectAustralia/cbioportal,yichaoS/cbioportal,jjgao/cbioportal,onursumer/cbioportal,adamabeshouse/cbioportal,jjgao/cbioportal,yichaoS/cbioportal,cBioPortal/cbioportal,IntersectAustralia/cbioportal,angelicaochoa/cbioportal,cBioPortal/cbioportal,pughlab/cbioportal,zhx828/cbioportal,adamabeshouse/cbioportal,kalletlak/cbioportal,angelicaochoa/cbioportal,jjgao/cbioportal,d3b-center/pedcbioportal,shrumit/cbioportal-gsoc-final,kalletlak/cbioportal,yichaoS/cbioportal,n1zea144/cbioportal,gsun83/cbioportal,zhx828/cbioportal,gsun83/cbioportal,jjgao/cbioportal,onursumer/cbioportal,inodb/cbioportal,mandawilson/cbioportal,n1zea144/cbioportal,pughlab/cbioportal,mandawilson/cbioportal,IntersectAustralia/cbioportal,d3b-center/pedcbioportal,cBioPortal/cbioportal,IntersectAustralia/cbioportal,pughlab/cbioportal,mandawilson/cbioportal,cBioPortal/cbioportal,zhx828/cbioportal,yichaoS/cbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,kalletlak/cbioportal,adamabeshouse/cbioportal,pughlab/cbioportal,yichaoS/cbioportal,bihealth/cbioportal,zhx828/cbioportal,bihealth/cbioportal,jjgao/cbioportal,IntersectAustralia/cbioportal,onursumer/cbioportal,pughlab/cbioportal,zhx828/cbioportal,bihealth/cbioportal,mandawilson/cbioportal,angelicaochoa/cbioportal,sheridancbio/cbioportal,zhx828/cbioportal,sheridancbio/cbioportal,angelicaochoa/cbioportal,d3b-center/pedcbioportal,inodb/cbioportal,adamabeshouse/cbioportal,cBioPortal/cbioportal,shrumit/cbioportal-gsoc-final,n1zea144/cbioportal,d3b-center/pedcbioportal,n1zea144/cbioportal,yichaoS/cbioportal,d3b-center/pedcbioportal,yichaoS/cbioportal,kalletlak/cbioportal,inodb/cbioportal,mandawilson/cbioportal,sheridancbio/cbioportal,adamabeshouse/cbioportal,adamabeshouse/cbioportal,sheridancbio/cbioportal,bihealth/cbioportal,bihealth/cbioportal,kalletlak/cbioportal,sheridancbio/cbioportal,mandawilson/cbioportal,angelicaochoa/cbioportal,gsun83/cbioportal,onursumer/cbioportal,pughlab/cbioportal,onursumer/cbioportal,jjgao/cbioportal,n1zea144/cbioportal,gsun83/cbioportal,jjgao/cbioportal,mandawilson/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,bihealth/cbioportal,zhx828/cbioportal,n1zea144/cbioportal,shrumit/cbioportal-gsoc-final,gsun83/cbioportal,inodb/cbioportal,kalletlak/cbioportal,shrumit/cbioportal-gsoc-final,sheridancbio/cbioportal,inodb/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,gsun83/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,n1zea144/cbioportal,shrumit/cbioportal-gsoc-final,cBioPortal/cbioportal,bihealth/cbioportal
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.DaoSampleList; import org.mskcc.cbio.portal.util.ConsoleUtil; import org.mskcc.cbio.portal.util.ProgressMonitor; /** * Command Line Tool to Delete All Sample Lists. */ public class DeleteAllSampleLists { public static void main(String[] args) throws Exception { ProgressMonitor.setConsoleMode(true); DaoSampleList daoSampleList = new DaoSampleList(); daoSampleList.deleteAllRecords(); System.out.println ("\nAll Existing Sample Lists Deleted."); ConsoleUtil.showWarnings(); } }
core/src/main/java/org/mskcc/cbio/portal/scripts/DeleteAllSampleLists.java
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.DaoSampleList; import org.mskcc.cbio.portal.util.ConsoleUtil; import org.mskcc.cbio.portal.util.ProgressMonitor; /** * Command Line Tool to Delete All Sample Lists. */ public class DeleteAllSampleLists { public static void main(String[] args) throws Exception { ProgressMonitor.setConsoleMode(true); DaoSampleList daoSampleList = new DaoSampleList(); daoSampleList.deleteAllRecords(); System.out.println ("\nAll Existing Sample Lists Deleted."); ConsoleUtil.showWarnings(pMonitor); } }
pMonitor missed in conflict resolving
core/src/main/java/org/mskcc/cbio/portal/scripts/DeleteAllSampleLists.java
pMonitor missed in conflict resolving
Java
apache-2.0
d39dc11358f9d263bd0b479c9f878b0644b323e6
0
esoco/esoco-business
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'esoco-business' project. // Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ package de.esoco.process.step; import de.esoco.data.DataRelationTypes; import de.esoco.data.SessionData; import de.esoco.data.SessionManager; import de.esoco.data.element.StringDataElement; import de.esoco.entity.Entity; import de.esoco.lib.logging.Log; import de.esoco.lib.property.Alignment; import de.esoco.lib.property.ContentType; import de.esoco.lib.property.LayoutType; import de.esoco.process.Parameter; import de.esoco.process.ProcessRelationTypes; import de.esoco.process.ValueEventHandler; import static de.esoco.lib.property.StateProperties.DISABLE_ON_INTERACTION; import static de.esoco.lib.property.StateProperties.FOCUSED; import static de.esoco.process.ProcessRelationTypes.AUTO_UPDATE; import static de.esoco.process.ProcessRelationTypes.CLIENT_INFO; import static de.esoco.process.ProcessRelationTypes.PROCESS_SESSION_EXPIRED; import static de.esoco.process.ProcessRelationTypes.PROCESS_USER; import static org.obrel.type.MetaTypes.AUTHENTICATED; /******************************************************************** * A generic login fragment for the authentication process of an application. * * @author eso */ public class LoginFragment extends InteractionFragment { //~ Enums ------------------------------------------------------------------ /******************************************************************** * Enumeration of the available login actions. */ public enum LoginAction { LOGIN, REGISTER, RESET_PASSWORD } //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 1L; //~ Instance fields -------------------------------------------------------- private final int nMaxLoginAttempts; private final int nInitialLoginErrorWaitTime; private Parameter<String> aLoginName; private Parameter<String> aPassword; private Parameter<String> aErrorMessage; private int nErrorCount = 0; private int nErrorWaitTime = 0; private long nErrorWaitStart; //~ Constructors ----------------------------------------------------------- /*************************************** * Default constructor with 3 allowed login attempts and 5 seconds initial * wait time. */ public LoginFragment() { this(3, 5); } /*************************************** * Creates a new instance with the given login failure parameters. * * @param nMaxLoginAttemptsUntilDelay The maximum number of login attempts * that can be done until the user must * wait a certain time before the next * attempt. -1 disabled login attempt * delays completely. * @param nInitialLoginErrorWaitTime The initial time in seconds the user * must wait after the maximum number of * login attempts has been reached; this * will double with each failure cycle. */ public LoginFragment( int nMaxLoginAttemptsUntilDelay, int nInitialLoginErrorWaitTime) { this.nMaxLoginAttempts = nMaxLoginAttemptsUntilDelay; this.nInitialLoginErrorWaitTime = nInitialLoginErrorWaitTime; } //~ Methods ---------------------------------------------------------------- /*************************************** * {@inheritDoc} */ @Override public void init() throws Exception { layout(LayoutType.FORM).set(DISABLE_ON_INTERACTION); addInputFields(); addErrorLabel(); addLoginButton(); } /*************************************** * Adds the next domain availability check result to this fragment on an * auto-update interaction. * * @see InteractionFragment#prepareInteraction() */ @Override @SuppressWarnings("boxing") public void prepareInteraction() throws Exception { if (nErrorWaitTime > 0) { int nWaitSeconds = (int) ((System.currentTimeMillis() - nErrorWaitStart) / 1000); if (nWaitSeconds > nErrorWaitTime) { if (hasFlag(AUTO_UPDATE)) { aErrorMessage.hide(); set(AUTO_UPDATE, false); fragmentParam().enableEdit(true); } } else { aErrorMessage.show() .value(createErrorWaitMessage(nErrorWaitTime - nWaitSeconds)); Thread.sleep(1000); } } else { if (hasFlagParameter(PROCESS_SESSION_EXPIRED)) { deleteParameters(PROCESS_SESSION_EXPIRED); aErrorMessage.show().value("$msgProcessSessionExpired"); } fragmentParam().enableEdit(true); } } /*************************************** * Adds the error label to this fragment. */ protected void addErrorLabel() { aErrorMessage = label("").style("ErrorMessage").hide(); } /*************************************** * Adds the login name and password input fields to this fragment. */ protected void addInputFields() { aLoginName = inputText("LoginName").ensureNotEmpty() .set(FOCUSED) .onAction(new ValueEventHandler<String>() { @Override public void handleValueUpdate(String sLoginName) throws Exception { handleLoginNameInput(sLoginName); } }); aPassword = inputText("Password").content(ContentType.PASSWORD) .ensureNotEmpty() .onAction(new ValueEventHandler<String>() { @Override public void handleValueUpdate(String sPassword) throws Exception { handlePasswordInput(sPassword); } }); } /*************************************** * Adds the login button to this fragment. */ protected void addLoginButton() { buttons(LoginAction.LOGIN).alignHorizontal(Alignment.CENTER) .continueOnInteraction(false) .onAction(eAction -> performLogin()); } /*************************************** * Creates the waiting message after successive login failures. * * @param nRemainingSeconds The number of seconds the user has to wait * * @return */ @SuppressWarnings("boxing") protected String createErrorWaitMessage(int nRemainingSeconds) { return String.format("$${$msgSuccessiveLoginErrorStart} %d " + "{$msgSuccessiveLoginErrorEnd}", nRemainingSeconds); } /*************************************** * Handles login name input. * * @param sLoginName The login name */ protected void handleLoginNameInput(String sLoginName) { if (aPassword.value().length() > 5) { performLogin(); } else { aPassword.set(FOCUSED); } } /*************************************** * Handles password input. * * @param sPassword The password */ protected void handlePasswordInput(String sPassword) { if (aLoginName.value().length() > 2) { performLogin(); } } /*************************************** * Will be invoked after the user has been successfully authenticated to * check whether she is authorized to use the application. Can be overridden * by subclasses that need to check additional constraints. Only if this * method returns TRUE will the process be initialized with the * authentication data. The default implementation always returns TRUE. * * @param rUser The user that has been authenticated * * @return TRUE if the user is authorized to use the application, FALSE if * not * * @throws Exception Implementations may alternatively throw any kind of * exception if the authorization fails. This has the same * effect as returning FALSE. */ protected boolean isUserAuthorized(Entity rUser) throws Exception { return true; } /*************************************** * Handles the login action that occurred. */ protected void performLogin() { String sLoginName = aLoginName.value().toLowerCase(); String sPassword = aPassword.value(); StringDataElement aLoginData = new StringDataElement(sLoginName, sPassword); try { SessionManager rSessionManager = getParameter(DataRelationTypes.SESSION_MANAGER); rSessionManager.loginUser(aLoginData, getParameter(CLIENT_INFO)); Entity rUser = rSessionManager.getSessionData().get(SessionData.SESSION_USER); if (!isUserAuthorized(rUser)) { // handle in catch block throw new Exception(); } nErrorCount = 0; nErrorWaitTime = 0; aPassword.value(""); // update the process user to the authenticated person setParameter(PROCESS_USER, rUser); setParameter(AUTHENTICATED, true); continueOnInteraction(getInteractiveInputParameter()); } catch (Exception e) { String sMessage = "$msgLoginError"; if (nMaxLoginAttempts > 0 && ++nErrorCount >= nMaxLoginAttempts) { if (nErrorWaitTime > 0) { Log.warnf(e, "Repeated login failure of user %s", sLoginName); } nErrorWaitTime = nErrorWaitTime == 0 ? nInitialLoginErrorWaitTime : nErrorWaitTime * 2; nErrorCount = 0; nErrorWaitStart = System.currentTimeMillis(); sMessage = createErrorWaitMessage(nErrorWaitTime); fragmentParam().enableEdit(false); set(ProcessRelationTypes.AUTO_UPDATE); } aErrorMessage.show().value(sMessage); } } }
src/main/java/de/esoco/process/step/LoginFragment.java
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'esoco-business' project. // Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ package de.esoco.process.step; import de.esoco.data.DataRelationTypes; import de.esoco.data.SessionData; import de.esoco.data.SessionManager; import de.esoco.data.element.StringDataElement; import de.esoco.entity.Entity; import de.esoco.lib.logging.Log; import de.esoco.lib.property.Alignment; import de.esoco.lib.property.ContentType; import de.esoco.lib.property.LayoutType; import de.esoco.process.Parameter; import de.esoco.process.ProcessRelationTypes; import de.esoco.process.ValueEventHandler; import static de.esoco.lib.property.StateProperties.DISABLE_ON_INTERACTION; import static de.esoco.lib.property.StateProperties.FOCUSED; import static de.esoco.process.ProcessRelationTypes.AUTO_UPDATE; import static de.esoco.process.ProcessRelationTypes.CLIENT_INFO; import static de.esoco.process.ProcessRelationTypes.PROCESS_SESSION_EXPIRED; import static de.esoco.process.ProcessRelationTypes.PROCESS_USER; import static org.obrel.type.MetaTypes.AUTHENTICATED; /******************************************************************** * A generic login fragment for the authentication process of an application. * * @author eso */ public class LoginFragment extends InteractionFragment { //~ Enums ------------------------------------------------------------------ /******************************************************************** * Enumeration of the available login actions. */ public enum LoginAction { LOGIN, REGISTER, RESET_PASSWORD } //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 1L; //~ Instance fields -------------------------------------------------------- private final int nMaxLoginAttempts; private final int nInitialLoginErrorWaitTime; private Parameter<String> aLoginName; private Parameter<String> aPassword; private Parameter<String> aErrorMessage; private int nErrorCount = 0; private int nErrorWaitTime = 0; private long nErrorWaitStart; //~ Constructors ----------------------------------------------------------- /*************************************** * Default constructor with 3 allowed login attempts and 5 seconds initial * wait time. */ public LoginFragment() { this(3, 5); } /*************************************** * Creates a new instance with the given login failure parameters. * * @param nMaxLoginAttemptsUntilDelay The maximum number of login attempts * that can be done until the user must * wait a certain time before the next * attempt. -1 disabled login attempt * delays completely. * @param nInitialLoginErrorWaitTime The initial time in seconds the user * must wait after the maximum number of * login attempts has been reached; this * will double with each failure cycle. */ public LoginFragment( int nMaxLoginAttemptsUntilDelay, int nInitialLoginErrorWaitTime) { this.nMaxLoginAttempts = nMaxLoginAttemptsUntilDelay; this.nInitialLoginErrorWaitTime = nInitialLoginErrorWaitTime; } //~ Methods ---------------------------------------------------------------- /*************************************** * {@inheritDoc} */ @Override public void init() throws Exception { layout(LayoutType.FORM).set(DISABLE_ON_INTERACTION); addInputFields(); addErrorLabel(); addLoginButton(); } /*************************************** * Adds the next domain availability check result to this fragment on an * auto-update interaction. * * @see InteractionFragment#prepareInteraction() */ @Override @SuppressWarnings("boxing") public void prepareInteraction() throws Exception { if (nErrorWaitTime > 0) { int nWaitSeconds = (int) ((System.currentTimeMillis() - nErrorWaitStart) / 1000); if (nWaitSeconds > nErrorWaitTime) { if (hasFlag(AUTO_UPDATE)) { aErrorMessage.hide(); set(AUTO_UPDATE, false); fragmentParam().enableEdit(true); } } else { aErrorMessage.show() .value(createErrorWaitMessage(nErrorWaitTime - nWaitSeconds)); Thread.sleep(1000); } } else { if (hasFlagParameter(PROCESS_SESSION_EXPIRED)) { deleteParameters(PROCESS_SESSION_EXPIRED); aErrorMessage.show().value("$msgProcessSessionExpired"); } fragmentParam().enableEdit(true); } } /*************************************** * Adds the error label to this fragment. */ protected void addErrorLabel() { aErrorMessage = label("").style("ErrorMessage").hide(); } /*************************************** * Adds the login name and password input fields to this fragment. */ protected void addInputFields() { aLoginName = inputText("LoginName").ensureNotEmpty() .set(FOCUSED) .onAction(new ValueEventHandler<String>() { @Override public void handleValueUpdate(String sLoginName) throws Exception { handleLoginNameInput(sLoginName); } }); aPassword = inputText("Password").content(ContentType.PASSWORD) .ensureNotEmpty() .onAction(new ValueEventHandler<String>() { @Override public void handleValueUpdate(String sPassword) throws Exception { handlePasswordInput(sPassword); } }); } /*************************************** * Adds the login button to this fragment. */ protected void addLoginButton() { buttons(LoginAction.LOGIN).alignHorizontal(Alignment.CENTER) .continueOnInteraction(false) .onAction(eAction -> performLogin()); } /*************************************** * Creates the waiting message after successive login failures. * * @param nRemainingSeconds The number of seconds the user has to wait * * @return */ @SuppressWarnings("boxing") protected String createErrorWaitMessage(int nRemainingSeconds) { return String.format("$${$msgSuccessiveLoginErrorStart} %d " + "{$msgSuccessiveLoginErrorEnd}", nRemainingSeconds); } /*************************************** * Handles login name input. * * @param sLoginName The login name */ protected void handleLoginNameInput(String sLoginName) { if (aPassword.value().length() > 5) { performLogin(); } else { aPassword.set(FOCUSED); } } /*************************************** * Handles password input. * * @param sPassword The password */ protected void handlePasswordInput(String sPassword) { if (aLoginName.value().length() > 2) { performLogin(); } } /*************************************** * Will be invoked after the user has been successfully authenticated to * check whether she is authorized to use the application. Can be overridden * by subclasses that need to check additional constraints. Only if this * method returns TRUE will the process be initialized with the * authentication data. The default implementation always returns TRUE. * * @param rUser The user that has been authenticated * * @return TRUE if the user is authorized to use the application, FALSE if * not * * @throws Exception Implementations may alternatively throw any kind of * exception if the authorization fails. This has the same * effect as returning FALSE. */ protected boolean isUserAuthorized(Entity rUser) throws Exception { return true; } /*************************************** * Handles the login action that occurred. */ protected void performLogin() { String sLoginName = aLoginName.value(); String sPassword = aPassword.value(); StringDataElement aLoginData = new StringDataElement(sLoginName, sPassword); try { SessionManager rSessionManager = getParameter(DataRelationTypes.SESSION_MANAGER); rSessionManager.loginUser(aLoginData, getParameter(CLIENT_INFO)); Entity rUser = rSessionManager.getSessionData().get(SessionData.SESSION_USER); if (!isUserAuthorized(rUser)) { // handle in catch block throw new Exception(); } nErrorCount = 0; nErrorWaitTime = 0; aPassword.value(""); // update the process user to the authenticated person setParameter(PROCESS_USER, rUser); setParameter(AUTHENTICATED, true); continueOnInteraction(getInteractiveInputParameter()); } catch (Exception e) { String sMessage = "$msgLoginError"; if (nMaxLoginAttempts > 0 && ++nErrorCount >= nMaxLoginAttempts) { if (nErrorWaitTime > 0) { Log.warnf(e, "Repeated login failure of user %s", sLoginName); } nErrorWaitTime = nErrorWaitTime == 0 ? nInitialLoginErrorWaitTime : nErrorWaitTime * 2; nErrorCount = 0; nErrorWaitStart = System.currentTimeMillis(); sMessage = createErrorWaitMessage(nErrorWaitTime); fragmentParam().enableEdit(false); set(ProcessRelationTypes.AUTO_UPDATE); } aErrorMessage.show().value(sMessage); } } }
OPT: always convert password to lower case
src/main/java/de/esoco/process/step/LoginFragment.java
OPT: always convert password to lower case
Java
apache-2.0
10d5d2fa325039260bdefa24cc12aa5334a6ab9c
0
prateekm/samza,lhaiesp/samza,apache/samza,prateekm/samza,apache/samza,apache/samza,lhaiesp/samza,lhaiesp/samza,apache/samza,apache/samza,prateekm/samza,prateekm/samza,lhaiesp/samza,lhaiesp/samza,prateekm/samza
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.system; import org.apache.samza.config.Config; import org.apache.samza.metrics.MetricsRegistry; /** * Build the {@link org.apache.samza.system.SystemConsumer} and {@link org.apache.samza.system.SystemProducer} for * a particular system, as well as the accompanying {@link org.apache.samza.system.SystemAdmin}. */ public interface SystemFactory { @Deprecated SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry); @Deprecated SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry); @Deprecated SystemAdmin getAdmin(String systemName, Config config); /** * This function provides an extra input parameter to {@link #getConsumer}, which can be used to provide extra * information for the consumer instance, e.g. ownership of client instance, to helper better identify consumers in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create consumer for. * @param config The config to create consumer with. * @param registry MetricsRegistry to which to publish consumer specific metrics. * @param consumerLabel a string to provide info the consumer instance. * @return A SystemConsumer */ default SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry, String consumerLabel) { return getConsumer(systemName, config, registry); } /** * This function provides an extra input parameter to {@link #getProducer}, which can be used to provide extra * information for the producer instance, e.g. ownership of client instance, to helper better identify producers in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create producer for. * @param config The config to create producer with. * @param registry MetricsRegistry to which to publish producer specific metrics. * @param producerLabel a string to provide info the producer instance. * @return A SystemProducer */ default SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry, String producerLabel) { return getProducer(systemName, config, registry); } /** * This function provides an extra input parameter to {@link #getAdmin}, which can be used to provide extra * information for the admin instance, e.g. ownership of client instance, to helper better identify admins in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create admin for. * @param config The config to create admin with. * @param adminLabel a string to provide info the admin instance. * @return A SystemAdmin */ default SystemAdmin getAdmin(String systemName, Config config, String adminLabel) { return getAdmin(systemName, config); } }
samza-api/src/main/java/org/apache/samza/system/SystemFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.system; import org.apache.samza.config.Config; import org.apache.samza.metrics.MetricsRegistry; /** * Build the {@link org.apache.samza.system.SystemConsumer} and {@link org.apache.samza.system.SystemProducer} for * a particular system, as well as the accompanying {@link org.apache.samza.system.SystemAdmin}. */ public interface SystemFactory { @Deprecated SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry); @Deprecated SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry); @Deprecated SystemAdmin getAdmin(String systemName, Config config); /** * This function provides an extra input parameter than {@link #getConsumer}, which can be used to provide extra * information e.g. ownership of client instance, to helper better identify consumers in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create consumer for. * @param config The config to create consumer with. * @param registry MetricsRegistry to which to publish consumer specific metrics. * @param consumerLabel a string to provide info the consumer instance. * @return A SystemConsumer */ default SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry, String consumerLabel) { return getConsumer(systemName, config, registry); } /** * This function provides an extra input parameter than {@link #getProducer}, which can be used to provide extra * information e.g. ownership of client instance, to helper better identify producers in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create producer for. * @param config The config to create producer with. * @param registry MetricsRegistry to which to publish producer specific metrics. * @param producerLabel a string to provide info the producer instance. * @return A SystemProducer */ default SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry, String producerLabel) { return getProducer(systemName, config, registry); } /** * This function provides an extra input parameter than {@link #getAdmin}, which can be used to provide extra * information e.g. ownership of client instance, to helper better identify admins in logs, * threads and client instances etc., along with other relevant information like systemName. * * @param systemName The name of the system to create admin for. * @param config The config to create admin with. * @param adminLabel a string to provide info the admin instance. * @return A SystemAdmin */ default SystemAdmin getAdmin(String systemName, Config config, String adminLabel) { return getAdmin(systemName, config); } }
address comments and provide better comments
samza-api/src/main/java/org/apache/samza/system/SystemFactory.java
address comments and provide better comments